repo_name
stringlengths 6
91
| ref
stringlengths 12
59
| path
stringlengths 7
936
| license
stringclasses 15
values | copies
stringlengths 1
3
| content
stringlengths 61
714k
| hash
stringlengths 32
32
| line_mean
float64 4.88
60.8
| line_max
int64 12
421
| alpha_frac
float64 0.1
0.92
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
frankcjw/CJWUtilsS
|
refs/heads/master
|
CJWUtilsS/QPLib/Utils/QPCacheUtils.swift
|
mit
|
1
|
//
// QPCacheUtils.swift
// QHProject
//
// Created by quickplain on 15/12/24.
// Copyright © 2015年 quickplain. All rights reserved.
//
import UIKit
import CryptoSwift
public class QPCacheUtils: NSObject {
public class var sharedInstance : QPCacheUtils {
struct Static {
static var onceToken : dispatch_once_t = 0
static var instance : QPCacheUtils? = nil
}
dispatch_once(&Static.onceToken) {
Static.instance = QPCacheUtils()
}
return Static.instance!
}
public var container = NSMutableDictionary()
public class func cache(value: AnyObject, forKey : String) {
QPCacheUtils.cache(value, forKey: forKey, toDisk: false)
}
public class func cache(value: AnyObject, forKey : String, toDisk: Bool) {
let newKey = forKey.md5()
// let newKey = (forKey as NSString).encryptToAESString()
// print("cache \(forKey) \(newKey) \(value)")
QPCacheUtils.sharedInstance.container.setObject(value, forKey: newKey)
if toDisk {
let userDefault = NSUserDefaults.standardUserDefaults()
userDefault.setObject(value, forKey: newKey)
}
}
public class func getCacheBy(key: String) -> AnyObject? {
let newKey = key.md5() //
// print("getCacheBy \(key) \(newKey)")
let obj = QPCacheUtils.sharedInstance.container[newKey]
if obj == nil {
let userDefault = NSUserDefaults.standardUserDefaults()
let value = userDefault.objectForKey(newKey)
return value
} else {
return obj
}
}
public class func isExist(key: String) -> Bool {
// let newKey = (key as NSString).encryptToAESString()
let newKey = key.md5() //
// print("isExist \(key) \(newKey)")
if let _ = QPCacheUtils.sharedInstance.container[newKey] {
return true
} else {
let userDefault = NSUserDefaults.standardUserDefaults()
if let _ = userDefault.objectForKey(newKey) {
return true
}
return false
}
}
}
public extension NSObject {
private func appendingKey() -> String {
return "\(HOST)-\(QPMemberUtils.sharedInstance.memberId)"
}
public func cacheBy(key : String) -> AnyObject? {
let newKey = key + appendingKey()
return QPCacheUtils.getCacheBy(newKey)
}
public func cache(cacheObject: AnyObject!, forKey: String!) {
let newKey = forKey + appendingKey()
QPCacheUtils.cache(cacheObject, forKey: newKey)
}
public func cacheToDisk(cacheObject: AnyObject!, forKey: String!) {
let newKey = forKey + appendingKey()
QPCacheUtils.cache(cacheObject, forKey: newKey, toDisk: true)
}
public func cacheIsExist(key: String) -> Bool {
let newKey = key + appendingKey()
return QPCacheUtils.isExist(newKey)
}
}
|
c4eb00d4244186dcefd52eec34f775b7
| 26.147368 | 75 | 0.702598 | false | false | false | false |
kumabook/StickyNotesiOS
|
refs/heads/master
|
StickyNotes/StickyTableViewController.swift
|
mit
|
1
|
//
// StickyTableViewController.swift
// StickyNotes
//
// Created by Hiroki Kumamoto on 8/11/16.
// Copyright © 2016 kumabook. All rights reserved.
//
import UIKit
import RealmSwift
import GoogleMobileAds
class StickyTableViewController: UITableViewController {
var cellHeight: CGFloat = 164
let reuseIdentifier = "StickyTableViewCell"
let reuseIdentifierForAd = "tableViewCellForAdView"
var stickies: Results<StickyEntity>!
var frequencyAdsInCells = 5
var adOffset = 3
var showAd: Bool {
return !PaymentManager.shared.isPremiumUser
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewDidLoad() {
self.automaticallyAdjustsScrollViewInsets = false
super.viewDidLoad()
let nib = UINib(nibName: "StickyTableViewCell", bundle: nil)
tableView.register(nib, forCellReuseIdentifier: reuseIdentifier)
tableView.register(UITableViewCell.self, forCellReuseIdentifier: reuseIdentifierForAd)
reloadData()
}
func reload() {
reloadData()
tableView.reloadData()
if APIClient.shared.isLoggedIn {
if PaymentManager().canSyncNow {
Store.shared.dispatch(FetchStickiesAction())
return
}
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.25) {
let _ = UIAlertController.showPurchaseAlert(self, message: "You can sync per hour. If you purchase premium service, you can sync immediately.".localize())
}
}
refreshControl?.endRefreshing()
}
func reloadData() {
stickies = Store.shared.state.value.stickiesRepository.items
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
Store.shared.state.value.stickiesRepository.state.signal.observeValues() { [weak self] state in
switch state {
case .normal:
self?.refreshControl?.endRefreshing()
self?.reloadData()
self?.tableView.reloadData()
case .fetching:
self?.refreshControl?.beginRefreshing()
case .updating:
self?.refreshControl?.beginRefreshing()
}
}
Store.shared.state.subscribe {[weak self] _ in
self?.reloadData()
self?.tableView.reloadData()
}
}
func getSticky(at indexPath: IndexPath) -> StickyEntity {
let index = indexPath.row
let offset = index % frequencyAdsInCells
let d = offset > adOffset ? 1 : 0
if showAd {
return stickies[index - index / frequencyAdsInCells - d]
}
return stickies[index]
}
// MARK: - Table view data source
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
if showAd && indexPath.row % frequencyAdsInCells == adOffset {
return cellHeight
}
let sticky = getSticky(at: indexPath)
return cellHeight - (sticky.tags.count == 0 ? 36 : 0)
}
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if showAd {
return stickies.count + (stickies.count / frequencyAdsInCells)
}
return stickies.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if showAd && indexPath.row % frequencyAdsInCells == adOffset {
let cell = tableView.dequeueReusableCell(withIdentifier: reuseIdentifierForAd, for:indexPath)
let size = GADAdSizeFromCGSize(CGSize(width: view.frame.width, height: cellHeight))
if cell.contentView.subviews.count == 0, let adView = GADNativeExpressAdView(adSize: size) {
if let config = Config.default {
adView.adUnitID = config.admobTableViewCellAdUnitID
}
adView.rootViewController = self
adView.load(GADRequest())
cell.contentView.addSubview(adView)
adView.snp.makeConstraints() { make in
make.top.equalTo(cell.contentView)
make.height.equalTo(cellHeight)
make.left.equalTo(cell.contentView)
make.right.equalTo(cell.contentView)
}
}
return cell
}
let cell = tableView.dequeueReusableCell(withIdentifier: reuseIdentifier, for: indexPath) as! StickyTableViewCell
let sticky = getSticky(at: indexPath)
cell.updateView(sticky)
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if showAd && indexPath.row % frequencyAdsInCells == adOffset {
return
}
let sticky = getSticky(at: indexPath)
if let page = sticky.page {
let vc = WebViewController(page: page)
navigationController?.pushViewController(vc, animated: true)
}
}
override func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
let sticky = getSticky(at: indexPath)
let remove = UITableViewRowAction(style: .default, title: "Remove".localize()) { (action, indexPath) in
Store.shared.dispatch(DeleteStickyAction(sticky: sticky))
}
remove.backgroundColor = UIColor.red
return [remove]
}
}
|
295f409e39f37c070eeea7181e3d8375
| 36.603896 | 170 | 0.622172 | false | false | false | false |
Tsiems/mobile-sensing-apps
|
refs/heads/master
|
06-Daily/code/Daily/IBAnimatable/SystemRevealAnimator.swift
|
gpl-3.0
|
5
|
//
// Created by Tom Baranes on 02/04/16.
// Copyright © 2016 IBAnimatable. All rights reserved.
//
import UIKit
public class SystemRevealAnimator: NSObject, AnimatedTransitioning {
// MARK: - AnimatorProtocol
public var transitionAnimationType: TransitionAnimationType
public var transitionDuration: Duration = defaultTransitionDuration
public var reverseAnimationType: TransitionAnimationType?
public var interactiveGestureType: InteractiveGestureType?
// MARK: - private
fileprivate var fromDirection: TransitionAnimationType.Direction
public init(from direction: TransitionAnimationType.Direction, transitionDuration: Duration) {
fromDirection = direction
self.transitionDuration = transitionDuration
switch fromDirection {
case .right:
self.transitionAnimationType = .systemReveal(from: .right)
self.reverseAnimationType = .systemReveal(from: .left)
self.interactiveGestureType = .pan(from: .left)
case .top:
self.transitionAnimationType = .systemReveal(from: .top)
self.reverseAnimationType = .systemReveal(from: .bottom)
self.interactiveGestureType = .pan(from: .bottom)
case .bottom:
self.transitionAnimationType = .systemReveal(from: .bottom)
self.reverseAnimationType = .systemReveal(from: .top)
self.interactiveGestureType = .pan(from: .top)
default:
self.transitionAnimationType = .systemPush(from: .left)
self.reverseAnimationType = .systemPush(from: .right)
self.interactiveGestureType = .pan(from: .right)
}
super.init()
}
}
extension SystemRevealAnimator: UIViewControllerAnimatedTransitioning {
public func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
return retrieveTransitionDuration(transitionContext: transitionContext)
}
public func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
animateWithCATransition(transitionContext: transitionContext, type: TransitionAnimationType.SystemTransitionType.reveal, subtype: fromDirection.caTransitionSubtype)
}
}
|
f563a2ba133fd77cef73410babe38663
| 39.169811 | 168 | 0.766557 | false | false | false | false |
itsaboutcode/WordPress-iOS
|
refs/heads/develop
|
WordPress/Classes/Stores/StatsWidgetsStore.swift
|
gpl-2.0
|
1
|
import WidgetKit
class StatsWidgetsStore {
init() {
observeAccountChangesForWidgets()
}
/// Refreshes the site list used to configure the widgets when sites are added or deleted
@objc func refreshStatsWidgetsSiteList() {
initializeStatsWidgetsIfNeeded()
if let newTodayData = refreshStats(type: HomeWidgetTodayData.self) {
HomeWidgetTodayData.write(items: newTodayData)
if #available(iOS 14.0, *) {
WidgetCenter.shared.reloadTimelines(ofKind: WPHomeWidgetTodayKind)
}
}
if let newAllTimeData = refreshStats(type: HomeWidgetAllTimeData.self) {
HomeWidgetAllTimeData.write(items: newAllTimeData)
if #available(iOS 14.0, *) {
WidgetCenter.shared.reloadTimelines(ofKind: WPHomeWidgetAllTimeKind)
}
}
if let newThisWeekData = refreshStats(type: HomeWidgetThisWeekData.self) {
HomeWidgetThisWeekData.write(items: newThisWeekData)
if #available(iOS 14.0, *) {
WidgetCenter.shared.reloadTimelines(ofKind: WPHomeWidgetThisWeekKind)
}
}
}
/// Initialize the local cache for widgets, if it does not exist
func initializeStatsWidgetsIfNeeded() {
guard #available(iOS 14.0, *) else {
return
}
if HomeWidgetTodayData.read() == nil {
DDLogInfo("StatsWidgets: Writing initialization data into HomeWidgetTodayData.plist")
HomeWidgetTodayData.write(items: initializeHomeWidgetData(type: HomeWidgetTodayData.self))
WidgetCenter.shared.reloadTimelines(ofKind: WPHomeWidgetTodayKind)
}
if HomeWidgetThisWeekData.read() == nil {
DDLogInfo("StatsWidgets: Writing initialization data into HomeWidgetThisWeekData.plist")
HomeWidgetThisWeekData.write(items: initializeHomeWidgetData(type: HomeWidgetThisWeekData.self))
WidgetCenter.shared.reloadTimelines(ofKind: WPHomeWidgetThisWeekKind)
}
if HomeWidgetAllTimeData.read() == nil {
DDLogInfo("StatsWidgets: Writing initialization data into HomeWidgetAllTimeData.plist")
HomeWidgetAllTimeData.write(items: initializeHomeWidgetData(type: HomeWidgetAllTimeData.self))
WidgetCenter.shared.reloadTimelines(ofKind: WPHomeWidgetAllTimeKind)
}
}
/// Store stats in the widget cache
/// - Parameters:
/// - widgetType: concrete type of the widget
/// - stats: stats to be stored
func storeHomeWidgetData<T: HomeWidgetData>(widgetType: T.Type, stats: Codable) {
guard #available(iOS 14.0, *),
let siteID = SiteStatsInformation.sharedInstance.siteID else {
return
}
var homeWidgetCache = T.read() ?? initializeHomeWidgetData(type: widgetType)
guard let oldData = homeWidgetCache[siteID.intValue] else {
DDLogError("StatsWidgets: Failed to find a matching site")
return
}
guard let blog = Blog.lookup(withID: siteID, in: ContextManager.shared.mainContext) else {
DDLogError("StatsWidgets: the site does not exist anymore")
// if for any reason that site does not exist anymore, remove it from the cache.
homeWidgetCache.removeValue(forKey: siteID.intValue)
T.write(items: homeWidgetCache)
return
}
var widgetKind = ""
if widgetType == HomeWidgetTodayData.self, let stats = stats as? TodayWidgetStats {
widgetKind = WPHomeWidgetTodayKind
homeWidgetCache[siteID.intValue] = HomeWidgetTodayData(siteID: siteID.intValue,
siteName: blog.title ?? oldData.siteName,
url: blog.url ?? oldData.url,
timeZone: blog.timeZone,
date: Date(),
stats: stats) as? T
} else if widgetType == HomeWidgetAllTimeData.self, let stats = stats as? AllTimeWidgetStats {
widgetKind = WPHomeWidgetAllTimeKind
homeWidgetCache[siteID.intValue] = HomeWidgetAllTimeData(siteID: siteID.intValue,
siteName: blog.title ?? oldData.siteName,
url: blog.url ?? oldData.url,
timeZone: blog.timeZone,
date: Date(),
stats: stats) as? T
} else if widgetType == HomeWidgetThisWeekData.self, let stats = stats as? ThisWeekWidgetStats {
homeWidgetCache[siteID.intValue] = HomeWidgetThisWeekData(siteID: siteID.intValue,
siteName: blog.title ?? oldData.siteName,
url: blog.url ?? oldData.url,
timeZone: blog.timeZone,
date: Date(),
stats: stats) as? T
}
T.write(items: homeWidgetCache)
WidgetCenter.shared.reloadTimelines(ofKind: widgetKind)
}
}
// MARK: - Helper methods
private extension StatsWidgetsStore {
// creates a list of days from the current date with empty stats to avoid showing an empty widget preview
var initializedWeekdays: [ThisWeekWidgetDay] {
var days = [ThisWeekWidgetDay]()
for index in 0...7 {
days.insert(ThisWeekWidgetDay(date: NSCalendar.current.date(byAdding: .day,
value: -index,
to: Date()) ?? Date(),
viewsCount: 0,
dailyChangePercent: 0),
at: index)
}
return days
}
func refreshStats<T: HomeWidgetData>(type: T.Type) -> [Int: T]? {
guard let currentData = T.read() else {
return nil
}
let blogService = BlogService(managedObjectContext: ContextManager.shared.mainContext)
let updatedSiteList = blogService.visibleBlogsForWPComAccounts()
let newData = updatedSiteList.reduce(into: [Int: T]()) { sitesList, site in
guard let blogID = site.dotComID else {
return
}
let existingSite = currentData[blogID.intValue]
let siteURL = site.url ?? existingSite?.url ?? ""
let siteName = (site.title ?? siteURL).isEmpty ? siteURL : site.title ?? siteURL
var timeZone = existingSite?.timeZone ?? TimeZone.current
if let blog = Blog.lookup(withID: blogID, in: ContextManager.shared.mainContext) {
timeZone = blog.timeZone
}
let date = existingSite?.date ?? Date()
if type == HomeWidgetTodayData.self {
let stats = (existingSite as? HomeWidgetTodayData)?.stats ?? TodayWidgetStats()
sitesList[blogID.intValue] = HomeWidgetTodayData(siteID: blogID.intValue,
siteName: siteName,
url: siteURL,
timeZone: timeZone,
date: date,
stats: stats) as? T
} else if type == HomeWidgetAllTimeData.self {
let stats = (existingSite as? HomeWidgetAllTimeData)?.stats ?? AllTimeWidgetStats()
sitesList[blogID.intValue] = HomeWidgetAllTimeData(siteID: blogID.intValue,
siteName: siteName,
url: siteURL,
timeZone: timeZone,
date: date,
stats: stats) as? T
} else if type == HomeWidgetThisWeekData.self {
let stats = (existingSite as? HomeWidgetThisWeekData)?.stats ?? ThisWeekWidgetStats(days: initializedWeekdays)
sitesList[blogID.intValue] = HomeWidgetThisWeekData(siteID: blogID.intValue,
siteName: siteName,
url: siteURL,
timeZone: timeZone,
date: date,
stats: stats) as? T
}
}
return newData
}
func initializeHomeWidgetData<T: HomeWidgetData>(type: T.Type) -> [Int: T] {
let blogService = BlogService(managedObjectContext: ContextManager.shared.mainContext)
return blogService.visibleBlogsForWPComAccounts().reduce(into: [Int: T]()) { result, element in
if let blogID = element.dotComID,
let url = element.url,
let blog = Blog.lookup(withID: blogID, in: ContextManager.shared.mainContext) {
// set the title to the site title, if it's not nil and not empty; otherwise use the site url
let title = (element.title ?? url).isEmpty ? url : element.title ?? url
let timeZone = blog.timeZone
if type == HomeWidgetTodayData.self {
result[blogID.intValue] = HomeWidgetTodayData(siteID: blogID.intValue,
siteName: title,
url: url,
timeZone: timeZone,
date: Date(timeIntervalSinceReferenceDate: 0),
stats: TodayWidgetStats()) as? T
} else if type == HomeWidgetAllTimeData.self {
result[blogID.intValue] = HomeWidgetAllTimeData(siteID: blogID.intValue,
siteName: title,
url: url,
timeZone: timeZone,
date: Date(timeIntervalSinceReferenceDate: 0),
stats: AllTimeWidgetStats()) as? T
} else if type == HomeWidgetThisWeekData.self {
result[blogID.intValue] = HomeWidgetThisWeekData(siteID: blogID.intValue,
siteName: title,
url: url,
timeZone: timeZone,
date: Date(timeIntervalSinceReferenceDate: 0),
stats: ThisWeekWidgetStats(days: initializedWeekdays)) as? T
}
}
}
}
}
// MARK: - Extract this week data
extension StatsWidgetsStore {
func updateThisWeekHomeWidget(summary: StatsSummaryTimeIntervalData?) {
guard #available(iOS 14.0, *) else {
return
}
switch summary?.period {
case .day:
guard summary?.periodEndDate == StatsDataHelper.currentDateForSite().normalizedDate() else {
return
}
let summaryData = Array(summary?.summaryData.reversed().prefix(ThisWeekWidgetStats.maxDaysToDisplay + 1) ?? [])
let stats = ThisWeekWidgetStats(days: ThisWeekWidgetStats.daysFrom(summaryData: summaryData))
StoreContainer.shared.statsWidgets.storeHomeWidgetData(widgetType: HomeWidgetThisWeekData.self, stats: stats)
case .week:
WidgetCenter.shared.reloadTimelines(ofKind: WPHomeWidgetThisWeekKind)
default:
break
}
}
}
// MARK: - Login/Logout notifications
private extension StatsWidgetsStore {
func observeAccountChangesForWidgets() {
guard #available(iOS 14.0, *) else {
return
}
NotificationCenter.default.addObserver(forName: .WPAccountDefaultWordPressComAccountChanged,
object: nil,
queue: nil) { notification in
if !AccountHelper.isLoggedIn {
HomeWidgetTodayData.delete()
HomeWidgetThisWeekData.delete()
HomeWidgetAllTimeData.delete()
}
UserDefaults(suiteName: WPAppGroupName)?.setValue(AccountHelper.isLoggedIn, forKey: WPStatsHomeWidgetsUserDefaultsLoggedInKey)
WidgetCenter.shared.reloadTimelines(ofKind: WPHomeWidgetTodayKind)
WidgetCenter.shared.reloadTimelines(ofKind: WPHomeWidgetThisWeekKind)
WidgetCenter.shared.reloadTimelines(ofKind: WPHomeWidgetAllTimeKind)
}
}
}
extension StatsViewController {
@objc func initializeStatsWidgetsIfNeeded() {
StoreContainer.shared.statsWidgets.initializeStatsWidgetsIfNeeded()
}
}
extension BlogListViewController {
@objc func refreshStatsWidgetsSiteList() {
StoreContainer.shared.statsWidgets.refreshStatsWidgetsSiteList()
}
}
|
e7835e6f76b19c537e41b84515f14e2c
| 46.752475 | 138 | 0.505771 | false | false | false | false |
ashfurrow/FunctionalReactiveAwesome
|
refs/heads/master
|
Demo/Pods/RxSwift/RxSwift/RxSwift/Observables/Implementations/Zip.swift
|
mit
|
2
|
//
// Zip.swift
// RxSwift
//
// Created by Krunoslav Zaher on 5/23/15.
// Copyright (c) 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
protocol ZipSinkProtocol : class
{
func next(index: Int)
func fail(error: ErrorType)
func done(index: Int)
}
protocol ZipObserverProtocol {
var hasElements: Bool { get }
}
class ZipSink<O: ObserverType> : Sink<O>, ZipSinkProtocol {
typealias Element = O.Element
let lock = NSRecursiveLock()
var observers: [ZipObserverProtocol] = []
var isDone: [Bool]
init(arity: Int, observer: O, cancel: Disposable) {
self.isDone = [Bool](count: arity, repeatedValue: false)
super.init(observer: observer, cancel: cancel)
}
func getResult() -> RxResult<Element> {
return abstractMethod()
}
func next(index: Int) {
var hasValueAll = true
for observer in observers {
if !observer.hasElements {
hasValueAll = false;
break;
}
}
if hasValueAll {
_ = getResult().flatMap { result in
trySendNext(self.observer, result)
return SuccessResult
}.recoverWith { e -> RxResult<Void> in
trySendError(self.observer, e)
dispose()
return SuccessResult
}
}
else {
var allOthersDone = true
var arity = self.isDone.count
for var i = 0; i < arity; ++i {
if i != index && !isDone[i] {
allOthersDone = false
break
}
}
if allOthersDone {
trySendCompleted(observer)
self.dispose()
}
}
}
func fail(error: ErrorType) {
trySendError(observer, error)
dispose()
}
func done(index: Int) {
isDone[index] = true
var allDone = true
for done in self.isDone {
if !done {
allDone = false
break
}
}
if allDone {
trySendCompleted(observer)
dispose()
}
}
}
class ZipObserver<ElementType> : ObserverType, ZipObserverProtocol {
typealias Element = ElementType
weak var parent: ZipSinkProtocol?
let lock: NSRecursiveLock
let index: Int
let this: Disposable
var values: Queue<Element> = Queue(capacity: 2)
init(lock: NSRecursiveLock, parent: ZipSinkProtocol, index: Int, this: Disposable) {
self.lock = lock
self.parent = parent
self.index = index
self.this = this
}
var hasElements: Bool {
get {
return values.count > 0
}
}
func on(event: Event<Element>) {
if let parent = parent {
switch event {
case .Next(let boxedValue):
break
case .Error(let error):
this.dispose()
case .Completed:
this.dispose()
}
}
lock.performLocked {
if let parent = parent {
switch event {
case .Next(let boxedValue):
values.enqueue(boxedValue.value)
parent.next(index)
case .Error(let error):
parent.fail(error)
case .Completed:
parent.done(index)
}
}
}
}
}
|
e7801a8c2c211d5507398ccd098d0835
| 22.986928 | 88 | 0.485286 | false | false | false | false |
rudkx/swift
|
refs/heads/main
|
test/Generics/sr14510.swift
|
apache-2.0
|
1
|
// RUN: %target-typecheck-verify-swift -requirement-machine-protocol-signatures=off
// RUN: %target-swift-frontend -debug-generic-signatures -typecheck %s -requirement-machine-protocol-signatures=on 2>&1 | %FileCheck %s
// CHECK-LABEL: Requirement signature: <Self where Self == Self.[Adjoint]Dual.[Adjoint]Dual, Self.[Adjoint]Dual : Adjoint>
public protocol Adjoint {
associatedtype Dual: Adjoint where Self.Dual.Dual == Self
}
// CHECK-LABEL: Requirement signature: <Self>
public protocol Diffable {
associatedtype Patch
}
// CHECK-LABEL: Requirement signature: <Self where Self : Adjoint, Self : Diffable, Self.[Adjoint]Dual : AdjointDiffable, Self.[Diffable]Patch : Adjoint, Self.[Adjoint]Dual.[Diffable]Patch == Self.[Diffable]Patch.[Adjoint]Dual>
public protocol AdjointDiffable: Adjoint & Diffable
where Self.Patch: Adjoint, Self.Dual: AdjointDiffable,
Self.Patch.Dual == Self.Dual.Patch {
}
// This is another example used to hit the same problem. Any one of the three
// conformance requirements 'A : P', 'B : P' or 'C : P' can be dropped and
// proven from the other two, but dropping two or more conformance requirements
// leaves us with an invalid signature.
// CHECK-LABEL: Requirement signature: <Self where Self.[P]A : P, Self.[P]A == Self.[P]B.[P]C, Self.[P]B : P, Self.[P]B == Self.[P]A.[P]C, Self.[P]C == Self.[P]A.[P]B>
protocol P {
associatedtype A : P where A == B.C
associatedtype B : P where B == A.C
// expected-note@-1 {{conformance constraint 'Self.C' : 'P' implied here}}
associatedtype C : P where C == A.B
// expected-warning@-1 {{redundant conformance constraint 'Self.C' : 'P'}}
}
|
558e63166ac237a080d40940d36b5b46
| 50.1875 | 227 | 0.713675 | false | false | false | false |
BasThomas/MacOSX
|
refs/heads/master
|
RaiseMan/RaiseKit/Employee.swift
|
mit
|
1
|
//
// Employee.swift
// RaiseMan
//
// Created by Bas Broek on 01/05/15.
// Copyright (c) 2015 Bas Broek. All rights reserved.
//
import Foundation
public class Employee: NSObject, NSCoding
{
public var name: String? = "New Employee"
public var raise: Float = 0.05
override public init()
{
super.init()
}
required public init(coder aDecoder: NSCoder)
{
self.name = aDecoder.decodeObjectForKey("name") as! String?
self.raise = aDecoder.decodeFloatForKey("raise")
super.init()
}
// MARK: - NSCoding
public func encodeWithCoder(aCoder: NSCoder)
{
if let name = self.name
{
aCoder.encodeObject(name, forKey: "name")
}
aCoder.encodeFloat(self.raise, forKey: "raise")
}
public func validateRaise(raiseNumberPointer: AutoreleasingUnsafeMutablePointer<NSNumber?>, error outError: NSErrorPointer) -> Bool
{
let raiseNumber = raiseNumberPointer.memory
if raiseNumber == nil
{
let domain = "UserInputValidationErrorDomain"
let code = 0
let userInfo = [NSLocalizedDescriptionKey: "An employee's raise must be a number."]
outError.memory = NSError(domain: domain, code: code, userInfo: userInfo)
return false
}
return true
}
}
|
10b166ade4e8cb256543edf0cf1d1059
| 24.517857 | 135 | 0.588235 | false | false | false | false |
lvogelzang/Blocky
|
refs/heads/master
|
Blocky/Levels/Level72.swift
|
mit
|
1
|
//
// Level72.swift
// Blocky
//
// Created by Lodewijck Vogelzang on 07-12-18
// Copyright (c) 2018 Lodewijck Vogelzang. All rights reserved.
//
import UIKit
final class Level72: Level {
let levelNumber = 72
var tiles = [[0, 1, 0, 1, 0], [1, 1, 1, 1, 1], [0, 1, 0, 1, 0], [0, 1, 0, 1, 0]]
let cameraFollowsBlock = false
let blocky: Blocky
let enemies: [Enemy]
let foods: [Food]
init() {
blocky = Blocky(startLocation: (0, 1), endLocation: (4, 1))
let pattern0 = [("S", 0.5), ("S", 0.5), ("S", 0.5), ("N", 0.5), ("N", 0.5), ("N", 0.5)]
let enemy0 = Enemy(enemyNumber: 0, startLocation: (1, 3), animationPattern: pattern0)
let pattern1 = [("S", 0.5), ("S", 0.5), ("S", 0.5), ("N", 0.5), ("N", 0.5), ("N", 0.5)]
let enemy1 = Enemy(enemyNumber: 1, startLocation: (3, 3), animationPattern: pattern1)
enemies = [enemy0, enemy1]
foods = []
}
}
|
7c29e766abc322f82cf813eb4763351c
| 24.794118 | 89 | 0.573546 | false | false | false | false |
nheagy/WordPress-iOS
|
refs/heads/develop
|
WordPress/Classes/Extensions/Notifications/Notification+Interface.swift
|
gpl-2.0
|
1
|
import Foundation
extension Notification
{
// MARK: - Helper Grouping Methods
public func sectionIdentifier() -> String {
// Normalize Dates: Time must not be considered. Just the raw dates
let fromDate = timestampAsDate.normalizedDate()
let toDate = NSDate().normalizedDate()
// Analyze the Delta-Components
let calendar = NSCalendar.currentCalendar()
let flags: NSCalendarUnit = [.Day, .WeekOfYear, .Month]
let components = calendar.components(flags, fromDate: fromDate, toDate: toDate, options: .MatchFirst)
var identifier: Int
// Months
if components.month >= 1 {
identifier = Sections.Months
// Weeks
} else if components.weekOfYear >= 1 {
identifier = Sections.Weeks
// Days
} else if components.day > 1 {
identifier = Sections.Days
} else if components.day == 1 {
identifier = Sections.Yesterday
} else {
identifier = Sections.Today
}
return String(format: "%d", identifier)
}
public class func descriptionForSectionIdentifier(identifier: String) -> String {
guard let kind = Int(identifier) else {
return String()
}
switch kind {
case Sections.Months:
return NSLocalizedString("Older than a Month", comment: "Notifications Months Section Header")
case Sections.Weeks:
return NSLocalizedString("Older than a Week", comment: "Notifications Weeks Section Header")
case Sections.Days:
return NSLocalizedString("Older than 2 days", comment: "Notifications +2 Days Section Header")
case Sections.Yesterday:
return NSLocalizedString("Yesterday", comment: "Notifications Yesterday Section Header")
default:
return NSLocalizedString("Today", comment: "Notifications Today Section Header")
}
}
// FIXME: Turn this into an enum, when llvm is fixed
private struct Sections
{
static let Months = 0
static let Weeks = 2
static let Days = 4
static let Yesterday = 5
static let Today = 6
}
}
|
a3ede070f2d5620617c6b6ba9f18b1b1
| 34.835821 | 122 | 0.570179 | false | false | false | false |
vanyaland/Popular-Movies
|
refs/heads/master
|
iOS/PopularMovies/Network/Network/Webservice.swift
|
mit
|
1
|
//
// Webservice.swift
// Videos
//
// Created by Florian on 13/04/16.
// Copyright © 2016 Chris Eidhof. All rights reserved.
//
import UIKit
public typealias JSONDictionary = [String: Any]
// We create our own session here without a URLCache to avoid playground error messages
private var session: URLSession {
let config = URLSessionConfiguration.default
config.urlCache = nil
return URLSession(configuration: config)
}
public final class Webservice {
public var authenticationToken: String?
public init() { }
/// Loads a resource. The completion handler is always called on the main queue.
public func load<A>(_ resource: Resource<A>, completion: @escaping (Result<A>) -> () = logError) {
session.dataTask(with: resource.url, completionHandler: { data, response, _ in
let result: Result<A>
if let httpResponse = response as? HTTPURLResponse , httpResponse.statusCode == 401 {
result = Result.error(WebserviceError.notAuthenticated)
} else {
let parsed = data.flatMap(resource.parse)
result = Result(parsed, or: WebserviceError.other)
}
DispatchQueue.main.async { completion(result) }
}) .resume()
}
}
|
dab4c78c7277325180352360b837165b
| 33.405405 | 102 | 0.655145 | false | true | false | false |
emersonbroga/LocationSwift
|
refs/heads/master
|
LocationSwift/BackgroundTaskManager.swift
|
mit
|
1
|
//
// BackgroundTaskManager.swift
// LocationSwift
//
// Created by Emerson Carvalho on 5/21/15.
// Copyright (c) 2015 Emerson Carvalho. All rights reserved.
//
import Foundation
import UIKit
class BackgroundTaskManager : NSObject {
var bgTaskIdList : NSMutableArray?
var masterTaskId : UIBackgroundTaskIdentifier?
override init() {
super.init()
self.bgTaskIdList = NSMutableArray()
self.masterTaskId = UIBackgroundTaskInvalid
}
class func sharedBackgroundTaskManager() -> BackgroundTaskManager? {
struct Static {
static var sharedBGTaskManager : BackgroundTaskManager?
static var onceToken : dispatch_once_t = 0
}
dispatch_once(&Static.onceToken) {
Static.sharedBGTaskManager = BackgroundTaskManager()
}
return Static.sharedBGTaskManager
}
func beginNewBackgroundTask() -> UIBackgroundTaskIdentifier? {
var application : UIApplication = UIApplication.sharedApplication()
var bgTaskId : UIBackgroundTaskIdentifier = UIBackgroundTaskInvalid
bgTaskId = application.beginBackgroundTaskWithExpirationHandler({
print("background task \(bgTaskId as Int) expired\n")
})
if self.masterTaskId == UIBackgroundTaskInvalid {
self.masterTaskId = bgTaskId
print("started master task \(self.masterTaskId)\n")
} else {
// add this ID to our list
print("started background task \(bgTaskId as Int)\n")
self.bgTaskIdList!.addObject(bgTaskId)
//self.endBackgr
}
return bgTaskId
}
func endBackgroundTask(){
self.drainBGTaskList(false)
}
func endAllBackgroundTasks() {
self.drainBGTaskList(true)
}
func drainBGTaskList(all:Bool) {
//mark end of each of our background task
var application: UIApplication = UIApplication.sharedApplication()
let endBackgroundTask : Selector = "endBackgroundTask"
var count: Int = self.bgTaskIdList!.count
for (var i = (all==true ? 0:1); i<count; i++) {
var bgTaskId : UIBackgroundTaskIdentifier = self.bgTaskIdList!.objectAtIndex(0) as! Int
print("ending background task with id \(bgTaskId as Int)\n")
application.endBackgroundTask(bgTaskId)
self.bgTaskIdList!.removeObjectAtIndex(0)
}
if self.bgTaskIdList!.count > 0 {
print("kept background task id \(self.bgTaskIdList!.objectAtIndex(0))\n")
}
if all == true {
print("no more background tasks running\n")
application.endBackgroundTask(self.masterTaskId!)
self.masterTaskId = UIBackgroundTaskInvalid
} else {
print("kept master background task id \(self.masterTaskId)\n")
}
}
}
|
87ad591ce5db5e8906a1e546b55ece11
| 30.416667 | 99 | 0.610282 | false | false | false | false |
huonw/swift
|
refs/heads/master
|
stdlib/public/core/StringUnicodeScalarView.swift
|
apache-2.0
|
1
|
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
extension String {
/// A view of a string's contents as a collection of Unicode scalar values.
///
/// You can access a string's view of Unicode scalar values by using its
/// `unicodeScalars` property. Unicode scalar values are the 21-bit codes
/// that are the basic unit of Unicode. Each scalar value is represented by
/// a `Unicode.Scalar` instance and is equivalent to a UTF-32 code unit.
///
/// let flowers = "Flowers 💐"
/// for v in flowers.unicodeScalars {
/// print(v.value)
/// }
/// // 70
/// // 108
/// // 111
/// // 119
/// // 101
/// // 114
/// // 115
/// // 32
/// // 128144
///
/// Some characters that are visible in a string are made up of more than one
/// Unicode scalar value. In that case, a string's `unicodeScalars` view
/// contains more elements than the string itself.
///
/// let flag = "🇵🇷"
/// for c in flag {
/// print(c)
/// }
/// // 🇵🇷
///
/// for v in flag.unicodeScalars {
/// print(v.value)
/// }
/// // 127477
/// // 127479
///
/// You can convert a `String.UnicodeScalarView` instance back into a string
/// using the `String` type's `init(_:)` initializer.
///
/// let favemoji = "My favorite emoji is 🎉"
/// if let i = favemoji.unicodeScalars.firstIndex(where: { $0.value >= 128 }) {
/// let asciiPrefix = String(favemoji.unicodeScalars[..<i])
/// print(asciiPrefix)
/// }
/// // Prints "My favorite emoji is "
@_fixed_layout // FIXME(sil-serialize-all)
public struct UnicodeScalarView :
BidirectionalCollection,
CustomStringConvertible,
CustomDebugStringConvertible
{
@usableFromInline
internal var _guts: _StringGuts
/// The offset of this view's `_guts` from the start of an original string,
/// in UTF-16 code units. This is here to support legacy Swift 3-style
/// slicing where `s.unicodeScalars[i..<j]` produces a
/// `String.UnicodeScalarView`. The offset should be subtracted from the
/// `encodedOffset` of view indices before it is passed to `_guts`.
///
/// Note: This should be removed when Swift 3 semantics are no longer
/// supported.
@usableFromInline // FIXME(sil-serialize-all)
internal var _coreOffset: Int
@inlinable // FIXME(sil-serialize-all)
internal init(_ _guts: _StringGuts, coreOffset: Int = 0) {
self._guts = _guts
self._coreOffset = coreOffset
}
public typealias Index = String.Index
/// Translates a `_guts` index into a `UnicodeScalarIndex` using this
/// view's `_coreOffset`.
@inlinable // FIXME(sil-serialize-all)
internal func _fromCoreIndex(_ i: Int) -> Index {
return Index(encodedOffset: i + _coreOffset)
}
/// Translates a `UnicodeScalarIndex` into a `_guts` index using this
/// view's `_coreOffset`.
@inlinable // FIXME(sil-serialize-all)
internal func _toCoreIndex(_ i: Index) -> Int {
return i.encodedOffset - _coreOffset
}
/// The position of the first Unicode scalar value if the string is
/// nonempty.
///
/// If the string is empty, `startIndex` is equal to `endIndex`.
@inlinable // FIXME(sil-serialize-all)
public var startIndex: Index {
return _fromCoreIndex(_guts.startIndex)
}
/// The "past the end" position---that is, the position one greater than
/// the last valid subscript argument.
///
/// In an empty Unicode scalars view, `endIndex` is equal to `startIndex`.
@inlinable // FIXME(sil-serialize-all)
public var endIndex: Index {
return _fromCoreIndex(_guts.endIndex)
}
/// Returns the next consecutive location after `i`.
///
/// - Precondition: The next location exists.
@inlinable // FIXME(sil-serialize-all)
public func index(after i: Index) -> Index {
let offset = _toCoreIndex(i)
let length: Int = _visitGuts(_guts, args: offset,
ascii: { _ -> Int in return 1 },
utf16: { utf16, offset in
return utf16.unicodeScalarWidth(startingAt: offset) },
opaque: { opaque, offset in
return opaque.unicodeScalarWidth(startingAt: offset) }
)
return _fromCoreIndex(offset + length)
}
/// Returns the previous consecutive location before `i`.
///
/// - Precondition: The previous location exists.
@inlinable // FIXME(sil-serialize-all)
public func index(before i: Index) -> Index {
let offset = _toCoreIndex(i)
let length: Int = _visitGuts(_guts, args: offset,
ascii: { _ -> Int in return 1 },
utf16: { utf16, offset in
return utf16.unicodeScalarWidth(endingAt: offset) },
opaque: { opaque, offset in
return opaque.unicodeScalarWidth(endingAt: offset) }
)
return _fromCoreIndex(offset - length)
}
/// Accesses the Unicode scalar value at the given position.
///
/// The following example searches a string's Unicode scalars view for a
/// capital letter and then prints the character and Unicode scalar value
/// at the found index:
///
/// let greeting = "Hello, friend!"
/// if let i = greeting.unicodeScalars.firstIndex(where: { "A"..."Z" ~= $0 }) {
/// print("First capital letter: \(greeting.unicodeScalars[i])")
/// print("Unicode scalar value: \(greeting.unicodeScalars[i].value)")
/// }
/// // Prints "First capital letter: H"
/// // Prints "Unicode scalar value: 72"
///
/// - Parameter position: A valid index of the character view. `position`
/// must be less than the view's end index.
@inlinable // FIXME(sil-serialize-all)
public subscript(position: Index) -> Unicode.Scalar {
let offset = position.encodedOffset
return _guts.unicodeScalar(startingAt: offset)
}
/// An iterator over the Unicode scalars that make up a `UnicodeScalarView`
/// collection.
@_fixed_layout // FIXME(sil-serialize-all)
public struct Iterator : IteratorProtocol {
@usableFromInline // FIXME(sil-serialize-all)
internal var _guts: _StringGuts
// FIXME(TODO: JIRA): the below is absurdly wasteful.
// UnicodeScalarView.Iterator should be able to be passed in-registers.
@usableFromInline // FIXME(sil-serialize-all)
internal var _asciiIterator: _UnmanagedASCIIString.UnicodeScalarIterator?
@usableFromInline // FIXME(sil-serialize-all)
internal var _utf16Iterator: _UnmanagedUTF16String.UnicodeScalarIterator?
@usableFromInline // FIXME(sil-serialize-all)
internal var _opaqueIterator: _UnmanagedOpaqueString.UnicodeScalarIterator?
@usableFromInline
internal var _smallIterator: _SmallUTF8String.UnicodeScalarIterator?
@inlinable // FIXME(sil-serialize-all)
internal init(_ guts: _StringGuts) {
if _slowPath(guts._isOpaque) {
self.init(_opaque: guts)
return
}
self.init(_concrete: guts)
}
@inlinable // FIXME(sil-serialize-all)
@inline(__always)
internal init(_concrete guts: _StringGuts) {
_sanityCheck(!guts._isOpaque)
self._guts = guts
defer { _fixLifetime(self) }
if _guts.isASCII {
self._asciiIterator =
_guts._unmanagedASCIIView.makeUnicodeScalarIterator()
} else {
self._utf16Iterator =
_guts._unmanagedUTF16View.makeUnicodeScalarIterator()
}
}
@usableFromInline // @opaque
init(_opaque _guts: _StringGuts) {
_sanityCheck(_guts._isOpaque)
defer { _fixLifetime(self) }
self._guts = _guts
// TODO: Replace the whole iterator scheme with a sensible solution.
if self._guts._isSmall {
self._smallIterator =
_guts._smallUTF8String.makeUnicodeScalarIterator()
} else {
self._opaqueIterator = _guts._asOpaque().makeUnicodeScalarIterator()
}
}
/// Advances to the next element and returns it, or `nil` if no next
/// element exists.
///
/// Once `nil` has been returned, all subsequent calls return `nil`.
///
/// - Precondition: `next()` has not been applied to a copy of `self`
/// since the copy was made.
@inlinable // FIXME(sil-serialize-all)
public mutating func next() -> Unicode.Scalar? {
if _slowPath(_opaqueIterator != nil) {
return _opaqueIterator!.next()
}
if _asciiIterator != nil {
return _asciiIterator!.next()
}
if _guts._isSmall {
return _smallIterator!.next()
}
return _utf16Iterator!.next()
}
}
/// Returns an iterator over the Unicode scalars that make up this view.
///
/// - Returns: An iterator over this collection's `Unicode.Scalar` elements.
@inlinable // FIXME(sil-serialize-all)
public func makeIterator() -> Iterator {
return Iterator(_guts)
}
@inlinable // FIXME(sil-serialize-all)
public var description: String {
return String(_guts)
}
public var debugDescription: String {
return "StringUnicodeScalarView(\(self.description.debugDescription))"
}
}
/// Creates a string corresponding to the given collection of Unicode
/// scalars.
///
/// You can use this initializer to create a new string from a slice of
/// another string's `unicodeScalars` view.
///
/// let picnicGuest = "Deserving porcupine"
/// if let i = picnicGuest.unicodeScalars.firstIndex(of: " ") {
/// let adjective = String(picnicGuest.unicodeScalars[..<i])
/// print(adjective)
/// }
/// // Prints "Deserving"
///
/// The `adjective` constant is created by calling this initializer with a
/// slice of the `picnicGuest.unicodeScalars` view.
///
/// - Parameter unicodeScalars: A collection of Unicode scalar values.
@inlinable // FIXME(sil-serialize-all)
public init(_ unicodeScalars: UnicodeScalarView) {
self.init(unicodeScalars._guts)
}
/// The index type for a string's `unicodeScalars` view.
public typealias UnicodeScalarIndex = UnicodeScalarView.Index
}
extension _StringGuts {
@inlinable
internal func unicodeScalar(startingAt offset: Int) -> Unicode.Scalar {
return _visitGuts(self, args: offset,
ascii: { ascii, offset in
let u = ascii.codeUnit(atCheckedOffset: offset)
return Unicode.Scalar(_unchecked: UInt32(u)) },
utf16: { utf16, offset in
return utf16.unicodeScalar(startingAt: offset) },
opaque: { opaque, offset in
return opaque.unicodeScalar(startingAt: offset) })
}
@inlinable
internal func unicodeScalar(endingAt offset: Int) -> Unicode.Scalar {
return _visitGuts(self, args: offset,
ascii: { ascii, offset in
let u = ascii.codeUnit(atCheckedOffset: offset &- 1)
return Unicode.Scalar(_unchecked: UInt32(u)) },
utf16: { utf16, offset in
return utf16.unicodeScalar(endingAt: offset) },
opaque: { opaque, offset in
return opaque.unicodeScalar(endingAt: offset) })
}
}
extension String.UnicodeScalarView : _SwiftStringView {
@inlinable // FIXME(sil-serialize-all)
internal var _persistentContent : String { return String(_guts) }
@inlinable // FIXME(sil-serialize-all)
var _wholeString : String {
return String(_guts)
}
@inlinable // FIXME(sil-serialize-all)
var _encodedOffsetRange : Range<Int> {
return 0..<_guts.count
}
}
extension String {
/// The string's value represented as a collection of Unicode scalar values.
@inlinable // FIXME(sil-serialize-all)
public var unicodeScalars: UnicodeScalarView {
get {
return UnicodeScalarView(_guts)
}
set {
_guts = newValue._guts
}
}
}
extension String.UnicodeScalarView : RangeReplaceableCollection {
/// Creates an empty view instance.
@inlinable // FIXME(sil-serialize-all)
public init() {
self = String.UnicodeScalarView(_StringGuts())
}
/// Reserves enough space in the view's underlying storage to store the
/// specified number of ASCII characters.
///
/// Because a Unicode scalar value can require more than a single ASCII
/// character's worth of storage, additional allocation may be necessary
/// when adding to a Unicode scalar view after a call to
/// `reserveCapacity(_:)`.
///
/// - Parameter n: The minimum number of ASCII character's worth of storage
/// to allocate.
///
/// - Complexity: O(*n*), where *n* is the capacity being reserved.
public mutating func reserveCapacity(_ n: Int) {
_guts.reserveCapacity(n)
}
/// Appends the given Unicode scalar to the view.
///
/// - Parameter c: The character to append to the string.
public mutating func append(_ c: Unicode.Scalar) {
if _fastPath(_guts.isASCII && c.value <= 0x7f) {
_guts.withMutableASCIIStorage(unusedCapacity: 1) { storage in
unowned(unsafe) let s = storage._value
s.end.pointee = UInt8(c.value)
s.count += 1
}
} else {
let width = UTF16.width(c)
_guts.withMutableUTF16Storage(unusedCapacity: width) { storage in
unowned(unsafe) let s = storage._value
_sanityCheck(s.count + width <= s.capacity)
if _fastPath(width == 1) {
s.end.pointee = UTF16.CodeUnit(c.value)
} else {
_sanityCheck(width == 2)
s.end[0] = UTF16.leadSurrogate(c)
s.end[1] = UTF16.trailSurrogate(c)
}
s.count += width
}
}
}
/// Appends the Unicode scalar values in the given sequence to the view.
///
/// - Parameter newElements: A sequence of Unicode scalar values.
///
/// - Complexity: O(*n*), where *n* is the length of the resulting view.
public mutating func append<S : Sequence>(contentsOf newElements: S)
where S.Element == Unicode.Scalar {
// FIXME: Keep ASCII storage if possible
_guts.reserveUnusedCapacity(newElements.underestimatedCount)
var it = newElements.makeIterator()
var next = it.next()
while let n = next {
_guts.withMutableUTF16Storage(unusedCapacity: UTF16.width(n)) { storage in
var p = storage._value.end
let limit = storage._value.capacityEnd
while let n = next {
let w = UTF16.width(n)
guard p + w <= limit else { break }
if w == 1 {
p.pointee = UTF16.CodeUnit(n.value)
} else {
_sanityCheck(w == 2)
p[0] = UTF16.leadSurrogate(n)
p[1] = UTF16.trailSurrogate(n)
}
p += w
next = it.next()
}
storage._value.count = p - storage._value.start
}
}
}
/// Replaces the elements within the specified bounds with the given Unicode
/// scalar values.
///
/// Calling this method invalidates any existing indices for use with this
/// string.
///
/// - Parameters:
/// - bounds: The range of elements to replace. The bounds of the range
/// must be valid indices of the view.
/// - newElements: The new Unicode scalar values to add to the string.
///
/// - Complexity: O(*m*), where *m* is the combined length of the view and
/// `newElements`. If the call to `replaceSubrange(_:with:)` simply
/// removes elements at the end of the string, the complexity is O(*n*),
/// where *n* is equal to `bounds.count`.
public mutating func replaceSubrange<C>(
_ bounds: Range<Index>,
with newElements: C
) where C : Collection, C.Element == Unicode.Scalar {
let rawSubRange: Range<Int> = _toCoreIndex(bounds.lowerBound) ..<
_toCoreIndex(bounds.upperBound)
let lazyUTF16 = newElements.lazy.flatMap { $0.utf16 }
_guts.replaceSubrange(rawSubRange, with: lazyUTF16)
}
}
// Index conversions
extension String.UnicodeScalarIndex {
/// Creates an index in the given Unicode scalars view that corresponds
/// exactly to the specified `UTF16View` position.
///
/// The following example finds the position of a space in a string's `utf16`
/// view and then converts that position to an index in the string's
/// `unicodeScalars` view:
///
/// let cafe = "Café 🍵"
///
/// let utf16Index = cafe.utf16.firstIndex(of: 32)!
/// let scalarIndex = String.Index(utf16Index, within: cafe.unicodeScalars)!
///
/// print(String(cafe.unicodeScalars[..<scalarIndex]))
/// // Prints "Café"
///
/// If the index passed as `sourcePosition` doesn't have an exact
/// corresponding position in `unicodeScalars`, the result of the
/// initializer is `nil`. For example, an attempt to convert the position of
/// the trailing surrogate of a UTF-16 surrogate pair results in `nil`.
///
/// - Parameters:
/// - sourcePosition: A position in the `utf16` view of a string. `utf16Index`
/// must be an element of `String(unicodeScalars).utf16.indices`.
/// - unicodeScalars: The `UnicodeScalarView` in which to find the new
/// position.
@inlinable // FIXME(sil-serialize-all)
public init?(
_ sourcePosition: String.UTF16Index,
within unicodeScalars: String.UnicodeScalarView
) {
if !unicodeScalars._isOnUnicodeScalarBoundary(sourcePosition) { return nil }
self = sourcePosition
}
/// Returns the position in the given string that corresponds exactly to this
/// index.
///
/// This example first finds the position of a space (UTF-8 code point `32`)
/// in a string's `utf8` view and then uses this method find the same position
/// in the string.
///
/// let cafe = "Café 🍵"
/// let i = cafe.unicodeScalars.firstIndex(of: "🍵")
/// let j = i.samePosition(in: cafe)!
/// print(cafe[j...])
/// // Prints "🍵"
///
/// - Parameter characters: The string to use for the index conversion.
/// This index must be a valid index of at least one view of `characters`.
/// - Returns: The position in `characters` that corresponds exactly to
/// this index. If this index does not have an exact corresponding
/// position in `characters`, this method returns `nil`. For example,
/// an attempt to convert the position of a UTF-8 continuation byte
/// returns `nil`.
@inlinable // FIXME(sil-serialize-all)
public func samePosition(in characters: String) -> String.Index? {
return String.Index(self, within: characters)
}
}
extension String.UnicodeScalarView {
@inlinable // FIXME(sil-serialize-all)
internal func _isOnUnicodeScalarBoundary(_ i: Index) -> Bool {
if _fastPath(_guts.isASCII) { return true }
if i == startIndex || i == endIndex {
return true
}
if i.transcodedOffset != 0 { return false }
let i2 = _toCoreIndex(i)
if _fastPath(!UTF16.isTrailSurrogate(_guts[i2])) { return true }
return i2 == 0 || !UTF16.isLeadSurrogate(_guts[i2 &- 1])
}
// NOTE: Don't make this function inlineable. Grapheme cluster
// segmentation uses a completely different algorithm in Unicode 9.0.
@inlinable // FIXME(sil-serialize-all)
internal func _isOnGraphemeClusterBoundary(_ i: Index) -> Bool {
if i == startIndex || i == endIndex {
return true
}
if !_isOnUnicodeScalarBoundary(i) { return false }
let str = String(_guts)
return i == str.index(before: str.index(after: i))
}
}
// Reflection
extension String.UnicodeScalarView : CustomReflectable {
/// Returns a mirror that reflects the Unicode scalars view of a string.
@inlinable // FIXME(sil-serialize-all)
public var customMirror: Mirror {
return Mirror(self, unlabeledChildren: self)
}
}
extension String.UnicodeScalarView : CustomPlaygroundQuickLookable {
@inlinable // FIXME(sil-serialize-all)
@available(*, deprecated, message: "UnicodeScalarView.customPlaygroundQuickLook will be removed in a future Swift version")
public var customPlaygroundQuickLook: PlaygroundQuickLook {
return .text(description)
}
}
// backward compatibility for index interchange.
extension String.UnicodeScalarView {
@inlinable // FIXME(sil-serialize-all)
@available(
swift, obsoleted: 4.0,
message: "Any String view index conversion can fail in Swift 4; please unwrap the optional index")
public func index(after i: Index?) -> Index {
return index(after: i!)
}
@inlinable // FIXME(sil-serialize-all)
@available(
swift, obsoleted: 4.0,
message: "Any String view index conversion can fail in Swift 4; please unwrap the optional index")
public func index(_ i: Index?, offsetBy n: Int) -> Index {
return index(i!, offsetBy: n)
}
@inlinable // FIXME(sil-serialize-all)
@available(
swift, obsoleted: 4.0,
message: "Any String view index conversion can fail in Swift 4; please unwrap the optional indices")
public func distance(from i: Index?, to j: Index?) -> Int {
return distance(from: i!, to: j!)
}
@inlinable // FIXME(sil-serialize-all)
@available(
swift, obsoleted: 4.0,
message: "Any String view index conversion can fail in Swift 4; please unwrap the optional index")
public subscript(i: Index?) -> Unicode.Scalar {
return self[i!]
}
}
//===--- Slicing Support --------------------------------------------------===//
/// In Swift 3.2, in the absence of type context,
///
/// someString.unicodeScalars[
/// someString.unicodeScalars.startIndex
/// ..< someString.unicodeScalars.endIndex]
///
/// was deduced to be of type `String.UnicodeScalarView`. Provide a
/// more-specific Swift-3-only `subscript` overload that continues to produce
/// `String.UnicodeScalarView`.
extension String.UnicodeScalarView {
public typealias SubSequence = Substring.UnicodeScalarView
@inlinable // FIXME(sil-serialize-all)
@available(swift, introduced: 4)
public subscript(r: Range<Index>) -> String.UnicodeScalarView.SubSequence {
return String.UnicodeScalarView.SubSequence(self, _bounds: r)
}
/// Accesses the Unicode scalar values in the given range.
///
/// The example below uses this subscript to access the scalar values up
/// to, but not including, the first comma (`","`) in the string.
///
/// let str = "All this happened, more or less."
/// let i = str.unicodeScalars.firstIndex(of: ",")!
/// let substring = str.unicodeScalars[str.unicodeScalars.startIndex ..< i]
/// print(String(substring))
/// // Prints "All this happened"
///
/// - Complexity: O(*n*) if the underlying string is bridged from
/// Objective-C, where *n* is the length of the string; otherwise, O(1).
@available(swift, obsoleted: 4)
public subscript(r: Range<Index>) -> String.UnicodeScalarView {
let rawSubRange: Range<Int> =
_toCoreIndex(r.lowerBound)..<_toCoreIndex(r.upperBound)
return String.UnicodeScalarView(
_guts._extractSlice(rawSubRange),
coreOffset: r.lowerBound.encodedOffset)
}
@inlinable // FIXME(sil-serialize-all)
@available(swift, obsoleted: 4)
public subscript(bounds: ClosedRange<Index>) -> String.UnicodeScalarView {
return self[bounds.relative(to: self)]
}
}
|
d4ce756eb46e78d9b8a43865de2bd03b
| 35.757764 | 125 | 0.639067 | false | false | false | false |
wayfindrltd/wayfindr-demo-ios
|
refs/heads/master
|
Common Tests/ConvenienceFunctions.swift
|
mit
|
1
|
//
// ConvenienceFunctions.swift
// Wayfindr Demo
//
// Created by Wayfindr on 02/12/2015.
// Copyright (c) 2016 Wayfindr (http://www.wayfindr.net)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is furnished
// to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
import Foundation
import AEXML
import SwiftyJSON
@testable import Wayfindr_Demo
func testVenue() -> WAYVenue? {
let graphFileName = "TestData"
let graphFileType = "graphml"
let venueFileName = "TestVenue"
let venueFileType = "json"
if let venueFilePath = Bundle(for: BeaconsInRangeViewController_Tests.self).path(forResource: venueFileName, ofType: venueFileType),
let graphFilePath = Bundle(for: BeaconsInRangeViewController_Tests.self).path(forResource: graphFileName, ofType: graphFileType) {
do {
let venue = try WAYVenue(venueFilePath: venueFilePath, graphFilePath: graphFilePath)
return venue
} catch {
return nil
}
}
return nil
}
|
e8df8ba83fc2c59c78ad320b0fd7d3e7
| 37.055556 | 138 | 0.700243 | false | true | false | false |
zenjoy/dotfiles
|
refs/heads/master
|
raycast/quit-app.swift
|
mit
|
2
|
#!/usr/bin/swift
// Required parameters:
// @raycast.schemaVersion 1
// @raycast.title Quit app
// @raycast.mode silent
// @raycast.packageName System
// Optional parameters:
// @raycast.icon 💥
// @raycast.argument1 { "type": "text", "placeholder": "Name or pid" }
// Documentation:
// @raycast.description Quits an app, by name or process id.
// @raycast.author Roland Leth
// @raycast.authorURL https://runtimesharks.com
import AppKit
let argument = Array(CommandLine.arguments.dropFirst()).first!
let runningApps = NSWorkspace.shared.runningApplications
if let processId = Int(argument) {
runningApps
.first { $0.processIdentifier == processId }
.map {
$0.terminate()
print("Quit \($0.localizedName ?? "\(processId)")")
exit(0)
}
print("No apps with process id \(processId)")
exit(1)
}
let apps = runningApps.filter {
$0.localizedName?.localizedCaseInsensitiveContains(argument) == true
}
if apps.isEmpty {
print("No apps with name \(argument)")
exit(1)
}
apps.first.map {
// If there's just one match, quit it and exit.
guard apps.count == 1 else { return }
$0.terminate()
print("Quit \($0.localizedName ?? argument)")
exit(0)
}
runningApps
.first { $0.localizedName?.localizedCaseInsensitiveCompare(argument) == .orderedSame }
.map {
// If an exact match exists, quit that and exit, even if there are several results.
$0.terminate()
print("Quit \($0.localizedName ?? argument)")
exit(0)
}
let names = apps
.compactMap { $0.localizedName }
.joined(separator: ", ")
if names.isEmpty {
// Just in case `localizedName` were all `nil`, which shouldn't really happen.
print("Multiple apps found")
} else {
print("Multiple apps found: \(names)")
}
|
007cb1830cb60766e67ea619ae307275
| 21.733333 | 87 | 0.692082 | false | false | false | false |
danholmes/point-of-sale-backend
|
refs/heads/master
|
Sources/App/Models/OrderedModifier.swift
|
mit
|
1
|
//
// OrderedModifier.swift
// POSBackendExample
//
// Created by Dan on 2017-04-01.
//
//
import Foundation
import Vapor
import Fluent
final class OrderedModifier: Model {
var exists: Bool = false
static var entity: String = "orderedmodifier"
var id: Node?
var name: String
var image_url: String?
var required: Bool
var unit_type: String
var unit_bounds: String?
var price_addition: Double?
var description: String?
var quantity: Int
var ordereditem_id: Int
init(name: String, description: String?, image_url: String?, required: Bool, unit_type: String, unit_bounds: String?, price_addition: Double?, ordereditem_id: Int, quantity: Int) throws {
self.id = nil
self.name = name
self.description = description
self.image_url = image_url
self.required = required
self.unit_type = unit_type
self.unit_bounds = unit_bounds
self.price_addition = price_addition
self.ordereditem_id = ordereditem_id
self.quantity = quantity
}
init(node: Node, in context: Context) throws {
id = try node.extract("id")
name = try node.extract("name")
description = try node.extract("description")
image_url = try node.extract("image_url")
required = try node.extract("required")
unit_type = try node.extract("unit_type")
unit_bounds = try node.extract("unit_bounds")
price_addition = try node.extract("price_addition")
quantity = try node.extract("quantity")
ordereditem_id = try node.extract("ordereditem_id")
}
func makeNode(context: Context) throws -> Node {
var node: [String: Node] = [:]
node["id"] = id
node["name"] = name.makeNode()
node["description"] = description?.makeNode() ?? Node.null
node["image_url"] = image_url?.makeNode() ?? Node.null
node["required"] = required.makeNode()
node["unit_type"] = unit_type.makeNode()
node["unit_bounds"] = unit_bounds?.makeNode() ?? Node.null
node["price_addition"] = price_addition?.makeNode() ?? Node.null
if context is DatabaseContext {
node["ordereditem_id"] = try ordereditem_id.makeNode()
}
if context is JSONContext {
let options = try self.orderedoptions().all().map { (option: OrderedOption) -> Node in
return try option.makeNode(context: context)
}
node["options"] = Node.array(options)
}
return Node.object(node)
}
static func prepare(_ database: Database) throws {
try database.create(entity) { modifier in
modifier.id()
modifier.string("name")
modifier.string("description", optional: true)
modifier.string("image_url", optional: true)
modifier.bool("required")
modifier.string("unit_type")
modifier.string("unit_bounds", optional: true)
modifier.string("price_addition", optional: true)
modifier.int("quantity")
modifier.parent(OrderedItem.self, optional: false, unique: false, default: nil)
}
}
static func revert(_ database: Database) throws {
try database.delete(entity)
}
func orderedoptions() -> Children<OrderedOption> {
return children()
}
}
|
9f20f8518ba4113323b4a5b6a83583d2
| 32.259615 | 191 | 0.595837 | false | false | false | false |
Brandon-J-Campbell/codemash
|
refs/heads/master
|
AutoLayoutSession/completed/demo8/codemash/ScheduleCollectionViewController.swift
|
mit
|
1
|
//
// ScheduleCollectionViewController.swift
// codemash
//
// Created by Brandon Campbell on 12/30/16.
// Copyright © 2016 Brandon Campbell. All rights reserved.
//
import Foundation
import UIKit
class ScheduleeRow {
var header : String?
var items = Array<ScheduleeRow>()
var session : Session?
convenience init(withHeader: String, items: Array<ScheduleeRow>) {
self.init()
self.header = withHeader
self.items = items
}
convenience init(withSession: Session) {
self.init()
self.session = withSession
}
}
class ScheduleCollectionCell : UICollectionViewCell {
@IBOutlet var titleLabel : UILabel?
@IBOutlet var roomLabel: UILabel?
@IBOutlet var speakerImageView: UIImageView?
var session : Session?
var isHeightCalculated: Bool = false
static func cellIdentifier() -> String {
return "ScheduleCollectionCell"
}
static func cell(forCollectionView collectionView: UICollectionView, indexPath: IndexPath, session: Session) -> ScheduleCollectionCell {
let cell : ScheduleCollectionCell = collectionView.dequeueReusableCell(withReuseIdentifier: ScheduleCollectionCell.cellIdentifier(), for: indexPath) as! ScheduleCollectionCell
cell.speakerImageView?.image = nil
cell.titleLabel?.text = session.title
cell.roomLabel?.text = session.rooms[0]
cell.session = session
if let url = URL.init(string: "https:" + (session.speakers[0].gravatarUrl)) {
URLSession.shared.dataTask(with: url) {
(data, response, error) in
guard let data = data, error == nil else { return }
print(response?.suggestedFilename ?? url.lastPathComponent)
print("Download Finished")
DispatchQueue.main.async() { () -> Void in
cell.speakerImageView?.image = UIImage(data: data)
}
}.resume()
}
return cell
}
override func preferredLayoutAttributesFitting(_ layoutAttributes: UICollectionViewLayoutAttributes) -> UICollectionViewLayoutAttributes {
setNeedsLayout()
layoutIfNeeded()
var layoutSize : CGSize = layoutAttributes.size
layoutSize.height = 80.0
let size = contentView.systemLayoutSizeFitting(layoutSize)
var newFrame = layoutAttributes.frame
newFrame.size.height = CGFloat(ceilf(Float(size.height)))
layoutAttributes.frame = newFrame
return layoutAttributes
}
}
class ScheduleCollectionHeaderView : UICollectionReusableView {
@IBOutlet var headerLabel : UILabel?
static func cellIdentifier() -> String {
return "ScheduleCollectionHeaderView"
}
}
class ScheduleCollectionViewController : UICollectionViewController {
var sections = Array<ScheduleTableRow>()
var sessions : Array<Session> = Array<Session>.init() {
didSet {
self.data = Dictionary<Date, Array<Session>>()
self.setupSections()
}
}
var data = Dictionary<Date, Array<Session>>()
override func viewDidLoad() {
super.viewDidLoad()
var width : CGFloat
let flowLayout : UICollectionViewFlowLayout = collectionViewLayout as! UICollectionViewFlowLayout
if (self.view.traitCollection.horizontalSizeClass == UIUserInterfaceSizeClass.compact) {
width = (self.collectionView?.bounds.size.width)!
} else {
width = ((self.collectionView?.bounds.size.width)! - flowLayout.minimumLineSpacing - flowLayout.minimumInteritemSpacing - flowLayout.sectionInset.left - flowLayout.sectionInset.right) / ((self.collectionView?.bounds.size.width)! > 800.0 ? 3.0 : 2.0)
}
flowLayout.estimatedItemSize = CGSize(width: width, height: 100)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "showSession" {
let vc = segue.destination as! SessionViewController
let cell = sender as! ScheduleCollectionCell
vc.session = cell.session
}
}
func setupSections() {
let timeFormatter = DateFormatter.init()
timeFormatter.dateFormat = "EEEE h:mm:ssa"
for session in self.sessions {
if data[session.startTime] == nil {
data[session.startTime] = Array<Session>()
}
data[session.startTime]?.append(session)
}
var sections : Array<ScheduleTableRow> = []
for key in data.keys.sorted() {
var rows : Array<ScheduleTableRow> = []
for session in data[key]! {
rows.append(ScheduleTableRow.init(withSession: session))
}
let time = timeFormatter.string(from: key)
sections.append(ScheduleTableRow.init(withHeader: time, items: rows))
}
self.sections = sections
self.collectionView?.reloadData()
}
}
extension ScheduleCollectionViewController {
override func numberOfSections(in collectionView: UICollectionView) -> Int {
return self.sections.count
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
let section = self.sections[section]
return section.items.count
}
}
extension ScheduleCollectionViewController {
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let section = self.sections[indexPath.section]
let row = section.items[indexPath.row]
let cell = ScheduleCollectionCell.cell(forCollectionView: collectionView, indexPath: indexPath, session: row.session!)
cell.contentView.layer.cornerRadius = 10
cell.contentView.layer.borderColor = UIColor.black.cgColor
if (self.view.traitCollection.horizontalSizeClass != UIUserInterfaceSizeClass.compact) {
cell.contentView.layer.borderWidth = 1.0
} else {
cell.contentView.layer.borderWidth = 0.0
}
return cell
}
override func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
let section = self.sections[indexPath.section]
let headerView: ScheduleCollectionHeaderView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: ScheduleCollectionHeaderView.cellIdentifier(), for: indexPath) as! ScheduleCollectionHeaderView
headerView.headerLabel?.text = section.header
return headerView
}
}
|
759f88a3bae7c539e892e8e6a967985a
| 36.861878 | 261 | 0.654166 | false | false | false | false |
mercadopago/px-ios
|
refs/heads/develop
|
MercadoPagoSDK/MercadoPagoSDK/UI/PXResult/New UI/PixCode/InstructionView.swift
|
mit
|
1
|
import UIKit
final class InstructionView: UIView {
// MARK: - Private properties
private weak var delegate: ActionViewDelegate?
private let titleLabel: UILabel = {
let label = UILabel()
label.font = UIFont.ml_semiboldSystemFont(ofSize: 20)
return label
}()
private let stepsStack: UIStackView = {
let stack = UIStackView()
stack.axis = .vertical
stack.alignment = .leading
stack.spacing = 16
return stack
}()
private let watchIcon: UIImageView = {
let image = UIImageView()
image.image = ResourceManager.shared.getImage("iconTime")
return image
}()
private let footerLabel: UILabel = {
let label = UILabel()
label.font = UIFont.ml_regularSystemFont(ofSize: 12)
label.numberOfLines = 0
return label
}()
// MARK: - Initialization
init(instruction: PXInstruction, delegate: ActionViewDelegate?) {
self.delegate = delegate
super.init(frame: .zero)
setupViewConfiguration()
setupInfos(with: instruction)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - Private methods
private func setupInfos(with instruction: PXInstruction) {
titleLabel.isHidden = instruction.subtitle == "" || instruction.subtitle == nil
titleLabel.attributedText = instruction.subtitle?.htmlToAttributedString?.with(font: titleLabel.font)
instruction.info.forEach { info in
addLabel(info: info)
}
instruction.interactions?.forEach { interaction in
addVariableComponents(interaction: interaction)
}
instruction.references?.forEach { reference in
stepsStack.addArrangedSubviews(views: [InstructionReferenceView(reference: reference)])
}
instruction.actions?.forEach { action in
stepsStack.addArrangedSubviews(views: [ActionView(action: action, delegate: self)])
}
instruction.secondaryInfo?.forEach { info in
addLabel(info: info)
}
instruction.tertiaryInfo?.forEach { info in
addLabel(info: info)
}
instruction.accreditationComments.forEach { info in
addLabel(info: info)
}
footerLabel.attributedText = instruction.accreditationMessage?.htmlToAttributedString?.with(font: footerLabel.font)
}
private func addVariableComponents(interaction: PXInstructionInteraction) {
stepsStack.addArrangedSubviews(views: [InstructionActionView(instruction: interaction, delegate: self)])
}
private func addLabel(info: String) {
let instructionLabel: UILabel = {
let label = UILabel()
label.attributedText = info.htmlToAttributedString?.with(font: UIFont.ml_lightSystemFont(ofSize: 16))
label.numberOfLines = 0
return label
}()
stepsStack.addArrangedSubviews(views: [instructionLabel])
}
}
extension InstructionView: ViewConfiguration {
func buildHierarchy() {
addSubviews(views: [titleLabel, stepsStack, watchIcon, footerLabel])
stepsStack.addArrangedSubviews(views: [titleLabel])
}
func setupConstraints() {
NSLayoutConstraint.activate([
stepsStack.topAnchor.constraint(equalTo: topAnchor, constant: 24),
stepsStack.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 32),
stepsStack.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -32),
watchIcon.centerYAnchor.constraint(equalTo: footerLabel.centerYAnchor),
watchIcon.leadingAnchor.constraint(equalTo: titleLabel.leadingAnchor),
watchIcon.heightAnchor.constraint(equalToConstant: 16),
watchIcon.widthAnchor.constraint(equalToConstant: 16),
footerLabel.topAnchor.constraint(equalTo: stepsStack.bottomAnchor, constant: 24),
footerLabel.leadingAnchor.constraint(equalTo: watchIcon.trailingAnchor, constant: 8),
footerLabel.trailingAnchor.constraint(equalTo: titleLabel.trailingAnchor),
footerLabel.bottomAnchor.constraint(equalTo: bottomAnchor, constant: -4)
])
}
func viewConfigure() {
backgroundColor = .white
}
}
extension InstructionView: ActionViewDelegate {
func didTapOnActionButton(action: PXInstructionAction?) {
delegate?.didTapOnActionButton(action: action)
}
}
|
fc5f3c7978ffa8eb03e88b16387baaaa
| 33.823077 | 123 | 0.666225 | false | false | false | false |
Appudo/Appudo.github.io
|
refs/heads/master
|
static/dashs/node/c/s/4/4.swift
|
apache-2.0
|
1
|
import libappudo
import libappudo_run
import libappudo_env
import libappudo_backend
import libappudo_master
import Foundation
typealias ErrorResult = Int
let ErrorDefault = 1
let ErrorNone = 0
struct Fail : Error {
}
var _nodeID = -1 // from the user dash perspective
enum PostType : Int32, Codable {
case STATUS = 0
case DASH_LIST = 1
case DASH_ADD = 2
case DASH_REMOVE = 3
case LOGIN = 4
case LOGOUT = 5
case DISABLE = 6
case STATUS_RETRY = 7
case DASH_ADD_PRECHECK = 8
case DOMAIN_ADD = 9
case SSL_REFRESH = 10
case LOGIN_ADD = 11
case LOGIN_REMOVE = 12
case DOMAIN_REMOVE = 13
case NAME_UPDATE = 14
case SSL_REMOVE = 15
case PING = 16
case DASH_NAME = 17
case SSL_NAME = 18
case DASH_USER = 19
case DASH_SET_EDIT = 20
case DASH_SET_PASSWORD = 21
}
struct TicketLogin : FastCodable {
let r : Int32
let n : Int
let t : Int
}
struct TicketInfo : FastCodable {
let n : Int
let t : Int
let p : Int
let sn : Int
let h : String
}
struct StateInfo : FastCodable {
let nid : String
let s : Int
}
struct PostParam : FastCodable {
let cmd : PostType
let data : String?
}
struct LoginData : FastCodable {
let name : String
let password : String
}
struct DashAddData : FastCodable {
let an : String
let dn : String
let un : String
let up : String
let ac : String?
let af : String?
let ed : String?
let ma : String?
let di : String?
let ds : String
let pp : String
let sn : String
let on : String
let se : String?
let sc : String?
let eo : String?
}
struct DashPasswordData : FastCodable {
let id : Int
let pwd : String
}
struct DashEditData : FastCodable {
let id : Int
let ed : Bool
}
struct DashRemData : FastCodable {
let d : String
let n : Int?
}
struct DomainAddData : FastCodable {
let an : String
let dn : String
let sn : String
let se : String?
let sc : String?
}
struct DomainRemoveData : FastCodable {
let an : String
let dn : String
let n : Int?
}
struct SSLRefreshData : FastCodable {
let an : String
}
struct SSLRemoveData : FastCodable {
let an : String
let u : Int?
}
struct FormFiles {
var ssl_key : FileItem? = nil
var ssl_cert : FileItem? = nil
var package : FileItem? = nil
}
struct CheckData : FastCodable {
let an : String
let dn : String
let sn : String
let on : String
let se : String?
let eo : String?
}
func createSign(_ data0 : Int, _ data1 : Int, _ data2 : Int, _ data3 : Int, _ secret : String) -> String? {
let outBuffer = ManagedCharBuffer.create(64)
let resBuffer = ManagedCharBuffer.create(64)
if let hmac = HMAC.begin(secret, flags:.SHA256),
<!hmac.update(data0, _nodeID, data1, data2, data3) != false,
let m = <!hmac.finish(outBuffer),
// convert sign hash to String
let s = <!Base64.encode(outBuffer, resBuffer, inSizeLimit:m) {
return resBuffer.toString(s)
}
return nil
}
func checkLogin(_ ticket : String) -> Bool {
if ticket != "" {
if let info = TicketLogin.from(json:ticket),
loginGet(info) != false {
return true
}
return false
}
if(User.logon != nil) {
let p : UInt = 0xFFFFFFFFFFFFFFFF
// Page.userData = p // userData is used for the file upload
return true
}
return false
}
func printStatus() -> ErrorResult {
if let txt = getStatus() {
print(txt)
return ErrorNone
}
return ErrorDefault;
}
func getNodeID() -> Bool {
_nodeID = Int(Setting.user_node_id.value) ?? -1
return _nodeID != -1
}
func getStatus() -> String? {
if var f = <!Dir.dev.open("ws_server", .O_APPUDO),
let _ = <!f.write("{\"cmd\":0}"),
let txt = <!f.readAsText() {
return txt
}
return nil
}
func statusRetry() -> ErrorResult {
if var f = <!Dir.dev.open("ws_server", .O_APPUDO),
let _ = <!f.write("{\"cmd\":2}"),
let txt = <!f.readAsText() {
print(txt)
return ErrorNone
}
return ErrorDefault
}
func setDisabled() -> ErrorResult {
if let m = <!TreeMenuItem.get(Page.root, 1, shift:1),
let uID = User.logon,
let g = <!Group.get("node_dash_user"),
let u = <!uID.value {
var r2 = m.id
if (<!u.removeGroup(g.id) && <!r2.setActive(false)) {
print("{\"r\":0}")
return ErrorNone
}
}
return ErrorDefault
}
func printDash(_ item : ServerDomainListItem) {
print("{\"id\":\"\(item.id)\",\"cid\":\"\(item.certId)\",\"aid\":\"\(item.accountId)\",\"host\":\"\(item.host)\"}")
}
func dashList() -> ErrorResult {
if let l = <!ServerDomain.list() {
print("[")
if let n = l.next() {
printDash(n)
}
while(true) {
if let n = l.next() {
print(",")
printDash(n)
} else {
break
}
}
print("]")
return ErrorNone
}
return ErrorDefault
}
func dashAddCheck(_ params : PostParam) -> ErrorResult {
if let frm = CheckData.from(json:params.data ?? "") {
let addOwner = frm.eo != nil
let addSSL = frm.se != nil
// check if account exists
if var _ = <!Account.get(frm.an) {
print("{\"r\":1,\"e\":1}")
return ErrorNone
}
// TODO check if domain exists
// TODO check if ssl name exists
// TODO check if owner name exists
print("{\"r\":0}")
return ErrorNone
}
return ErrorDefault
}
func domainAdd(_ params : PostParam) -> ErrorResult {
var err = AsyncError()
if let frm = DomainAddData.from(json:params.data ?? ""),
var a = err <! Account.get(frm.an),
(err <! a.addDomain(frm.dn)) != false {
var sadd = false
let addSSL = frm.se != nil
let ssl = frm.sn
do {
if(addSSL) {
var _cert : FileItem? = nil
var _key : FileItem? = nil
if frm.sc != nil,
let key = <!Dir.tmp.open("." , [.O_RDWR, .O_TMPFILE]),
let cert = <!Dir.tmp.open("." , [.O_RDWR, .O_TMPFILE]),
<!Cert.selfsigned(name:frm.dn, country:"EN", org:"dummy", outKey:key, outCert:cert) != false {
_cert = cert
_key = key
} else {
if let dummy = <!Dir.tmp.open("." , [.O_RDWR, .O_TMPFILE]) {
_cert = dummy
_key = dummy
}
}
if let key = _key,
let cert = _cert,
<!a.addSSLCert(ssl, cert:cert, key:key) {
sadd = true
} else {
throw Fail()
}
}
if ssl != "" {
guard <!Account.linkSSLCert(frm.dn, cert:ssl) else {
throw Fail()
}
}
print("{\"r\":0}")
return ErrorNone
} catch {
_ = <!a.removeDomain(frm.dn)
if(sadd) {
_ = <!Account.removeSSLCert(ssl)
}
}
}
if(err.errValue != ErrorNone) {
return Int(err.errValue)
}
return ErrorDefault
}
func domainRemove(_ params : PostParam) -> ErrorResult {
var err = AsyncError()
if let frm = DomainRemoveData.from(json:params.data ?? ""),
var a = frm.n != nil ? err <! Account.get(frm.an) : err <! AccountID(Int(frm.an) ?? -1).value,
(err <! a.removeDomain(frm.dn)) != false {
print("{\"r\":0}")
return ErrorNone
}
if(err.errValue != ErrorNone) {
return Int(err.errValue)
}
return ErrorDefault
}
func sslRefresh(_ params : PostParam) -> ErrorResult {
if let frm = SSLRefreshData.from(json:params.data ?? ""),
let l = <!ServerDomain.list(cert:frm.an){
var hosts = [String]()
var account : Int = -1
while(true) {
if let n = l.next() {
hosts.append(n.host)
account = n.accountId
} else {
break
}
}
if(acmeDashRequest(frm.an, hosts, account)) {
print("{\"r\":0}")
return ErrorNone
}
}
return ErrorDefault
}
func sslRemove(_ params : PostParam) -> ErrorResult {
var err = AsyncError()
if let frm = SSLRemoveData.from(json:params.data ?? ""),
err <! Account.removeSSLCert(frm.an, unused:frm.u != nil) {
print("{\"r\":0}")
return ErrorNone
}
if(err.errValue != ErrorNone) {
return Int(err.errValue)
}
return ErrorDefault
}
func sslNameById(_ data : String) -> ErrorResult {
if let id = Int(data),
let a = <!CertID(id).value {
print("{\"r\":0,\"d\":\"\(a.name)\"}")
return ErrorNone
}
return ErrorDefault
}
func dashNameById(_ data : String) -> ErrorResult {
if let id = Int(data),
let a = <!AccountID(id).value {
print("{\"r\":0,\"d\":\"\(a.name)\"}")
return ErrorNone
}
return ErrorDefault
}
func dashGetUser(_ data : String) -> ErrorResult {
if let id = Int(data),
let a = <!AccountID(id).value,
let u = <!a.user {
print("{\"r\":0,\"d\":{\"i\":\(u.id.rawValue),\"n\":\"\(u.name)\"}}")
return ErrorNone
}
return ErrorDefault
}
func dashSetPassword(_ data : String) -> ErrorResult {
if let frm = DashPasswordData.from(json:data),
let a = <!AccountID(frm.id).value,
var u = <!a.user,
<!Account.swap(a.id) != false,
<!u.setPassword(frm.pwd) != false {
<!Account.swap()
print("{\"r\":0}")
return ErrorNone
}
<!Account.swap()
return ErrorDefault
}
func dashSetEdit(_ data : String) -> ErrorResult {
if let frm = DashEditData.from(json:data),
var a = <!AccountID(frm.id).value,
<!a.setEdit(frm.ed) != false {
print("{\"r\":0}")
return ErrorNone
}
return ErrorDefault
}
func dashAdd(_ params : PostParam) -> ErrorResult {
if let frm = DashAddData.from(json:params.data ?? "") {
let addOwner = frm.eo != nil
let addSSL = frm.se != nil
let owner = frm.on
let ssl = frm.sn
var flags = Account.CreatFlags.NONE
var account : Account? = nil
var oadd = false
var sadd = false
if(frm.ac != nil) {
flags = flags.union(.ACTIVE)
}
if(frm.ed != nil) {
flags = flags.union(.EDIT)
}
if(frm.ma != nil) {
flags = flags.union(.MASTER)
}
if(frm.di != nil) {
flags = flags.union(.DISK)
}
do {
if var a = <!Account.add(frm.an, frm.un, frm.up, flags, diskSize:Int32(frm.ds) ?? 0) {
account = a
if(addOwner) {
var err = AsyncError()
guard (err <! Account.addOwner(owner)) || (frm.af != nil && err.asSQL == .UNIQUE_VIOLATION) else {
throw Fail()
}
if(err.noError) {
oadd = true
}
}
if owner != "" {
guard <!a.updateOwner(owner) else {
throw Fail()
}
}
guard <!a.addDomain(frm.dn) else {
throw Fail()
}
if(addSSL) {
var _cert : FileItem? = nil
var _key : FileItem? = nil
if let files = Page.userData as? FormFiles,
let cert = files.ssl_cert,
let key = files.ssl_key {
_cert = cert
_key = key
} else {
if frm.sc != nil,
let key = <!Dir.tmp.open("." , [.O_RDWR, .O_TMPFILE]),
let cert = <!Dir.tmp.open("." , [.O_RDWR, .O_TMPFILE]),
<!Cert.selfsigned(name:frm.dn, country:"EN", org:"dummy", outKey:key, outCert:cert) != false {
_cert = cert
_key = key
}
}
if let key = _key,
let cert = _cert,
<!a.addSSLCert(ssl, cert:cert, key:key) {
sadd = true
} else {
throw Fail()
}
}
if ssl != "" {
guard <!Account.linkSSLCert(frm.dn, cert:ssl) else {
throw Fail()
}
}
if let files = Page.userData as? FormFiles,
let pkg = files.package,
let acc = account {
guard <!Package.deploy(acc.id, pkg, frm.pp) else {
throw Fail()
}
}
print("{\"r\":0}")
return ErrorNone
} else {
throw Fail()
}
} catch {
if var a = account {
_ = <!a.remove()
}
if(sadd) {
_ = <!Account.removeSSLCert(ssl)
}
if(oadd) {
_ = <!Account.removeOwner(owner)
}
}
}
return ErrorDefault
}
func dashRemove(_ params : PostParam) -> ErrorResult {
var err = AsyncError()
if let data = DashRemData.from(json:params.data ?? "") {
var a : Account? = nil
if(data.n != nil) {
a = err <! Account.get(data.d)
} else {
a = err <! AccountID(Int(data.d) ?? -1).value
}
if var account = a,
err <! account.remove() {
print("{\"r\":0}")
return ErrorNone;
}
if(err.errValue != ErrorNone) {
return Int(err.errValue)
}
}
return ErrorDefault
}
func nameUpdate(_ name : String) -> ErrorResult {
if let m = <!MenuItem.get(Run.current, 1, shift:-1),
<!Setting.update(m.id, "node_name", name) != false {
return ErrorNone
}
return ErrorDefault
}
var _loginArray : TimedArray? = nil
func loginArray() -> TimedArray? {
if let arr = _loginArray {
return arr
}
do {
_loginArray = try TimedArray(5*60)
return _loginArray
} catch {
return nil
}
}
func loginAdd(_ ticket : String) -> ErrorResult {
let secret = Setting.user_psk.value
var idx : Int32 = 0
if _nodeID == -1 && getNodeID() == false {
return ErrorDefault;
}
if secret != "",
let info = TicketInfo.from(json:ticket),
let hash = createSign(info.sn, info.n, info.t, info.p, secret),
hash == info.h,
Date().to1970 < info.t + 60,
let rt = <!Rand.int64(),
let rn = <!Rand.int64(),
let arr = loginArray() {
idx = arr.Insert(rt, rn, info.p)
if(idx != 0) {
let tk = "{\\\"t\\\":\(rt),\\\"n\\\":\(rn),\\\"r\\\":\(idx)}"
print("{\"r\":0, \"tk\":\"\(tk)\"}")
return ErrorNone
}
}
return ErrorDefault
}
func loginRemove(_ ticket : String) -> ErrorResult {
if let arr = loginArray(),
let info = TicketLogin.from(json:ticket),
arr.Remove(info.r) != false {
print("{\"r\":0}")
return ErrorNone
}
return ErrorDefault
}
func loginGet(_ info : TicketLogin) -> Bool {
if let arr = loginArray(),
let v = arr.GetAndUpdate(info.r),
v.0 == info.t,
v.1 == info.n {
return true
}
return false
}
func doLogin(_ params : PostParam) -> ErrorResult {
if let data = LoginData.from(json:params.data ?? ""),
let g = <!Group.get("node_dash_user"),
<!User.login(data.name, data.password),
let uid = User.logon,
let u = <!uid.value,
<!u.hasGroup(g.id) {
print("{\"r\":0}")
return ErrorNone
}
User.logout()
return ErrorDefault
}
func doLogout() -> ErrorResult {
User.logout()
return ErrorNone
}
func onUpload(ev : PageEvent) -> UploadResult {
var f : FileItem? = nil
if let data = ev.data as? UploadData {
var files : FormFiles = FormFiles()
if let _files = Page.userData as? FormFiles {
files = _files
}
if let of = <!Dir.tmp.open(".", [.O_TMPFILE, .O_RDWR]) {
f = of
switch(data.name) {
case "pkg":
files.package = of
case "ssc":
files.ssl_key = of
case "ssk":
files.ssl_cert = of
default:
f = nil
}
}
Page.userData = files
}
if(f != nil) {
return .OK(f!)
}
return .ABORT
}
func acmeDashRequest(_ name : String, _ domains : [String], _ firstAccount : Int) -> Bool {
_ = <!Dir.acme_out.mkpath(name)
if var p = <!Dir.acme_certs.mkpath(name, [.S_IRWXU, .S_IRWXG]) {
_ = <!p.setOwner(User.admin, Group.master)
}
// get cert
var a = ACME()
if var log = <!Dir.tmp.open(".", [.O_RDWR, .O_TMPFILE]),
let resDir = <!Dir.acme_certs.open(name, .O_DIRECTORY),
let cngDir = <!Dir.acme_cdir.open(".", .O_DIRECTORY),
let accPKey = <!Dir.acme_out.open("\(name)/accountKey.pem", [.O_CREAT, .O_RDWR]),
let dmnPKey = <!Dir.acme_out.open("\(name)/domainKey.pem", [.O_CREAT, .O_RDWR]) {
//a.logTo = log
if(<!a.request(resDir:resDir,
cngDir:cngDir,
accPKey:accPKey,
dmnPKey:dmnPKey,
domains:domains,
flags:[ .DEFAULT, .NEW_ACCOUNT, .NEW_DOMAIN, .VERBOSE ]) == false) {
print(<!log.readAsText() ?? "")
return false
}
} else {
return false
}
// set cert
if let c = <!Dir.acme_certs.open("\(name)/fullchain.pem", .O_RDONLY),
let k = <!Dir.acme_out.open("\(name)/domainKey.pem", .O_RDONLY),
var a = <!AccountID(firstAccount).value,
<!a.addSSLCert(name, cert:c, key:k, flags:.UPDATE_ONLY) != false {
return true
}
return false
}
func getSubdomain(_ dmn : String) -> String? {
if let idx = dmn.index(of: "."),
idx.encodedOffset < 15 {
return String(dmn[dmn.startIndex...idx])
}
return nil
}
func doPing() -> ErrorResult {
print("{\"r\":0}")
return ErrorNone
}
func main() {
var res = ErrorDefault
if(Page.requestMethod == .POST) {
if(!Page.sameOrigin) {
if let sd = getSubdomain(Page.origin ?? "") {
_ = Page.addResultHeader("Access-Control-Allow-Origin: \(sd)\(Setting.static_host.value)\n")
_ = Page.addResultHeader("Access-Control-Allow-Credentials: true\n")
}
}
let postData = Post.data.value
if let params = PostParam.from(json:postData) {
if(params.cmd == .LOGIN || params.cmd == .LOGIN_ADD || checkLogin(Post.tk.value)) {
switch(params.cmd) {
case .STATUS:
res = printStatus()
case .LOGIN:
res = doLogin(params)
case .LOGOUT:
res = doLogout()
case .DASH_LIST:
res = dashList()
case .DASH_ADD:
res = dashAdd(params)
case .DASH_REMOVE:
res = dashRemove(params)
case .DISABLE:
res = setDisabled()
case .STATUS_RETRY:
res = statusRetry()
case .DASH_ADD_PRECHECK:
res = dashAddCheck(params)
case .DOMAIN_ADD:
res = domainAdd(params)
case .DOMAIN_REMOVE:
res = domainRemove(params)
case .SSL_REFRESH:
res = sslRefresh(params)
case .SSL_REMOVE:
res = sslRemove(params)
case .LOGIN_ADD:
res = loginAdd(Post.tk.value)
case .LOGIN_REMOVE:
res = loginRemove(Post.tk.value)
case .NAME_UPDATE:
res = nameUpdate(params.data ?? "")
case .PING:
res = doPing()
case .DASH_NAME:
res = dashNameById(params.data ?? "")
case .SSL_NAME:
res = sslNameById(params.data ?? "")
case .DASH_USER:
res = dashGetUser(params.data ?? "")
case .DASH_SET_EDIT:
res = dashSetEdit(params.data ?? "")
case .DASH_SET_PASSWORD:
res = dashSetPassword(params.data ?? "")
}
if(res == ErrorNone) {
return
}
} else {
print("{\"r\":1,\"l\":1}")
return
}
}
} else {
if(Page.requestMethod == .OPTIONS) {
if let sd = getSubdomain(Page.origin ?? "") {
_ = Page.addResultHeader("""
Access-Control-Allow-Origin: \(sd)\(Setting.static_host.value)
Access-Control-Allow-Methods: GET, POST, OPTIONS
Access-Control-Allow-Credentials: true
Access-Control-Max-Age: 86400
""")
}
return
}
}
print("{\"r\":\(res)}")
}
|
0bcdd31040adb3d627db043d7ca8fb86
| 26.850801 | 121 | 0.467747 | false | false | false | false |
dn-m/Collections
|
refs/heads/master
|
Collections/DictionaryProtocol.swift
|
mit
|
1
|
//
// DictionaryProtocol.swift
// Collections
//
// Created by James Bean on 12/23/16.
//
//
public protocol ArrayProtocol: Collection {
associatedtype Element
init()
mutating func append(_ element: Element)
mutating func append<S> (contentsOf newElements: S)
where S: Sequence, S.Iterator.Element == Iterator.Element
}
extension Array: ArrayProtocol { }
public enum DictionaryProtocolError: Error {
case illFormedKeyPath
}
/// Interface for Dictionary-like structures.
public protocol DictionaryProtocol: Collection {
// MARK: - Associated Types
/// Key type.
associatedtype Key: Hashable
/// Value type.
associatedtype Value
// MARK: - Initializers
/// Create an empty `DictionaryProtocol` value.
init()
// MARK: - Subscripts
/// - returns: `Value` for the given `key`, if present. Otherwise, `nil`.
subscript (key: Key) -> Value? { get set }
}
extension DictionaryProtocol {
/// Create a `DictionaryProtocol` with two parallel arrays.
///
/// - Note: Usefule for creating a dataset from x- and y-value arrays.
public init(_ xs: [Key], _ ys: [Value]) {
self.init()
zip(xs,ys).forEach { key, value in self[key] = value }
}
/// Create a `DictionaryProtocol` with an array of tuples.
public init(_ keysAndValues: [(Key, Value)]) {
self.init()
for (key, value) in keysAndValues {
self[key] = value
}
}
}
extension DictionaryProtocol where Iterator.Element == (key: Key, value: Value) {
// MARK: - Instance Methods
/// Merge the contents of the given `dictionary` destructively into this one.
public mutating func merge(with dictionary: Self) {
for (k,v) in dictionary { self[k] = v }
}
/// - returns: A new `Dictionary` with the contents of the given `dictionary` merged `self`
/// over those of `self`.
public func merged(with dictionary: Self) -> Self {
var copy = self
copy.merge(with: dictionary)
return copy
}
}
extension DictionaryProtocol where Value: ArrayProtocol {
/// Ensure that an Array-type value exists for the given `key`.
public mutating func ensureValue(for key: Key) {
if self[key] == nil {
self[key] = Value()
}
}
/// Safely append the given `value` to the Array-type `value` for the given `key`.
public mutating func safelyAppend(_ value: Value.Element, toArrayWith key: Key) {
ensureValue(for: key)
self[key]!.append(value)
}
/// Safely append the contents of an array to the Array-type `value` for the given `key`.
public mutating func safelyAppendContents(of values: Value, toArrayWith key: Key) {
ensureValue(for: key)
self[key]!.append(contentsOf: values)
}
}
extension DictionaryProtocol where Value: ArrayProtocol, Value.Element: Equatable {
/**
Safely append value to the array value for a given key.
If this value already exists in desired array, the new value will not be added.
*/
public mutating func safelyAndUniquelyAppend(
_ value: Value.Element,
toArrayWith key: Key
)
{
ensureValue(for: key)
// FIXME: Find a way to not cast to Array!
if (self[key] as! Array).contains(value) {
return
}
self[key]!.append(value)
}
}
extension DictionaryProtocol where
Value: DictionaryProtocol,
Value.Key: Hashable
{
/// Ensure there is a value for a given `key`.
public mutating func ensureValue(for key: Key) {
if self[key] == nil {
self[key] = Value()
}
}
/**
Update the `value` for the given `keyPath`.
- TODO: Use subscript (keyPath: KeyPath) { get set }
*/
public mutating func update(_ value: Value.Value, keyPath: KeyPath) throws {
guard
keyPath.count >= 2,
let key = keyPath[0] as? Key,
let subKey = keyPath[1] as? Value.Key
else {
throw DictionaryProtocolError.illFormedKeyPath
}
ensureValue(for: key)
self[key]![subKey] = value
}
}
extension DictionaryProtocol where
Value: DictionaryProtocol,
Iterator.Element == (Key, Value),
Value.Iterator.Element == (Value.Key, Value.Value)
{
/// Merge the contents of the given `dictionary` destructively into this one.
///
/// - warning: The value of a given key of the given `dictionary` will override that of
/// this one.
public mutating func merge(with dictionary: Self) {
for (key, subDict) in dictionary {
ensureValue(for: key)
for (subKey, value) in subDict {
self[key]![subKey] = value
}
}
}
/// - returns: A new `Dictionary` with the contents of the given `dictionary` merged `self`
/// over those of `self`.
public mutating func merged(with dictionary: Self) -> Self {
var copy = self
copy.merge(with: dictionary)
return copy
}
}
extension DictionaryProtocol where
Value: DictionaryProtocol,
Iterator.Element == (Key, Value),
Value.Iterator.Element == (Value.Key, Value.Value),
Value.Value: ArrayProtocol
{
/// Ensure that there is an Array-type value for the given `keyPath`.
public mutating func ensureValue(for keyPath: KeyPath) throws {
guard
let key = keyPath[0] as? Key,
let subKey = keyPath[1] as? Value.Key
else {
throw DictionaryProtocolError.illFormedKeyPath
}
ensureValue(for: key)
self[key]!.ensureValue(for: subKey)
}
/// Append the given `value` to the array at the given `keyPath`.
///
/// > If no such subdictionary or array exists, these structures will be created.
public mutating func safelyAppend(
_ value: Value.Value.Element,
toArrayWith keyPath: KeyPath
) throws
{
guard
let key = keyPath[0] as? Key,
let subKey = keyPath[1] as? Value.Key
else {
throw DictionaryProtocolError.illFormedKeyPath
}
try ensureValue(for: keyPath)
self[key]!.safelyAppend(value, toArrayWith: subKey)
}
/// Append the given `values` to the array at the given `keyPath`.
///
/// > If no such subdictionary or array exists, these structures will be created.
public mutating func safelyAppendContents(
of values: Value.Value,
toArrayWith keyPath: KeyPath
) throws
{
guard
let key = keyPath[0] as? Key,
let subKey = keyPath[1] as? Value.Key
else {
throw DictionaryProtocolError.illFormedKeyPath
}
try ensureValue(for: keyPath)
self[key]!.safelyAppendContents(of: values, toArrayWith: subKey)
}
}
extension DictionaryProtocol where
Value: DictionaryProtocol,
Iterator.Element == (Key, Value),
Value.Iterator.Element == (Value.Key, Value.Value),
Value.Value: ArrayProtocol,
Value.Value.Element: Equatable
{
/// Append given `value` to the array at the given `keyPath`, ensuring that there are no
/// duplicates.
///
/// > If no such subdictionary or array exists, these structures will be created.
public mutating func safelyAndUniquelyAppend(
_ value: Value.Value.Element,
toArrayWith keyPath: KeyPath
) throws
{
guard
let key = keyPath[0] as? Key,
let subKey = keyPath[1] as? Value.Key
else {
throw DictionaryProtocolError.illFormedKeyPath
}
try ensureValue(for: keyPath)
self[key]!.safelyAndUniquelyAppend(value, toArrayWith: subKey)
}
}
// MARK: - Evaluating the equality of `DictionaryProtocol` values
/// - returns: `true` if all values in `[H: T]` types are equivalent. Otherwise, `false`.
public func == <D: DictionaryProtocol> (lhs: D, rhs: D) -> Bool where
D.Iterator.Element == (D.Key, D.Value),
D.Value: Equatable
{
for (key, _) in lhs {
guard let rhsValue = rhs[key], lhs[key]! == rhsValue else {
return false
}
}
return true
}
/// - returns: `true` if any values in `[H: T]` types are not equivalent. Otherwise, `false`.
public func != <D: DictionaryProtocol> (lhs: D, rhs: D) -> Bool where
D.Iterator.Element == (D.Key, D.Value),
D.Value: Equatable
{
return !(lhs == rhs)
}
/// - returns: `true` if all values in `[H: [T]]` types are equivalent. Otherwise, `false`.
public func == <D: DictionaryProtocol> (lhs: D, rhs: D) -> Bool where
D.Iterator.Element == (D.Key, D.Value),
D.Value: Collection,
D.Value.Iterator.Element: Equatable,
D.Value.Index == Int // FIXME: Find a way to do without this constraint
{
for (key, lhsArray) in lhs {
guard let rhsArray = rhs[key] else { return false }
if lhsArray.count != rhsArray.count { return false }
for i in 0 ..< lhsArray.endIndex {
if lhsArray[i] != rhsArray[i] { return false }
}
}
return true
}
/// - returns: `true` if any values in `[H: [T]]` types are not equivalent. Otherwise, `false`.
public func != <D: DictionaryProtocol> (lhs: D, rhs: D) -> Bool where
D.Iterator.Element == (D.Key, D.Value),
D.Value: Collection,
D.Value.Iterator.Element: Equatable,
D.Value.Index == Int // FIXME: Find a way to do without this constraint
{
return !(lhs == rhs)
}
/// - returns: `true` if all values in `[H: [HH: T]]` types are equivalent. Otherwise, `false`.
public func == <D: DictionaryProtocol> (lhs: D, rhs: D) -> Bool where
D.Iterator.Element == (D.Key, D.Value),
D.Value: DictionaryProtocol,
D.Value.Iterator.Element == (D.Value.Key, D.Value.Value),
D.Value.Value: Equatable
{
for (key, lhsDict) in lhs {
guard let rhsDict = rhs[key], lhsDict != rhsDict else {
return false
}
}
return true
}
/// - returns: `true` if any values in `[H: [HH: T]]` types are not equivalent. Otherwise,
/// `false`.
public func != <D: DictionaryProtocol> (lhs: D, rhs: D) -> Bool where
D.Iterator.Element == (D.Key, D.Value),
D.Value: DictionaryProtocol,
D.Value.Iterator.Element == (D.Value.Key, D.Value.Value),
D.Value.Value: Equatable
{
return !(lhs == rhs)
}
/// - returns: `true` if all values in `[H: [HH: [T]]]` types are equivalent. Otherwise,
/// `false`.
public func == <D: DictionaryProtocol> (lhs: D, rhs: D) -> Bool where
D.Iterator.Element == (D.Key, D.Value),
D.Value: DictionaryProtocol,
D.Value.Iterator.Element == (D.Value.Key, D.Value.Value),
D.Value.Value: Collection,
D.Value.Value.Iterator.Element: Equatable,
D.Value.Value.Index == Int // FIXME: Find a way to do without this constraint
{
for (key, lhsDict) in lhs {
guard let rhsDict = rhs[key] else {
return false
}
if lhsDict != rhsDict {
return false
}
}
return true
}
/// - returns: `true` if any values in `[H: [HH: [T]]]` types are not equivalent.
// Otherwise, `false`.
public func != <D: DictionaryProtocol> (lhs: D, rhs: D) -> Bool where
D.Iterator.Element == (D.Key, D.Value),
D.Value: DictionaryProtocol,
D.Value.Iterator.Element == (D.Value.Key, D.Value.Value),
D.Value.Value: Collection,
D.Value.Value.Iterator.Element: Equatable,
D.Value.Value.Index == Int // FIXME: Find a way to do without this constraint
{
return !(lhs == rhs)
}
extension Dictionary: DictionaryProtocol {
// MARK: - `DictionaryProtocol`
}
|
acc4c7b077cee67215c5d6feeb20b393
| 28.409091 | 95 | 0.616692 | false | false | false | false |
krummler/SKPhotoBrowser
|
refs/heads/master
|
SKPhotoBrowser/extensions/UIImage+Rotation.swift
|
mit
|
1
|
//
// UIImage+Rotation.swift
// SKPhotoBrowser
//
// Created by K Rummler on 15/03/16.
// Copyright © 2016 suzuki_keishi. All rights reserved.
//
import UIKit
extension UIImage {
func rotateImageByOrientation() -> UIImage {
// No-op if the orientation is already correct
guard self.imageOrientation != .Up else {
return self
}
// We need to calculate the proper transformation to make the image upright.
// We do it in 2 steps: Rotate if Left/Right/Down, and then flip if Mirrored.
var transform = CGAffineTransformIdentity
switch self.imageOrientation {
case .Down, .DownMirrored:
transform = CGAffineTransformTranslate(transform, self.size.width, self.size.height)
transform = CGAffineTransformRotate(transform, CGFloat(M_PI))
case .Left, .LeftMirrored:
transform = CGAffineTransformTranslate(transform, self.size.width, 0)
transform = CGAffineTransformRotate(transform, CGFloat(M_PI_2))
case .Right, .RightMirrored:
transform = CGAffineTransformTranslate(transform, 0, self.size.height)
transform = CGAffineTransformRotate(transform, CGFloat(-M_PI_2))
default:
break
}
switch self.imageOrientation {
case .UpMirrored, .DownMirrored:
transform = CGAffineTransformTranslate(transform, self.size.width, 0)
transform = CGAffineTransformScale(transform, -1, 1)
case .LeftMirrored, .RightMirrored:
transform = CGAffineTransformTranslate(transform, self.size.height, 0)
transform = CGAffineTransformScale(transform, -1, 1)
default:
break
}
// Now we draw the underlying CGImage into a new context, applying the transform
// calculated above.
let ctx = CGBitmapContextCreate(nil, Int(self.size.width), Int(self.size.height),
CGImageGetBitsPerComponent(self.CGImage!), 0,
CGImageGetColorSpace(self.CGImage!)!,
CGImageGetBitmapInfo(self.CGImage!).rawValue)
CGContextConcatCTM(ctx!, transform)
switch self.imageOrientation {
case .Left, .LeftMirrored, .Right, .RightMirrored:
CGContextDrawImage(ctx!, CGRect(x: 0, y: 0, width: size.height, height: size.width), self.CGImage!)
default:
CGContextDrawImage(ctx!, CGRect(x: 0, y: 0, width: size.width, height: size.height), self.CGImage!)
}
// And now we just create a new UIImage from the drawing context
if let cgImage = CGBitmapContextCreateImage(ctx!) {
return UIImage(CGImage: cgImage)
} else {
return self
}
}
}
|
882dbda28a3de7faaf458e7df2cf78f6
| 36.828947 | 111 | 0.611478 | false | false | false | false |
Ricky-Choi/UIScrollView-AutoLayout
|
refs/heads/master
|
Scroll/AppDelegate.swift
|
mit
|
1
|
//
// AppDelegate.swift
// Scroll
//
// Created by Jae Young Choi on 2017. 6. 28..
// Copyright © 2017년 Appcid. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
var scrollViewController: ScrollViewController!
if let nc = window?.rootViewController as? UINavigationController, let vc = nc.topViewController as? ScrollViewController {
scrollViewController = vc
} else if let vc = window?.rootViewController as? ScrollViewController {
scrollViewController = vc
}
scrollViewController.contentView = UIImageView(image: UIImage(named: "sample.jpg"))
scrollViewController.fitScale = 0.8
scrollViewController.margins = 100
return true
}
}
|
bcbd3dd85b31a7cac7f247c6d54e55e3
| 28.647059 | 145 | 0.676587 | false | false | false | false |
nessBautista/iOSBackup
|
refs/heads/master
|
iOSNotebook/Pods/Outlaw/Sources/Outlaw/Date+Value.swift
|
cc0-1.0
|
1
|
//
// Date+Value.swift
// Outlaw
//
// Created by Brian Mullen on 11/17/16.
// Copyright © 2016 Molbie LLC. All rights reserved.
//
import Foundation
extension Date: Value {
public static func value(from object: Any) throws -> Date {
guard let value = object as? String else {
throw OutlawError.typeMismatch(expected: String.self, actual: type(of: object))
}
let formattedDate: Date?
if #available(OSX 10.12, iOS 10.0, tvOS 10.0, watchOS 3.0, *) {
formattedDate = ISO8601DateFormatter().date(from: value)
}
else {
formattedDate = DateFormatter.ISO8601DateFormatter.date(from: value)
}
guard let date = formattedDate else {
throw OutlawError.typeMismatch(expected: "ISO8601 formatted string", actual: value)
}
return date
}
}
fileprivate extension DateFormatter {
fileprivate static var ISO8601DateFormatter: DateFormatter {
let formatter = DateFormatter()
formatter.timeZone = TimeZone(abbreviation: "GMT")
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssXXXXX"
return formatter
}
}
|
48be5655ac6f9dc820bade3ed3923dd8
| 28.04878 | 95 | 0.623006 | false | false | false | false |
jariz/Noti
|
refs/heads/master
|
Noti/RoundedImage.swift
|
mit
|
1
|
//
// RoundedImage.swift
// Noti
//
// Created by Jari on 06/07/16.
// Copyright © 2016 Jari Zwarts. All rights reserved.
//
// Converted to Swift by me, taken from
// https://github.com/venj/Cocoa-blog-code/blob/master/Round%20Corner%20Image/Round%20Corner%20Image/NSImage%2BRoundCorner.m
//
import Foundation
import Cocoa
class RoundedImage {
internal static func addRoundedRectToPath(_ context:CGContext, rect:CGRect, ovalWidth:CGFloat, ovalHeight:CGFloat )
{
let fw:CGFloat, fh:CGFloat;
if (ovalWidth == 0 || ovalHeight == 0) {
context.addRect(rect);
return;
}
context.saveGState();
context.translateBy (x: rect.minX, y: rect.minY);
context.scaleBy (x: ovalWidth, y: ovalHeight);
fw = rect.width / ovalWidth;
fh = rect.height / ovalHeight;
context.move(to: CGPoint(x: fw, y: fh/2));
context.addArc(tangent1End: CGPoint(x: fw, y: fh), tangent2End: CGPoint(x: fw / 2, y: fh), radius: 1)
context.addArc(tangent1End: CGPoint(x: 0, y: fh), tangent2End: CGPoint(x: 0, y: fh / 2), radius: 1)
context.addArc(tangent1End: CGPoint(x: 0, y: 0), tangent2End: CGPoint(x: fw / 2, y: 0), radius: 1)
context.addArc(tangent1End: CGPoint(x: fw, y: 0), tangent2End: CGPoint(x: fw, y: fh / 2), radius: 1)
context.closePath();
context.restoreGState();
}
static func create(_ radius: Int, source: NSImage) -> NSImage {
let w = source.size.width
let h = source.size.height
let colorSpace = CGColorSpaceCreateDeviceRGB()
let context = CGContext(data: nil, width: Int(w), height: Int(h), bitsPerComponent: 8, bytesPerRow: 4 * Int(w), space: colorSpace, bitmapInfo: 2)
context?.beginPath()
let rect = CGRect(x: 0, y: 0, width: w, height: h)
addRoundedRectToPath(context!, rect: rect, ovalWidth: CGFloat(radius), ovalHeight: CGFloat(radius))
context?.closePath()
context?.clip()
let cgImage = NSBitmapImageRep(data: source.tiffRepresentation!)!.cgImage!
context?.draw(cgImage, in: CGRect(x: 0, y: 0, width: w, height: h))
let imageMasked = context?.makeImage()
let tmpImage = NSImage(cgImage: imageMasked!, size:source.size)
let imageData = tmpImage.tiffRepresentation!
let image = NSImage(data: imageData)
return image!
}
}
|
799914ad0268c9f4babf1df8bb25bcf1
| 42.142857 | 153 | 0.632036 | false | false | false | false |
liyanhuadev/ObjectMapper-Plugin
|
refs/heads/master
|
ExCommand/MappableCommand.swift
|
mit
|
1
|
//
// SourceEditorCommand.swift
// ObjectMapperEx
//
// Created by LyhDev on 2016/12/27.
// Copyright © 2016年 LyhDev. All rights reserved.
//
import Foundation
import XcodeKit
class MappableCommand: NSObject, XCSourceEditorCommand {
func perform(with invocation: XCSourceEditorCommandInvocation, completionHandler: @escaping (Error?) -> Void ) -> Void {
let lines: [String] = invocation.buffer.lines.compactMap { "\($0)" }
var classModelImpl: [(Int, String)] = []
let metadatas = Parser().parse(buffer: lines)
for case let Metadata.model(range, elements) in metadatas {
let modelBuffer = Array(lines[range])
let pattern = ".*(struct|class)\\s+(\\w+)([^{\\n]*)"
if let regex = try? Regex(string: pattern), let matche = regex.match(modelBuffer[0]) {
let isStruct = matche.captures[0] == "struct"
let modelName = matche.captures[1]!
if matche.captures[0] == "class" {
let protocolStr = matche.captures[2]!.contains(":") ? ", Mappable " : ": Mappable "
var str = modelBuffer[0]
str.replaceSubrange(matche.range, with: matche.matchedString + protocolStr)
invocation.buffer.lines[range.lowerBound] = str
}
let initial = String(format: "\n\n\t%@init?(map: Map) {\n\n\t}", isStruct ? "" : "required ")
var mapping = String(format: "\n\n\t%@func mapping(map: Map) {", isStruct ? "mutating " : "")
for case let Metadata.property(lineNumber) in elements {
if let regex = try? Regex(string: "(.*)(let|var)\\s+(\\w+)\\s*:"),
let matche = regex.match(modelBuffer[lineNumber+1]) {
if matche.captures[0]?.contains("static") == false && matche.captures[1] == "var" {
let value = matche.captures[2]!
mapping += String(format: "\n\t\t%-20s <- map[\"%@\"]", (value as NSString).utf8String!, value)
}
}
}
mapping += "\n\t}"
if isStruct {
let protocolImpl = String(format: "\n\nextension %@: Mappable {%@%@\n}", modelName, initial, mapping)
invocation.buffer.lines.add(protocolImpl)
} else {
let protocolImpl = String(format: "%@%@", initial, mapping)
classModelImpl.append((range.upperBound-1, protocolImpl))
}
}
}
classModelImpl.sort { (args1, args2) -> Bool in return args1.0 > args2.0 }
for (index, impl) in classModelImpl {
invocation.buffer.lines.insert(impl, at: index)
}
completionHandler(nil)
}
}
|
b2d507a0082eeafb2e2188726a1dbb76
| 39.702703 | 124 | 0.503984 | false | false | false | false |
sealgair/UniversalChords
|
refs/heads/master
|
UniversalChords/MusicExtensions.swift
|
gpl-3.0
|
1
|
//
// MusicExtensions.swift
// UniversalChords
//
// Created by Chase Caster on 6/23/16.
// Copyright © 2016 chasecaster. All rights reserved.
//
import Foundation
import MusicKit
let kSavedNoteDisplayNameType = "kSavedNoteDisplayNameType"
let kSavedNoteDisplayAccidental = "kSavedNoteDisplayAccidental"
enum NoteNameType: Int, CustomStringConvertible {
case letter = 0
case solfège = 1
var description: String {
switch self {
case .letter: return "Letter"
case .solfège: return "Solfège"
}
}
static func getCurrent() -> NoteNameType {
return NoteNameType(rawValue: UserDefaults.standard.integer(forKey: kSavedNoteDisplayNameType)) ?? .letter
}
func setCurrent() {
UserDefaults.standard.setValue(self.rawValue, forKey: kSavedNoteDisplayNameType)
}
}
extension Accidental {
static func getCurrent() -> Accidental {
let acc = Accidental(rawValue: UserDefaults.standard.float(forKey: kSavedNoteDisplayAccidental)) ?? .flat
if acc == .sharp || acc == .flat {
return acc
}
return .flat
}
func setCurrent() {
UserDefaults.standard.setValue(self.rawValue, forKey: kSavedNoteDisplayAccidental)
}
}
extension Chroma {
// TODO: would be nice to not have to copy this
var names: [(LetterName, Accidental)] {
switch self.rawValue {
case 0:
return [(.c, .natural), (.b, .sharp), (.d, .doubleFlat)]
case 1:
return [(.c, .sharp), (.d, .flat), (.b, .doubleSharp)]
case 2:
return [(.d, .natural), (.c, .doubleSharp), (.e, .doubleFlat)]
case 3:
return [(.e, .flat), (.d, .sharp), (.f, .doubleFlat)]
case 4:
return [(.e, .natural), (.f, .flat), (.d, .doubleSharp)]
case 5:
return [(.f, .natural), (.e, .sharp), (.g, .doubleFlat)]
case 6:
return [(.f, .sharp), (.g, .flat), (.e, .doubleSharp)]
case 7:
return [(.g, .natural), (.f, .doubleSharp), (.a, .doubleFlat)]
case 8:
return [(.a, .flat), (.g, .sharp)]
case 9:
return [(.a, .natural), (.g, .doubleSharp), (.b, .doubleFlat)]
case 10:
return [(.b, .flat), (.a, .sharp), (.c, .doubleFlat)]
case 11:
return [(.b, .natural), (.c, .flat), (.a, .doubleSharp)]
default:
return []
}
}
public var isNatural: Bool {
let (_, accidental) = self.names[0]
return accidental == .natural
}
func describe(displayName: NoteNameType, displayAccidental: Accidental) -> String {
for (letterName, accidental) in self.names {
if accidental == .natural || accidental == displayAccidental {
return "\(letterName.describe(nameScheme: displayName))\(accidental.description(true))"
}
}
return ""
}
func describeCurrent() -> String {
return describe(displayName: NoteNameType.getCurrent(), displayAccidental: Accidental.getCurrent())
}
}
extension LetterName {
public var solfège : String {
switch self {
case .c: return "Do"
case .d: return "Re"
case .e: return "Mi"
case .f: return "Fa"
case .g: return "Sol"
case .a: return "La"
case .b: return "Si"
}
}
func describe(nameScheme: NoteNameType) -> String {
switch nameScheme {
case .letter: return description
case .solfège: return solfège
}
}
}
extension ChordQuality {
var name: String {
switch self {
case .Major:
return "Major"
case .Minor:
return "Minor"
case .Diminished:
return "dim"
case .Augmented:
return "aug"
default:
return self.rawValue
}
}
}
|
d1d4542d113264fd68bf05d1fcfbaa16
| 27.710145 | 114 | 0.552751 | false | false | false | false |
DayLogger/ADVOperation
|
refs/heads/master
|
Source/URLSessionTaskOperation.swift
|
unlicense
|
1
|
/*
Copyright (C) 2015 Apple Inc. All Rights Reserved.
See LICENSE.txt for this sample’s licensing information
Abstract:
Shows how to lift operation-like objects in to the NSOperation world.
*/
import Foundation
private var URLSessionTaksOperationKVOContext = 0
/**
`URLSessionTaskOperation` is an `Operation` that lifts an `NSURLSessionTask`
into an operation.
Note that this operation does not participate in any of the delegate callbacks \
of an `NSURLSession`, but instead uses Key-Value-Observing to know when the
task has been completed. It also does not get notified about any errors that
occurred during execution of the task.
An example usage of `URLSessionTaskOperation` can be seen in the `DownloadEarthquakesOperation`.
*/
public class URLSessionTaskOperation: Operation {
let task: NSURLSessionTask
public init(task: NSURLSessionTask) {
assert(task.state == .Suspended, "Tasks must be suspended.")
self.task = task
super.init()
}
override public func execute() {
assert(task.state == .Suspended, "Task was resumed by something other than \(self).")
task.addObserver(self, forKeyPath: "state", options: [], context: &URLSessionTaksOperationKVOContext)
task.resume()
}
override public func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
guard context == &URLSessionTaksOperationKVOContext else { return }
if object === task && keyPath == "state" && task.state == .Completed {
task.removeObserver(self, forKeyPath: "state")
finish()
}
}
override public func cancel() {
task.cancel()
super.cancel()
}
}
|
b08cdf52ac389e3430ad9091ddd0becf
| 32.740741 | 164 | 0.681668 | false | false | false | false |
rdlester/simply-giphy
|
refs/heads/master
|
SimplyGiphyTests/view/RootViewTest.swift
|
apache-2.0
|
1
|
import Nimble
import Quick
@testable import SimplyGiphy
class RootViewTest: QuickSpec {
// swiftlint:disable:next function_body_length
override func spec() {
var state: SearchState!
var root: RootView!
beforeEach {
state = SearchState()
root = RootView(state: state)
}
describe("RootView") {
it("Initializes visibility correctly") {
expect(root.activityIndicator.isHidden).to(beTrue())
expect(root.errorMessage.isHidden).to(beTrue())
expect(root.noResultsMessage.isHidden).to(beTrue())
expect(root.gifCollection.isHidden).to(beTrue())
}
it("updates visibility during a search") {
state.searchResults.value = .searching(query: "")
expect(root.activityIndicator.isHidden).to(beFalse()) // Shown.
expect(root.errorMessage.isHidden).to(beTrue())
expect(root.noResultsMessage.isHidden).to(beTrue())
expect(root.gifCollection.isHidden).to(beTrue())
}
it("updates visibility after a successful search") {
// Initialize with a single empty element.
state.searchResults.value = .results(query: "",
results: [Gif(json: [:])!],
page: Pagination(json: [:])!)
expect(root.activityIndicator.isHidden).to(beTrue())
expect(root.errorMessage.isHidden).to(beTrue())
expect(root.noResultsMessage.isHidden).to(beTrue())
expect(root.gifCollection.isHidden).to(beFalse()) // Shown.
}
it("updates visibility after an empty search") {
state.searchResults.value = .results(query: "", results: [], page: Pagination(json: [:])!)
expect(root.activityIndicator.isHidden).to(beTrue())
expect(root.errorMessage.isHidden).to(beTrue())
expect(root.noResultsMessage.isHidden).to(beFalse()) // Shown.
expect(root.gifCollection.isHidden).to(beTrue())
}
it("updates visibility after a failed search") {
state.searchResults.value = .error
expect(root.activityIndicator.isHidden).to(beTrue())
expect(root.errorMessage.isHidden).to(beFalse()) // Shown.
expect(root.noResultsMessage.isHidden).to(beTrue())
expect(root.gifCollection.isHidden).to(beTrue())
}
}
}
}
|
8c26f22043811c695e977c80c510b229
| 42.983333 | 106 | 0.554756 | false | false | false | false |
googlesamples/mlkit
|
refs/heads/master
|
ios/showcase/translate-showcase/TranslateDemo/SearchViewController.swift
|
apache-2.0
|
1
|
//
// Copyright (c) 2019 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import MLKit
import MaterialComponents.MaterialList
private let reuseIdentifier = "Cell"
class SearchViewController: UICollectionViewController, UISearchBarDelegate,
UISearchControllerDelegate
{
private var allLanguages: [TranslateLanguage] = {
return TranslateLanguage.allLanguages().sorted {
$0.localizedName() < $1.localizedName()
}
}()
private lazy var languages = self.allLanguages
let searchController = UISearchController(searchResultsController: nil)
let emptyLabel: UILabel = {
let messageLabel = UILabel()
messageLabel.text = "No language found."
messageLabel.textColor = UIColor.black
messageLabel.numberOfLines = 0
messageLabel.textAlignment = .center
messageLabel.font = UIFont.preferredFont(forTextStyle: .title3)
messageLabel.sizeToFit()
return messageLabel
}()
// We keep track of the pending work item as a property
private var pendingRequestWorkItem: DispatchWorkItem?
override func viewDidLoad() {
super.viewDidLoad()
self.collectionView!.register(
MDCSelfSizingStereoCell.self, forCellWithReuseIdentifier: reuseIdentifier)
guard let col = collectionViewLayout as? UICollectionViewFlowLayout else { return }
col.estimatedItemSize = CGSize.init(width: collectionView!.bounds.width, height: 52)
searchController.searchResultsUpdater = self
searchController.searchBar.delegate = self
searchController.delegate = self
searchController.obscuresBackgroundDuringPresentation = false
searchController.hidesNavigationBarDuringPresentation = false
searchController.searchBar.placeholder = "Search for a language"
UITextField.appearance(whenContainedInInstancesOf: [UISearchBar.self]).leftViewMode = .never
searchController.searchBar.setImage(
#imageLiteral(resourceName: "ic_close"), for: .clear, state: .normal)
UIImageView.appearance(whenContainedInInstancesOf: [UISearchBar.self]).bounds = CGRect(
x: 0, y: 0, width: 24, height: 24)
let x = UIButton.init()
x.setImage(#imageLiteral(resourceName: "ic_arrow_back"), for: .normal)
x.addTarget(self, action: #selector(back), for: .touchUpInside)
UIButton.appearance(whenContainedInInstancesOf: [UINavigationBar.self])
.translatesAutoresizingMaskIntoConstraints = false
UIButton.appearance(whenContainedInInstancesOf: [UINavigationBar.self]).contentEdgeInsets =
UIEdgeInsets(top: 0, left: 0, bottom: 0, right: -4)
navigationItem.leftBarButtonItem = UIBarButtonItem(customView: x)
navigationItem.titleView = searchController.searchBar
navigationItem.hidesBackButton = true
definesPresentationContext = true
searchController.searchBar.showsCancelButton = false
UITextField.appearance(whenContainedInInstancesOf: [UISearchBar.self]).tintColor = UIColor.init(
red: 0, green: 137 / 255, blue: 249 / 255, alpha: 1)
}
@objc func back() {
navigationController?.popViewController(animated: true)
}
func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {
searchController.searchBar.showsCancelButton = false
self.searchController.searchBar.becomeFirstResponder()
}
func didPresentSearchController(_ searchController: UISearchController) {
searchController.searchBar.showsCancelButton = false
self.searchController.searchBar.becomeFirstResponder()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
navigationController?.setNavigationBarHidden(false, animated: false)
navigationController?.navigationBar.barTintColor = .white
navigationController?.navigationBar.tintColor = .gray
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
navigationController?.navigationBar.barTintColor = UIColor(
red: 0.01, green: 0.53, blue: 0.82, alpha: 1.0)
navigationController?.navigationBar.tintColor = .white
}
// MARK: UICollectionViewDataSource
override func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func filterContentForSearchText(_ searchText: String, scope: String = "All") {
if searchText.isEmpty {
self.languages = self.allLanguages
collectionView?.reloadData()
return
}
// Cancel the currently pending item
pendingRequestWorkItem?.cancel()
// Wrap our request in a work item
let requestWorkItem = DispatchWorkItem { [weak self] in
guard let self = self else { return }
self.languages =
self.allLanguages.filter { $0.localizedName().localizedStandardContains(searchText) }
self.collectionView?.reloadData()
}
// Save the new work item and execute it after 250 ms
pendingRequestWorkItem = requestWorkItem
DispatchQueue.main.asyncAfter(
deadline: .now() + .milliseconds(250),
execute: requestWorkItem)
}
override func collectionView(
_ collectionView: UICollectionView, numberOfItemsInSection section: Int
) -> Int {
collectionView.backgroundView = languages.isEmpty ? emptyLabel : nil
return languages.count
}
override func collectionView(
_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath
) -> UICollectionViewCell {
guard
let cell = collectionView.dequeueReusableCell(
withReuseIdentifier: reuseIdentifier,
for: indexPath) as? MDCSelfSizingStereoCell
else {
return UICollectionViewCell()
}
cell.titleLabel.text = languages[indexPath.item].localizedName()
return cell
}
override func collectionView(
_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath
) {
guard let cameraController = self.parent?.childViewControllers[0] as? CameraViewController
else { return }
let recents = cameraController.recentOutputLanguages
let selected = languages[indexPath.item]
if selected != recents[0] {
cameraController.recentOutputLanguages[1] = recents[0]
cameraController.recentOutputLanguages[0] = selected
}
cameraController.selectedItem = 0
back()
}
}
extension SearchViewController: UISearchResultsUpdating {
func updateSearchResults(for searchController: UISearchController) {
filterContentForSearchText(searchController.searchBar.text!)
}
}
|
de26412a06a367dff49442d393bb1c6e
| 35.265625 | 100 | 0.744938 | false | false | false | false |
Kievkao/YoutubeClassicPlayer
|
refs/heads/master
|
ClassicalPlayer/Flows/AppCoordinator.swift
|
mit
|
1
|
//
// AppCoordinator.swift
// ClassicalPlayer
//
// Created by Andrii Kravchenko on 06.02.18.
// Copyright © 2018 Kievkao. All rights reserved.
//
import UIKit
import AVFoundation
import RxFlow
import RxSwift
import RxCocoa
class AppCoordinator {
private let disposeBag = DisposeBag()
private let coordinator = Coordinator()
private let networkFactory = NetworkServiceFactory()
private lazy var initialFlow = {
return ComposersFlow(networkServicesFactory: networkFactory)
}()
func start(inWindow window: UIWindow) {
setupAudioSession()
coordinator.rx.didNavigate.subscribe(onNext: { (flow, step) in
print ("did navigate to flow=\(flow) and step=\(step)")
}).disposed(by: self.disposeBag)
Flows.whenReady(flow1: initialFlow, block: { [unowned window] root in
window.rootViewController = root
})
coordinator.coordinate(flow: initialFlow, withStepper: OneStepper(withSingleStep: AppStep.composers))
}
private func setupAudioSession() {
try? AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
}
}
|
f85e610426ccd9f46c6ce1f6ef0af1a5
| 28.02439 | 109 | 0.67563 | false | false | false | false |
JackieQi/ReSwift-Router
|
refs/heads/master
|
Carthage/Checkouts/ReSwift/ReSwift/CoreTypes/Store.swift
|
mit
|
2
|
//
// Store.swift
// ReSwift
//
// Created by Benjamin Encz on 11/11/15.
// Copyright © 2015 DigiTales. All rights reserved.
//
import Foundation
/**
This class is the default implementation of the `Store` protocol. You will use this store in most
of your applications. You shouldn't need to implement your own store.
You initialize the store with a reducer and an initial application state. If your app has multiple
reducers you can combine them by initializng a `MainReducer` with all of your reducers as an
argument.
*/
open class Store<State: StateType>: StoreType {
typealias SubscriptionType = Subscription<State>
// swiftlint:disable todo
// TODO: Setter should not be public; need way for store enhancers to modify appState anyway
/*private (set)*/ public var state: State! {
didSet {
subscriptions = subscriptions.filter { $0.subscriber != nil }
subscriptions.forEach {
// if a selector is available, subselect the relevant state
// otherwise pass the entire state to the subscriber
$0.subscriber?._newState(state: $0.selector?(state) ?? state)
}
}
}
public var dispatchFunction: DispatchFunction!
private var reducer: Reducer<State>
var subscriptions: [SubscriptionType] = []
private var isDispatching = false
public required convenience init(reducer: @escaping Reducer<State>, state: State?) {
self.init(reducer: reducer, state: state, middleware: [])
}
public required init(
reducer: @escaping Reducer<State>,
state: State?,
middleware: [Middleware]
) {
self.reducer = reducer
// Wrap the dispatch function with all middlewares
self.dispatchFunction = middleware
.reversed()
.reduce({ [unowned self] action in
return self._defaultDispatch(action: action)
}) {
[weak self] dispatchFunction, middleware in
let getState = { self?.state }
return middleware(self?.dispatch, getState)(dispatchFunction)
}
if let state = state {
self.state = state
} else {
dispatch(ReSwiftInit())
}
}
private func _isNewSubscriber(subscriber: AnyStoreSubscriber) -> Bool {
let contains = subscriptions.contains(where: { $0.subscriber === subscriber })
if contains {
print("Store subscriber is already added, ignoring.")
return false
}
return true
}
open func subscribe<S: StoreSubscriber>(_ subscriber: S)
where S.StoreSubscriberStateType == State {
subscribe(subscriber, selector: nil)
}
open func subscribe<SelectedState, S: StoreSubscriber>
(_ subscriber: S, selector: ((State) -> SelectedState)?)
where S.StoreSubscriberStateType == SelectedState {
if !_isNewSubscriber(subscriber: subscriber) { return }
subscriptions.append(Subscription(subscriber: subscriber, selector: selector))
if let state = self.state {
subscriber._newState(state: selector?(state) ?? state)
}
}
open func unsubscribe(_ subscriber: AnyStoreSubscriber) {
if let index = subscriptions.index(where: { return $0.subscriber === subscriber }) {
subscriptions.remove(at: index)
}
}
open func _defaultDispatch(action: Action) -> Any {
guard !isDispatching else {
raiseFatalError(
"ReSwift:IllegalDispatchFromReducer - Reducers may not dispatch actions.")
}
isDispatching = true
let newState = reducer(action, state)
isDispatching = false
state = newState
return action
}
@discardableResult
open func dispatch(_ action: Action) -> Any {
let returnValue = dispatchFunction(action)
return returnValue
}
@discardableResult
open func dispatch(_ actionCreatorProvider: @escaping ActionCreator) -> Any {
let action = actionCreatorProvider(state, self)
if let action = action {
dispatch(action)
}
return action as Any
}
open func dispatch(_ asyncActionCreatorProvider: @escaping AsyncActionCreator) {
dispatch(asyncActionCreatorProvider, callback: nil)
}
open func dispatch(_ actionCreatorProvider: @escaping AsyncActionCreator,
callback: DispatchCallback?) {
actionCreatorProvider(state, self) { actionProvider in
let action = actionProvider(self.state, self)
if let action = action {
self.dispatch(action)
callback?(self.state)
}
}
}
public typealias DispatchCallback = (State) -> Void
public typealias ActionCreator = (_ state: State, _ store: Store) -> Action?
public typealias AsyncActionCreator = (
_ state: State,
_ store: Store,
_ actionCreatorCallback: @escaping ((ActionCreator) -> Void)
) -> Void
}
|
e32699694e684175afd7651d929ad43d
| 30.157576 | 99 | 0.619724 | false | false | false | false |
honghaoz/CrackingTheCodingInterview
|
refs/heads/master
|
Swift/LeetCode/Dynamic Programming/64_Minimum Path Sum.swift
|
mit
|
1
|
// 64_Minimum Path Sum
// https://leetcode.com/problems/minimum-path-sum/
//
// Created by Honghao Zhang on 9/20/19.
// Copyright © 2019 Honghaoz. All rights reserved.
//
// Description:
// Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right which minimizes the sum of all numbers along its path.
//
//Note: You can only move either down or right at any point in time.
//
//Example:
//
//Input:
//[
// [1,3,1],
// [1,5,1],
// [4,2,1]
//]
//Output: 7
//Explanation: Because the path 1→3→1→1→1 minimizes the sum.
//
import Foundation
class Num64 {
// 经典DP问题
// 坐标型动态规划
func minPathSum(_ grid: [[Int]]) -> Int {
guard grid.count > 0 else {
return 0
}
let m = grid.count
guard grid[0].count > 0 else {
return 0
}
let n = grid[0].count
// state: s[i][j] represents the min path to (i, j)
// initialize
var s: [[Int]] = Array(repeating: Array(repeating: 0, count: n), count: m)
s[0][0] = grid[0][0]
// init row 0
for j in 1..<n {
s[0][j] = s[0][j - 1] + grid[0][j]
}
// init column 0
for i in 1..<m {
s[i][0] = s[i - 1][0] + grid[i][0]
}
// transition function
for i in 1..<m {
for j in 1..<n {
s[i][j] = min(s[i - 1][j], s[i][j - 1]) + grid[i][j]
}
}
return s[m - 1][n - 1]
}
}
|
7867dada23ff9489242dc17f7d7a2853
| 21.229508 | 152 | 0.54646 | false | false | false | false |
DTVD/APIKitExt
|
refs/heads/master
|
Example/Himotoki Sample/View/RepoViewController.swift
|
mit
|
1
|
//
// RepoViewController.swift
// Himotoki Sample
//
// Created by DTVD on 12/24/16.
// Copyright © 2016 CocoaPods. All rights reserved.
//
import UIKit
import RxSwift
import RxCocoa
class RepoViewController: UIViewController {
@IBOutlet var tableView: UITableView!
var searchBar = UISearchBar()
fileprivate let reuseIdentifier = "RepoCell"
fileprivate var viewModel = RepoViewModel()
fileprivate let diposeBag = DisposeBag()
fileprivate let veryLightGray = UIColor(
red:200/255,
green:200/255,
blue:206/255,
alpha:1
)
override func viewDidLoad() {
super.viewDidLoad()
searchBar.delegate = self
self.navigationItem.titleView = searchBar
tableView.register( UINib(nibName: "Repo", bundle: nil) , forCellReuseIdentifier: reuseIdentifier)
rxBinding()
}
func rxBinding() {
let query = searchBar.rx.text
.orEmpty
.throttle(0.5, scheduler: MainScheduler.instance)
.distinctUntilChanged()
viewModel.receive(query)
viewModel.repos
.asDriver(onErrorJustReturn: [])
.drive(tableView.rx.items(cellIdentifier: reuseIdentifier, cellType: RepoTableViewCell.self)) { _, repo, cell in
cell.name.text = repo.fullName
let stars = repo.stargazersCount
cell.stargazersCount.text = String(describing: stars) + " stars"
let url = repo.avatar
cell.avatar.downloadFrom(url: url)
}
.addDisposableTo(diposeBag)
}
}
extension RepoViewController: UISearchBarDelegate {
func searchBarShouldBeginEditing(_ searchBar: UISearchBar) -> Bool {
self.navigationController?.navigationBar.barTintColor = veryLightGray
searchBar.setShowsCancelButton(true, animated: true)
return true
}
func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
searchBar.text = ""
searchBar.setShowsCancelButton(false, animated: true)
searchBar.resignFirstResponder()
self.navigationController?.navigationBar.barTintColor = nil
}
}
|
de33700019958f5437c7bae322aabc41
| 30 | 124 | 0.652995 | false | false | false | false |
goborrega/PresentIO
|
refs/heads/master
|
PresentIO/DeviceUtils.swift
|
mit
|
1
|
//
// DeviceUtils.swift
// PresentIO
//
// Created by Gonçalo Borrêga on 01/03/15.
// Copyright (c) 2015 Borrega. All rights reserved.
//
import Foundation
import CoreMediaIO
import Cocoa
import AVKit
import AVFoundation
enum DeviceType {
case iPhone
case iPad
}
enum DeviceOrientation {
case Portrait
case Landscape
}
class DeviceUtils {
var type: DeviceType
var skinSize: NSSize! //video dimensions
var skin = "Skin"
var orientation = DeviceOrientation.Portrait
var videDimensions: CMVideoDimensions = CMVideoDimensions(width: 0,height: 0) {
didSet {
orientation = videDimensions.width > videDimensions.height ? .Landscape : .Portrait
}
}
init(deviceType:DeviceType) {
self.type = deviceType
self.skinSize = getSkinSize()
switch deviceType {
case .iPhone:
skin = "Skin"
case .iPad:
skin = "Skin_iPad"
}
}
class func initWithDimensions(dimensions:CMVideoDimensions) -> DeviceUtils {
var device : DeviceUtils
if((dimensions.width == 1024 && dimensions.height == 768)
|| (dimensions.width == 768 && dimensions.height == 1024)
|| (dimensions.width == 900 && dimensions.height == 1200)
|| (dimensions.width == 1200 && dimensions.height == 900)
|| (dimensions.width == 1200 && dimensions.height == 1600)
|| (dimensions.width == 1600 && dimensions.height == 1200)) {
device = DeviceUtils(deviceType: .iPad)
} else {
device = DeviceUtils(deviceType: .iPhone)
}
device.videDimensions = dimensions
return device
}
func getSkinDeviceImage() -> String {
let imgLandscape = self.orientation == .Landscape ? "_landscape" : ""
let imgtype = self.type == .iPad ? "iPad" : "iphone6"
return "\(imgtype)_white\(imgLandscape)"
}
func getSkinSize() -> NSSize {
var size : NSSize
switch self.type {
case .iPhone:
size = NSSize(width: 350,height: 700) //640x1136 (iPhone5)
case .iPad:
size = NSSize(width: 435,height: 646) // 768x1024 (ipad mini)
}
return self.orientation == .Portrait ?
NSSize(width: size.width, height: size.height) :
NSSize(width: size.height, height: size.width)
}
func getFrame() -> CGRect {
return CGRectMake(0, 0, skinSize.width, skinSize.height)
}
func getWindowSize() -> NSSize {
//return NSSize(width: max(skinSize.width, skinSize.height), height: max(skinSize.width, skinSize.height))
if(self.orientation == .Portrait) {
return NSSize(width: skinSize.width, height: skinSize.height)
} else {
return NSSize(width: skinSize.height, height: skinSize.width)
}
}
class func getCenteredRect(windowSize : NSSize, screenFrame: NSRect) -> NSRect{
let origin = NSPoint(
x: screenFrame.width / 2 - windowSize.width / 2,
y: screenFrame.height / 2 - windowSize.height / 2 )
return NSRect(origin: origin, size: windowSize)
}
class func registerForScreenCaptureDevices() {
var prop : CMIOObjectPropertyAddress = CMIOObjectPropertyAddress(
mSelector: CMIOObjectPropertySelector(kCMIOHardwarePropertyAllowScreenCaptureDevices),
mScope: CMIOObjectPropertyScope(kCMIOObjectPropertyScopeGlobal),
mElement: CMIOObjectPropertyElement(kCMIOObjectPropertyElementMaster))
var allow:UInt32 = 1
CMIOObjectSetPropertyData( CMIOObjectID(kCMIOObjectSystemObject),
&prop,
0,
nil,
UInt32(sizeofValue(allow)),
&allow)
}
}
|
a25d587909c4a21b5abb5c618a91ce9f
| 29.880952 | 114 | 0.599229 | false | false | false | false |
klep/SKBatcher
|
refs/heads/master
|
SKBatcher/SKBatcher.swift
|
mit
|
1
|
//
// SKBatcher.swift
//
// Created by Scott J. Kleper on 12/21/16.
//
import Foundation
import SwiftyJSON
open class SKBatcher {
let apiCall: (([Int], @escaping ((JSON?) -> Void)) -> Void)
open var allIds = [Int]() {
didSet {
cache = [Int: AnyObject]()
}
}
var cache = [Int: AnyObject]()
var completionHandlers: [Int: [((AnyObject) -> Void)?]] = [:]
public init(apiCall: @escaping (([Int], @escaping ((JSON?) -> Void)) -> Void)) {
self.apiCall = apiCall
}
func idIsPending(_ id: Int) -> Bool {
return cache[id] is Bool
}
func cachedValueForId(_ id: Int) -> AnyObject? {
guard !(cache[id] is Bool) else { return nil }
if let value = cache[id] {
return value
}
return nil
}
open func fetch(_ id: Int, completion: @escaping (AnyObject) -> Void) {
if let cachedValue = cachedValueForId(id) {
completion(cachedValue)
return
}
if completionHandlers[id] == nil {
completionHandlers[id] = []
}
completionHandlers[id]!.append(completion)
if idIsPending(id) {
return
}
// Batch up the next 10, but omit any that are already pending
var batch = [Int]()
batch.append(id)
cache[id] = true as AnyObject?
if let loc = allIds.index(of: id) {
allIds[loc..<min(loc+10, allIds.count)].forEach({ (id) in
if !idIsPending(id) {
batch.append(id)
cache[id] = true as AnyObject?
}
})
}
apiCall(batch) { (json) in
if let results = json?.dictionary {
results.keys.forEach{ id in
if let excerpt = results[id] {
self.cache[Int(id)!] = excerpt.object as AnyObject?
if let handlers = self.completionHandlers[Int(id)!] {
handlers.forEach({ (handler) in
handler?(excerpt.object as AnyObject)
})
}
self.completionHandlers[Int(id)!] = []
}
}
}
}
}
}
|
43ac3a963d964e7f41fda1c2e5cad736
| 26.588235 | 84 | 0.467804 | false | false | false | false |
vector-im/vector-ios
|
refs/heads/master
|
Riot/Modules/Room/ParticipantsInviteModal/ShareInviteLink/ShareInviteLinkHeaderView.swift
|
apache-2.0
|
1
|
//
// Copyright 2020 New Vector Ltd
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import UIKit
import Reusable
@objc
protocol ShareInviteLinkHeaderViewDelegate: AnyObject {
func shareInviteLinkHeaderView(_ headerView: ShareInviteLinkHeaderView, didTapButton button: UIButton)
}
@objcMembers
final class ShareInviteLinkHeaderView: UIView, NibLoadable, Themable {
// MARK: - Constants
private enum Constants {
static let buttonHighlightedAlpha: CGFloat = 0.2
}
// MARK: - Properties
@IBOutlet private weak var button: CustomRoundedButton!
weak var delegate: ShareInviteLinkHeaderViewDelegate?
// MARK: - Setup
static func instantiate() -> ShareInviteLinkHeaderView {
let view = ShareInviteLinkHeaderView.loadFromNib()
view.update(theme: ThemeService.shared().theme)
return view
}
// MARK: - Life cycle
override func awakeFromNib() {
super.awakeFromNib()
button.setTitle(VectorL10n.shareInviteLinkAction, for: .normal)
button.addTarget(self, action: #selector(buttonAction), for: .touchUpInside)
button.layer.cornerRadius = 8
button.layer.borderWidth = 2
}
// MARK: - Public
func update(theme: Theme) {
button.layer.borderColor = theme.tintColor.cgColor
button.setTitleColor(theme.tintColor, for: .normal)
button.setTitleColor(theme.tintColor.withAlphaComponent(Constants.buttonHighlightedAlpha), for: .highlighted)
button.vc_setBackgroundColor(theme.baseColor, for: .normal)
let buttonImage = Asset.Images.shareActionButton.image.vc_tintedImage(usingColor: theme.tintColor)
button.setImage(buttonImage, for: .normal)
}
// MARK: - Action
@objc private func buttonAction(_ sender: UIButton) {
delegate?.shareInviteLinkHeaderView(self, didTapButton: button)
}
}
|
edd6e99c91ab54b05028d561ee69b1cb
| 31.051948 | 117 | 0.692464 | false | false | false | false |
almazrafi/Metatron
|
refs/heads/master
|
Sources/MPEG/MPEGProperties.swift
|
mit
|
1
|
//
// MPEGProperties.swift
// Metatron
//
// Copyright (c) 2016 Almaz Ibragimov
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
public class MPEGProperties {
// MARK: Instance Properties
public internal(set) var framesRange: Range<UInt64>
private let header: MPEGHeader
public let xingHeader: MPEGXingHeader?
public let vbriHeader: MPEGVBRIHeader?
public let duration: Double
public let bitRate: Int
// MARK:
public var version: MPEGVersion {
return self.header.version
}
public var layer: MPEGLayer {
return self.header.layer
}
public var sampleRate: Int {
return self.header.sampleRate
}
public var channelMode: MPEGChannelMode {
return self.header.channelMode
}
public var copyrighted: Bool {
return self.header.copyrighted
}
public var original: Bool {
return self.header.original
}
public var emphasis: MPEGEmphasis {
return self.header.emphasis
}
public var bitRateMode: MPEGBitRateMode {
if let xingHeader = self.xingHeader {
return xingHeader.bitRateMode
} else if self.vbriHeader != nil {
return MPEGBitRateMode.variable
} else {
return MPEGBitRateMode.constant
}
}
// MARK: Initializers
public init?(fromStream stream: Stream, range: Range<UInt64>) {
assert(stream.isOpen && stream.isReadable && (stream.length >= range.upperBound), "Invalid stream")
guard UInt64(range.count) >= UInt64(MPEGHeader.anyDataLength) else {
return nil
}
self.framesRange = range
var header: MPEGHeader?
repeat {
guard stream.seek(offset: self.framesRange.lowerBound) else {
return nil
}
let data = stream.read(maxLength: MPEGHeader.anyDataLength)
guard data.count == MPEGHeader.anyDataLength else {
return nil
}
header = MPEGHeader(fromData: data)
if let header = header {
if header.isValid {
if UInt64(self.framesRange.count) <= UInt64(header.frameLength) {
break
}
guard stream.seek(offset: self.framesRange.lowerBound + UInt64(header.frameLength)) else {
return nil
}
let nextData = stream.read(maxLength: MPEGHeader.anyDataLength)
guard nextData.count == MPEGHeader.anyDataLength else {
return nil
}
if nextData[0] == 255 {
if nextData[1] & 254 == data[1] & 254 {
if nextData[2] & 12 == data[2] & 12 {
break
}
}
}
}
}
self.framesRange = (self.framesRange.lowerBound + 1)..<self.framesRange.upperBound
}
while UInt64(self.framesRange.count) >= UInt64(MPEGHeader.anyDataLength)
guard header != nil else {
return nil
}
self.header = header!
let headerRange = Range(range.lowerBound..<(range.lowerBound + UInt64(MPEGHeader.anyDataLength)))
var xingHeaderRange = Range((headerRange.upperBound + UInt64(self.header.sideInfoLength))..<range.upperBound)
var vbriHeaderRange = Range((headerRange.upperBound + 32)..<range.upperBound)
let bitRateMode: MPEGBitRateMode
let bytesCount: UInt32
let framesCount: UInt32
if let xingHeader = MPEGXingHeader(fromStream: stream, range: &xingHeaderRange) {
bitRateMode = xingHeader.bitRateMode
bytesCount = xingHeader.bytesCount ?? 0
framesCount = xingHeader.framesCount ?? 0
self.xingHeader = xingHeader
self.vbriHeader = nil
} else if let vbriHeader = MPEGVBRIHeader(fromStream: stream, range: &vbriHeaderRange) {
bitRateMode = MPEGBitRateMode.variable
bytesCount = vbriHeader.bytesCount
framesCount = vbriHeader.framesCount
self.xingHeader = nil
self.vbriHeader = vbriHeader
} else {
bitRateMode = MPEGBitRateMode.constant
bytesCount = 0
framesCount = 0
self.xingHeader = nil
self.vbriHeader = nil
}
switch bitRateMode {
case MPEGBitRateMode.variable:
if (self.header.sampleRate > 0) && (framesCount > 0) {
let samplesPerFrame = Double(self.header.samplesPerFrame)
let sampleRate = Double(self.header.sampleRate)
self.duration = Double(framesCount) * (samplesPerFrame * 1000.0 / sampleRate)
if bytesCount > 0 {
self.bitRate = Int(Double(bytesCount) * 8.0 / self.duration + 0.5)
} else {
self.bitRate = Int(Double(self.framesRange.count) * 8.0 / self.duration + 0.5)
}
} else {
self.duration = 0.0
self.bitRate = max(self.header.bitRate, 0)
}
case MPEGBitRateMode.constant:
self.bitRate = max(self.header.bitRate, 0)
if self.bitRate > 0 {
if bytesCount > 0 {
self.duration = Double(bytesCount) * 8.0 / Double(self.bitRate)
} else {
self.duration = Double(self.framesRange.count) * 8.0 / Double(self.bitRate)
}
} else {
self.duration = 0.0
}
}
}
}
|
122d41133aae0755c39d508cccab7f2c
| 31.065728 | 117 | 0.585359 | false | false | false | false |
ortizraf/macsoftwarecenter
|
refs/heads/master
|
Mac Application Store/WindowController.swift
|
gpl-3.0
|
1
|
//
// WindowController.swift
// MMac Software Center
//
// Created by Rafael Ortiz.
// Copyright © 2017 Nextneo. All rights reserved.
//
import Cocoa
class WindowController: NSWindowController, NSToolbarDelegate {
@IBOutlet weak var toolbarView: NSToolbar!
@IBOutlet weak var spinnerView: NSProgressIndicator!
@IBOutlet var segmentedControl : NSSegmentedControl?
var viewController: ViewController {
get {
return self.window!.contentViewController! as! ViewController
}
}
override func windowDidLoad() {
super.windowDidLoad()
}
override func awakeFromNib() {
super.awakeFromNib();
print("Window")
setToolbarView()
}
func showProgressIndicator(){
spinnerView.isHidden = false
spinnerView.startAnimation(spinnerView)
}
func hideProgressIndicator(){
spinnerView.isHidden = true
}
func setToolbarView(){
for toolbarItemView in self.toolbarView.items {
print(toolbarItemView.itemIdentifier)
//toolbarItemView.label = "xx"
toolbarItemView.isEnabled = true
toolbarItemView.target = self
if((toolbarItemView.itemIdentifier as? String) == "NSToolbarCategories"){
toolbarItemView.action = Selector("actionToCategoriesController")
} else if ((toolbarItemView.itemIdentifier as? String) == "NSToolbarFeatured"){
toolbarItemView.action = Selector("actionToProductController")
} else if ((toolbarItemView.itemIdentifier as? String) == "NSSearchFieldCustom"){
//toolbarItemView.action = Selector("fieldTextDidChange:")
}
}
}
func actionToCategoriesController(){
print("action categories")
showProgressIndicator()
self.viewController.view.wantsLayer = true
let mainStoryboard: NSStoryboard = NSStoryboard(name: "Main", bundle: nil)
let getViewController = mainStoryboard.instantiateController(withIdentifier: "categoriesViewController") as! NSViewController
for view in self.viewController.view.subviews {
view.removeFromSuperview()
}
self.viewController.insertChild(getViewController, at: 0)
self.viewController.view.addSubview(getViewController.view)
self.viewController.view.frame = getViewController.view.frame
hideProgressIndicator()
}
func actionToProductController(){
print("action product")
showProgressIndicator()
self.viewController.view.wantsLayer = true
let mainStoryboard: NSStoryboard = NSStoryboard(name: "Main", bundle: nil)
let getViewController = mainStoryboard.instantiateController(withIdentifier: "productViewController") as! NSViewController
for view in self.viewController.view.subviews {
view.removeFromSuperview()
}
self.viewController.insertChild(getViewController, at: 0)
self.viewController.view.addSubview(getViewController.view)
self.viewController.view.frame = getViewController.view.frame
hideProgressIndicator()
}
func actionToSearchProductController(searchWord: String?){
print("action search product")
showProgressIndicator()
self.viewController.view.wantsLayer = true
let mainStoryboard: NSStoryboard = NSStoryboard(name: "Main", bundle: nil)
let getViewController = mainStoryboard.instantiateController(withIdentifier: "productViewController") as! ProductController
getViewController.taskName = "search"
getViewController.searchWord = searchWord!
for view in self.viewController.view.subviews {
view.removeFromSuperview()
}
self.viewController.insertChild(getViewController, at: 0)
self.viewController.view.addSubview(getViewController.view)
self.viewController.view.frame = getViewController.view.frame
hideProgressIndicator()
}
@IBAction func getSearch(sender: NSSearchField?){
print("Button pressed search 👍 ")
if (!(sender?.stringValue.isEmpty)!) {
print("Searched: \(sender?.stringValue)")
var searchWord = sender?.stringValue
if((searchWord?.count)!>3){
actionToSearchProductController(searchWord: searchWord)
}
} else {
print("empty")
actionToProductController()
}
}
@IBAction func selectSegmentsControl(sender: NSSegmentedControl) {
print("Button segments")
switch sender.selectedSegment {
case 0:
print("before")
modifySegmentsControl(active: false, segmentIndex: 0)
modifySegmentsControl(active: true, segmentIndex: 1)
case 1:
print("after")
modifySegmentsControl(active: false, segmentIndex: 1)
modifySegmentsControl(active: true, segmentIndex: 0)
default:
break
}
}
func modifySegmentsControl(active: Bool ,segmentIndex: Int){
segmentedControl?.setEnabled(active, forSegment: segmentIndex)
}
@IBAction func btnTouchBarFeatured(sender: AnyObject){
print("Touchbar Button featured pressed 👍 ")
actionToProductController()
}
@IBAction func btnTouchBarCategories(sender: AnyObject){
print("Touchbar Button categories pressed 👍 ")
actionToCategoriesController()
}
}
|
6037765eb2811113936ed1c0dcdbcbaa
| 30.770492 | 133 | 0.628655 | false | false | false | false |
akiramur/PeerClient
|
refs/heads/master
|
PeerClient/Peer+PeerSocketDelegate.swift
|
mit
|
1
|
//
// Peer+PeerSocketDelegate.swift
// PeerClient
//
// Created by Akira Murao on 2017/03/15.
// Copyright © 2017 Akira Murao. All rights reserved.
//
import Foundation
extension Peer: PeerSocketDelegate {
// MARK: PeerSocketDelegate
func webSocketDidOpen(webSocket: PeerSocket) {
print("webSocketDidOpen")
}
func webSocket(webSocket: PeerSocket, didReceiveMessage message: [String: Any]?) {
print("webSocket didReceiveMessage")
if let m = message {
self.handleMessage(message: m)
}
}
func webSocket(webSocket: PeerSocket, didCloseWithReason reason: String?) {
print("webSocket didCloseWithReason reason: \(reason ?? "Underlying socket is already closed.")")
if !self.isDisconnected {
self.abort(type: "socket-closed", completion: { (error) in
})
}
self.isOpen = false
self.keepAliveTimer?.invalidate()
}
func webSocket(webSocket: PeerSocket, didFailWithError error: Error?) {
print("webSocket didFailWithError error: \(error?.localizedDescription ?? "")")
self.abort(type: "socket-error", completion: { (error) in
})
self.keepAliveTimer?.invalidate()
}
// MARK: Private method
func handleMessage(message: [String: Any]) {
print("RECV MESSAGE: \(message)")
//var connection: RTCPeerConnection?
guard let type = message["type"] as? String else {
print("ERROR: type doesn't exist")
return
}
print("TYPE: \(type)")
switch type {
case "OPEN": // The connection to the server is open.
//this.emit('open', this.id);
self.delegate?.peer(self, didOpen: self.peerId)
self.isOpen = true
case "ERROR": // Server error.
let payload = message["payload"] as? [String: Any]
let payloadMessage = payload?["message"] as? String
self.abort(type: "socket-error", completion: { (error) in
print("payloadMessage: \(payloadMessage ?? "")")
})
break
case "ID-TAKEN": // The selected ID is taken.
self.abort(type: "unavailable-id", completion: { (error) in
print("ID \(self.peerId ?? "") is taken")
})
break
case "INVALID-KEY": // The given API key cannot be found.
//self.abort("invalid-key", message: "API KEY \(self.options.key) is invalid")
break
case "LEAVE": // Another peer has closed its connection to this peer.
guard let peerId = message["src"] as? String else {
print("ERROR: src doesn't exist")
return
}
print("Received leave message from \(peerId)")
self.cleanup(peerId: peerId)
break
case "EXPIRE": // The offer sent to a peer has expired without response.
//this.emitError('peer-unavailable', 'Could not connect to peer ' + peer)
DispatchQueue.main.async {
self.delegate?.peer(self, didReceiveError: PeerError.receivedExpire)
}
break
case "OFFER": // we should consider switching this to CALL/CONNECT, but this is the least breaking option.
guard let peerId = message["src"] as? String else {
print("ERROR: src is nil")
return
}
guard let payload = message["payload"] as? [String: Any] else {
print("ERROR: payload is nil")
return
}
guard let connectionId = payload["connectionId"] as? String else {
print("ERROR: connectionId is nil")
return
}
if let _ = self.connectionStore.findConnection(peerId: peerId, connectionId: connectionId) {
print("Offer received for existing Connection ID: \(connectionId)")
}
else {
// Create a new connection.
guard let connectionType = payload["type"] as? String else {
print("ERROR: type doesn't exist")
return
}
var connection: PeerConnection?
if connectionType == "media" {
let metadata = payload["metadata"] as? [String: Any]
let connectionOptions = PeerConnectionOptions(connectionType: .media, connectionId: connectionId, payload: payload, metadata: metadata, label: nil, serialization: nil, isReliable: nil, iceServerOptions: self.options?.iceServerOptions)
let mediaConnection = MediaConnection(peerId: peerId, delegate: self, options: connectionOptions)
self.connectionStore.addConnection(connection: mediaConnection)
connection = mediaConnection
// this calls mediaConnection.answer
// once answer is triggered by user in upper layer, startConnection is called.
// emit -> peer.on('call', function(call)) in index.html -> mediaConnection.answer
//self.emit('call', connection)
DispatchQueue.main.async {
self.delegate?.peer(self, didReceiveConnection: mediaConnection)
}
}
else if connectionType == "data" {
let label = payload["label"] as? String
let serialization = payload["serialization"] as? String
let reliable = payload["reliable"] as? Bool
let metadata = payload["metadata"] as? [String: Any]
let connectionOptions = PeerConnectionOptions(connectionType: .data, connectionId: connectionId, payload: payload, metadata: metadata, label: label, serialization: serialization, isReliable: reliable, iceServerOptions: self.options?.iceServerOptions)
let dataConnection = DataConnection(peerId: peerId, delegate: self, options: connectionOptions)
self.connectionStore.addConnection(connection: dataConnection)
connection = dataConnection
//this.emit('connection', connection)
DispatchQueue.main.async {
self.delegate?.peer(self, didReceiveConnection: dataConnection)
}
}
else {
print("Received malformed connection type: \(connectionType)")
return
}
/*
// Find messages.
let messages = self.getMessages(connectionId)
for var message in messages {
self.handleMessage(connection, message: message)
}
*/
connection?.handleLostMessages()
}
default:
guard let peerId = message["src"] as? String else {
print("You received a malformed message \(message)")
return
}
guard let type = message["type"] as? String else {
print("You received a malformed message \(message)")
print("from \(peerId)")
return
}
guard let payload = message["payload"] as? [String: Any] else {
print("You received a malformed message \(message)")
print("from \(peerId) type \(type)")
return
}
guard let connectionId = payload["connectionId"] as? String else {
print("You received an unrecognized message: \(message)")
print("from \(peerId), type \(type), payload \(payload)")
return
}
guard let connection = self.connectionStore.findConnection(peerId: peerId, connectionId: connectionId) else {
print("You received an unrecognized message: \(message)")
print("from \(peerId), type \(type), payload \(payload), connectionId \(connectionId)")
return
}
if connection.pc != nil {
// Pass it on.
connection.handleMessage(message: message)
}
else {
// Store for possible later use
connection.storeMessage(message: message)
}
}
}
}
|
12b38e091f47686b21cc6e17d13cb17c
| 36.517544 | 270 | 0.545593 | false | false | false | false |
shoheiyokoyama/Gemini
|
refs/heads/master
|
Gemini/CustomAnimatable.swift
|
mit
|
1
|
extension GeminiAnimationModel {
struct Coordinate {
var x: CGFloat = 1
var y: CGFloat = 1
var z: CGFloat = 1
}
}
public protocol CustomAnimatable: EasingAnimatable, UIAppearanceAnimatable {
/// The Scale in 3-Dimensional vector.
/// The default value is (x: 1, y: 1, z: 1).
/// The range 0.0 to 1.0.
@discardableResult func scale(x: CGFloat, y: CGFloat, z: CGFloat) -> CustomAnimatable
@discardableResult func scaleEffect(_ effect: GeminScaleEffect) -> CustomAnimatable
/// The Angre of rotation in 3-Dimensional vector.
/// The default value is (x: 0, y: 0, z: 0).
/// The range 0.0 to 90.0.
@discardableResult func rotationAngle(x: CGFloat, y: CGFloat, z: CGFloat) -> CustomAnimatable
/// The translation in 3-Dimensional vector.
/// The default value is (x: 0, y: 0, z: 0).
@discardableResult func translation(x: CGFloat, y: CGFloat, z: CGFloat) -> CustomAnimatable
/// The anchor point of the layer's bounds rectangle.
/// The default value is (x: 0.5, y: 0.5).
/// - SeeAlso: [anchorPoint on Apple Developer Documentation](https://developer.apple.com/documentation/quartzcore/calayer/1410817-anchorpoint)
@discardableResult func anchorPoint(_ anchorPoint: CGPoint) -> CustomAnimatable
}
extension GeminiAnimationModel: CustomAnimatable {
public func scale(x: CGFloat = 1, y: CGFloat = 1, z: CGFloat = 1) -> CustomAnimatable {
scaleCoordinate.x = x
scaleCoordinate.y = y
scaleCoordinate.z = z
return self
}
@discardableResult
public func scaleEffect(_ effect: GeminScaleEffect) -> CustomAnimatable {
scaleEffect = effect
return self
}
@discardableResult
public func rotationAngle(x: CGFloat = 0, y: CGFloat = 0, z: CGFloat = 0) -> CustomAnimatable {
rotationCoordinate.x = x
rotationCoordinate.y = y
rotationCoordinate.z = z
return self
}
@discardableResult
public func translation(x: CGFloat = 0, y: CGFloat = 0, z: CGFloat = 0) -> CustomAnimatable {
translationCoordinate.x = x
translationCoordinate.y = y
translationCoordinate.z = z
return self
}
@discardableResult
public func anchorPoint(_ anchorPoint: CGPoint) -> CustomAnimatable {
self.anchorPoint = anchorPoint
return self
}
}
|
64b094170b248802731cf76c47111c86
| 34.537313 | 147 | 0.656447 | false | false | false | false |
Mars-Zhu/ImageUpload
|
refs/heads/master
|
BlogUpload/UploadView.swift
|
mit
|
1
|
//
// UploadView.swift
// BlogUpload
//
// Created by ZhuBicheng on 15/8/29.
// Copyright (c) 2015年 当扈. All rights reserved.
//
import Cocoa
protocol UploadViewProtocol {
func dragInto (path: String)
}
class UploadView: NSImageView {
var delegate: UploadViewProtocol?
var isHoveringFile:Bool = false
override func drawRect(var dirtyRect: NSRect) {
super.drawRect(dirtyRect)
let color = NSColor(calibratedRed: 0.7, green: 0.7, blue: 0.7, alpha: 1)
let color2 = NSColor(calibratedRed: 0.6, green: 0.6, blue: 0.6, alpha: 1)
let color3 = NSColor(calibratedRed: 0.4, green: 0.4, blue: 0.4, alpha: 1)
let color4 = NSColor(calibratedRed: 0, green: 0, blue: 0, alpha: 0.025)
let color5 = NSColor(calibratedRed: 0, green: 0, blue: 0, alpha: 0)
let backgroud = NSBezierPath(rect: dirtyRect)
isHoveringFile ? color4.setFill() : color5.setFill();
backgroud.fill()
dirtyRect = NSMakeRect(dirtyRect.origin.x + 5, dirtyRect.origin.y + 5, dirtyRect.size.width - 10, dirtyRect.size.height - 10)
let rounderRectanglePath = NSBezierPath(roundedRect: dirtyRect, xRadius: 8, yRadius: 8)
isHoveringFile ? color3.setFill() : color.setFill();
rounderRectanglePath.lineWidth = 2.0
var roundedRectanglePathern : [CGFloat] = [6.0,6.0,6.0,6.0];
rounderRectanglePath.setLineDash(&roundedRectanglePathern, count: 4, phase: 0)
rounderRectanglePath.stroke()
}
override func awakeFromNib() {
registerForDraggedTypes([NSFilenamesPboardType])
}
override func draggingEntered(sender: NSDraggingInfo) -> NSDragOperation {
// Swift.print("\(__FUNCTION__)")
return NSDragOperation.Copy
}
override func prepareForDragOperation(sender: NSDraggingInfo) -> Bool {
// Swift.print("\(__FUNCTION__)")
return true
}
override func performDragOperation(sender: NSDraggingInfo) -> Bool {
// Swift.print("\(__FUNCTION__)")
let draggedFiles = sender.draggingPasteboard().propertyListForType(NSFilenamesPboardType) as! [String]
for aString in draggedFiles {
delegate?.dragInto(aString)
}
return true
}
override func draggingExited(sender: NSDraggingInfo?) {
// Swift.print("\(__FUNCTION__)")
}
}
|
67ff889e1cf601e85f40f1865fe5b6f4
| 30.177215 | 133 | 0.6216 | false | false | false | false |
CodaFi/swift
|
refs/heads/main
|
test/Index/property_wrappers.swift
|
apache-2.0
|
19
|
// RUN: %target-swift-ide-test -print-indexed-symbols -source-filename %s | %FileCheck -check-prefix=CHECK %s
@propertyWrapper
public struct Wrapper<T> {
// CHECK: [[@LINE-1]]:15 | struct/Swift | Wrapper | [[Wrapper_USR:.*]] | Def | rel: 0
public var wrappedValue: T
// CHECK: [[@LINE-1]]:14 | instance-property/Swift | wrappedValue | [[wrappedValue_USR:.*]] | Def,RelChild | rel: 1
public init(initialValue: T) {
// CHECK: [[@LINE-1]]:10 | constructor/Swift | init(initialValue:) | [[WrapperInit_USR:.*]] | Def,RelChild | rel: 1
self.wrappedValue = initialValue
}
public init(body: () -> T) {
// CHECK: [[@LINE-1]]:10 | constructor/Swift | init(body:) | [[WrapperBodyInit_USR:.*]] | Def,RelChild | rel: 1
self.wrappedValue = body()
}
public var projectedValue: Projection<T> {
get { Projection(item: wrappedValue) }
}
}
public struct Projection<T> {
var item: T
}
var globalInt: Int { return 17 }
// CHECK: [[@LINE-1]]:5 | variable/Swift | globalInt | [[globalInt_USR:.*]] | Def | rel: 0
public struct HasWrappers {
@Wrapper
// CHECK: [[@LINE-1]]:4 | struct/Swift | Wrapper | [[Wrapper_USR]] | Ref | rel: 0
public var x: Int = globalInt
// CHECK-NOT: [[@LINE-1]]:23 | variable/Swift | globalInt
// CHECK: [[@LINE-4]]:4 | constructor/Swift | init(initialValue:) | [[WrapperInit_USR]] | Ref,Call,Impl | rel: 0
// CHECK: [[@LINE-3]]:14 | instance-property/Swift | x | [[x_USR:.*]] | Def,RelChild | rel: 1
// CHECK: [[@LINE-4]]:23 | variable/Swift | globalInt | [[globalInt_USR]] | Ref,Read | rel: 0
@Wrapper(body: { globalInt })
// CHECK: [[@LINE-1]]:4 | struct/Swift | Wrapper | [[Wrapper_USR]] | Ref | rel: 0
// CHECK: [[@LINE-2]]:20 | variable/Swift | globalInt | [[globalInt_USR]] | Ref,Read | rel: 0
// CHECK: [[@LINE-3]]:4 | constructor/Swift | init(body:) | [[WrapperBodyInit_USR]] | Ref,Call | rel: 0
public var y: Int
// CHECK: [[@LINE-1]]:14 | instance-property/Swift | y | [[y_USR:.*]] | Def,RelChild | rel: 1
// CHECK-NOT: [[@LINE-6]]:20 | variable/Swift | globalInt
@Wrapper(body: {
// CHECK: [[@LINE-1]]:4 | struct/Swift | Wrapper | [[Wrapper_USR]] | Ref | rel: 0
struct Inner {
@Wrapper
// CHECK: [[@LINE-1]]:8 | struct/Swift | Wrapper | [[Wrapper_USR]] | Ref | rel: 0
// CHECK: [[@LINE-2]]:8 | constructor/Swift | init(initialValue:) | [[WrapperInit_USR]] | Ref,Call,Impl | rel: 0
var x: Int = globalInt
// CHECK: [[@LINE-1]]:20 | variable/Swift | globalInt | [[globalInt_USR]] | Ref,Read | rel: 0
}
return Inner().x + globalInt
// CHECK: [[@LINE-1]]:24 | variable/Swift | globalInt | [[globalInt_USR]] | Ref,Read | rel: 0
})
// CHECK: [[@LINE-12]]:4 | constructor/Swift | init(body:) | [[WrapperBodyInit_USR]] | Ref,Call | rel: 0
public var z: Int
// CHECK: [[@LINE-1]]:14 | instance-property/Swift | z | [[z_USR:.*]] | Def,RelChild | rel: 1
func backingUse() {
_ = _y.wrappedValue + _z.wrappedValue + x + _x.wrappedValue + $y.item
// CHECK: [[@LINE-1]]:10 | instance-property/Swift | y | [[y_USR]] | Ref,Read,RelCont | rel: 1
// CHECK: [[@LINE-2]]:12 | instance-property/Swift | wrappedValue | [[wrappedValue_USR:.*]] | Ref,Read,RelCont | rel: 1
// CHECK: [[@LINE-3]]:28 | instance-property/Swift | z | [[z_USR]] | Ref,Read,RelCont | rel: 1
// CHECK: [[@LINE-4]]:45 | instance-property/Swift | x | [[x_USR]] | Ref,Read,RelCont | rel: 1
// CHECK: [[@LINE-5]]:50 | instance-property/Swift | x | [[x_USR]] | Ref,Read,RelCont | rel: 1
// CHECK: [[@LINE-6]]:68 | instance-property/Swift | y | [[y_USR]] | Ref,Read,RelCont | rel: 1
}
}
func useMemberwiseInits(i: Int) {
_ = HasWrappers(x: i)
_ = HasWrappers(y: Wrapper(initialValue: i))
}
|
4f112b641b951af20d6439573bb6527d
| 46.692308 | 123 | 0.598656 | false | false | false | false |
rafaelcpalmeida/UFP-iOS
|
refs/heads/master
|
UFP/UFP/QueueViewController.swift
|
mit
|
1
|
//
// FinalGrades.swift
// UFP
//
// Created by Rafael Almeida on 28/03/17.
// Copyright © 2017 Rafael Almeida. All rights reserved.
//
import UIKit
import SwiftyJSON
class QueueTableViewCell: UITableViewCell {
@IBOutlet weak var descriptionLabel: UILabel!
@IBOutlet weak var numberLabel: UILabel!
@IBOutlet weak var waitingLabel: UILabel!
@IBOutlet weak var lastUpdateLabel: UILabel!
}
class QueueViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
@IBOutlet weak var activityIndicator: UIActivityIndicatorView!
@IBOutlet weak var queueTable: UITableView!
let apiController = APIController()
let tableCellIdentifier = "tableCell"
var queueStatus = [Queue]()
var timer = Timer()
lazy var refreshControl: UIRefreshControl = {
let refreshControl = UIRefreshControl()
refreshControl.addTarget(self, action: #selector(QueueViewController.handleRefresh(_:)), for: UIControlEvents.valueChanged)
return refreshControl
}()
override func viewDidLoad() {
super.viewDidLoad()
queueTable.delegate = self
queueTable.dataSource = self
self.queueTable.addSubview(self.refreshControl)
fetchNewData()
Timer.scheduledTimer(timeInterval: 180, target: self, selector: #selector(self.fetchNewData), userInfo: nil, repeats: true)
}
@objc func handleRefresh(_ refreshControl: UIRefreshControl) {
fetchNewData(updated: true)
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.queueStatus.count
}
internal func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: tableCellIdentifier, for: indexPath as IndexPath) as! QueueTableViewCell
if self.queueStatus.indices.contains(indexPath.row) {
cell.descriptionLabel.text = String(format: NSLocalizedString("Service %@ - %@", comment: ""), self.queueStatus[indexPath.row].service, self.queueStatus[indexPath.row].description)
cell.numberLabel.text = String(format: NSLocalizedString("Number %@", comment: ""), self.queueStatus[indexPath.row].number)
if (Int(self.queueStatus[indexPath.row].waiting) == 0) {
cell.waitingLabel.isHidden = true
} else {
cell.waitingLabel.text = String(format: NSLocalizedString("%@ waiting", comment: ""), self.queueStatus[indexPath.row].waiting)
}
cell.lastUpdateLabel.text = String(format: NSLocalizedString("Last update - %@", comment: ""), self.queueStatus[indexPath.row].lastUpdate)
}
return cell
}
@objc func fetchNewData(updated: Bool = false) {
self.queueStatus.removeAll()
apiController.getQueueStatus(completionHandler: { (json, error) in
self.activityIndicator.stopAnimating()
if(json["status"] == "Ok") {
for (keyLevel, data) in json["message"] {
self.queueStatus.append(Queue(service: keyLevel, number: data["number"].stringValue, description: data["desc"].stringValue, waiting: data["waiting"].stringValue, lastUpdate: data["last_update"].stringValue))
}
} else {
}
self.queueTable.reloadData()
if updated {
self.refreshControl.endRefreshing()
}
})
}
}
|
c04e6aeb339eff6a791b6255cae6fee7
| 36.469388 | 227 | 0.636983 | false | false | false | false |
achimk/Cars
|
refs/heads/master
|
CarsApp/Repositories/Cars/Adapters/InMemoryCarsServiceAdapter.swift
|
mit
|
1
|
//
// InMemoryCarsServiceAdapter.swift
// CarsApp
//
// Created by Joachim Kret on 29/07/2017.
// Copyright © 2017 Joachim Kret. All rights reserved.
//
import Foundation
import RxSwift
final class InMemoryCarsServiceAdapter: CarsServiceType {
private let service = InMemoryCarsService()
init(_ models: Array<CarModel> = []) {
service.models = models
}
func requestCarsList() -> Observable<Array<CarType>> {
let service = self.service
return Observable.just(
service.models.map(CarsModelEntityMapper.from).flatMap { $0 }
)
}
func createCar(with model: CarCreateModel) -> Observable<Void> {
let service = self.service
let operation = Observable.create({ (observer: AnyObserver<Void>) -> Disposable in
let identifier = String(service.models.count.advanced(by: 1))
let car = CarModel(
id: identifier,
name: model.name,
model: model.model,
brand: model.brand,
year: model.year
)
service.models.append(car)
observer.onNext()
observer.onCompleted()
return Disposables.create()
})
return operation
}
func requestCarDetails(using identity: CarIdentityModel) -> Observable<CarType> {
let service = self.service
let operation = Observable.create { (observer: AnyObserver<CarType>) -> Disposable in
let model = service.models
.filter { $0.id == identity.id }
.first
.map(CarsModelEntityMapper.from)
if let model = model {
observer.onNext(model)
observer.onCompleted()
} else {
observer.onError(CarsServiceError.notFound)
}
return Disposables.create()
}
return operation
}
}
|
ea3657f061baa5dc67acafaf23078eb4
| 26.041667 | 93 | 0.57319 | false | false | false | false |
cliqz-oss/browser-ios
|
refs/heads/development
|
Shared/UserAgent.swift
|
mpl-2.0
|
2
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import AVFoundation
import UIKit
open class UserAgent {
fileprivate static var defaults = UserDefaults(suiteName: AppInfo.sharedContainerIdentifier())!
open static var syncUserAgent: String {
let appName = DeviceInfo.appName()
return "Firefox-iOS-Sync/\(AppInfo.appVersion) (\(appName))"
}
open static var tokenServerClientUserAgent: String {
let appName = DeviceInfo.appName()
return "Firefox-iOS-Token/\(AppInfo.appVersion) (\(appName))"
}
open static var fxaUserAgent: String {
let appName = DeviceInfo.appName()
return "Firefox-iOS-FxA/\(AppInfo.appVersion) (\(appName))"
}
/**
* Use this if you know that a value must have been computed before your
* code runs, or you don't mind failure.
*/
open static func cachedUserAgent(checkiOSVersion: Bool = true, checkFirefoxVersion: Bool = true) -> String? {
let currentiOSVersion = UIDevice.current.systemVersion
let lastiOSVersion = defaults.string(forKey: "LastDeviceSystemVersionNumber")
let currentFirefoxVersion = AppInfo.appVersion
let lastFirefoxVersion = defaults.string(forKey: "LastFirefoxVersionNumber")
if let firefoxUA = defaults.string(forKey: "UserAgent") {
if (!checkiOSVersion || (lastiOSVersion == currentiOSVersion))
&& (!checkFirefoxVersion || (lastFirefoxVersion == currentFirefoxVersion)){
return firefoxUA
}
}
return nil
}
/**
* This will typically return quickly, but can require creation of a UIWebView.
* As a result, it must be called on the UI thread.
*/
open static func defaultUserAgent() -> String {
assert(Thread.current.isMainThread, "This method must be called on the main thread.")
if let firefoxUA = UserAgent.cachedUserAgent(checkiOSVersion: true) {
return firefoxUA
}
let webView = UIWebView()
//Always use Chrome's latest (if we are still using Chrome's User Agent...see below)
let appVersion = "62.0"//AppInfo.appVersion
let currentiOSVersion = UIDevice.current.systemVersion
defaults.set(currentiOSVersion,forKey: "LastDeviceSystemVersionNumber")
defaults.set(appVersion, forKey: "LastFirefoxVersionNumber")
let userAgent = webView.stringByEvaluatingJavaScript(from: "navigator.userAgent")!
// Extract the WebKit version and use it as the Safari version.
let webKitVersionRegex = try! NSRegularExpression(pattern: "AppleWebKit/([^ ]+) ", options: [])
let match = webKitVersionRegex.firstMatch(in: userAgent, options:[],
range: NSMakeRange(0, userAgent.characters.count))
if match == nil {
print("Error: Unable to determine WebKit version in UA.")
return userAgent // Fall back to Safari's.
}
let webKitVersion = (userAgent as NSString).substring(with: match!.rangeAt(1))
// Insert "FxiOS/<version>" before the Mobile/ section.
let mobileRange = (userAgent as NSString).range(of: "Mobile/")
if mobileRange.location == NSNotFound {
print("Error: Unable to find Mobile section in UA.")
return userAgent // Fall back to Safari's.
}
let mutableUA = NSMutableString(string: userAgent)
mutableUA.insert("CriOS/\(appVersion) ", at: mobileRange.location)
let firefoxUA = "\(mutableUA) Safari/\(webKitVersion)"
defaults.set(firefoxUA, forKey: "UserAgent")
return firefoxUA
}
open static func desktopUserAgent() -> String {
let userAgent = NSMutableString(string: defaultUserAgent())
// Spoof platform section
let platformRegex = try! NSRegularExpression(pattern: "\\([^\\)]+\\)", options: [])
guard let platformMatch = platformRegex.firstMatch(in: userAgent as String, options:[], range: NSMakeRange(0, userAgent.length)) else {
print("Error: Unable to determine platform in UA.")
return String(userAgent)
}
userAgent.replaceCharacters(in: platformMatch.range, with: "(Macintosh; Intel Mac OS X 10_11_1)")
// Strip mobile section
let mobileRegex = try! NSRegularExpression(pattern: "CriOS/[^ ]+ Mobile/[^ ]+", options: [])
guard let mobileMatch = mobileRegex.firstMatch(in: userAgent as String, options:[], range: NSMakeRange(0, userAgent.length)) else {
print("Error: Unable to find Mobile section in UA.")
return String(userAgent)
}
userAgent.replaceCharacters(in: mobileMatch.range, with: "")
return String(userAgent)
}
}
|
74814639c1cf148e74bb710695264229
| 40.336134 | 143 | 0.653588 | false | false | false | false |
asurinsaka/swift_examples_2.1
|
refs/heads/master
|
yahooQuote/yahooQuote/main.swift
|
mit
|
1
|
//
// main.swift
// yahooQuote
//
// Created by larryhou on 4/16/15.
// Copyright (c) 2015 larryhou. All rights reserved.
//
import Foundation
var verbose = false
var eventTimeFormatter = NSDateFormatter()
eventTimeFormatter.dateFormat = "yyyy-MM-dd"
enum CooprActionType:String
{
case SPLIT = "SPLIT"
case DIVIDEND = "DIVIDEND"
}
struct CoorpAction:CustomStringConvertible
{
let date:NSDate
let type:CooprActionType
var value:Double
var description:String
{
let vstr = String(format:"%.6f", value)
return "\(eventTimeFormatter.stringFromDate(date))|\(vstr)|\(type.rawValue)"
}
}
func getQuoteRequest(ticket:String)->NSURLRequest
{
let formatter = NSDateFormatter()
formatter.dateFormat = "MM-dd-yyyy"
var date = formatter.stringFromDate(NSDate()).componentsSeparatedByString("-")
let url = "http://real-chart.finance.yahoo.com/table.csv?s=\(ticket)&d=\(date[0])&e=\(date[1])&f=\(date[2])&g=d&ignore=.csv"
return NSURLRequest(URL: NSURL(string: url)!)
}
func getCoorpActionRequest(ticket:String)->NSURLRequest
{
let formatter = NSDateFormatter()
formatter.dateFormat = "MM-dd-yyyy"
var date = formatter.stringFromDate(NSDate()).componentsSeparatedByString("-")
let url = "http://ichart.finance.yahoo.com/x?s=\(ticket)&d=\(date[0])&e=\(date[1])&f=\(date[2])&g=v"
return NSURLRequest(URL: NSURL(string: url)!)
}
var splits, dividends:[CoorpAction]!
func fetchCooprActions(request:NSURLRequest)
{
if verbose
{
print(request.URL!)
}
var coorpActions:[CoorpAction]!
let formatter = NSDateFormatter()
formatter.dateFormat = "yyyyMMdd"
var response:NSURLResponse?, error:NSError?
let data: NSData?
do {
data = try NSURLConnection.sendSynchronousRequest(request, returningResponse: &response)
} catch let error1 as NSError {
error = error1
data = nil
}
if error == nil && (response as! NSHTTPURLResponse).statusCode == 200
{
coorpActions = []
let list = (NSString(data: data!, encoding: NSUTF8StringEncoding) as! String).componentsSeparatedByCharactersInSet(NSCharacterSet.newlineCharacterSet())
for i in 1..<list.count
{
let line = list[i].stringByReplacingOccurrencesOfString(" ", withString: "", options: NSStringCompareOptions.ForcedOrderingSearch, range: nil)
let cols = line.componentsSeparatedByCharactersInSet(NSCharacterSet(charactersInString: ", "))
if cols.count < 3
{
continue
}
let type = CooprActionType(rawValue: cols[0])
let date = formatter.dateFromString(cols[1])
let value:Double
let digits = cols[2].componentsSeparatedByString(":").map({NSString(string:$0).doubleValue})
if type == CooprActionType.SPLIT
{
value = digits[0] / digits[1]
}
else
{
value = digits[0]
}
if type != nil && date != nil
{
coorpActions.append(CoorpAction(date: date!, type: type!, value: value))
}
}
if coorpActions.count == 0
{
coorpActions = nil
}
}
else
{
coorpActions = nil
if verbose
{
print(response == nil ? error! : response!)
}
}
if coorpActions != nil
{
coorpActions.sortInPlace({$0.date.timeIntervalSince1970 < $1.date.timeIntervalSince1970})
var values:[Double] = []
for i in 0..<coorpActions.count
{
if coorpActions[i].type == CooprActionType.SPLIT
{
splits = splits ?? []
splits.append(coorpActions[i])
values.append(coorpActions[i].value)
}
else
if coorpActions[i].type == CooprActionType.DIVIDEND
{
dividends = dividends ?? []
dividends.append(coorpActions[i])
}
}
if verbose
{
print(dividends)
print(splits)
}
if splits != nil
{
for i in 0..<splits.count
{
var multiple = values[i]
for j in (i + 1)..<splits.count
{
multiple *= values[j]
}
splits[i].value = multiple
}
}
}
else
{
dividends = nil
splits = nil
}
}
func createActionMap(list:[CoorpAction]?, formatter:NSDateFormatter)->[String:CoorpAction]
{
var map:[String:CoorpAction] = [:]
if list == nil
{
return map
}
for i in 0..<list!.count
{
let key = formatter.stringFromDate(list![i].date)
map[key] = list![i]
}
return map
}
func formatQuote(text:String)->String
{
let value = NSString(string: text).doubleValue
return String(format: "%6.2f", value)
}
func parseQuote(data:[String])
{
let formatter = NSDateFormatter()
formatter.dateFormat = "yyyy-MM-dd"
var dmap = createActionMap(dividends, formatter: formatter)
var splitAction:CoorpAction!
print("date,open,high,low,close,volume,split,dividend,adjclose")
for i in 0..<data.count
{
let cols = data[i].componentsSeparatedByString(",")
if cols.count < 7
{
continue
}
let date = formatter.dateFromString(cols[0])!
let open = formatQuote(cols[1])
let high = formatQuote(cols[2])
let low = formatQuote(cols[3])
let close = formatQuote(cols[4])
let volume = NSString(string: cols[5]).doubleValue
let adjclose = formatQuote(cols[6])
var msg = "\(cols[0]),\(open),\(high),\(low),\(close)," + String(format:"%10.0f", volume)
if splits != nil && splits.count > 0
{
while splits.count > 0
{
if (splitAction == nil || date.timeIntervalSinceDate(splitAction.date) >= 0)
&& date.timeIntervalSinceDate(splits[0].date) < 0
{
splitAction = splits.first!
}
else
{
break
}
splits.removeAtIndex(0)
}
}
else
{
if splitAction != nil && date.timeIntervalSinceDate(splitAction.date) >= 0
{
splitAction = nil
}
}
msg += "," + String(format:"%.6f", splitAction != nil ? splitAction.value : 1.0)
var dividend = 0.0, key = cols[0]
if dmap[key] != nil
{
dividend = dmap[key]!.value
}
msg += "," + String(format:"%.6f", dividend)
msg += ",\(adjclose)"
print(msg)
}
}
func fetchQuote(request:NSURLRequest)
{
if verbose
{
print(request.URL!)
}
var response:NSURLResponse?, error:NSError?
let data: NSData?
do {
data = try NSURLConnection.sendSynchronousRequest(request, returningResponse: &response)
} catch let error1 as NSError {
error = error1
data = nil
}
if error == nil && (response as! NSHTTPURLResponse).statusCode == 200
{
let text = NSString(data: data!, encoding: NSUTF8StringEncoding)!
var list = text.componentsSeparatedByCharactersInSet(NSCharacterSet.newlineCharacterSet())
list.removeAtIndex(0)
parseQuote(Array(list.reverse()))
}
else
{
if verbose
{
print(response == nil ? error! : response!)
}
}
}
func judge(@autoclosure condition:()->Bool, message:String)
{
if !condition()
{
print("ERR: " + message)
exit(1)
}
}
if Process.arguments.filter({$0 == "-h"}).count == 0
{
let count = Process.arguments.filter({$0 == "-t"}).count
judge(count >= 1, message: "[-t STOCK_TICKET] MUST be provided")
judge(count == 1, message: "[-t STOCK_TICKET] has been set \(count) times")
judge(Process.argc >= 3, message: "Unenough Parameters")
}
var ticket:String = "0700"
var skip:Bool = false
for i in 1..<Int(Process.argc)
{
let option = Process.arguments[i]
if skip
{
skip = false
continue
}
switch option
{
case "-t":
judge(Process.arguments.count > i + 1, message: "-t lack of parameter")
ticket = Process.arguments[i + 1]
skip = true
break
case "-v":
verbose = true
break
case "-h":
let msg = Process.arguments[0] + " -t STOCK_TICKET"
print(msg)
exit(0)
break
default:
print("Unsupported arguments: " + Process.arguments[i])
exit(2)
}
}
fetchCooprActions(getCoorpActionRequest(ticket))
fetchQuote(getQuoteRequest(ticket))
|
e9f0956a314a4fad9b843692810d1615
| 20.56 | 154 | 0.662735 | false | false | false | false |
mrahmiao/Velociraptor
|
refs/heads/master
|
Velociraptor/VLRStubbedPair.swift
|
mit
|
1
|
//
// VLRStubbedPair.swift
// Velociraptor
//
// Created by mrahmiao on 4/21/15.
// Copyright (c) 2015 Code4Blues. All rights reserved.
//
import Foundation
/**
An object contains both stubbed request and response. You can use methods
on the object to modify stub configurations.
*/
public class VLRStubbedPair {
/// Stubbed request information
var request: VLRStubbedRequest
/// Stubbed resposne information
var response: VLRStubbedResponse?
init(request: VLRStubbedRequest, response: VLRStubbedResponse? = nil) {
self.request = request
self.response = response
}
}
// MARK: - Printable
extension VLRStubbedPair: Printable {
public var description: String {
var text = "Request: \(request)\n"
if let response = response {
text += "Response: \(response)\n"
}
return text
}
}
// MARK: - DebugPrintable
extension VLRStubbedPair: DebugPrintable {
public var debugDescription: String {
return description
}
}
// MARK: - Request DSL
extension VLRStubbedPair {
/**
Specify the HTTP method of the request you want to stub.
:param: method HTTP method, see http://tools.ietf.org/html/rfc7231#section-4.3
:returns: An object you used to specify more stubbed information.
*/
public func requestHTTPMethod(method: VLRHTTPMethod) -> Self {
request.HTTPMethod = method
return self
}
/**
Adds an HTTP header to the stubbed request's HTTP header dictionary.
:param: value The value of the header field.
:param: field The name of the header field. In keeping with the HTTP RFC, HTTP header field names are case-insensitive. The value of the same header field will be replaced while the name of the header field will be remained (ignoring the new name of the header field).
:returns: An object you used to specify more stubbed information.
*/
public func requestHeaderValue(value: String, forHTTPHeaderField field: String) -> Self {
setValue(value, forHTTPHeaderField: field, inHTTPHeaderFields: &request.HTTPHeaderFields)
return self
}
/**
Replace all the header fileds of the stubbed request's HTTP header fields.
:param: headers The HTTP header fields.
:returns: An object you used to specify more stubbed information.
*/
public func requestHTTPHeaderFields(headers: [String: String]) -> Self {
request.HTTPHeaderFields = headers
return self
}
/**
Stub the HTTP body data of the request.
:param: data The stubbed HTTP body data.
:returns: An object you used to specify more stubbed information.
*/
public func requestBodyData(data: NSData) -> Self {
request.HTTPBody = data
request.HTTPHeaderFields["Content-Length"] = String(data.length)
return self
}
/**
TODO: requestParameters
Stub the request data. If the method of stubbed request is `GET`, `HEAD`
or `DELETE`, parameters will be appended to the URL query.
For other HTTP methods, parameters will be set as the body data of the
request, and the `Content-Type` header field will be set to
`application/x-www-form-urlencoded`.
:param: parameters The parameters attched to the stubbed request.
:returns: An object you used to specify more stubbed information.
*/
private func requestParameters(parameters: [String: AnyObject]) -> Self {
switch request.HTTPMethod {
case .GET, .HEAD, .DELETE:
println("TODO: encoded the parameters as a query string")
default:
request.HTTPHeaderFields["Content-Type"] = "x-www-form-urlencoded"
}
return self
}
}
// MARK: - Response DSL
extension VLRStubbedPair {
/**
Set the stubbed response.
:param: response An object contains all the stubbed response information.
:returns: An object you used to specify more stubbed information.
*/
public func response(response: VLRStubbedResponse) -> Self {
self.response = response
return self
}
/**
Adds an HTTP header to the stubbed response's HTTP header dictionary.
:param: value The value of the header field.
:param: field The name of the header field. In keeping with the HTTP RFC, HTTP header field names are case-insensitive. The value of the same header field will be replaced while the name of the header field will be remained (ignoring the new name of the header field).
:returns: An object you used to specify more stubbed information.
*/
public func responseHeaderValue(value: String, forHTTPHeaderField field: String) -> Self {
response = response ?? defaultResponseWithURL(request.URL)
setValue(value, forHTTPHeaderField: field, inHTTPHeaderFields: &response!.HTTPHeaderFields)
return self
}
/**
Replace all the header fileds of the stubbed response's HTTP header fields.
:param: headers The HTTP header fields.
:returns: An object you used to specify more stubbed information.
*/
public func responseHTTPHeaderFields(headers: [String: String]) -> Self {
response = response ?? defaultResponseWithURL(request.URL)
response?.HTTPHeaderFields = headers
return self
}
/**
Specify the status code and/or error of the stubbed response.
:param: statusCode The HTTP response status code. See http://tools.ietf.org/html/rfc7231#page-47
:returns: An object you used to specify more stubbed information.
*/
public func responseStatusCode(statusCode: Int) -> Self {
response = response ?? defaultResponseWithURL(request.URL)
response?.statusCode = statusCode
return self
}
/**
Specify the error that completion handler received.
:param: error The error that you will received in the completion handler.
:returns: An object you used to specify more stubbed information.
*/
public func failWithError(error: NSError) -> Self {
response = response ?? defaultResponseWithURL(request.URL)
response?.responseError = error
return self
}
/**
Specify the stubbed response data.
:param: data The HTTP body data you want to stubbed.
:returns: An object you used to specify more stubbed information.
*/
public func responseBodyData(data: NSData) -> Self {
response = response ?? defaultResponseWithURL(request.URL)
response?.HTTPBody = data
responseHeaderValue("\(data.length)", forHTTPHeaderField: "Content-Length")
return self
}
/**
Specify the an object as the stubbed response data. The object would be
decoded to JSON data. The `Content-Type` of the response header will be set to
`application/json; charset=utf-8`.
Note that only objects that satisfied the conditions listed in the documentation
of `NSJSONSerialization` could be converted to JSON. Otherwise, an exception will
be raised.
:param: object The JSON object that will be stubbed as the response data.
:returns: An object you used to specify more stubbed information.
*/
public func responseJSONObject(object: AnyObject) -> Self {
response = response ?? defaultResponseWithURL(request.URL)
if let JSONData = NSJSONSerialization.dataWithJSONObject(object, options: NSJSONWritingOptions.allZeros, error: nil) {
responseHeaderValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
responseBodyData(JSONData)
}
return self
}
/**
Specify the a JSON data object as the stubbed response data. This method is
equivalent to
`responseBodyData(JSONData).responseHeaderValue(value: "application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")`
:param: data The JSON data that will be stubbed as the response data.
:returns: An object you used to specify more stubbed information.
*/
public func responseJSONData(data: NSData) -> Self {
response = response ?? defaultResponseWithURL(request.URL)
responseHeaderValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
responseBodyData(data)
return self
}
/**
Specify the content of the file in current bundle as the stubbed response data.
:param: filename The name of the file.
:param: contentType The value of "Content-Type" in HTTP header fields.
:returns: An object you used to specify more stubbed information.
*/
public func responseContentsOfFile(filename: String, contentType: String? = nil) -> Self {
response = response ?? defaultResponseWithURL(request.URL)
if let contentType = contentType {
responseHeaderValue(contentType, forHTTPHeaderField: "Content-Type")
}
let bundle = NSBundle(forClass: VLRStubbedPair.self)
if let URL = bundle.URLForResource(filename, withExtension: nil), data = NSData(contentsOfURL: URL) {
responseBodyData(data)
}
return self
}
}
// MARK: - Private helpers
extension VLRStubbedPair {
/// Provide default stubbed response
private func defaultResponseWithURL(URL: VLRURLStringConvertible) -> VLRStubbedResponse {
return VLRStubbedResponse(URL: URL)
}
/**
Add header field to header fields. If same header name exists, the value
of the header will be replaced while ignoring the new header
name (case-insensitive).
*/
private func setValue(value: String, forHTTPHeaderField field: String, inout inHTTPHeaderFields fields: [String: String]) {
// Check whehter same header field exists
for (headerKey, headerValue) in fields {
// Same header field exists
if headerKey.lowercaseString == field.lowercaseString {
fields[headerKey] = value
return
}
}
// Insert new header field
fields[field] = value
}
}
|
15dbcc2c93c1729066d977dc85e6556d
| 30.298077 | 272 | 0.701557 | false | false | false | false |
anders617/ABCSV
|
refs/heads/master
|
ABCSV/ABCSV+String.swift
|
mit
|
2
|
//
// ABCSV+String.swift
// ABCSV
//
// Created by Anders Boberg on 1/27/16.
// Copyright © 2016 Anders boberg. All rights reserved.
//
import Foundation
extension String {
/**
Finds and returns all occurences of a given string in order, from lowest to highest indices.
*/
func rangesOfString(string:String, options:NSStringCompareOptions, range: Range<Index>?, locale: NSLocale?) -> [Range<Index>] {
var searchRange = range ?? Range(start: startIndex, end: endIndex)
var ranges:[Range<Index>] = []
while let newRange = self.rangeOfString(string,options: options,range: searchRange,locale: locale) {
ranges += [newRange]
searchRange.startIndex = newRange.endIndex
}
return ranges
}
func rangesOfString(string:String, options:NSStringCompareOptions, ranges: [Range<Index>], locale: NSLocale?) -> [Range<Index>] {
var foundRanges:[Range<Index>] = []
for range in ranges {
foundRanges += rangesOfString(string, options: options, range: range, locale: locale)
}
return foundRanges
}
}
|
23a8a82ea81cd49762e3919a6c567c06
| 34.3125 | 133 | 0.647476 | false | false | false | false |
pauljohanneskraft/Math
|
refs/heads/master
|
CoreMath/Classes/Functions/Discrete Functions/Sampling/SamplingRange.swift
|
mit
|
1
|
//
// InterpolationData.swift
// Math
//
// Created by Paul Kraft on 05.12.17.
// Copyright © 2017 pauljohanneskraft. All rights reserved.
//
import Foundation
public struct SamplingRange {
public static var zero = SamplingRange(start: 0, interval: 0, end: 0, count: 0)
public let start: Double
public let end: Double
public let interval: Double
public let count: Int
private init(start: Double, interval: Double, end: Double, count: Int) {
self.start = start
self.interval = interval
self.end = end
self.count = count
}
public init(start: Double, interval: Double, end: Double) {
self.init(start: start, interval: interval, end: end, count: lround((end - start) / interval) + 1)
}
public init(start: Double, interval: Double, count: Int) {
self.init(start: start, interval: interval, end: start + (interval * Double(count)), count: count)
}
public init(start: Double, end: Double, count: Int) {
self.init(start: start, interval: (end - start) / Double(count - 1), end: end, count: count)
}
public subscript(index: Int) -> Double {
return start + Double(index) * interval
}
public var isEmpty: Bool {
return start >= end
}
}
extension SamplingRange: Sequence {
public func makeIterator() -> Iterator {
return Iterator(range: self, index: 0)
}
public struct Iterator: IteratorProtocol {
var range: SamplingRange
var index = 0
public mutating func next() -> Double? {
let n = range.start + Double(index) * range.interval
guard n <= range.end else { return nil }
index += 1
return n
}
}
}
|
ac95a32a2f00b2d567ce60e375ada40e
| 27.725806 | 106 | 0.59854 | false | false | false | false |
NorgannasAddOns/ColorDial
|
refs/heads/master
|
ColorDial/Color.swift
|
agpl-3.0
|
1
|
//
// Color.swift
// ColorDial
//
// Created by Kenneth Allan on 11/12/2015.
// Copyright © 2015 Kenneth Allan. All rights reserved.
//
import Cocoa
extension NSColor {
func get(_ hue: UnsafeMutablePointer<CGFloat>, saturation: UnsafeMutablePointer<CGFloat>, lightness: UnsafeMutablePointer<CGFloat>, alpha: UnsafeMutablePointer<CGFloat>) {
var h, s, l: CGFloat
//let color = self.colorUsingColorSpaceName(NSCalibratedRGBColorSpace)!
let r = self.redComponent
let g = self.greenComponent
let b = self.blueComponent
let a = self.alphaComponent
h = 0
s = 0
let maxi: CGFloat = max(r, g, b)
let mini: CGFloat = min(r, g, b)
l = (mini + maxi) / 2
if l >= 0 {
let d = maxi - mini
s = l > 0.5 ? d / (2 - maxi - mini) : d / (maxi + mini)
if r == maxi {
h = (g - b) / d + (g < b ? 6 : 0)
} else if g == maxi {
h = (b - r) / d + 2
} else if b == maxi {
h = (r - g) / d + 4
}
h /= 6
}
hue.initialize(to: h)
saturation.initialize(to: s)
lightness.initialize(to: l)
alpha.initialize(to: a)
}
static func colorWith(_ hue: CGFloat, saturation: CGFloat, lightness: CGFloat, alpha: CGFloat) -> NSColor {
if saturation == 0 {
return NSColor(red: lightness, green: lightness, blue: lightness, alpha: alpha)
}
let q = lightness < 0.5 ? lightness * (1 + saturation) : lightness + saturation - lightness * saturation
let p = 2 * lightness - q
var rgb = [CGFloat](repeating: 0, count: 3)
rgb[0] = hue + 1 / 3
rgb[1] = hue
rgb[2] = hue - 1 / 3
for i in 0 ..< 3 {
if rgb[i] < 0 {
rgb[i] += 1
}
if rgb[i] > 1 {
rgb[i] -= 1
}
if rgb[i] * 6 < 1 {
rgb[i] = p + (q - p) * rgb[i] * 6
} else if rgb[i] * 2 < 1 {
rgb[i] = q
} else if rgb[i] * 3 < 2 {
rgb[i] = p + (q - p) * ((2/3) - rgb[i]) * 6
} else {
rgb[i] = p
}
}
let color = NSColor(red: rgb[0], green: rgb[1], blue: rgb[2], alpha: alpha)
return color
}
func colorDifference(_ with: NSColor) -> CGFloat {
let r: CGFloat = pow(self.redComponent-with.redComponent, 2.0)
let g: CGFloat = pow(self.greenComponent-with.greenComponent, 2.0)
let b: CGFloat = pow(self.blueComponent-with.blueComponent, 2.0)
let d: CGFloat = sqrt(r + g + b)
return d
}
}
func mapRange(_ value: CGFloat, _ fromLower: CGFloat, _ fromUpper: CGFloat, _ toLower: CGFloat, _ toUpper: CGFloat) -> CGFloat {
return (round((toLower) + (value - fromLower) * ((toUpper - toLower) / (fromUpper - fromLower))))
}
func convertHueRYBtoRGB(_ hue: CGFloat) -> CGFloat {
if hue < 60 { return (round((hue) * (35 / 60))) }
if hue < 122 { return mapRange(hue, 60, 122, 35, 60) }
if hue < 165 { return mapRange(hue, 122, 165, 60, 120) }
if hue < 218 { return mapRange(hue, 165, 218, 120, 180) }
if hue < 275 { return mapRange(hue, 218, 275, 180, 240) }
if hue < 330 { return mapRange(hue, 275, 330, 240, 300) }
return mapRange(hue, 330, 360, 300, 360)
}
func convertHueRGBtoRYB (_ hue: CGFloat) -> CGFloat {
if hue < 35 { return (round(CGFloat(hue) * (60 / 35))) }
if hue < 60 { return mapRange(hue, 35, 60, 60, 122) }
if hue < 120 { return mapRange(hue, 60, 120, 122, 165) }
if hue < 180 { return mapRange(hue, 120, 180, 165, 218) }
if hue < 240 { return mapRange(hue, 180, 240, 218, 275) }
if hue < 300 { return mapRange(hue, 240, 300, 275, 330) }
return mapRange(hue, 300, 360, 330, 360)
}
func addValueOverflowCap(_ v: CGFloat, _ add: CGFloat, cap: CGFloat = 100, min: CGFloat = -1, max: CGFloat = -1) -> CGFloat {
var w = v + add
if (min > -1 && w < min) { w = min }
if (max > -1 && w > max) { w = max }
if w > cap {
return cap
} else if w < 0 {
return 0
}
return w
}
func addValueOverflowFlip(_ v: CGFloat, _ add: CGFloat, cap: CGFloat = 100, lcap: CGFloat = 0, min: CGFloat = -1, max: CGFloat = -1) -> CGFloat {
var w = v + add
if (min > -1 && w < min) { w = min }
if (max > -1 && w > max) { w = max }
// If we overflow, need to subtract instead
if (w > cap || w < lcap) {
return v - add
}
return w
}
func addValueOverflowBounce(_ v: CGFloat, _ add: CGFloat, cap: CGFloat = 100, lcap: CGFloat = 0, min: CGFloat = -1, max: CGFloat = -1) -> CGFloat {
var w = v + add
if (min > -1 && w < min) { w = min }
if (max > -1 && w > max) { w = max }
// If we overflow, need to subtract overflow amount
if (w > cap) {
return cap - (w - cap)
} else if (w < lcap) {
return lcap + (lcap - w)
}
return w
}
func addValueOverflowSlow(_ v: CGFloat, _ add: CGFloat, cap: CGFloat = 100, lcap: CGFloat = 0, min: CGFloat = -1, max: CGFloat = -1, brake: CGFloat = -1) -> CGFloat {
var w = v + add
if (min > -1 && w < min) { w = min }
if (max > -1 && w > max) { w = max }
let b = brake > -1 ? brake : abs(add)
// Stop us from overflowing by slowing add down (by 50%) as we approch cap.
if (w > cap - b) {
let d = v - (cap - b)
w = v + (floor((add) * (d)/(b)))
return w
} else if (w < lcap + b) {
let d = lcap + b - w
w += (floor((d) / 2))
}
return w
}
func addValueOverflowOppose(_ v: CGFloat, _ add: CGFloat, cap: CGFloat = 100, roffs: CGFloat = 0) -> CGFloat {
var w = v + add
if w > cap { w = (roffs + w).truncatingRemainder(dividingBy: cap) }
return w
}
|
6435dced4d95e1f9f9cc43710c85d461
| 32.143646 | 175 | 0.504917 | false | false | false | false |
xhjkl/rayban
|
refs/heads/master
|
Rayban/MainView.swift
|
mit
|
1
|
//
// Overlay window main view
// which watches sources for changes,
// offers to select a new watching target
// and tells its subordinate Render View to recompile
// when needed
//
import Cocoa
class MainViewController: NSViewController {
lazy var openPanel: NSOpenPanel = {
let panel = NSOpenPanel()
panel.canChooseFiles = true
panel.canChooseDirectories = false
panel.allowsMultipleSelection = false
return panel
}()
lazy var detailsCallout: NSPopover = {
let callout = NSPopover()
callout.behavior = .transient
callout.contentViewController = self.detailsViewController
return callout
}()
lazy var detailsViewController: NSViewController = (
self.storyboard!.instantiateController(withIdentifier: "DetailsViewController")
) as! NSViewController
@IBOutlet weak var currentShaderField: NSTextField!
@IBOutlet weak var bottomStack: NSStackView!
@IBOutlet weak var renderView: RenderView!
private var filewatch = Filewatch()
private var targetPath = "" {
didSet {
targetFilenameDidChange(path: targetPath)
targetFileContentDidChange()
}
}
override func viewDidLoad() {
super.viewDidLoad()
renderView!.logListener = self
filewatch.addHandler { [weak self] in
self?.targetFileContentDidChange()
}
openPanel.orderFront(self)
let result = openPanel.runModal()
if result != NSFileHandlingPanelOKButton {
NSApp.terminate(self)
}
openPanel.close()
let path = openPanel.urls.first!.path
targetPath = path
filewatch.setTarget(path: targetPath)
}
private func targetFilenameDidChange(path: String) {
// Chop the home part
guard let home = ProcessInfo.processInfo.environment["HOME"] else {
// No home -- no chopping
currentShaderField.stringValue = path
return
}
var prettyPath = path
if prettyPath.hasPrefix(home) {
let afterHome = prettyPath.characters.index(prettyPath.startIndex, offsetBy: home.characters.count)
let pathAfterTilde = path.substring(from: afterHome)
prettyPath = "~"
if !pathAfterTilde.hasPrefix("/") {
prettyPath.append("/" as Character)
}
prettyPath.append(pathAfterTilde)
}
currentShaderField.stringValue = prettyPath
}
private func targetFileContentDidChange() {
let targetURL = URL(fileURLWithPath: targetPath)
// FS API could be slippery at times
var data = try? Data(contentsOf: targetURL)
if data == nil {
data = try? Data(contentsOf: targetURL)
if data == nil {
do {
data = try Data(contentsOf: targetURL)
} catch(let error) {
filewatch.setTarget(path: targetPath)
complainAboutFS(error: error, filewatch: filewatch.working)
}
}
}
guard data != nil else {
return
}
guard let source = String(data: data!, encoding: .utf8) else {
return
}
clearMessages()
renderView!.setSource(source)
// Reset the filewatch for the case when the editor writes by and moves over
filewatch.setTarget(path: targetPath)
if !filewatch.working {
complainAboutFilewatch()
}
}
@IBAction func moreButtonHasBeenClicked(_ sender: NSButton) {
self.detailsCallout.show(relativeTo: sender.frame, of: sender.superview!, preferredEdge: .minX)
}
@IBAction func currentShaderFieldHasBeenClicked(_ sender: AnyObject) {
openPanel.orderFront(self)
openPanel.begin(completionHandler: { [unowned self] status in
self.openPanel.orderOut(self)
if status != NSFileHandlingPanelOKButton {
return
}
let path = self.openPanel.urls.first!.path
self.targetPath = path
})
}
@IBAction func quitButtonHasBeenClicked(_ sender: AnyObject) {
NSApp.terminate(sender);
}
func clearMessages() {
DispatchQueue.main.async { [unowned self] in
self.bottomStack.arrangedSubviews.forEach { $0.removeFromSuperview() }
self.view.superview?.needsDisplay = true
}
}
func addMessage(severity: RenderLogMessageSeverity, header: String, body: String) {
DispatchQueue.main.async { [unowned self] in
self.bottomStack.addArrangedSubview(self.makeReportView(severity, header, body))
self.view.superview?.needsDisplay = true
}
}
private func complainAboutFS(error: Error, filewatch working: Bool) {
NSLog("run-time expectation violated:\n"
+ "detected change in target file; however could not read it: \n\(error)\n"
+ "continuing to watch the same file")
if !working {
NSLog("moreover, file watch mechanism could not open the file for reading; suspending")
}
}
private func complainAboutFilewatch() {
NSLog("could not attach watcher to the target file; try picking the file again")
}
private func makeReportView(_ severity: RenderLogMessageSeverity, _ header: String, _ message: String) -> NSView {
var bulletColor: NSColor! = nil
switch severity {
case .unknown:
bulletColor = NSColor(calibratedHue: 0.86, saturation: 0.9, brightness: 0.9, alpha: 1.0)
case .warning:
bulletColor = NSColor(calibratedHue: 0.14, saturation: 0.9, brightness: 0.9, alpha: 1.0)
case .error:
bulletColor = NSColor(calibratedHue: 0.01, saturation: 0.9, brightness: 0.9, alpha: 1.0)
}
let fontSize = NSFont.systemFontSize()
let sigilView = NSTextField()
sigilView.isEditable = false
sigilView.isSelectable = false
sigilView.isBordered = false
sigilView.drawsBackground = false
sigilView.font = NSFont.monospacedDigitSystemFont(ofSize: 1.4 * fontSize, weight: 1.0)
sigilView.textColor = bulletColor
sigilView.stringValue = "•"
sigilView.sizeToFit()
let headerView = NSTextField()
headerView.isEditable = false
headerView.isSelectable = false
headerView.isBordered = false
headerView.drawsBackground = false
headerView.font = NSFont.monospacedDigitSystemFont(ofSize: fontSize, weight: 1.0)
headerView.textColor = .white
headerView.stringValue = header
headerView.sizeToFit()
let messageView = NSTextField()
messageView.isEditable = false
messageView.isSelectable = true
messageView.isBordered = false
messageView.drawsBackground = false
messageView.font = NSFont.systemFont(ofSize: fontSize, weight: 0.1)
messageView.textColor = .white
messageView.stringValue = message
messageView.sizeToFit()
let container = NSStackView(views: [sigilView, headerView, messageView])
container.orientation = .horizontal
container.alignment = .firstBaseline
return container
}
}
extension MainViewController: RenderLogListener {
func onReport(_ message: RenderLogMessage) {
let (severity, row, column, body) = message
var header = ""
if let row = row, let column = column {
header = "\(row):\(column): "
}
addMessage(severity: severity, header: header, body: body)
}
}
class MainView: NSView {
let borderRadius = CGFloat(8)
let backgroundColor = NSColor(deviceRed: 0.0, green: 0.0, blue: 0.0, alpha: 0.7)
override init(frame: NSRect) {
super.init(frame: frame)
}
required init?(coder: NSCoder) {
super.init(coder: coder)
}
override func draw(_ dirtyRect: NSRect) {
super.draw(dirtyRect)
let roundedRect = NSBezierPath(
roundedRect: self.frame,
xRadius: self.borderRadius,
yRadius: self.borderRadius
)
self.backgroundColor.set()
roundedRect.fill()
}
}
|
b4144e5fa284d871884488345d7614bd
| 28.382813 | 116 | 0.688913 | false | false | false | false |
csontosgabor/Twitter_Post
|
refs/heads/master
|
Twitter_Post/Functions.swift
|
mit
|
1
|
//
// Functions.swift
// Twitter_Post
//
// Created by Gabor Csontos on 12/15/16.
// Copyright © 2016 GaborMajorszki. All rights reserved.
//
import Foundation
import Photos
//check PhotoIsAllowed
public func PhotoAutorizationStatusCheck() -> Bool {
let status = PHPhotoLibrary.authorizationStatus()
switch status {
case .authorized:
return true
case .denied, .restricted,.notDetermined:
PHPhotoLibrary.authorizationStatus()
return false
}
}
//AlertView on Controller
public func showAlertViewWithTitleAndText(_ title: String?, message: String, vc: UIViewController) {
let ac = UIAlertController(title: title, message: message, preferredStyle: .alert)
ac.addAction(UIAlertAction(title: "Okay", style: .default, handler: { (action) in
}))
vc.present(ac, animated: true, completion: nil)
}
//AlertView to open Settings
public func alertViewToOpenSettings(_ title: String?, message: String) {
let alertController = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.alert)
alertController.addAction(UIAlertAction(title: "Settings", style: .default, handler: { (UIAlertAction) in
openApplicationSettings()
}))
alertController.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.cancel, handler: nil))
let alertWindow = UIWindow(frame: UIScreen.main.bounds)
alertWindow.rootViewController = UIViewController()
alertWindow.windowLevel = UIWindowLevelAlert + 1;
alertWindow.makeKeyAndVisible()
alertWindow.rootViewController?.present(alertController, animated: true, completion: nil)
}
//Open settings function
public func openApplicationSettings() {
let urlObj = NSURL.init(string:UIApplicationOpenSettingsURLString)
if #available(iOS 10.0, *) {
UIApplication.shared.open(urlObj as! URL, options: [ : ], completionHandler: { Success in
})
} else {
let success = UIApplication.shared.openURL(urlObj as! URL)
print("Open \(urlObj): \(success)")
}
}
public func hideStatusBar(_ yOffset: CGFloat) {
let statusBarWindow = UIApplication.shared.value(forKey: "statusBarWindow") as! UIWindow
statusBarWindow.frame = CGRect(x: 0, y: yOffset, width: statusBarWindow.frame.size.width, height: statusBarWindow.frame.size.height)
}
|
ec73aee448cbd771711234378462a703
| 32.39726 | 136 | 0.696473 | false | false | false | false |
beforeload/love-finder-app
|
refs/heads/master
|
LoveFinder/ViewController.swift
|
mit
|
1
|
//
// ViewController.swift
// LoveFinder
//
// Created by daniel on 9/28/14.
// Copyright (c) 2014 beforeload. All rights reserved.
//
import UIKit
class ViewController: UIViewController, UITextFieldDelegate {
@IBOutlet weak var name: UITextField!
@IBOutlet weak var birthday: UIDatePicker!
@IBOutlet weak var hasHouse: UISwitch!
@IBOutlet weak var height: UILabel!
@IBOutlet weak var result: UITextView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
name.delegate = self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
@IBAction func heightChanged(slider: UISlider) {
var i = Int(slider.value)
slider.value = Float(i)
height.text = "\(i)厘米"
}
@IBAction func confirm(sender: UIButton) {
result.text = name.text
self.view.endEditing(true)
}
override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
self.view.endEditing(true)
}
// UITextFieldDelegate
func textFieldShouldReturn(textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
}
|
f9c7679cc268fe98ce23cb46f1f22ac6
| 24.48 | 80 | 0.653061 | false | false | false | false |
BirdBrainTechnologies/Hummingbird-iOS-Support
|
refs/heads/master
|
BirdBlox/BirdBlox/SwifterFiles/HttpResponse.swift
|
mit
|
1
|
//
// HttpResponse.swift
// Swifter
//
// Copyright (c) 2014-2016 Damian Kołakowski. All rights reserved.
//
import Foundation
public enum SerializationError: Error {
case invalidObject
case notSupported
}
public protocol HttpResponseBodyWriter {
func write(_ file: String.File) throws
func write(_ data: [UInt8]) throws
func write(_ data: ArraySlice<UInt8>) throws
func write(_ data: NSData) throws
func write(_ data: Data) throws
}
public enum HttpResponseBody {
case json(AnyObject)
case html(String)
case text(String)
case custom(Any, (Any) throws -> String)
public func content() -> (Int, ((HttpResponseBodyWriter) throws -> Void)?) {
do {
switch self {
case .json(let object):
#if os(Linux)
let data = [UInt8]("Not ready for Linux.".utf8)
return (data.count, {
try $0.write(data)
})
#else
guard JSONSerialization.isValidJSONObject(object) else {
throw SerializationError.invalidObject
}
let data = try JSONSerialization.data(withJSONObject: object)
return (data.count, {
try $0.write(data)
})
#endif
case .text(let body):
let data = [UInt8](body.utf8)
return (data.count, {
try $0.write(data)
})
case .html(let body):
let serialised = "<html><meta charset=\"UTF-8\"><body>\(body)</body></html>"
let data = [UInt8](serialised.utf8)
return (data.count, {
try $0.write(data)
})
case .custom(let object, let closure):
let serialised = try closure(object)
let data = [UInt8](serialised.utf8)
return (data.count, {
try $0.write(data)
})
}
} catch {
let data = [UInt8]("Serialisation error: \(error)".utf8)
return (data.count, {
try $0.write(data)
})
}
}
}
public enum HttpResponse {
case switchProtocols([String: String], (Socket) -> Void)
case ok(HttpResponseBody), created, accepted
case movedPermanently(String)
case badRequest(HttpResponseBody?), unauthorized, forbidden, notFound
case internalServerError
case raw(Int, String, [String:String]?, ((HttpResponseBodyWriter) throws -> Void)? )
public func statusCode() -> Int {
switch self {
case .switchProtocols(_, _) : return 101
case .ok(_) : return 200
case .created : return 201
case .accepted : return 202
case .movedPermanently : return 301
case .badRequest(_) : return 400
case .unauthorized : return 401
case .forbidden : return 403
case .notFound : return 404
case .internalServerError : return 500
case .raw(let code, _ , _, _) : return code
}
}
func reasonPhrase() -> String {
switch self {
case .switchProtocols(_, _) : return "Switching Protocols"
case .ok(_) : return "OK"
case .created : return "Created"
case .accepted : return "Accepted"
case .movedPermanently : return "Moved Permanently"
case .badRequest(_) : return "Bad Request"
case .unauthorized : return "Unauthorized"
case .forbidden : return "Forbidden"
case .notFound : return "Not Found"
case .internalServerError : return "Internal Server Error"
case .raw(_, let phrase, _, _) : return phrase
}
}
func headers() -> [String: String] {
//var headers = ["Server" : "Swifter \(HttpServer.VERSION)"]
var headers = ["Server" : "Swifter BBT mod version"]
switch self {
case .switchProtocols(let switchHeaders, _):
for (key, value) in switchHeaders {
headers[key] = value
}
case .ok(let body):
switch body {
case .json(_) : headers["Content-Type"] = "application/json"
case .html(_) : headers["Content-Type"] = "text/html"
default:break
}
case .movedPermanently(let location):
headers["Location"] = location
case .raw(_, _, let rawHeaders, _):
if let rawHeaders = rawHeaders {
for (k, v) in rawHeaders {
headers.updateValue(v, forKey: k)
}
}
default:break
}
return headers
}
public func content() -> (length: Int, write: ((HttpResponseBodyWriter) throws -> Void)?) {
switch self {
case .ok(let body) : return body.content()
case .badRequest(let body) : return body?.content() ?? (-1, nil)
case .raw(_, _, _, let writer) : return (-1, writer)
default : return (-1, nil)
}
}
func socketSession() -> ((Socket) -> Void)? {
switch self {
case .switchProtocols(_, let handler) : return handler
default: return nil
}
}
}
/**
Makes it possible to compare handler responses with '==', but
ignores any associated values. This should generally be what
you want. E.g.:
let resp = handler(updatedRequest)
if resp == .NotFound {
print("Client requested not found: \(request.url)")
}
*/
func ==(inLeft: HttpResponse, inRight: HttpResponse) -> Bool {
return inLeft.statusCode() == inRight.statusCode()
}
|
6ae68b26d99caddbeb9ed6a743eefd53
| 33.534483 | 95 | 0.510734 | false | false | false | false |
kciter/GlitchLabel
|
refs/heads/master
|
Sources/GlitchLabel.swift
|
mit
|
1
|
//
// GlitchLabel.swift
// GlitchLabel
//
// Created by LeeSunhyoup on 2016. 4. 22..
// Copyright © 2016년 Lee Sun-Hyoup. All rights reserved.
//
import UIKit
@IBDesignable
open class GlitchLabel: UILabel {
@IBInspectable open var amplitudeBase: Double = 2.0
@IBInspectable open var amplitudeRange: Double = 1.0
@IBInspectable open var glitchAmplitude: Double = 10.0
@IBInspectable open var glitchThreshold: Double = 0.9
@IBInspectable open var alphaMin: Double = 0.8
@IBInspectable open var glitchEnabled: Bool = true
@IBInspectable open var drawScanline: Bool = true
open var blendMode: CGBlendMode = .lighten
fileprivate var channel: Int = 0
fileprivate var amplitude: Double = 2.5
fileprivate var phase: Double = 0.9
fileprivate var phaseStep: Double = 0.05
fileprivate var globalAlpha: Double = 0.8
override public init(frame: CGRect) {
super.init(frame: frame)
setTimer()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setTimer()
}
override open func drawText(in rect: CGRect) {
if !glitchEnabled {
super.drawText(in: rect)
return
}
var x0 = CGFloat(amplitude * sin((.pi * 2.0) * phase))
if random() >= glitchThreshold {
x0 *= CGFloat(glitchAmplitude)
}
let x1 = CGFloat(Int(bounds.origin.x))
let x2 = x1 + x0
let x3 = x1 - x0
globalAlpha = alphaMin + ((1 - alphaMin) * random())
var channelsImage: UIImage?
switch channel {
case 0:
channelsImage = getChannelsImage(x1, x2: x2, x3: x3)
case 1:
channelsImage = getChannelsImage(x2, x2: x3, x3: x1)
case 2:
channelsImage = getChannelsImage(x3, x2: x1, x3: x2)
default:
print("ERROR")
}
channelsImage?.draw(in: bounds)
if let channelsImage = channelsImage , drawScanline {
getScanlineImage(channelsImage).draw(in: bounds)
if floor(random() * 2) > 1 {
getScanlineImage(channelsImage).draw(in: bounds)
}
}
}
fileprivate func getChannelsImage(_ x1: CGFloat, x2: CGFloat, x3: CGFloat) -> UIImage {
let redImage = getRedImage(bounds)
let greenImage = getGreenImage(bounds)
let blueImage = getBlueImage(bounds)
UIGraphicsBeginImageContextWithOptions(bounds.size, false, UIScreen.main.scale)
redImage.draw(in: bounds + CGRect(x: x1, y: 0, width: 0, height: 0),
blendMode: blendMode,
alpha: CGFloat(globalAlpha))
greenImage.draw(in: bounds + CGRect(x: x2, y: 0, width: 0, height: 0),
blendMode: blendMode,
alpha: CGFloat(globalAlpha))
blueImage.draw(in: bounds + CGRect(x: x3, y: 0, width: 0, height: 0),
blendMode: blendMode,
alpha: CGFloat(globalAlpha))
let channelsImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return channelsImage!
}
fileprivate func getScanlineImage(_ channelsImage: UIImage) -> UIImage {
let y = bounds.size.height * CGFloat(random())
let y2 = bounds.size.height * CGFloat(random())
UIGraphicsBeginImageContextWithOptions(bounds.size, false, UIScreen.main.scale)
let context = UIGraphicsGetCurrentContext()
let provider: CGDataProvider = channelsImage.cgImage!.dataProvider!
let data: Data = provider.data! as Data
let bytes = (data as NSData).bytes
let bytePointer = bytes.assumingMemoryBound(to: UInt8.self)
for col in 0 ..< Int(bounds.size.width) {
let offset = 4*(Int(y) * Int(bounds.size.width) + col)
let alpha = bytePointer[offset]
let red = bytePointer[offset+1]
let green = bytePointer[offset+2]
let blue = bytePointer[offset+3]
context?.setFillColor(red: CGFloat(red), green: CGFloat(green), blue: CGFloat(blue), alpha: CGFloat(alpha))
context?.fill(CGRect(x: CGFloat(col), y: y2, width: 1, height: 0.5))
}
let scanlineImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return scanlineImage!
}
fileprivate func getRedImage(_ rect: CGRect) -> UIImage {
UIGraphicsBeginImageContextWithOptions(rect.size, false, UIScreen.main.scale)
text?.draw(in: rect, withAttributes: [
NSAttributedString.Key.font: UIFont.init(name: font.fontName, size: font.pointSize)!,
NSAttributedString.Key.foregroundColor: UIColor.red
])
let redImage: UIImage = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
return redImage
}
fileprivate func getGreenImage(_ rect: CGRect) -> UIImage {
UIGraphicsBeginImageContextWithOptions(rect.size, false, UIScreen.main.scale)
text?.draw(in: rect, withAttributes: [
NSAttributedString.Key.font: UIFont.init(name: font.fontName, size: font.pointSize)!,
NSAttributedString.Key.foregroundColor: UIColor.green
])
let greenImage: UIImage = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
return greenImage
}
fileprivate func getBlueImage(_ rect: CGRect) -> UIImage {
UIGraphicsBeginImageContextWithOptions(rect.size, false, UIScreen.main.scale)
text?.draw(in: rect, withAttributes: [
NSAttributedString.Key.font: UIFont.init(name: font.fontName, size: font.pointSize)!,
NSAttributedString.Key.foregroundColor: UIColor.blue
])
let blueImage: UIImage = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
return blueImage
}
@objc fileprivate func tick() {
phase += phaseStep
if phase > 1 {
phase = 0
channel = (channel == 2) ? 0 : channel + 1
amplitude = amplitudeBase + (amplitudeRange * random())
}
setNeedsDisplay()
}
fileprivate func setTimer() {
let timer = Timer(timeInterval: 1/30.0,
target: self,
selector: #selector(GlitchLabel.tick),
userInfo: nil,
repeats: true)
RunLoop.current.add(timer, forMode: RunLoop.Mode.default)
}
fileprivate func random() -> Double {
return (Double(arc4random()) / Double(UINT32_MAX))
}
}
func +(rect1: CGRect, rect2: CGRect) -> CGRect {
return CGRect(x: rect1.origin.x + rect2.origin.x,
y: rect1.origin.y + rect2.origin.y,
width: rect1.size.width + rect2.size.width,
height: rect1.size.height + rect2.size.height)
}
func +(size1: CGSize, size2: CGSize) -> CGSize {
return CGSize(width: size1.width + size2.width,
height: size1.height + size2.height)
}
|
eb8bc273348ea73e9f5648739be1beb8
| 35.336585 | 119 | 0.587327 | false | false | false | false |
cbpowell/MarqueeLabel-Swift
|
refs/heads/master
|
Classes/MarqueeLabel.swift
|
mit
|
1
|
//
// MarqueeLabel.swift
//
// Created by Charles Powell on 8/6/14.
// Copyright (c) 2015 Charles Powell. All rights reserved.
//
import UIKit
import QuartzCore
public class MarqueeLabel: UILabel {
/**
An enum that defines the types of `MarqueeLabel` scrolling
- LeftRight: Scrolls left first, then back right to the original position.
- RightLeft: Scrolls right first, then back left to the original position.
- Continuous: Continuously scrolls left (with a pause at the original position if animationDelay is set).
- ContinuousReverse: Continuously scrolls right (with a pause at the original position if animationDelay is set).
*/
public enum Type {
case LeftRight
case RightLeft
case Continuous
case ContinuousReverse
}
//
// MARK: - Public properties
//
/**
Defines the direction and method in which the `MarqueeLabel` instance scrolls.
`MarqueeLabel` supports four types of scrolling: `MLLeftRight`, `MLRightLeft`, `MLContinuous`, and `MLContinuousReverse`.
Given the nature of how text direction works, the options for the `marqueeType` property require specific text alignments
and will set the textAlignment property accordingly.
- `MLLeftRight` type is ONLY compatible with a label text alignment of `NSTextAlignmentLeft`.
- `MLRightLeft` type is ONLY compatible with a label text alignment of `NSTextAlignmentRight`.
- `MLContinuous` does not require a text alignment (it is effectively centered).
- `MLContinuousReverse` does not require a text alignment (it is effectively centered).
Defaults to `MLContinuous`.
- SeeAlso: Type
- SeeAlso: textAlignment
*/
public var type: Type = .Continuous {
didSet {
if type == oldValue {
return
}
updateAndScroll()
}
}
/**
Specifies the animation curve used in the scrolling motion of the labels.
Allowable options:
- `UIViewAnimationOptionCurveEaseInOut`
- `UIViewAnimationOptionCurveEaseIn`
- `UIViewAnimationOptionCurveEaseOut`
- `UIViewAnimationOptionCurveLinear`
Defaults to `UIViewAnimationOptionCurveEaseInOut`.
*/
public var animationCurve: UIViewAnimationCurve = .Linear
/**
A boolean property that sets whether the `MarqueeLabel` should behave like a normal `UILabel`.
When set to `true` the `MarqueeLabel` will behave and look like a normal `UILabel`, and will not begin any scrolling animations.
Changes to this property take effect immediately, removing any in-flight animation as well as any edge fade. Note that `MarqueeLabel`
will respect the current values of the `lineBreakMode` and `textAlignment`properties while labelized.
To simply prevent automatic scrolling, use the `holdScrolling` property.
Defaults to `false`.
- SeeAlso: holdScrolling
- SeeAlso: lineBreakMode
@warning The label will not automatically scroll when this property is set to `YES`.
@warning The UILabel default setting for the `lineBreakMode` property is `NSLineBreakByTruncatingTail`, which truncates
the text adds an ellipsis glyph (...). Set the `lineBreakMode` property to `NSLineBreakByClipping` in order to avoid the
ellipsis, especially if using an edge transparency fade.
*/
@IBInspectable public var labelize: Bool = false {
didSet {
if labelize != oldValue {
updateAndScroll()
}
}
}
/**
A boolean property that sets whether the `MarqueeLabel` should hold (prevent) automatic label scrolling.
When set to `true`, `MarqueeLabel` will not automatically scroll even its text is larger than the specified frame,
although the specified edge fades will remain.
To set `MarqueeLabel` to act like a normal UILabel, use the `labelize` property.
Defaults to `false`.
- SeeAlso: labelize
@warning The label will not automatically scroll when this property is set to `YES`.
*/
@IBInspectable public var holdScrolling: Bool = false {
didSet {
if holdScrolling != oldValue {
if oldValue == true && !(awayFromHome || labelize || tapToScroll ) && labelShouldScroll() {
beginScroll()
}
}
}
}
/**
A boolean property that sets whether the `MarqueeLabel` should only begin a scroll when tapped.
If this property is set to `true`, the `MarqueeLabel` will only begin a scroll animation cycle when tapped. The label will
not automatically being a scroll. This setting overrides the setting of the `holdScrolling` property.
Defaults to `false`.
@warning The label will not automatically scroll when this property is set to `false`.
- SeeAlso: holdScrolling
*/
@IBInspectable public var tapToScroll: Bool = false {
didSet {
if tapToScroll != oldValue {
if tapToScroll {
let tapRecognizer = UITapGestureRecognizer(target: self, action: #selector(MarqueeLabel.labelWasTapped(_:)))
self.addGestureRecognizer(tapRecognizer)
userInteractionEnabled = true
} else {
if let recognizer = self.gestureRecognizers!.first as UIGestureRecognizer? {
self.removeGestureRecognizer(recognizer)
}
userInteractionEnabled = false
}
}
}
}
/**
A read-only boolean property that indicates if the label's scroll animation has been paused.
- SeeAlso: pauseLabel
- SeeAlso: unpauseLabel
*/
public var isPaused: Bool {
return (sublabel.layer.speed == 0.0)
}
/**
A boolean property that indicates if the label is currently away from the home location.
The "home" location is the traditional location of `UILabel` text. This property essentially reflects if a scroll animation is underway.
*/
public var awayFromHome: Bool {
if let presentationLayer = sublabel.layer.presentationLayer() as? CALayer {
return !(presentationLayer.position.x == homeLabelFrame.origin.x)
}
return false
}
/**
The `MarqueeLabel` scrolling speed may be defined by one of two ways:
- Rate(CGFloat): The speed is defined by a rate of motion, in units of points per second.
- Duration(CGFloat): The speed is defined by the time to complete a scrolling animation cycle, in units of seconds.
Each case takes an associated `CGFloat` value, which is the rate/duration desired.
*/
public enum SpeedLimit {
case Rate(CGFloat)
case Duration(CGFloat)
var value: CGFloat {
switch self {
case .Rate(let rate):
return rate
case .Duration(let duration):
return duration
}
}
}
/**
Defines the speed of the `MarqueeLabel` scrolling animation.
The speed is set by specifying a case of the `SpeedLimit` enum along with an associated value.
- SeeAlso: SpeedLimit
*/
public var speed: SpeedLimit = .Duration(7.0) {
didSet {
switch (speed, oldValue) {
case (.Rate(let a), .Rate(let b)) where a == b:
return
case (.Duration(let a), .Duration(let b)) where a == b:
return
default:
updateAndScroll()
}
}
}
// @available attribute seems to cause SourceKit to crash right now
// @available(*, deprecated = 2.6, message = "Use speed property instead")
@IBInspectable public var scrollDuration: CGFloat? {
get {
switch speed {
case .Duration(let duration): return duration
case .Rate(_): return nil
}
}
set {
if let duration = newValue {
speed = .Duration(duration)
}
}
}
// @available attribute seems to cause SourceKit to crash right now
// @available(*, deprecated = 2.6, message = "Use speed property instead")
@IBInspectable public var scrollRate: CGFloat? {
get {
switch speed {
case .Duration(_): return nil
case .Rate(let rate): return rate
}
}
set {
if let rate = newValue {
speed = .Rate(rate)
}
}
}
/**
A buffer (offset) between the leading edge of the label text and the label frame.
This property adds additional space between the leading edge of the label text and the label frame. The
leading edge is the edge of the label text facing the direction of scroll (i.e. the edge that animates
offscreen first during scrolling).
Defaults to `0`.
- Note: The value set to this property affects label positioning at all times (including when `labelize` is set to `true`),
including when the text string length is short enough that the label does not need to scroll.
- Note: For Continuous-type labels, the smallest value of `leadingBuffer`, `trailingBuffer`, and `fadeLength`
is used as spacing between the two label instances. Zero is an allowable value for all three properties.
- SeeAlso: trailingBuffer
*/
@IBInspectable public var leadingBuffer: CGFloat = 0.0 {
didSet {
if leadingBuffer != oldValue {
updateAndScroll()
}
}
}
/**
A buffer (offset) between the trailing edge of the label text and the label frame.
This property adds additional space (buffer) between the trailing edge of the label text and the label frame. The
trailing edge is the edge of the label text facing away from the direction of scroll (i.e. the edge that animates
offscreen last during scrolling).
Defaults to `0`.
- Note: The value set to this property has no effect when the `labelize` property is set to `true`.
- Note: For Continuous-type labels, the smallest value of `leadingBuffer`, `trailingBuffer`, and `fadeLength`
is used as spacing between the two label instances. Zero is an allowable value for all three properties.
- SeeAlso: leadingBuffer
*/
@IBInspectable public var trailingBuffer: CGFloat = 0.0 {
didSet {
if trailingBuffer != oldValue {
updateAndScroll()
}
}
}
/**
The length of transparency fade at the left and right edges of the frame.
This propery sets the size (in points) of the view edge transparency fades on the left and right edges of a `MarqueeLabel`. The
transparency fades from an alpha of 1.0 (fully visible) to 0.0 (fully transparent) over this distance. Values set to this property
will be sanitized to prevent a fade length greater than 1/2 of the frame width.
Defaults to `0`.
*/
@IBInspectable public var fadeLength: CGFloat = 0.0 {
didSet {
if fadeLength != oldValue {
applyGradientMask(fadeLength, animated: true)
updateAndScroll()
}
}
}
/**
The length of delay in seconds that the label pauses at the completion of a scroll.
*/
@IBInspectable public var animationDelay: CGFloat = 1.0
//
// MARK: - Class Functions and Helpers
//
/**
Convenience method to restart all `MarqueeLabel` instances that have the specified view controller in their next responder chain.
- Parameter controller: The view controller for which to restart all `MarqueeLabel` instances.
- Warning: View controllers that appear with animation (such as from underneath a modal-style controller) can cause some `MarqueeLabel` text
position "jumping" when this method is used in `viewDidAppear` if scroll animations are already underway. Use this method inside `viewWillAppear:`
instead to avoid this problem.
- Warning: This method may not function properly if passed the parent view controller when using view controller containment.
- SeeAlso: restartLabel
- SeeAlso: controllerViewDidAppear:
- SeeAlso: controllerViewWillAppear:
*/
class func restartLabelsOfController(controller: UIViewController) {
MarqueeLabel.notifyController(controller, message: .Restart)
}
/**
Convenience method to restart all `MarqueeLabel` instances that have the specified view controller in their next responder chain.
Alternative to `restartLabelsOfController`. This method is retained for backwards compatibility and future enhancements.
- Parameter controller: The view controller that will appear.
- SeeAlso: restartLabel
- SeeAlso: controllerViewDidAppear
*/
class func controllerViewWillAppear(controller: UIViewController) {
MarqueeLabel.restartLabelsOfController(controller)
}
/**
Convenience method to restart all `MarqueeLabel` instances that have the specified view controller in their next responder chain.
Alternative to `restartLabelsOfController`. This method is retained for backwards compatibility and future enhancements.
- Parameter controller: The view controller that did appear.
- SeeAlso: restartLabel
- SeeAlso: controllerViewWillAppear
*/
class func controllerViewDidAppear(controller: UIViewController) {
MarqueeLabel.restartLabelsOfController(controller)
}
/**
Labelizes all `MarqueeLabel` instances that have the specified view controller in their next responder chain.
The `labelize` property of all recognized `MarqueeLabel` instances will be set to `true`.
- Parameter controller: The view controller for which all `MarqueeLabel` instances should be labelized.
- SeeAlso: labelize
*/
class func controllerLabelsLabelize(controller: UIViewController) {
MarqueeLabel.notifyController(controller, message: .Labelize)
}
/**
De-labelizes all `MarqueeLabel` instances that have the specified view controller in their next responder chain.
The `labelize` property of all recognized `MarqueeLabel` instances will be set to `false`.
- Parameter controller: The view controller for which all `MarqueeLabel` instances should be de-labelized.
- SeeAlso: labelize
*/
class func controllerLabelsAnimate(controller: UIViewController) {
MarqueeLabel.notifyController(controller, message: .Animate)
}
//
// MARK: - Initialization
//
/**
Returns a newly initialized `MarqueeLabel` instance with the specified scroll rate and edge transparency fade length.
- Parameter frame: A rectangle specifying the initial location and size of the view in its superview's coordinates. Text (for the given font, font size, etc.) that does not fit in this frame will automatically scroll.
- Parameter pixelsPerSec: A rate of scroll for the label scroll animation. Must be non-zero. Note that this will be the peak (mid-transition) rate for ease-type animation.
- Parameter fadeLength: A length of transparency fade at the left and right edges of the `MarqueeLabel` instance's frame.
- Returns: An initialized `MarqueeLabel` object or nil if the object couldn't be created.
- SeeAlso: fadeLength
*/
init(frame: CGRect, rate: CGFloat, fadeLength fade: CGFloat) {
speed = .Rate(rate)
fadeLength = CGFloat(min(fade, frame.size.width/2.0))
super.init(frame: frame)
setup()
}
/**
Returns a newly initialized `MarqueeLabel` instance with the specified scroll rate and edge transparency fade length.
- Parameter frame: A rectangle specifying the initial location and size of the view in its superview's coordinates. Text (for the given font, font size, etc.) that does not fit in this frame will automatically scroll.
- Parameter scrollDuration: A scroll duration the label scroll animation. Must be non-zero. This will be the duration that the animation takes for one-half of the scroll cycle in the case of left-right and right-left marquee types, and for one loop of a continuous marquee type.
- Parameter fadeLength: A length of transparency fade at the left and right edges of the `MarqueeLabel` instance's frame.
- Returns: An initialized `MarqueeLabel` object or nil if the object couldn't be created.
- SeeAlso: fadeLength
*/
init(frame: CGRect, duration: CGFloat, fadeLength fade: CGFloat) {
speed = .Duration(duration)
fadeLength = CGFloat(min(fade, frame.size.width/2.0))
super.init(frame: frame)
setup()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
/**
Returns a newly initialized `MarqueeLabel` instance.
The default scroll duration of 7.0 seconds and fade length of 0.0 are used.
- Parameter frame: A rectangle specifying the initial location and size of the view in its superview's coordinates. Text (for the given font, font size, etc.) that does not fit in this frame will automatically scroll.
- Returns: An initialized `MarqueeLabel` object or nil if the object couldn't be created.
*/
convenience public override init(frame: CGRect) {
self.init(frame: frame, duration:7.0, fadeLength:0.0)
}
private func setup() {
// Create sublabel
sublabel = UILabel(frame: self.bounds)
sublabel.tag = 700
sublabel.layer.anchorPoint = CGPoint.zero
// Add sublabel
addSubview(sublabel)
// Configure self
super.clipsToBounds = true
super.numberOfLines = 1
// Add notification observers
// Custom class notifications
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(MarqueeLabel.restartForViewController(_:)), name: MarqueeKeys.Restart.rawValue, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(MarqueeLabel.labelizeForController(_:)), name: MarqueeKeys.Labelize.rawValue, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(MarqueeLabel.animateForController(_:)), name: MarqueeKeys.Animate.rawValue, object: nil)
// UIApplication state notifications
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(MarqueeLabel.restartLabel), name: UIApplicationDidBecomeActiveNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(MarqueeLabel.shutdownLabel), name: UIApplicationDidEnterBackgroundNotification, object: nil)
}
override public func awakeFromNib() {
super.awakeFromNib()
forwardPropertiesToSublabel()
}
private func forwardPropertiesToSublabel() {
/*
Note that this method is currently ONLY called from awakeFromNib, i.e. when
text properties are set via a Storyboard. As the Storyboard/IB doesn't currently
support attributed strings, there's no need to "forward" the super attributedString value.
*/
// Since we're a UILabel, we actually do implement all of UILabel's properties.
// We don't care about these values, we just want to forward them on to our sublabel.
let properties = ["baselineAdjustment", "enabled", "highlighted", "highlightedTextColor",
"minimumFontSize", "shadowOffset", "textAlignment",
"userInteractionEnabled", "adjustsFontSizeToFitWidth",
"lineBreakMode", "numberOfLines"]
// Iterate through properties
sublabel.text = super.text
sublabel.font = super.font
sublabel.textColor = super.textColor
sublabel.backgroundColor = super.backgroundColor ?? UIColor.clearColor()
sublabel.shadowColor = super.shadowColor
sublabel.shadowOffset = super.shadowOffset
for prop in properties {
let value: AnyObject! = super.valueForKey(prop)
sublabel.setValue(value, forKeyPath: prop)
}
}
//
// MARK: - MarqueeLabel Heavy Lifting
//
override public func layoutSubviews() {
super.layoutSubviews()
updateAndScroll(true)
}
override public func willMoveToWindow(newWindow: UIWindow?) {
if newWindow == nil {
shutdownLabel()
}
}
override public func didMoveToWindow() {
if self.window == nil {
shutdownLabel()
} else {
updateAndScroll()
}
}
private func updateAndScroll() {
updateAndScroll(true)
}
private func updateAndScroll(shouldBeginScroll: Bool) {
// Check if scrolling can occur
if !labelReadyForScroll() {
return
}
// Calculate expected size
let expectedLabelSize = sublabelSize()
// Invalidate intrinsic size
invalidateIntrinsicContentSize()
// Move label to home
returnLabelToHome()
// Check if label should scroll
// Note that the holdScrolling propery does not affect this
if !labelShouldScroll() {
// Set text alignment and break mode to act like a normal label
sublabel.textAlignment = super.textAlignment
sublabel.lineBreakMode = super.lineBreakMode
var unusedFrame = CGRect.zero
var labelFrame = CGRect.zero
switch type {
case .ContinuousReverse, .RightLeft:
CGRectDivide(bounds, &unusedFrame, &labelFrame, leadingBuffer, CGRectEdge.MaxXEdge)
labelFrame = CGRectIntegral(labelFrame)
default:
labelFrame = CGRectIntegral(CGRectMake(leadingBuffer, 0.0, bounds.size.width - leadingBuffer, bounds.size.height))
}
homeLabelFrame = labelFrame
awayOffset = 0.0
// Remove an additional sublabels (for continuous types)
repliLayer.instanceCount = 1;
// Set the sublabel frame to calculated labelFrame
sublabel.frame = labelFrame
// Configure fade
applyGradientMask(fadeLength, animated: !labelize)
return
}
// Label DOES need to scroll
// Spacing between primary and second sublabel must be at least equal to leadingBuffer, and at least equal to the fadeLength
let minTrailing = max(max(leadingBuffer, trailingBuffer), fadeLength)
switch type {
case .Continuous, .ContinuousReverse:
if (type == .Continuous) {
homeLabelFrame = CGRectIntegral(CGRectMake(leadingBuffer, 0.0, expectedLabelSize.width, bounds.size.height))
awayOffset = -(homeLabelFrame.size.width + minTrailing)
} else { // .ContinuousReverse
homeLabelFrame = CGRectIntegral(CGRectMake(bounds.size.width - (expectedLabelSize.width + leadingBuffer), 0.0, expectedLabelSize.width, bounds.size.height))
awayOffset = (homeLabelFrame.size.width + minTrailing)
}
// Set frame and text
sublabel.frame = homeLabelFrame
// Configure replication
repliLayer.instanceCount = 2
repliLayer.instanceTransform = CATransform3DMakeTranslation(-awayOffset, 0.0, 0.0)
case .RightLeft:
homeLabelFrame = CGRectIntegral(CGRectMake(bounds.size.width - (expectedLabelSize.width + leadingBuffer), 0.0, expectedLabelSize.width, bounds.size.height))
awayOffset = (expectedLabelSize.width + trailingBuffer + leadingBuffer) - bounds.size.width
// Set frame and text
sublabel.frame = homeLabelFrame
// Remove any replication
repliLayer.instanceCount = 1
// Enforce text alignment for this type
sublabel.textAlignment = NSTextAlignment.Right
case .LeftRight:
homeLabelFrame = CGRectIntegral(CGRectMake(leadingBuffer, 0.0, expectedLabelSize.width, expectedLabelSize.height))
awayOffset = bounds.size.width - (expectedLabelSize.width + leadingBuffer + trailingBuffer)
// Set frame and text
sublabel.frame = homeLabelFrame
// Remove any replication
self.repliLayer.instanceCount = 1
// Enforce text alignment for this type
sublabel.textAlignment = NSTextAlignment.Left
// Default case not required
}
// Recompute the animation duration
animationDuration = {
switch self.speed {
case .Rate(let rate):
return CGFloat(fabs(self.awayOffset) / rate)
case .Duration(let duration):
return duration
}
}()
// Configure gradient for current condition
applyGradientMask(fadeLength, animated: !self.labelize)
if !tapToScroll && !holdScrolling && shouldBeginScroll {
beginScroll()
}
}
func sublabelSize() -> CGSize {
// Bound the expected size
let maximumLabelSize = CGSizeMake(CGFloat.max, CGFloat.max)
// Calculate the expected size
var expectedLabelSize = sublabel.sizeThatFits(maximumLabelSize)
// Sanitize width to 5461.0 (largest width a UILabel will draw on an iPhone 6S Plus)
expectedLabelSize.width = min(expectedLabelSize.width, 5461.0)
// Adjust to own height (make text baseline match normal label)
expectedLabelSize.height = bounds.size.height
return expectedLabelSize
}
override public func sizeThatFits(size: CGSize) -> CGSize {
var fitSize = sublabel.sizeThatFits(size)
fitSize.width += leadingBuffer
return fitSize
}
//
// MARK: - Animation Handling
//
private func labelShouldScroll() -> Bool {
// Check for nil string
if sublabel.text == nil {
return false
}
// Check for empty string
if sublabel.text!.isEmpty {
return false
}
// Check if the label string fits
let labelTooLarge = (sublabelSize().width + leadingBuffer) > self.bounds.size.width
let animationHasDuration = speed.value > 0.0
return (!labelize && labelTooLarge && animationHasDuration)
}
private func labelReadyForScroll() -> Bool {
// Check if we have a superview
if superview == nil {
return false
}
// Check if we are attached to a window
if window == nil {
return false
}
// Check if our view controller is ready
let viewController = firstAvailableViewController()
if viewController != nil {
if !viewController!.isViewLoaded() {
return false
}
}
return true
}
private func beginScroll() {
beginScroll(true)
}
private func beginScroll(delay: Bool) {
switch self.type {
case .LeftRight, .RightLeft:
scrollAway(animationDuration, delay: animationDelay)
default:
scrollContinuous(animationDuration, delay: animationDelay)
}
}
private func returnLabelToHome() {
// Remove any gradient animation
maskLayer?.removeAllAnimations()
// Remove all sublabel position animations
sublabel.layer.removeAllAnimations()
}
// Define animation completion closure type
private typealias MLAnimationCompletion = (finished: Bool) -> ()
private func scroll(interval: CGFloat, delay: CGFloat = 0.0, scroller: Scroller, fader: CAKeyframeAnimation?) {
var scroller = scroller
// Check for conditions which would prevent scrolling
if !labelReadyForScroll() {
return
}
// Call pre-animation hook
labelWillBeginScroll()
// Start animation transactions
CATransaction.begin()
let transDuration = transactionDurationType(type, interval: interval, delay: delay)
CATransaction.setAnimationDuration(transDuration)
// Create gradient animation, if needed
let gradientAnimation: CAKeyframeAnimation?
if fadeLength > 0.0 {
// Remove any setup animation, but apply final values
if let setupAnim = maskLayer?.animationForKey("setupFade") as? CABasicAnimation, finalColors = setupAnim.toValue as? [CGColorRef] {
maskLayer?.colors = finalColors
}
maskLayer?.removeAnimationForKey("setupFade")
// Generate animation if needed
if let previousAnimation = fader {
gradientAnimation = previousAnimation
} else {
gradientAnimation = keyFrameAnimationForGradient(fadeLength, interval: interval, delay: delay)
}
// Apply scrolling animation
maskLayer?.addAnimation(gradientAnimation!, forKey: "gradient")
} else {
// No animation needed
gradientAnimation = nil
}
let completion = CompletionBlock<MLAnimationCompletion>({ (finished: Bool) -> () in
guard finished else {
// Do not continue into the next loop
return
}
// Call returned home function
self.labelReturnedToHome(true)
// Check to ensure that:
// 1) We don't double fire if an animation already exists
// 2) The instance is still attached to a window - this completion block is called for
// many reasons, including if the animation is removed due to the view being removed
// from the UIWindow (typically when the view controller is no longer the "top" view)
guard self.window != nil else {
return
}
guard self.sublabel.layer.animationForKey("position") == nil else {
return
}
// Begin again, if conditions met
if (self.labelShouldScroll() && !self.tapToScroll && !self.holdScrolling) {
// Perform completion callback
self.scroll(interval, delay: delay, scroller: scroller, fader: gradientAnimation)
}
})
// Call scroller
let scrolls = scroller.generate(interval, delay: delay)
// Perform all animations in scrolls
for (index, scroll) in scrolls.enumerate() {
let layer = scroll.layer
let anim = scroll.anim
// Add callback to single animation
if index == 0 {
anim.setValue(completion as AnyObject, forKey: MarqueeKeys.CompletionClosure.rawValue)
anim.delegate = self
}
// Add animation
layer.addAnimation(anim, forKey: "position")
}
CATransaction.commit()
}
private func scrollAway(interval: CGFloat, delay: CGFloat = 0.0) {
// Create scroller, which defines the animation to perform
let homeOrigin = homeLabelFrame.origin
let awayOrigin = offsetCGPoint(homeLabelFrame.origin, offset: awayOffset)
let scroller = Scroller(generator: {(interval: CGFloat, delay: CGFloat) -> [(layer: CALayer, anim: CAKeyframeAnimation)] in
// Create animation for position
let values: [NSValue] = [
NSValue(CGPoint: homeOrigin), // Start at home
NSValue(CGPoint: homeOrigin), // Stay at home for delay
NSValue(CGPoint: awayOrigin), // Move to away
NSValue(CGPoint: awayOrigin), // Stay at away for delay
NSValue(CGPoint: homeOrigin) // Move back to home
]
let layer = self.sublabel.layer
let anim = self.keyFrameAnimationForProperty("position", values: values, interval: interval, delay: delay)
return [(layer: layer, anim: anim)]
})
// Scroll
scroll(interval, delay: delay, scroller: scroller, fader: nil)
}
private func scrollContinuous(interval: CGFloat, delay: CGFloat) {
// Create scroller, which defines the animation to perform
let homeOrigin = homeLabelFrame.origin
let awayOrigin = offsetCGPoint(homeLabelFrame.origin, offset: awayOffset)
let scroller = Scroller(generator: { (interval: CGFloat, delay: CGFloat) -> [(layer: CALayer, anim: CAKeyframeAnimation)] in
// Create animation for position
let values: [NSValue] = [
NSValue(CGPoint: homeOrigin), // Start at home
NSValue(CGPoint: homeOrigin), // Stay at home for delay
NSValue(CGPoint: awayOrigin) // Move to away
]
// Generate animation
let layer = self.sublabel.layer
let anim = self.keyFrameAnimationForProperty("position", values: values, interval: interval, delay: delay)
return [(layer: layer, anim: anim)]
})
// Scroll
scroll(interval, delay: delay, scroller: scroller, fader: nil)
}
private func applyGradientMask(fadeLength: CGFloat, animated: Bool) {
// Remove any in-flight animations
maskLayer?.removeAllAnimations()
// Check for zero-length fade
if (fadeLength <= 0.0) {
removeGradientMask()
return
}
// Configure gradient mask without implicit animations
CATransaction.begin()
CATransaction.setDisableActions(true)
// Determine if gradient mask needs to be created
let gradientMask: CAGradientLayer
if let currentMask = self.maskLayer {
// Mask layer already configured
gradientMask = currentMask
} else {
// No mask exists, create new mask
gradientMask = CAGradientLayer()
gradientMask.shouldRasterize = true
gradientMask.rasterizationScale = UIScreen.mainScreen().scale
gradientMask.startPoint = CGPointMake(0.0, 0.5)
gradientMask.endPoint = CGPointMake(1.0, 0.5)
// Adjust stops based on fade length
let leftFadeStop = fadeLength/self.bounds.size.width
let rightFadeStop = fadeLength/self.bounds.size.width
gradientMask.locations = [0.0, leftFadeStop, (1.0 - rightFadeStop), 1.0]
}
// Set up colors
let transparent = UIColor.clearColor().CGColor
let opaque = UIColor.blackColor().CGColor
// Set mask
self.layer.mask = gradientMask
gradientMask.bounds = self.layer.bounds
gradientMask.position = CGPointMake(CGRectGetMidX(self.bounds), CGRectGetMidY(self.bounds))
// Determine colors for non-scrolling label (i.e. at home)
let adjustedColors: [CGColorRef]
let trailingFadeNeeded = self.labelShouldScroll()
switch (type) {
case .ContinuousReverse, .RightLeft:
adjustedColors = [(trailingFadeNeeded ? transparent : opaque), opaque, opaque, opaque]
// .MLContinuous, .MLLeftRight
default:
adjustedColors = [opaque, opaque, opaque, (trailingFadeNeeded ? transparent : opaque)]
break
}
if (animated) {
// Finish transaction
CATransaction.commit()
// Create animation for color change
let colorAnimation = GradientAnimation(keyPath: "colors")
colorAnimation.fromValue = gradientMask.colors
colorAnimation.toValue = adjustedColors
colorAnimation.fillMode = kCAFillModeForwards
colorAnimation.removedOnCompletion = false
colorAnimation.delegate = self
gradientMask.addAnimation(colorAnimation, forKey: "setupFade")
} else {
gradientMask.colors = adjustedColors
CATransaction.commit()
}
}
private func removeGradientMask() {
self.layer.mask = nil
}
private func keyFrameAnimationForGradient(fadeLength: CGFloat, interval: CGFloat, delay: CGFloat) -> CAKeyframeAnimation {
// Setup
let values: [[CGColorRef]]
let keyTimes: [CGFloat]
let transp = UIColor.clearColor().CGColor
let opaque = UIColor.blackColor().CGColor
// Create new animation
let animation = CAKeyframeAnimation(keyPath: "colors")
// Get timing function
let timingFunction = timingFunctionForAnimationCurve(animationCurve)
// Define keyTimes
switch (type) {
case .LeftRight, .RightLeft:
// Calculate total animation duration
let totalDuration = 2.0 * (delay + interval)
keyTimes =
[
0.0, // 1) Initial gradient
delay/totalDuration, // 2) Begin of LE fade-in, just as scroll away starts
(delay + 0.4)/totalDuration, // 3) End of LE fade in [LE fully faded]
(delay + interval - 0.4)/totalDuration, // 4) Begin of TE fade out, just before scroll away finishes
(delay + interval)/totalDuration, // 5) End of TE fade out [TE fade removed]
(delay + interval + delay)/totalDuration, // 6) Begin of TE fade back in, just as scroll home starts
(delay + interval + delay + 0.4)/totalDuration, // 7) End of TE fade back in [TE fully faded]
(totalDuration - 0.4)/totalDuration, // 8) Begin of LE fade out, just before scroll home finishes
1.0 // 9) End of LE fade out, just as scroll home finishes
]
// .MLContinuous, .MLContinuousReverse
default:
// Calculate total animation duration
let totalDuration = delay + interval
// Find when the lead label will be totally offscreen
let offsetDistance = awayOffset
let startFadeFraction = fabs((sublabel.bounds.size.width + leadingBuffer) / offsetDistance)
// Find when the animation will hit that point
let startFadeTimeFraction = timingFunction.durationPercentageForPositionPercentage(startFadeFraction, duration: totalDuration)
let startFadeTime = delay + CGFloat(startFadeTimeFraction) * interval
keyTimes = [
0.0, // Initial gradient
delay/totalDuration, // Begin of fade in
(delay + 0.2)/totalDuration, // End of fade in, just as scroll away starts
startFadeTime/totalDuration, // Begin of fade out, just before scroll home completes
(startFadeTime + 0.1)/totalDuration, // End of fade out, as scroll home completes
1.0 // Buffer final value (used on continuous types)
]
break
}
// Define values
// Get current layer values
let mask = maskLayer?.presentationLayer() as? CAGradientLayer
let currentValues = mask?.colors as? [CGColorRef]
switch (type) {
case .ContinuousReverse:
values = [
currentValues ?? [transp, opaque, opaque, opaque], // Initial gradient
[transp, opaque, opaque, opaque], // Begin of fade in
[transp, opaque, opaque, transp], // End of fade in, just as scroll away starts
[transp, opaque, opaque, transp], // Begin of fade out, just before scroll home completes
[transp, opaque, opaque, opaque], // End of fade out, as scroll home completes
[transp, opaque, opaque, opaque] // Final "home" value
]
break
case .RightLeft:
values = [
currentValues ?? [transp, opaque, opaque, opaque], // 1)
[transp, opaque, opaque, opaque], // 2)
[transp, opaque, opaque, transp], // 3)
[transp, opaque, opaque, transp], // 4)
[opaque, opaque, opaque, transp], // 5)
[opaque, opaque, opaque, transp], // 6)
[transp, opaque, opaque, transp], // 7)
[transp, opaque, opaque, transp], // 8)
[transp, opaque, opaque, opaque] // 9)
]
break
case .Continuous:
values = [
currentValues ?? [opaque, opaque, opaque, transp], // Initial gradient
[opaque, opaque, opaque, transp], // Begin of fade in
[transp, opaque, opaque, transp], // End of fade in, just as scroll away starts
[transp, opaque, opaque, transp], // Begin of fade out, just before scroll home completes
[opaque, opaque, opaque, transp], // End of fade out, as scroll home completes
[opaque, opaque, opaque, transp] // Final "home" value
]
break
case .LeftRight:
values = [
currentValues ?? [opaque, opaque, opaque, transp], // 1)
[opaque, opaque, opaque, transp], // 2)
[transp, opaque, opaque, transp], // 3)
[transp, opaque, opaque, transp], // 4)
[transp, opaque, opaque, opaque], // 5)
[transp, opaque, opaque, opaque], // 6)
[transp, opaque, opaque, transp], // 7)
[transp, opaque, opaque, transp], // 8)
[opaque, opaque, opaque, transp] // 9)
]
break
}
animation.values = values
animation.keyTimes = keyTimes
animation.timingFunctions = [timingFunction, timingFunction, timingFunction, timingFunction]
return animation
}
private func keyFrameAnimationForProperty(property: String, values: [NSValue], interval: CGFloat, delay: CGFloat) -> CAKeyframeAnimation {
// Create new animation
let animation = CAKeyframeAnimation(keyPath: property)
// Get timing function
let timingFunction = timingFunctionForAnimationCurve(animationCurve)
// Calculate times based on marqueeType
let totalDuration: CGFloat
switch (type) {
case .LeftRight, .RightLeft:
//NSAssert(values.count == 5, @"Incorrect number of values passed for MLLeftRight-type animation")
totalDuration = 2.0 * (delay + interval)
// Set up keyTimes
animation.keyTimes = [
0.0, // Initial location, home
delay/totalDuration, // Initial delay, at home
(delay + interval)/totalDuration, // Animation to away
(delay + interval + delay)/totalDuration, // Delay at away
1.0 // Animation to home
]
animation.timingFunctions = [
timingFunction,
timingFunction,
timingFunction,
timingFunction
]
// .Continuous
// .ContinuousReverse
default:
//NSAssert(values.count == 3, @"Incorrect number of values passed for MLContinous-type animation")
totalDuration = delay + interval
// Set up keyTimes
animation.keyTimes = [
0.0, // Initial location, home
delay/totalDuration, // Initial delay, at home
1.0 // Animation to away
]
animation.timingFunctions = [
timingFunction,
timingFunction
]
}
// Set values
animation.values = values
return animation
}
private func timingFunctionForAnimationCurve(curve: UIViewAnimationCurve) -> CAMediaTimingFunction {
let timingFunction: String?
switch curve {
case .EaseIn:
timingFunction = kCAMediaTimingFunctionEaseIn
case .EaseInOut:
timingFunction = kCAMediaTimingFunctionEaseInEaseOut
case .EaseOut:
timingFunction = kCAMediaTimingFunctionEaseOut
default:
timingFunction = kCAMediaTimingFunctionLinear
}
return CAMediaTimingFunction(name: timingFunction!)
}
private func transactionDurationType(labelType: Type, interval: CGFloat, delay: CGFloat) -> NSTimeInterval {
switch (labelType) {
case .LeftRight, .RightLeft:
return NSTimeInterval(2.0 * (delay + interval))
default:
return NSTimeInterval(delay + interval)
}
}
override public func animationDidStop(anim: CAAnimation, finished flag: Bool) {
if anim is GradientAnimation {
if let setupAnim = maskLayer?.animationForKey("setupFade") as? CABasicAnimation, finalColors = setupAnim.toValue as? [CGColorRef] {
maskLayer?.colors = finalColors
}
// Remove regardless, since we set removeOnCompletion = false
maskLayer?.removeAnimationForKey("setupFade")
} else {
let completion = anim.valueForKey(MarqueeKeys.CompletionClosure.rawValue) as? CompletionBlock<MLAnimationCompletion>
completion?.f(finished: flag)
}
}
//
// MARK: - Private details
//
private var sublabel = UILabel()
private var animationDuration: CGFloat = 0.0
private var homeLabelFrame = CGRect.zero
private var awayOffset: CGFloat = 0.0
override public class func layerClass() -> AnyClass {
return CAReplicatorLayer.self
}
private var repliLayer: CAReplicatorLayer {
return self.layer as! CAReplicatorLayer
}
private var maskLayer: CAGradientLayer? {
return self.layer.mask as! CAGradientLayer?
}
override public func drawLayer(layer: CALayer, inContext ctx: CGContext) {
// Do NOT call super, to prevent UILabel superclass from drawing into context
// Label drawing is handled by sublabel and CAReplicatorLayer layer class
// Draw only background color
if let bgColor = backgroundColor {
CGContextSetFillColorWithColor(ctx, bgColor.CGColor);
CGContextFillRect(ctx, layer.bounds);
}
}
private enum MarqueeKeys: String {
case Restart = "MLViewControllerRestart"
case Labelize = "MLShouldLabelize"
case Animate = "MLShouldAnimate"
case CompletionClosure = "MLAnimationCompletion"
}
class private func notifyController(controller: UIViewController, message: MarqueeKeys) {
NSNotificationCenter.defaultCenter().postNotificationName(message.rawValue, object: nil, userInfo: ["controller" : controller])
}
public func restartForViewController(notification: NSNotification) {
if let controller = notification.userInfo?["controller"] as? UIViewController {
if controller === self.firstAvailableViewController() {
self.restartLabel()
}
}
}
public func labelizeForController(notification: NSNotification) {
if let controller = notification.userInfo?["controller"] as? UIViewController {
if controller === self.firstAvailableViewController() {
self.labelize = true
}
}
}
public func animateForController(notification: NSNotification) {
if let controller = notification.userInfo?["controller"] as? UIViewController {
if controller === self.firstAvailableViewController() {
self.labelize = false
}
}
}
//
// MARK: - Label Control
//
/**
Overrides any non-size condition which is preventing the receiver from automatically scrolling, and begins a scroll animation.
Currently the only non-size conditions which can prevent a label from scrolling are the `tapToScroll` and `holdScrolling` properties. This
method will not force a label with a string that fits inside the label bounds (i.e. that would not automatically scroll) to begin a scroll
animation.
Upon the completion of the first forced scroll animation, the receiver will not automatically continue to scroll unless the conditions
preventing scrolling have been removed.
- Note: This method has no effect if called during an already in-flight scroll animation.
- SeeAlso: restartLabel
*/
public func triggerScrollStart() {
if labelShouldScroll() && !awayFromHome {
beginScroll()
}
}
/**
Immediately resets the label to the home position, cancelling any in-flight scroll animation, and restarts the scroll animation if the appropriate conditions are met.
- SeeAlso: resetLabel
- SeeAlso: triggerScrollStart
*/
public func restartLabel() {
// Shutdown the label
shutdownLabel()
// Restart scrolling if appropriate
if labelShouldScroll() && !tapToScroll && !holdScrolling {
beginScroll()
}
}
/**
Resets the label text, recalculating the scroll animation.
The text is immediately returned to the home position, and the scroll animation positions are cleared. Scrolling will not resume automatically after
a call to this method. To re-initiate scrolling, use either a call to `restartLabel` or make a change to a UILabel property such as text, bounds/frame,
font, font size, etc.
- SeeAlso: restartLabel
*/
public func resetLabel() {
returnLabelToHome()
homeLabelFrame = CGRect.null
awayOffset = 0.0
}
/**
Immediately resets the label to the home position, cancelling any in-flight scroll animation.
The text is immediately returned to the home position. Scrolling will not resume automatically after a call to this method.
To re-initiate scrolling use a call to `restartLabel` or `triggerScrollStart`, or make a change to a UILabel property such as text, bounds/frame,
font, font size, etc.
- SeeAlso: restartLabel
- SeeAlso: triggerScrollStart
*/
public func shutdownLabel() {
// Bring label to home location
returnLabelToHome()
// Apply gradient mask for home location
applyGradientMask(fadeLength, animated: false)
}
/**
Pauses the text scrolling animation, at any point during an in-progress animation.
- Note: This method has no effect if a scroll animation is NOT already in progress. To prevent automatic scrolling on a newly-initialized label prior to its presentation onscreen, see the `holdScrolling` property.
- SeeAlso: holdScrolling
- SeeAlso: unpauseLabel
*/
public func pauseLabel() {
// Prevent pausing label while not in scrolling animation, or when already paused
guard (!isPaused && awayFromHome) else {
return
}
// Pause sublabel position animations
let labelPauseTime = sublabel.layer.convertTime(CACurrentMediaTime(), fromLayer: nil)
sublabel.layer.speed = 0.0
sublabel.layer.timeOffset = labelPauseTime
// Pause gradient fade animation
let gradientPauseTime = maskLayer?.convertTime(CACurrentMediaTime(), fromLayer:nil)
maskLayer?.speed = 0.0
maskLayer?.timeOffset = gradientPauseTime!
}
/**
Un-pauses a previously paused text scrolling animation. This method has no effect if the label was not previously paused using `pauseLabel`.
- SeeAlso: pauseLabel
*/
public func unpauseLabel() {
// Only unpause if label was previously paused
guard (isPaused) else {
return
}
// Unpause sublabel position animations
let labelPausedTime = sublabel.layer.timeOffset
sublabel.layer.speed = 1.0
sublabel.layer.timeOffset = 0.0
sublabel.layer.beginTime = 0.0
sublabel.layer.beginTime = sublabel.layer.convertTime(CACurrentMediaTime(), fromLayer:nil) - labelPausedTime
// Unpause gradient fade animation
let gradientPauseTime = maskLayer?.timeOffset
maskLayer?.speed = 1.0
maskLayer?.timeOffset = 0.0
maskLayer?.beginTime = 0.0
maskLayer?.beginTime = maskLayer!.convertTime(CACurrentMediaTime(), fromLayer:nil) - gradientPauseTime!
}
public func labelWasTapped(recognizer: UIGestureRecognizer) {
if labelShouldScroll() && !awayFromHome {
beginScroll(true)
}
}
/**
Called when the label animation is about to begin.
The default implementation of this method does nothing. Subclasses may override this method in order to perform any custom actions just as
the label animation begins. This is only called in the event that the conditions for scrolling to begin are met.
*/
public func labelWillBeginScroll() {
// Default implementation does nothing - override to customize
return
}
/**
Called when the label animation has finished, and the label is at the home position.
The default implementation of this method does nothing. Subclasses may override this method in order to perform any custom actions jas as
the label animation completes, and before the next animation would begin (assuming the scroll conditions are met).
- Parameter finished: A Boolean that indicates whether or not the scroll animation actually finished before the completion handler was called.
- Warning: This method will be called, and the `finished` parameter will be `NO`, when any property changes are made that would cause the label
scrolling to be automatically reset. This includes changes to label text and font/font size changes.
*/
public func labelReturnedToHome(finished: Bool) {
// Default implementation does nothing - override to customize
return
}
//
// MARK: - Modified UILabel Functions/Getters/Setters
//
#if os(iOS)
override public func viewForBaselineLayout() -> UIView {
// Use subLabel view for handling baseline layouts
return sublabel
}
public override var viewForLastBaselineLayout: UIView {
// Use subLabel view for handling baseline layouts
return sublabel
}
#endif
public override var text: String? {
get {
return sublabel.text
}
set {
if sublabel.text == newValue {
return
}
sublabel.text = newValue
updateAndScroll()
super.text = text
}
}
public override var attributedText: NSAttributedString? {
get {
return sublabel.attributedText
}
set {
if sublabel.attributedText == newValue {
return
}
sublabel.attributedText = newValue
updateAndScroll()
super.attributedText = attributedText
}
}
public override var font: UIFont! {
get {
return sublabel.font
}
set {
if sublabel.font == newValue {
return
}
sublabel.font = newValue
super.font = newValue
updateAndScroll()
}
}
public override var textColor: UIColor! {
get {
return sublabel.textColor
}
set {
sublabel.textColor = newValue
super.textColor = newValue
}
}
public override var backgroundColor: UIColor? {
get {
return sublabel.backgroundColor
}
set {
sublabel.backgroundColor = newValue
super.backgroundColor = newValue
}
}
public override var shadowColor: UIColor? {
get {
return sublabel.shadowColor
}
set {
sublabel.shadowColor = newValue
super.shadowColor = newValue
}
}
public override var shadowOffset: CGSize {
get {
return sublabel.shadowOffset
}
set {
sublabel.shadowOffset = newValue
super.shadowOffset = newValue
}
}
public override var highlightedTextColor: UIColor? {
get {
return sublabel.highlightedTextColor
}
set {
sublabel.highlightedTextColor = newValue
super.highlightedTextColor = newValue
}
}
public override var highlighted: Bool {
get {
return sublabel.highlighted
}
set {
sublabel.highlighted = newValue
super.highlighted = newValue
}
}
public override var enabled: Bool {
get {
return sublabel.enabled
}
set {
sublabel.enabled = newValue
super.enabled = newValue
}
}
public override var numberOfLines: Int {
get {
return super.numberOfLines
}
set {
// By the nature of MarqueeLabel, this is 1
super.numberOfLines = 1
}
}
public override var adjustsFontSizeToFitWidth: Bool {
get {
return super.adjustsFontSizeToFitWidth
}
set {
// By the nature of MarqueeLabel, this is false
super.adjustsFontSizeToFitWidth = false
}
}
public override var minimumScaleFactor: CGFloat {
get {
return super.minimumScaleFactor
}
set {
super.minimumScaleFactor = 0.0
}
}
public override var baselineAdjustment: UIBaselineAdjustment {
get {
return sublabel.baselineAdjustment
}
set {
sublabel.baselineAdjustment = newValue
super.baselineAdjustment = newValue
}
}
public override func intrinsicContentSize() -> CGSize {
var content = sublabel.intrinsicContentSize()
content.width += leadingBuffer
return content
}
//
// MARK: - Support
//
private func offsetCGPoint(point: CGPoint, offset: CGFloat) -> CGPoint {
return CGPointMake(point.x + offset, point.y)
}
//
// MARK: - Deinit
//
deinit {
NSNotificationCenter.defaultCenter().removeObserver(self)
}
}
//
// MARK: - Support
//
// Solution from: http://stackoverflow.com/a/24760061/580913
private class CompletionBlock<T> {
let f : T
init (_ f: T) { self.f = f }
}
private class GradientAnimation: CABasicAnimation {
}
private struct Scroller {
typealias Scroll = (layer: CALayer, anim: CAKeyframeAnimation)
init(generator gen: (interval: CGFloat, delay: CGFloat) -> [Scroll]) {
self.generator = gen
}
let generator: (interval: CGFloat, delay: CGFloat) -> [Scroll]
var scrolls: [Scroll]? = nil
mutating func generate(interval: CGFloat, delay: CGFloat) -> [Scroll] {
if let existing = scrolls {
return existing
} else {
scrolls = generator(interval: interval, delay: delay)
return scrolls!
}
}
}
private extension UIResponder {
// Thanks to Phil M
// http://stackoverflow.com/questions/1340434/get-to-uiviewcontroller-from-uiview-on-iphone
func firstAvailableViewController() -> UIViewController? {
// convenience function for casting and to "mask" the recursive function
return self.traverseResponderChainForFirstViewController()
}
func traverseResponderChainForFirstViewController() -> UIViewController? {
if let nextResponder = self.nextResponder() {
if nextResponder.isKindOfClass(UIViewController) {
return nextResponder as? UIViewController
} else if (nextResponder.isKindOfClass(UIView)) {
return nextResponder.traverseResponderChainForFirstViewController()
} else {
return nil
}
}
return nil
}
}
private extension CAMediaTimingFunction {
func durationPercentageForPositionPercentage(positionPercentage: CGFloat, duration: CGFloat) -> CGFloat {
// Finds the animation duration percentage that corresponds with the given animation "position" percentage.
// Utilizes Newton's Method to solve for the parametric Bezier curve that is used by CAMediaAnimation.
let controlPoints = self.controlPoints()
let epsilon: CGFloat = 1.0 / (100.0 * CGFloat(duration))
// Find the t value that gives the position percentage we want
let t_found = solveTforY(positionPercentage, epsilon: epsilon, controlPoints: controlPoints)
// With that t, find the corresponding animation percentage
let durationPercentage = XforCurveAt(t_found, controlPoints: controlPoints)
return durationPercentage
}
func solveTforY(y_0: CGFloat, epsilon: CGFloat, controlPoints: [CGPoint]) -> CGFloat {
// Use Newton's Method: http://en.wikipedia.org/wiki/Newton's_method
// For first guess, use t = y (i.e. if curve were linear)
var t0 = y_0
var t1 = y_0
var f0, df0: CGFloat
for _ in 0..<15 {
// Base this iteration of t1 calculated from last iteration
t0 = t1
// Calculate f(t0)
f0 = YforCurveAt(t0, controlPoints:controlPoints) - y_0
// Check if this is close (enough)
if (fabs(f0) < epsilon) {
// Done!
return t0
}
// Else continue Newton's Method
df0 = derivativeCurveYValueAt(t0, controlPoints:controlPoints)
// Check if derivative is small or zero ( http://en.wikipedia.org/wiki/Newton's_method#Failure_analysis )
if (fabs(df0) < 1e-6) {
break
}
// Else recalculate t1
t1 = t0 - f0/df0
}
// Give up - shouldn't ever get here...I hope
print("MarqueeLabel: Failed to find t for Y input!")
return t0
}
func YforCurveAt(t: CGFloat, controlPoints:[CGPoint]) -> CGFloat {
let P0 = controlPoints[0]
let P1 = controlPoints[1]
let P2 = controlPoints[2]
let P3 = controlPoints[3]
// Per http://en.wikipedia.org/wiki/Bezier_curve#Cubic_B.C3.A9zier_curves
let y0 = (pow((1.0 - t),3.0) * P0.y)
let y1 = (3.0 * pow(1.0 - t, 2.0) * t * P1.y)
let y2 = (3.0 * (1.0 - t) * pow(t, 2.0) * P2.y)
let y3 = (pow(t, 3.0) * P3.y)
return y0 + y1 + y2 + y3
}
func XforCurveAt(t: CGFloat, controlPoints: [CGPoint]) -> CGFloat {
let P0 = controlPoints[0]
let P1 = controlPoints[1]
let P2 = controlPoints[2]
let P3 = controlPoints[3]
// Per http://en.wikipedia.org/wiki/Bezier_curve#Cubic_B.C3.A9zier_curves
let x0 = (pow((1.0 - t),3.0) * P0.x)
let x1 = (3.0 * pow(1.0 - t, 2.0) * t * P1.x)
let x2 = (3.0 * (1.0 - t) * pow(t, 2.0) * P2.x)
let x3 = (pow(t, 3.0) * P3.x)
return x0 + x1 + x2 + x3
}
func derivativeCurveYValueAt(t: CGFloat, controlPoints: [CGPoint]) -> CGFloat {
let P0 = controlPoints[0]
let P1 = controlPoints[1]
let P2 = controlPoints[2]
let P3 = controlPoints[3]
let dy0 = (P0.y + 3.0 * P1.y + 3.0 * P2.y - P3.y) * -3.0
let dy1 = t * (6.0 * P0.y + 6.0 * P2.y)
let dy2 = (-3.0 * P0.y + 3.0 * P1.y)
return dy0 * pow(t, 2.0) + dy1 + dy2
}
func controlPoints() -> [CGPoint] {
// Create point array to point to
var point: [Float] = [0.0, 0.0]
var pointArray = [CGPoint]()
for i in 0...3 {
self.getControlPointAtIndex(i, values: &point)
pointArray.append(CGPoint(x: CGFloat(point[0]), y: CGFloat(point[1])))
}
return pointArray
}
}
|
572155b4938ce8077a040dcbb4ffe27f
| 37.256 | 283 | 0.599749 | false | false | false | false |
SD10/SwifterSwift
|
refs/heads/master
|
Carthage/Checkouts/SwifterSwift/Source/Extensions/IntExtensions.swift
|
apache-2.0
|
4
|
//
// IntExtensions.swift
// SwifterSwift
//
// Created by Omar Albeik on 8/6/16.
// Copyright © 2016 Omar Albeik. All rights reserved.
//
#if os(macOS)
import Cocoa
#else
import UIKit
#endif
// MARK: - Properties
public extension Int {
/// SwifterSwift: Absolute value of integer.
public var abs: Int {
return Swift.abs(self)
}
/// SwifterSwift: String with number and current locale currency.
public var asLocaleCurrency: String {
let formatter = NumberFormatter()
formatter.numberStyle = .currency
formatter.locale = Locale.current
return formatter.string(from: self as NSNumber)!
}
/// SwifterSwift: Radian value of degree input.
public var degreesToRadians: Double {
return Double.pi * Double(self) / 180.0
}
/// SwifterSwift: Array of digits of integer value.
public var digits: [Int] {
var digits: [Int] = []
for char in String(self).characters {
if let int = Int(String(char)) {
digits.append(int)
}
}
return digits
}
/// SwifterSwift: Number of digits of integer value.
public var digitsCount: Int {
return String(self).characters.count
}
/// SwifterSwift: Check if integer is even.
public var isEven: Bool {
return (self % 2) == 0
}
/// SwifterSwift: Check if integer is odd.
public var isOdd: Bool {
return (self % 2) != 0
}
/// SwifterSwift: Check if integer is positive.
public var isPositive: Bool {
return self > 0
}
/// SwifterSwift: Check if integer is negative.
public var isNegative: Bool {
return self < 0
}
/// SwifterSwift: Double.
public var double: Double {
return Double(self)
}
/// SwifterSwift: Float.
public var float: Float {
return Float(self)
}
/// SwifterSwift: CGFloat.
public var cgFloat: CGFloat {
return CGFloat(self)
}
/// SwifterSwift: String.
public var string: String {
return String(self)
}
/// SwifterSwift: Degree value of radian input
public var radiansToDegrees: Double {
return Double(self) * 180 / Double.pi
}
/// SwifterSwift: Roman numeral string from integer (if applicable).
public var romanNumeral: String? {
// https://gist.github.com/kumo/a8e1cb1f4b7cff1548c7
guard self > 0 else { // there is no roman numerals for 0 or negative numbers
return nil
}
let romanValues = ["M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"]
let arabicValues = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1]
var romanValue = ""
var startingValue = self
for (index, romanChar) in romanValues.enumerated() {
let arabicValue = arabicValues[index]
let div = startingValue / arabicValue
if (div > 0) {
for _ in 0..<div {
romanValue += romanChar
}
startingValue -= arabicValue * div
}
}
return romanValue
}
/// SwifterSwift: String of format (XXh XXm) from seconds Int.
public var timeString: String {
guard self > 0 else {
return "0 sec"
}
if self < 60 {
return "\(self) sec"
}
if self < 3600 {
return "\(self / 60) min"
}
let hours = self / 3600
let mins = (self % 3600) / 60
if hours != 0 && mins == 0 {
return "\(hours)h"
}
return "\(hours)h \(mins)m"
}
/// SwifterSwift: String formatted for values over ±1000 (example: 1k, -2k, 100k, 1kk, -5kk..)
public var kFormatted: String {
var sign: String {
return self >= 0 ? "" : "-"
}
let abs = self.abs
if abs == 0 {
return "0k"
} else if abs >= 0 && abs < 1000 {
return "0k"
} else if abs >= 1000 && abs < 1000000 {
return String(format: "\(sign)%ik", abs / 1000)
}
return String(format: "\(sign)%ikk", abs / 100000)
}
}
// MARK: - Methods
public extension Int {
/// SwifterSwift: Greatest common divisor of integer value and n.
///
/// - Parameter n: integer value to find gcd with.
/// - Returns: greatest common divisor of self and n.
public func gcd(of n: Int) -> Int {
return n == 0 ? self : n.gcd(of: self % n)
}
/// SwifterSwift: Least common multiple of integer and n.
///
/// - Parameter n: integer value to find lcm with.
/// - Returns: least common multiple of self and n.
public func lcm(of n: Int) -> Int {
return (self * n).abs / gcd(of: n)
}
/// SwifterSwift: Random integer between two integer values.
///
/// - Parameters:
/// - min: minimum number to start random from.
/// - max: maximum number random number end before.
/// - Returns: random double between two double values.
public static func random(between min: Int, and max: Int) -> Int {
return random(inRange: min...max)
}
/// SwifterSwift: Random integer in a closed interval range.
///
/// - Parameter range: closed interval range.
/// - Returns: random double in the given closed range.
public static func random(inRange range: ClosedRange<Int>) -> Int {
let delta = UInt32(range.upperBound - range.lowerBound + 1)
return range.lowerBound + Int(arc4random_uniform(delta))
}
}
// MARK: - Initializers
public extension Int {
/// SwifterSwift: Created a random integer between two integer values.
///
/// - Parameters:
/// - min: minimum number to start random from.
/// - max: maximum number random number end before.
public init(randomBetween min: Int, and max: Int) {
self = Int.random(between: min, and: max)
}
/// SwifterSwift: Create a random integer in a closed interval range.
///
/// - Parameter range: closed interval range.
public init(randomInRange range: ClosedRange<Int>) {
self = Int.random(inRange: range)
}
}
// MARK: - Operators
precedencegroup PowerPrecedence { higherThan: MultiplicationPrecedence }
infix operator ** : PowerPrecedence
/// SwifterSwift: Value of exponentiation.
///
/// - Parameters:
/// - lhs: base integer.
/// - rhs: exponent integer.
/// - Returns: exponentiation result (example: 2 ** 3 = 8).
public func ** (lhs: Int, rhs: Int) -> Double {
// http://nshipster.com/swift-operators/
return pow(Double(lhs), Double(rhs))
}
prefix operator √
/// SwifterSwift: Square root of integer.
///
/// - Parameter int: integer value to find square root for
/// - Returns: square root of given integer.
public prefix func √ (int: Int) -> Double {
// http://nshipster.com/swift-operators/
return sqrt(Double(int))
}
infix operator ±
/// SwifterSwift: Tuple of plus-minus operation.
///
/// - Parameters:
/// - lhs: integer number.
/// - rhs: integer number.
/// - Returns: tuple of plus-minus operation (example: 2 ± 3 -> (5, -1)).
public func ± (lhs: Int, rhs: Int) -> (Int, Int) {
// http://nshipster.com/swift-operators/
return (lhs + rhs, lhs - rhs)
}
prefix operator ±
/// SwifterSwift: Tuple of plus-minus operation.
///
/// - Parameter int: integer number
/// - Returns: tuple of plus-minus operation (example: ± 2 -> (2, -2)).
public prefix func ± (int: Int) -> (Int, Int) {
// http://nshipster.com/swift-operators/
return 0 ± int
}
|
671334e23328c343bcb6ee7b606d1338
| 24.262963 | 95 | 0.651078 | false | false | false | false |
iineva/ResizeImage
|
refs/heads/master
|
ResizeImage/ViewController.swift
|
mit
|
1
|
//
// ViewController.swift
// ResizeImage
//
// Created by Steven on 15/12/9.
// Copyright © 2015年 Neva. All rights reserved.
//
import Cocoa
class ViewController: NSViewController {
let suportList = ["JPG", "jpg", "png", "PNG", "jpeg", "JPEG"]
var inputFileList = [String]() {
didSet {
outputToUserLab.stringValue = "已经选择 \(inputFileList.count) 张图片"
switch inputFileList.count {
case 0:
outputToUserLab.stringValue = "请选择需要转换的图片..."
inputLab.stringValue = ""
case 1:
inputLab.stringValue = inputFileList[0]
default:
inputLab.stringValue = inputFileList.debugDescription
}
}
}
var outputDirPath: String? {
didSet {
outputLab.stringValue = outputDirPath ?? ""
}
}
@IBOutlet weak var inputLab: NSTextField!
@IBOutlet weak var outputLab: NSTextField!
@IBOutlet weak var widthLab: NSTextField!
@IBOutlet weak var heightLab: NSTextField!
@IBOutlet weak var outputToUserLab: NSTextField!
@IBAction func onStartBtnClick(sender: NSButton) {
let list = inputFileList
let width = Int(widthLab.stringValue)
let height = Int(heightLab.stringValue)
if list.count == 0 {
outputToUserLab.stringValue = "请选择输入文件"
return
} else if outputDirPath == nil {
outputToUserLab.stringValue = "请选择输出目录"
return
} else if width == nil || height == nil {
outputToUserLab.stringValue = "请输入: width,height"
return
}
// 压缩图片
let size = NSSize(width: width!, height: height!)
sender.enabled = false
dispatch_async(dispatch_get_global_queue(0, 0)) { () -> Void in
for var i = 0; i < list.count; i++ {
let path = list[i]
let fileName = (path as NSString).lastPathComponent
let savePath = (self.outputDirPath! as NSString).stringByAppendingPathComponent(fileName)
dispatch_sync(dispatch_get_main_queue(), { () -> Void in
self.outputToUserLab.stringValue = "\(fileName)\n\(i)/\(list.count)"
})
if let image = NSImage(contentsOfFile: path) {
image.resizingMode = .Stretch
image.size = size
image.saveAsPNGatPath(savePath)
}
}
dispatch_sync(dispatch_get_main_queue(), { () -> Void in
self.inputFileList.removeAll()
sender.enabled = true
})
}
}
// 选择输入文件
@IBAction func onInputBtnTouch(sender: AnyObject) {
inputFileList.removeAll()
let panel = createPlanel(true)
if panel.runModal() == NSModalResponseOK {
// 遍历出文件
var fileList = [String]()
let fileManager = NSFileManager.defaultManager()
var isDirectory : ObjCBool = false
for url in panel.URLs {
if let path = url.path where fileManager.fileExistsAtPath(path, isDirectory: &isDirectory) {
if (isDirectory) {
fileList.appendContentsOf(recursiveFileList(url.path!))
} else {
fileList.append(url.path!)
}
}
}
inputFileList = fileList
}
}
// 选择输出目录
@IBAction func onOutputBtnTouch(sender: AnyObject) {
outputDirPath = nil
let panel = createPlanel(false)
if panel.runModal() == NSModalResponseOK {
if let path = panel.URLs[0].path {
outputDirPath = path
}
}
}
// 递归获取目录下的所有图片文件
func recursiveFileList(dir: String) -> [String] {
var fileList = [String]()
let fileManager = NSFileManager.defaultManager()
let directoryEnumerator = fileManager.enumeratorAtPath(dir)
var isDirectory : ObjCBool = false
if let directoryEnumerator = directoryEnumerator {
var file = directoryEnumerator.nextObject() as? String
while file != nil {
file = (dir as NSString).stringByAppendingPathComponent(file!)
if fileManager.fileExistsAtPath(file!, isDirectory: &isDirectory) {
if isDirectory {
// 目录
fileList.appendContentsOf( recursiveFileList(file!) )
} else if suportList.contains( (file! as NSString).pathExtension ) {
// 文件
fileList.append(file! as String)
}
}
// 下一个文件
file = directoryEnumerator.nextObject() as? String
}
}
return fileList
}
// 创建一个文件选择面板
func createPlanel(isIn: Bool) -> NSOpenPanel {
let panel = NSOpenPanel()
panel.canChooseFiles = isIn
panel.canChooseDirectories = true
panel.allowsMultipleSelection = isIn
panel.allowsOtherFileTypes = false
panel.allowedFileTypes = suportList
panel.canCreateDirectories = !isIn
return panel
}
override func viewDidLoad() {
super.viewDidLoad()
}
override var representedObject: AnyObject? {
didSet {
// Update the view, if already loaded.
}
}
}
|
fe643e8a70d7e647e47e414e25af0a51
| 32.059172 | 108 | 0.538572 | false | false | false | false |
myafer/AFUIKit
|
refs/heads/master
|
AFUIKitExample/AFUIKitExample/ViewController.swift
|
mit
|
1
|
//
// ViewController.swift
// AFUIKitExample
//
// Created by 口贷网 on 16/8/3.
// Copyright © 2016年 Afer. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
lazy var btn: UIButton = {
return UIButton()
.frame(CGRect(x: 100, y: 60, width: 100, height: 40))
.bgColor(.red)
.cornerRadiusHalf()
.border(2, .blue)
.hidden(false)
.title("一般", state: .normal)
.selectedStateTitle("选中")
.highlightedStateTitle("高亮")
.hidden(false)
.bgColor(.black)
.tag(11)
.target(self, action: #selector(ViewController.test(_:)), forControlEvents: .touchUpInside)
}()
override func viewDidLoad() {
super.viewDidLoad()
UIButton()
.frame(CGRect(x: 100, y: 60, width: 100, height: 40))
.bgColor( .red)
.cornerRadiusHalf()
.border(2, UIColor.blue)
.hidden(false)
.title("一般", state: .normal)
.selectedStateTitle("选中")
.highlightedStateTitle("高亮")
.hidden(false)
.bgColor(.black)
.tag(11)
.target(self, action: #selector(ViewController.test(_:)), forControlEvents: UIControlEvents.touchUpInside)
.addToView(self.view)
let attr = NSMutableAttributedString()
.append_attr("123", [AFFontColor: UIColor.red])
.append_attr("456", [AFFontColor: UIColor.blue])
.append_attr("3333", [AFBgColor: UIColor.red])
let label = UILabel()
.frame(CGRect(x: 10, y: 300, width: 100, height: 50))
.cornerRadiusHalf()
.bgColor( .purple)
.text("Lable")
.textAlignment(.center)
.attributedText(attr)
self.view.addSubview(label)
// // Just for fun
let 视图 = UI视图()
.位置大小(大小(100, 100, 100, 100))
.背景色(.红色)
.圆角(30)
.边线(1, .蓝色)
self.视图.添加视图(视图)
let btn1 = UIButton()
btn1.frame = CGRect(x: 100, y: 200, width: 100, height: 40)
btn1.backgroundColor = UIColor.red
btn1.layer.cornerRadius = btn1.frame.height / 2.0
btn1.layer.borderColor = UIColor.blue.cgColor
btn1.layer.borderWidth = 2.0
btn1.isHidden = false
btn1.setTitle("一般", for: UIControlState.normal)
btn1.setTitle("选中", for: UIControlState.selected)
btn1.setTitle("高亮", for: UIControlState.highlighted)
btn1.addTarget(self, action: #selector(ViewController.test(_:)), for: UIControlEvents.touchUpInside)
self.view.addSubview(btn1)
}
func test(_ sender: UIButton) {
sender.isSelected = !sender.isSelected
}
}
|
d93154d1d7d3c3dab5fe5f9201367963
| 27.558824 | 118 | 0.532097 | false | false | false | false |
feiin/swiftmi-app
|
refs/heads/master
|
swiftmi/swiftmi/WebViewController.swift
|
mit
|
2
|
//
// WebViewController.swift
// swiftmi
//
// Created by yangyin on 15/5/3.
// Copyright (c) 2015年 swiftmi. All rights reserved.
//
import UIKit
class WebViewController: UIViewController,UIWebViewDelegate {
internal var isPop:Bool = false
internal var webUrl:String?
@IBOutlet weak var webView: UIWebView!
override func viewDidLoad() {
super.viewDidLoad()
self.webView.delegate = self
if webUrl != nil {
self.pleaseWait()
let url = URL(string: webUrl!)
let request = URLRequest(url: url!)
webView.loadRequest(request)
}
if self.title == nil {
self.title = "内容"
}
setWebViewTop()
// Do any additional setup after loading the view.
}
fileprivate func setWebViewTop(){
if self.isPop {
for constraint in self.view.constraints {
if constraint.firstAttribute == NSLayoutAttribute.top {
let inputWrapContraint = constraint as NSLayoutConstraint
inputWrapContraint.constant = UIApplication.shared.statusBarFrame.height+self.navigationController!.navigationBar.frame.height
break;
}
}
}
}
override func didRotate(from fromInterfaceOrientation: UIInterfaceOrientation) {
setWebViewTop()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func stopAndClose(_ sender: AnyObject) {
webView.stopLoading()
self.clearAllNotice()
if self.isPop {
self.navigationController?.popViewController(animated: true)
}else {
self.dismiss(animated: true, completion: nil)
}
}
override func viewWillDisappear(_ animated: Bool) {
self.clearAllNotice()
}
@IBAction func refreshWebView(_ sender: AnyObject) {
webView.reload()
}
@IBAction func rewindWebView(_ sender: AnyObject) {
webView.goBack()
}
@IBAction func forwardWebView(_ sender: AnyObject) {
webView.goForward()
}
@IBAction func shareClick(_ sender: AnyObject) {
let url = URL(fileURLWithPath:self.webView.request!.url!.absoluteString)
let title = self.webView.stringByEvaluatingJavaScript(from: "document.title")
let activityViewController = UIActivityViewController(activityItems: [title!,url], applicationActivities: nil)
self.present(activityViewController, animated: true,completion:nil)
}
func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool
{
self.clearAllNotice()
self.pleaseWait()
return true
}
func webViewDidStartLoad(_ webView: UIWebView)
{
}
func webViewDidFinishLoad(_ webView: UIWebView)
{
self.clearAllNotice()
self.title = self.webView.stringByEvaluatingJavaScript(from: "document.title")
}
func webView(_ webView: UIWebView, didFailLoadWithError error: Error)
{
self.clearAllNotice()
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
self.clearAllNotice()
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
|
b0e59219346f852e938c6bf1175ab820
| 24.4625 | 147 | 0.586892 | false | false | false | false |
prolificinteractive/Caishen
|
refs/heads/master
|
Pod/Classes/UI/Text Fields/CVCInputTextField.swift
|
mit
|
1
|
//
// CVCInputTextField.swift
// Caishen
//
// Created by Daniel Vancura on 3/8/16.
// Copyright © 2016 Prolific Interactive. All rights reserved.
//
import UIKit
/// A text field which can be used to enter CVCs and provides validation of the same.
open class CVCInputTextField: DetailInputTextField {
/// The card type for the CVC that should be entered. The length of a CVC can vary based on this card type.
open var cardType: CardType?
override var expectedInputLength: Int {
return cardType?.CVCLength ?? 3
}
/**
Checks the validity of the entered card validation code.
- precondition: The property `cardType` of `self` must match the card type for which a CVC should be validated.
- returns: True, if the card validation code is valid.
*/
internal override func isInputValid(_ cvcString: String, partiallyValid: Bool) -> Bool {
if cvcString.count == 0 && partiallyValid {
return true
}
let cvc = CVC(rawValue: cvcString)
return (cardType?.validate(cvc: cvc) == .Valid)
|| partiallyValid && (cardType?.validate(cvc: cvc) == .CVCIncomplete)
}
}
|
0568c87488156504a4292f1c5591bb49
| 32.138889 | 116 | 0.653814 | false | false | false | false |
wjk930726/weibo
|
refs/heads/master
|
weiBo/weiBo/iPhone/Modules/Compose/WBComposeCell.swift
|
mit
|
1
|
//
// WBComposeCell.swift
// weiBo
//
// Created by 王靖凯 on 2016/12/5.
// Copyright © 2016年 王靖凯. All rights reserved.
//
import UIKit
protocol WBComposeCellDelegate: NSObjectProtocol {
func composeCell(_ composeCell: WBComposeCell, addOrChangePhotoAtIndex index: Int)
func composeCell(_ composeCell: WBComposeCell, deletePhotoAtIndex index: Int)
}
class WBComposeCell: UICollectionViewCell {
weak var delegate: WBComposeCellDelegate?
var photo: UIImage? {
didSet {
if photo != nil {
photoButton.setImage(photo, for: .normal)
photoButton.isHidden = false
addButton.isHidden = true
} else {
photoButton.isHidden = true
addButton.isHidden = false
}
}
}
fileprivate lazy var addButton: UIButton = UIButton(title: nil, bgImage: "compose_pic_add", target: self, action: #selector(addOrChangePhoto))
fileprivate lazy var photoButton: UIButton = UIButton(title: nil, target: self, action: #selector(addOrChangePhoto))
fileprivate lazy var deleteButton: UIButton = UIButton(title: nil, image: "compose_photo_close", target: self, action: #selector(deletePhoto))
override init(frame: CGRect) {
super.init(frame: frame)
setupView()
}
required init?(coder _: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
extension WBComposeCell {
fileprivate func setupView() {
contentView.addSubview(addButton)
addButton.snp.makeConstraints { make in
make.edges.equalTo(contentView).inset(10)
}
contentView.addSubview(photoButton)
photoButton.contentMode = .scaleAspectFill
photoButton.snp.makeConstraints { make in
make.edges.equalTo(addButton)
}
photoButton.addSubview(deleteButton)
deleteButton.sizeToFit()
deleteButton.snp.makeConstraints { make in
make.top.equalTo(photoButton).offset(-10)
make.trailing.equalTo(photoButton.snp.trailing).offset(10)
}
}
}
extension WBComposeCell {
@objc fileprivate func addOrChangePhoto() {
delegate?.composeCell(self, addOrChangePhotoAtIndex: 0)
}
@objc fileprivate func deletePhoto() {
delegate?.composeCell(self, deletePhotoAtIndex: 0)
}
}
|
849b81233b1326963fdfb2b9ca7527dd
| 29.423077 | 146 | 0.653603 | false | false | false | false |
programersun/HiChongSwift
|
refs/heads/master
|
HiChongSwift/ICYShareViewController.swift
|
apache-2.0
|
1
|
//
// ICYShareViewController.swift
// HiChongSwift
//
// Created by eagle on 15/2/4.
// Copyright (c) 2015年 多思科技. All rights reserved.
//
import UIKit
class ICYShareViewController: UIViewController {
var messageDescription: String?
var weiboImage: UIImage?
var weiboMessage: String?
var wxTitle : String?
var wxDesciption : String?
var wxImg : UIImage?
var wxURL : String?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func weChatButtonPressed(sender: UIButton) {
println("message button pressed")
let message = WXMediaMessage()
message.title = wxTitle ?? "嗨宠宠物"
message.description = messageDescription ?? "嗨宠宠物,为您服务。"
message.setThumbImage(wxImg ?? UIImage(named: "placeholderLogo"))
// message.messageExt = "messageExt"
// message.messageAction = "<action>hichong</action>"
let ext = WXAppExtendObject()
ext.url = wxURL ?? "https://itunes.apple.com/us/app/hai-chong-chong-wu/id918809824?l=zh&ls=1&mt=8"
message.mediaObject = ext
let req = SendMessageToWXReq()
req.bText = false
req.message = message
req.scene = Int32(sender.tag)
WXApi.sendReq(req)
// let messageSender = MessageSender()
// messageSender.sendAppContent()
}
@IBAction func weiboButtonPressed(sender: AnyObject) {
let messageSender = MessageSender()
let wbMessage = WBWebpageObject()
wbMessage.title = wxTitle ?? "嗨宠宠物"
wbMessage.description = messageDescription ?? "嗨宠宠物,为您服务。"
wbMessage.thumbnailData = UIImageJPEGRepresentation(wxImg ?? UIImage(named: "placeholderLogo"), 1)
wbMessage.webpageUrl = wxURL ?? "https://itunes.apple.com/us/app/hai-chong-chong-wu/id918809824?l=zh&ls=1&mt=8"
messageSender.sendWeiboContent(wbMessage)
}
@IBAction func backgroundTouched(sender: AnyObject) {
view.removeFromSuperview()
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
deinit {
println("share view controller de init called")
}
}
|
33a299ceef5e593c37d8a1c254f601f8
| 30.886364 | 122 | 0.62402 | false | false | false | false |
googleprojectzero/fuzzilli
|
refs/heads/main
|
Sources/Fuzzilli/FuzzIL/Program.swift
|
apache-2.0
|
1
|
// Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import Foundation
/// Immutable unit of code that can, amongst others, be lifted, executed, scored, (de)serialized, and serve as basis for mutations.
///
/// A Program's code is guaranteed to have a number of static properties, as checked by code.isStaticallyValid():
/// * All input variables must have previously been defined
/// * Variables have increasing numbers starting at zero and there are no holes
/// * Variables are only used while they are visible (the block they were defined in is still active)
/// * Blocks are balanced and the opening and closing operations match (e.g. BeginIf is closed by EndIf)
/// * The outputs of an instruction are always new variables and never overwrite an existing variable
///
public final class Program {
/// The immutable code of this program.
public let code: Code
/// The parent program that was used to construct this program.
/// This is mostly only used when inspection mode is enabled to reconstruct
/// the "history" of a program.
public private(set) var parent: Program? = nil
/// Comments attached to this program
public var comments = ProgramComments()
/// Everything that contributed to this program. This is not preserved across protobuf serialization.
public var contributors = Contributors()
/// Each program has a unique ID to identify it even accross different fuzzer instances.
public private(set) lazy var id = UUID()
/// Constructs an empty program.
public init() {
self.code = Code()
self.parent = nil
}
/// Constructs a program with the given code. The code must be statically valid.
public init(with code: Code) {
assert(code.isStaticallyValid())
self.code = code
}
/// Construct a program with the given code and type information.
public convenience init(code: Code, parent: Program? = nil, comments: ProgramComments = ProgramComments(), contributors: Contributors = Contributors()) {
self.init(with: code)
self.comments = comments
self.contributors = contributors
self.parent = parent
}
/// The number of instructions in this program.
public var size: Int {
return code.count
}
/// Indicates whether this program is empty.
public var isEmpty: Bool {
return size == 0
}
public func clearParent() {
parent = nil
}
// Create and return a deep copy of this program.
public func copy() -> Program {
let proto = self.asProtobuf()
return try! Program(from: proto)
}
}
extension Program: ProtobufConvertible {
public typealias ProtobufType = Fuzzilli_Protobuf_Program
func asProtobuf(opCache: OperationCache? = nil, typeCache: TypeCache? = nil) -> ProtobufType {
return ProtobufType.with {
$0.uuid = id.uuidData
$0.code = code.map({ $0.asProtobuf(with: opCache) })
if !comments.isEmpty {
$0.comments = comments.asProtobuf()
}
if let parent = parent {
$0.parent = parent.asProtobuf(opCache: opCache, typeCache: typeCache)
}
}
}
public func asProtobuf() -> ProtobufType {
return asProtobuf(opCache: nil, typeCache: nil)
}
convenience init(from proto: ProtobufType, opCache: OperationCache? = nil, typeCache: TypeCache? = nil) throws {
var code = Code()
for (i, protoInstr) in proto.code.enumerated() {
do {
code.append(try Instruction(from: protoInstr, with: opCache))
} catch FuzzilliError.instructionDecodingError(let reason) {
throw FuzzilliError.programDecodingError("could not decode instruction #\(i): \(reason)")
}
}
do {
try code.check()
} catch FuzzilliError.codeVerificationError(let reason) {
throw FuzzilliError.programDecodingError("decoded code is not statically valid: \(reason)")
}
self.init(code: code)
if let uuid = UUID(uuidData: proto.uuid) {
self.id = uuid
}
self.comments = ProgramComments(from: proto.comments)
if proto.hasParent {
self.parent = try Program(from: proto.parent, opCache: opCache, typeCache: typeCache)
}
}
public convenience init(from proto: ProtobufType) throws {
try self.init(from: proto, opCache: nil, typeCache: nil)
}
}
|
adf5ec7a95e2e0d402d1b5bd3e94926d
| 35.330935 | 157 | 0.658218 | false | false | false | false |
rnystrom/GitHawk
|
refs/heads/master
|
Local Pods/GitHubAPI/Pods/Apollo/Sources/Apollo/RecordSet.swift
|
mit
|
1
|
/// A set of cache records.
public struct RecordSet {
public private(set) var storage: [CacheKey: Record] = [:]
public init<S: Sequence>(records: S) where S.Iterator.Element == Record {
insert(contentsOf: records)
}
public mutating func insert(_ record: Record) {
storage[record.key] = record
}
public mutating func clear() {
storage.removeAll()
}
public mutating func insert<S: Sequence>(contentsOf records: S) where S.Iterator.Element == Record {
for record in records {
insert(record)
}
}
public subscript(key: CacheKey) -> Record? {
return storage[key]
}
public var isEmpty: Bool {
return storage.isEmpty
}
public var keys: [CacheKey] {
return Array(storage.keys)
}
@discardableResult public mutating func merge(records: RecordSet) -> Set<CacheKey> {
var changedKeys: Set<CacheKey> = Set()
for (_, record) in records.storage {
changedKeys.formUnion(merge(record: record))
}
return changedKeys
}
@discardableResult public mutating func merge(record: Record) -> Set<CacheKey> {
if var oldRecord = storage.removeValue(forKey: record.key) {
var changedKeys: Set<CacheKey> = Set()
for (key, value) in record.fields {
if let oldValue = oldRecord.fields[key], equals(oldValue, value) {
continue
}
oldRecord[key] = value
changedKeys.insert([record.key, key].joined(separator: "."))
}
storage[record.key] = oldRecord
return changedKeys
} else {
storage[record.key] = record
return Set(record.fields.keys.map { [record.key, $0].joined(separator: ".") })
}
}
}
extension RecordSet: ExpressibleByDictionaryLiteral {
public init(dictionaryLiteral elements: (CacheKey, Record.Fields)...) {
self.init(records: elements.map { Record(key: $0.0, $0.1) })
}
}
extension RecordSet: CustomStringConvertible {
public var description: String {
return String(describing: Array(storage.values))
}
}
extension RecordSet: CustomPlaygroundQuickLookable {
public var customPlaygroundQuickLook: PlaygroundQuickLook {
return .text(description)
}
}
|
c826ae11ea39d1d5add571faf0117823
| 25.938272 | 102 | 0.659487 | false | false | false | false |
Rawrcoon/Twinkle
|
refs/heads/master
|
Twinkle/Twinkle/ViewController.swift
|
mit
|
3
|
// ViewController.swift
//
// Created by patrick piemonte on 2/20/15.
//
// The MIT License (MIT)
//
// Copyright (c) 2015-present patrick piemonte (http://patrickpiemonte.com/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import UIKit
class ViewController: UIViewController {
// MARK: object lifecycle
convenience init() {
self.init(nibName: nil, bundle:nil)
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
}
// MARK: view lifecycle
override func viewDidLoad() {
super.viewDidLoad()
self.view.autoresizingMask = (UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleHeight)
self.view.backgroundColor = UIColor(red: 81/255, green: 0, blue: 97/255, alpha: 1)
let button: UIButton = UIButton(frame: CGRectMake(0, 0, 240, 50))
button.center = self.view.center
button.setTitle("Tap to Twinkle", forState: .Normal)
button.titleLabel!.font = UIFont(name: "AvenirNext-Regular", size: 32)
button.addTarget(self, action: "handleButton:", forControlEvents: .TouchUpInside)
self.view.addSubview(button)
}
// MARK: UIButton handler
func handleButton(button: UIButton!) {
button.twinkle()
}
}
|
e4098808abe1afbed8e02936a432ab72
| 36.298507 | 107 | 0.697879 | false | false | false | false |
wattson12/Moya-Argo
|
refs/heads/master
|
Pod/Classes/ReactiveSwift/SignalProducer+Argo.swift
|
mit
|
1
|
//
// SignalProducer+Argo.swift
// Pods
//
// Created by Sam Watts on 23/01/2016.
//
//
import ReactiveSwift
import Moya
import Argo
public extension SignalProducerProtocol where Value == Moya.Response, Error == MoyaError {
/**
Map stream of responses into stream of objects decoded via Argo
- parameter type: Type used to make mapping more explicit. This isnt required, but means type needs to be specified at use
- parameter rootKey: optional root key of JSON used for mapping
- returns: returns Observable of mapped objects
*/
public func mapObject<T: Argo.Decodable>(type: T.Type, rootKey: String? = nil) -> SignalProducer<T, Error> where T == T.DecodedType {
return producer.flatMap(.latest) { response -> SignalProducer<T, Error> in
do {
return SignalProducer(value: try response.mapObject(rootKey: rootKey))
} catch let error as MoyaError {
return SignalProducer(error: error)
} catch let error as NSError {
return SignalProducer(error: Error.underlying(error, response))
}
}
}
/// convenience for mapping object without passing in decodable type as argument
public func mapObject<T: Argo.Decodable>(rootKey: String? = nil) -> SignalProducer<T, Error> where T == T.DecodedType {
return mapObject(type: T.self, rootKey: rootKey)
}
/**
Map stream of responses into stream of object array decoded via Argo
- parameter type: Type used to make mapping more explicit. This isnt required, but means type needs to be specified at use
- parameter rootKey: optional root key of JSON used for mapping
- returns: returns Observable of mapped object array
*/
public func mapArray<T: Argo.Decodable>(type: T.Type, rootKey: String? = nil) -> SignalProducer<[T], Error> where T == T.DecodedType {
return producer.flatMap(.latest) { response -> SignalProducer<[T], Error> in
do {
return SignalProducer(value: try response.mapArray(rootKey: rootKey))
} catch let error as MoyaError {
return SignalProducer(error: error)
} catch let error as NSError {
return SignalProducer(error: Error.underlying(error, response))
}
}
}
/// Convenience method for mapping array without passing in decodable type as argument
public func mapArray<T: Argo.Decodable>(rootKey: String? = nil) -> SignalProducer<[T], Error> where T == T.DecodedType {
return mapArray(type: T.self, rootKey: rootKey)
}
}
|
8c64ae6f998e5fbf6844395f440a614c
| 38.808824 | 138 | 0.636498 | false | false | false | false |
jbrjake/caturlog
|
refs/heads/develop
|
Caturlog/Caturlog/AppDelegate.swift
|
mit
|
1
|
//
// AppDelegate.swift
// Caturlog
//
// Created by Jonathon Rubin on 7/3/14.
// Copyright (c) 2014 Jonathon Rubin. All rights reserved.
//
import Cocoa
class AppDelegate: NSObject, NSApplicationDelegate {
let windowController: CaturlogWindowController = CaturlogWindowController(windowNibName: "CaturlogWindow")
let caturlogServices = CaturlogServices()
func applicationDidFinishLaunching(aNotification: NSNotification?) {
// Insert code here to initialize your application
windowController.showWindow(nil)
}
func applicationWillTerminate(aNotification: NSNotification?) {
// Insert code here to tear down your application
}
@IBAction func saveAction(sender: AnyObject) {
// Performs the save action for the application, which is to send the save: message to the application's managed object context. Any encountered errors are presented to the user.
var error: NSError? = nil
if let moc = self.managedObjectContext {
if !moc.commitEditing() {
println("\(NSStringFromClass(self.dynamicType)) unable to commit editing before saving")
}
if !moc.save(&error) {
NSApplication.sharedApplication().presentError(error)
}
}
}
var applicationFilesDirectory: NSURL {
// Returns the directory the application uses to store the Core Data store file. This code uses a directory named "us.ubiquit.Caturlog" in the user's Application Support directory.
let fileManager = NSFileManager.defaultManager()
let urls = fileManager.URLsForDirectory(.ApplicationSupportDirectory, inDomains: .UserDomainMask)
let appSupportURL: AnyObject = urls[urls.endIndex - 1]
return appSupportURL.URLByAppendingPathComponent("Caturlog")
}
var managedObjectModel: NSManagedObjectModel {
// Creates if necessary and returns the managed object model for the application.
if let mom = _managedObjectModel {
return mom
}
let modelURL = NSBundle.mainBundle().URLForResource("Caturlog", withExtension: "mom")
_managedObjectModel = NSManagedObjectModel(contentsOfURL: modelURL)
return _managedObjectModel!
}
var _managedObjectModel: NSManagedObjectModel? = nil
var persistentStoreCoordinator: NSPersistentStoreCoordinator? {
// Returns the persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it. (The directory for the store is created, if necessary.)
if let psc = _persistentStoreCoordinator {
return psc
}
let mom = self.managedObjectModel
let fileManager = NSFileManager.defaultManager()
let applicationFilesDirectory = self.applicationFilesDirectory
var error: NSError? = nil
let optProperties: NSDictionary? = applicationFilesDirectory.resourceValuesForKeys([NSURLIsDirectoryKey], error: &error)
if let properties = optProperties {
if !properties[NSURLIsDirectoryKey].boolValue {
// Customize and localize this error.
let failureDescription = "Expected a folder to store application data, found a file \(applicationFilesDirectory.path)."
let dict = NSMutableDictionary()
dict[NSLocalizedDescriptionKey] = failureDescription
error = NSError.errorWithDomain("YOUR_ERROR_DOMAIN", code: 101, userInfo: dict)
NSApplication.sharedApplication().presentError(error)
return nil
}
} else {
var ok = false
if error!.code == NSFileReadNoSuchFileError {
ok = fileManager.createDirectoryAtPath(applicationFilesDirectory.path, withIntermediateDirectories: true, attributes: nil, error: &error)
}
if !ok {
NSApplication.sharedApplication().presentError(error)
return nil
}
}
let url = applicationFilesDirectory.URLByAppendingPathComponent("Caturlog.storedata")
var coordinator = NSPersistentStoreCoordinator(managedObjectModel: mom)
if coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: [NSMigratePersistentStoresAutomaticallyOption : true, NSInferMappingModelAutomaticallyOption: true], error: &error) == nil {
NSApplication.sharedApplication().presentError(error)
return nil
}
_persistentStoreCoordinator = coordinator
return _persistentStoreCoordinator
}
var _persistentStoreCoordinator: NSPersistentStoreCoordinator? = nil
var managedObjectContext: NSManagedObjectContext? {
// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.)
if let moc = _managedObjectContext {
return moc
}
let coordinator = self.persistentStoreCoordinator
if !coordinator {
var dict = NSMutableDictionary()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the store"
dict[NSLocalizedFailureReasonErrorKey] = "There was an error building up the data file."
let error = NSError.errorWithDomain("YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
NSApplication.sharedApplication().presentError(error)
return nil
}
_managedObjectContext = NSManagedObjectContext()
_managedObjectContext!.persistentStoreCoordinator = coordinator!
return _managedObjectContext
}
var _managedObjectContext: NSManagedObjectContext? = nil
func windowWillReturnUndoManager(window: NSWindow?) -> NSUndoManager? {
// Returns the NSUndoManager for the application. In this case, the manager returned is that of the managed object context for the application.
if let moc = self.managedObjectContext {
return moc.undoManager
} else {
return nil
}
}
func applicationShouldTerminate(sender: NSApplication) -> NSApplicationTerminateReply {
// Save changes in the application's managed object context before the application terminates.
if !_managedObjectContext {
// Accesses the underlying stored property because we don't want to cause the lazy initialization
return .TerminateNow
}
let moc = self.managedObjectContext!
if !moc.commitEditing() {
println("\(NSStringFromClass(self.dynamicType)) unable to commit editing to terminate")
return .TerminateCancel
}
if !moc.hasChanges {
return .TerminateNow
}
var error: NSError? = nil
if !moc.save(&error) {
// Customize this code block to include application-specific recovery steps.
let result = sender.presentError(error)
if (result) {
return .TerminateCancel
}
let question = "Could not save changes while quitting. Quit anyway?" // NSLocalizedString(@"Could not save changes while quitting. Quit anyway?", @"Quit without saves error question message")
let info = "Quitting now will lose any changes you have made since the last successful save" // NSLocalizedString(@"Quitting now will lose any changes you have made since the last successful save", @"Quit without saves error question info");
let quitButton = "Quit anyway" // NSLocalizedString(@"Quit anyway", @"Quit anyway button title")
let cancelButton = "Cancel" // NSLocalizedString(@"Cancel", @"Cancel button title")
let alert = NSAlert()
alert.messageText = question
alert.informativeText = info
alert.addButtonWithTitle(quitButton)
alert.addButtonWithTitle(cancelButton)
let answer = alert.runModal()
if answer == NSAlertFirstButtonReturn {
return .TerminateCancel
}
}
return .TerminateNow
}
}
|
f2b982695b55dcd4e6ddcd459da45832
| 44.320652 | 253 | 0.660391 | false | false | false | false |
SmartThingsOSS/tigon.swift
|
refs/heads/master
|
Tigon/TigonExecutor.swift
|
apache-2.0
|
1
|
//
// TigonExecutor.swift
// Tigon
//
// Created by Steven Vlaminck on 4/4/16.
// Copyright © 2016 SmartThings. All rights reserved.
//
import Foundation
import WebKit
/**
TigonExecuter provides a simple interface for interacting with Javascript. It assumes Tigon.js is included in the HTML.
TigonExecutor has default implementations for WKWebView.
There is no need to implement this protocol unless you want custom behavior.
- seealso:
[tigon-js](https://github.com/SmartThingsOSS/tigon-js)
*/
public protocol TigonExecutor {
/**
A way to respond to a message with an error.
- parameters:
- id: The id of the original message
- error: The error to pass back to the sender of the original message
*/
func sendErrorResponse(_ id: String, error: NSError)
/**
A way to respond to a message with a success object.
- parameters:
- id: The id of the original message
- response: The success object to pass back to the sender of the original message
*/
func sendSuccessResponse(_ id: String, response: AnyObject)
/**
A way to send a message to javascript.
- parameters:
- message: The message to send. This can be a stringified object.
*/
func sendMessage(_ message: String)
/**
A way to stringify objects in a way that is standard to Tigon
- parameters:
- object: The object to stringify
This is called by `sendSuccessResponse` and `sendErrorResponse` before sending the message response.
*/
func stringifyResponse(_ object: AnyObject) -> String
/**
A simplified wrapper for `evaluateJavaScript`
- paramters:
- script: The script to be executed
*/
func executeJavascript(_ script: String)
}
extension WKWebView: TigonExecutor {
open func sendErrorResponse(_ id: String, error: NSError) {
let responseString = stringifyResponse(error)
let script = "tigon.receivedErrorResponse('\(id)', \(responseString))"
executeJavascript(script)
}
open func sendSuccessResponse(_ id: String, response: AnyObject) {
let responseString = stringifyResponse(response)
let script = "tigon.receivedSuccessResponse('\(id)', \(responseString))"
executeJavascript(script)
}
public func sendMessage(_ message: String) {
executeJavascript("tigon.receivedMessage(\(message))")
}
public func stringifyResponse(_ object: AnyObject) -> String {
var responseString = "{}"
do {
switch object {
case let dictionary as [AnyHashable: Any]:
let json = try JSONSerialization.data(withJSONObject: dictionary, options: .prettyPrinted)
if let encodedString = String(data: json, encoding: String.Encoding.utf8) {
responseString = encodedString
}
case let array as [AnyObject]:
let json = try JSONSerialization.data(withJSONObject: array, options: .prettyPrinted)
if let encodedString = String(data: json, encoding: String.Encoding.utf8) {
responseString = encodedString
}
case let string as String:
responseString = "{\n \"response\" : \"\(string)\"\n}"
case let error as NSError:
responseString = "{\n \"error\" : \"\(error.localizedDescription)\"\n}"
case let b as Bool:
responseString = "{\n \"response\" : \(b)\n}"
default:
print("Failed to match a condition for response object \(object)")
}
} catch {
print("Failed to stringify response object: \(object)")
}
return responseString
}
public func executeJavascript(_ script: String) {
evaluateJavaScript(script) { (_, error) -> Void in
if let error = error {
print("Tigon failed to evaluate javascript: \(script); error: \(error.localizedDescription)")
}
}
}
}
|
c7e5035432acc1b571de6841e1ed6fee
| 32.150794 | 120 | 0.606655 | false | false | false | false |
srn214/Floral
|
refs/heads/master
|
Floral/Pods/RxSwiftExt/Source/RxSwift/pausableBuffered.swift
|
mit
|
1
|
//
// pausableBuffered.swift
// RxSwiftExt
//
// Created by Tanguy Helesbeux on 24/05/2017.
// Copyright © 2017 RxSwift Community. All rights reserved.
//
import Foundation
import RxSwift
extension ObservableType {
/**
Pauses the elements of the source observable sequence based on the latest element from the second observable sequence.
While paused, elements from the source are buffered, limited to a maximum number of element.
When resumed, all bufered elements are flushed as single events in a contiguous stream.
- seealso: [pausable operator on reactivex.io](http://reactivex.io/documentation/operators/backpressure.html)
- parameter pauser: The observable sequence used to pause the source observable sequence.
- parameter limit: The maximum number of element buffered. Pass `nil` to buffer all elements without limit. Default 1.
- parameter flushOnCompleted: If `true` bufered elements will be flushed when the source completes. Default `true`.
- parameter flushOnError: If `true` bufered elements will be flushed when the source errors. Default `true`.
- returns: The observable sequence which is paused and resumed based upon the pauser observable sequence.
*/
public func pausableBuffered<P: ObservableType> (_ pauser: P, limit: Int? = 1, flushOnCompleted: Bool = true, flushOnError: Bool = true) -> Observable<Element> where P.Element == Bool {
return Observable<Element>.create { observer in
var buffer: [Element] = []
if let limit = limit {
buffer.reserveCapacity(limit)
}
var paused = true
let lock = NSRecursiveLock()
let flush = {
for value in buffer {
observer.onNext(value)
}
buffer.removeAll(keepingCapacity: limit != nil)
}
let boundaryDisposable = pauser.subscribe { event in
lock.lock(); defer { lock.unlock() }
switch event {
case .next(let resume):
paused = !resume
if resume && buffer.count > 0 {
flush()
}
case .completed:
observer.onCompleted()
case .error(let error):
observer.onError(error)
}
}
let disposable = self.subscribe { event in
lock.lock(); defer { lock.unlock() }
switch event {
case .next(let element):
if paused {
buffer.append(element)
if let limit = limit, buffer.count > limit {
buffer.remove(at: 0)
}
} else {
observer.onNext(element)
}
case .completed:
if flushOnCompleted { flush() }
observer.onCompleted()
case .error(let error):
if flushOnError { flush() }
observer.onError(error)
}
}
return Disposables.create([disposable, boundaryDisposable])
}
}
}
|
dd14fb2467bc3a812a22822219e4070a
| 36 | 189 | 0.547147 | false | false | false | false |
apple/swift
|
refs/heads/main
|
test/expr/primary/keypath/keypath-observe-objc.swift
|
apache-2.0
|
1
|
// RUN: %target-typecheck-verify-swift
// REQUIRES: objc_interop
import Foundation
class Foo: NSObject {
var number1 = 1
dynamic var number2 = 2
@objc var number3 = 3
@objc dynamic var number4 = 4
@objc var number5: Int {
get { return 5 }
set {}
}
}
class Bar: NSObject {
@objc dynamic let foo: Foo
init(foo: Foo) {
self.foo = foo
super.init()
_ = observe(\.foo.number1, options: [.new]) { _, change in
// expected-warning@-1 {{passing reference to non-'@objc dynamic' property 'number1' to KVO method 'observe(_:options:changeHandler:)' may lead to unexpected behavior or runtime trap}}
print("observer1")
}
_ = observe(\.foo.number2, options: [.new]) { _, change in
// expected-warning@-1 {{passing reference to non-'@objc dynamic' property 'number2' to KVO method 'observe(_:options:changeHandler:)' may lead to unexpected behavior or runtime trap}}
print("observer2")
}
_ = observe(\.foo.number3, options: [.new]) { _, change in
// expected-warning@-1 {{passing reference to non-'@objc dynamic' property 'number3' to KVO method 'observe(_:options:changeHandler:)' may lead to unexpected behavior or runtime trap}}
print("observer3")
}
_ = observe(\.foo.number4, options: [.new]) { _, change in // Okay
print("observer4")
}
_ = observe(\.foo.number5, options: [.new]) { _, change in // Okay
print("observer4")
}
}
}
@_semantics("keypath.mustBeValidForKVO")
func quux<T, V, U>(_ object: T, at keyPath: KeyPath<T, V>, _ keyPath2: KeyPath<T, U>) { }
// The presence of a valid keypath should not prevent detection of invalid ones
// later in the argument list, so start with a valid one here.
quux(Foo(), at: \.number4, \.number1)
// expected-warning@-1 {{passing reference to non-'@objc dynamic' property 'number1' to KVO method 'quux(_:at:_:)' may lead to unexpected behavior or runtime trap}}
|
56c71fef7b22da63fe02907f2243046e
| 34.4 | 190 | 0.645095 | false | false | false | false |
BigxMac/firefox-ios
|
refs/heads/master
|
Client/Frontend/Browser/URIFixup.swift
|
mpl-2.0
|
29
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
class URIFixup {
func getURL(entry: String) -> NSURL? {
let trimmed = entry.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
var url = NSURL(string: trimmed)
// First check if the URL includes a scheme. This will handle
// all valid requests starting with "http://", "about:", etc.
if url?.scheme != nil {
return url
}
// If there's no scheme, we're going to prepend "http://". First,
// make sure there's at least one "." in the host. This means
// we'll allow single-word searches (e.g., "foo") at the expense
// of breaking single-word hosts without a scheme (e.g., "localhost").
if trimmed.rangeOfString(".") == nil {
return nil
}
// If there is a ".", prepend "http://" and try again. Since this
// is strictly an "http://" URL, we also require a host.
url = NSURL(string: "http://\(trimmed)")
if url?.host != nil {
return url
}
return nil
}
}
|
ef69637cdfc61911f83951997a5cf29c
| 36.142857 | 110 | 0.594303 | false | false | false | false |
mittenimraum/CVGenericDataSource
|
refs/heads/master
|
Sources/CVGenericDataSourceSection.swift
|
mit
|
1
|
//
// CVGenericDataSourceSection.swift
// CVGenericDataSource
//
// Created by Stephan Schulz on 12.04.17.
// Copyright © 2017 Stephan Schulz. All rights reserved.
//
import Foundation
// MARK: - CVSectionProtocol
public protocol CVSectionProtocol {
associatedtype Item: Equatable
var items: [Item] { get set }
var headerTitle: String? { get }
var footerTitle: String? { get }
}
// MARK: - CVSectionOptionProtocol
public protocol CVSectionOptionProtocol {
associatedtype Item: Equatable
var insets: UIEdgeInsets? { get }
var headerShouldAppear: Bool { get }
var footerShouldAppear: Bool { get }
var lineSpacing: CGFloat? { get }
var cellSpacing: CGFloat? { get }
func selection(_ item: Item?, _ index: Int) -> Void
}
// MARK: - CVSection
public struct CVSection<Item: Equatable>: CVSectionProtocol {
// MARK: - Options
public enum CVSectionOption {
case insets(UIEdgeInsets)
case selection(CVSectionSelection)
case headerShouldAppear(Bool)
case footerShouldAppear(Bool)
case lineSpacing(CGFloat)
case cellSpacing(CGFloat)
}
public var options: [CVSectionOption]? {
didSet {
guard let options = options else {
return
}
for option in options {
switch option {
case let .insets(value):
_optionInsets = value
case let .selection(value):
_optionSelection = value
case let .headerShouldAppear(value):
_optionHeaderShouldAppear = value
case let .footerShouldAppear(value):
_optionFooterShouldAppear = value
case let .lineSpacing(value):
_optionLineSpacing = value
case let .cellSpacing(value):
_optionCellSpacing = value
}
}
}
}
fileprivate var _optionLineSpacing: CGFloat?
fileprivate var _optionCellSpacing: CGFloat?
fileprivate var _optionFooterShouldAppear: Bool?
fileprivate var _optionHeaderShouldAppear: Bool?
fileprivate var _optionInsets: UIEdgeInsets?
fileprivate var _optionSelection: CVSectionSelection?
// MARK: - Constants
public let headerTitle: String?
public let footerTitle: String?
// MARK: - Variables
public var items: [Item]
public var count: Int {
return items.count
}
// MARK: - Init
public init(items: Item..., headerTitle: String? = nil, footerTitle: String? = nil, _ options: [CVSectionOption]? = nil) {
self.init(items, headerTitle: headerTitle, footerTitle: footerTitle, options)
}
public init(_ items: [Item], headerTitle: String? = nil, footerTitle: String? = nil, _ options: [CVSectionOption]? = nil) {
self.items = items
self.headerTitle = headerTitle
self.footerTitle = footerTitle
defer {
self.options = options
}
}
// MARK: - Subscript
public subscript(index: Int) -> Item {
get {
return items[index]
}
set {
items[index] = newValue
}
}
}
// MARK: - Extensions
extension CVSection: CVSectionOptionProtocol {
public typealias CVSectionSelection = (_ item: Item?, _ index: Int) -> Void
public var cellSpacing: CGFloat? {
return _optionCellSpacing
}
public var lineSpacing: CGFloat? {
return _optionLineSpacing
}
public var insets: UIEdgeInsets? {
return _optionInsets
}
public var headerShouldAppear: Bool {
return _optionHeaderShouldAppear ?? true
}
public var footerShouldAppear: Bool {
return _optionFooterShouldAppear ?? false
}
public func selection(_ item: Item?, _ index: Int) {
_optionSelection?(item, index)
}
}
|
24a3df5dd5d225abd77122f894e5ae3a
| 25.177632 | 127 | 0.601156 | false | false | false | false |
kay-kim/stitch-examples
|
refs/heads/master
|
todo/ios/MongoDBSample/Classes/Controllers/Authentication/EmailAuthViewController.swift
|
apache-2.0
|
1
|
//
// EmailAuthViewController.swift
// MongoDBSample
//
//
import UIKit
import StitchCore
protocol EmailAuthViewControllerDelegate {
func emailAuthViewControllerDidPressCloseEmail()
}
enum EmailAuthOperationType {
case confirmEmail(token: String, tokenId: String)
case resetPassword(token: String, tokenId: String)
}
class EmailAuthViewController: UIViewController {
@IBOutlet weak var activityIndicator: UIActivityIndicatorView!
@IBOutlet weak var infoLabel: UILabel!
var stitchClient: StitchClient?
var delegate: EmailAuthViewControllerDelegate?
var operationType: EmailAuthOperationType?
override func viewDidLoad() {
super.viewDidLoad()
if let operationType = operationType {
switch operationType {
case .confirmEmail(let token, let tokenId):
confirmEmail(token: token, tokenId: tokenId)
case .resetPassword(let token, let tokenId):
resetPassword(token: token, tokenId: tokenId)
}
}
else {
activityIndicator.isHidden = true
infoLabel.text = "Missing operation to perform"
}
}
func confirmEmail(token: String, tokenId: String) {
/*
activityIndicator.isHidden = false
infoLabel.text = "Confirming Email..."
stitchClient?.emailConfirm(token: token, tokenId: tokenId)
.response(completionHandler: { [weak self] (result) in
self?.activityIndicator.isHidden = true
switch result {
case .success:
self?.infoLabel.text = "Email Confirmed!"
break
case .failure(let error):
self?.infoLabel.text = error.localizedDescription
break
}
})*/
}
func resetPassword(token: String, tokenId: String) {
/*
activityIndicator.isHidden = false
infoLabel.text = "Resetting Password..."
stitchClient?.resetPassword(token: token, tokenId: tokenId)
.response(completionHandler: { [weak self] (result) in
self?.activityIndicator.isHidden = true
switch result {
case .success:
self?.infoLabel.text = "Password Reset!"
break
case .failure(let error):
self?.infoLabel.text = error.localizedDescription
break
}
})
*/
}
//MARK: - Actions
@IBAction func closeButtonPressed(_ sender: Any) {
delegate?.emailAuthViewControllerDidPressCloseEmail()
}
}
|
da5371619ff4a05bef550e8d028bad06
| 28.521739 | 69 | 0.58542 | false | false | false | false |
e-liu/LayoutKit
|
refs/heads/master
|
LayoutKitTests/TextExtension.swift
|
apache-2.0
|
2
|
// Copyright 2016 LinkedIn Corp.
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License.
// You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
import UIKit
import LayoutKit
extension Text {
struct TestCase {
let text: Text
let font: UIFont?
}
static var testCases: [TestCase] {
let fontNames: [String?] = [
nil,
"Helvetica",
"Helvetica Neue"
]
let texts: [Text] = [
.unattributed(""),
.unattributed(" "),
.unattributed("Hi"),
.unattributed("Hello world"),
.unattributed("Hello! 😄😄😄"),
.attributed(NSAttributedString(string: "")),
.attributed(NSAttributedString(string: " ")),
.attributed(NSAttributedString(string: "", attributes: [NSFontAttributeName: UIFont.helvetica(size: 42)])),
.attributed(NSAttributedString(string: " ", attributes: [NSFontAttributeName: UIFont.helvetica(size: 42)])),
.attributed(NSAttributedString(string: "Hi")),
.attributed(NSAttributedString(string: "Hello world")),
.attributed(NSAttributedString(string: "Hello! 😄😄😄")),
.attributed(NSAttributedString(string: "Hello! 😄😄😄", attributes: [NSFontAttributeName: UIFont.helvetica(size: 42)])),
]
let fontSizes = 0...20
var tests = [TestCase]()
for fontName in fontNames {
for fontSize in fontSizes {
let font = fontName.flatMap({ (fontName) -> UIFont? in
return UIFont(name: fontName, size: CGFloat(fontSize))
})
for text in texts {
tests.append(TestCase(text: text, font: font))
}
}
}
return tests
}
}
|
a31a685e09af9fe29e3db7333399445e
| 36.54386 | 131 | 0.585047 | false | true | false | false |
rokuz/omim
|
refs/heads/master
|
iphone/Maps/Bookmarks/Categories/Sharing/BookmarksSharingViewController.swift
|
apache-2.0
|
1
|
import SafariServices
@objc
protocol BookmarksSharingViewControllerDelegate: AnyObject {
func didShareCategory()
}
final class BookmarksSharingViewController: MWMTableViewController {
@objc var category: MWMCategory!
@objc weak var delegate: BookmarksSharingViewControllerDelegate?
private var sharingTags: [MWMTag]?
private var sharingUserStatus: MWMCategoryAuthorType?
private var manager: MWMBookmarksManager {
return MWMBookmarksManager.shared()
}
private let kPropertiesControllerIdentifier = "chooseProperties"
private let kTagsControllerIdentifier = "tags"
private let kNameControllerIdentifier = "guideName"
private let kDescriptionControllerIdentifier = "guideDescription"
private let kEditOnWebSegueIdentifier = "editOnWeb"
private let privateSectionIndex = 0
private let publicSectionIndex = 1
private let editOnWebSectionIndex = 2
private let rowsInEditOnWebSection = 1
private let directLinkUpdateRowIndex = 2
private let publishUpdateRowIndex = 2
private var rowsInPublicSection: Int {
return (category.accessStatus == .public && uploadAndPublishCell.cellState != .updating) ? 3 : 2
}
private var rowsInPrivateSection: Int {
return (category.accessStatus == .private && getDirectLinkCell.cellState != .updating) ? 3 : 2
}
@IBOutlet weak var uploadAndPublishCell: UploadActionCell!
@IBOutlet weak var getDirectLinkCell: UploadActionCell!
@IBOutlet weak var updatePublishCell: UITableViewCell!
@IBOutlet weak var updateDirectLinkCell: UITableViewCell!
@IBOutlet weak var directLinkInstructionsLabel: UILabel!
@IBOutlet weak var editOnWebButton: UIButton! {
didSet {
editOnWebButton.setTitle(L("edit_on_web").uppercased(), for: .normal)
}
}
@IBOutlet private weak var licenseAgreementTextView: UITextView! {
didSet {
let htmlString = String(coreFormat: L("ugc_routes_user_agreement"),
arguments: [MWMAuthorizationViewModel.termsOfUseLink()])
let attributes: [NSAttributedString.Key : Any] = [NSAttributedString.Key.font: UIFont.regular14(),
NSAttributedString.Key.foregroundColor: UIColor.blackSecondaryText()]
licenseAgreementTextView.attributedText = NSAttributedString.string(withHtml: htmlString,
defaultAttributes: attributes)
licenseAgreementTextView.delegate = self
}
}
override func viewDidLoad() {
super.viewDidLoad()
assert(category != nil, "We can't share nothing")
title = L("sharing_options")
configureActionCells()
switch category.accessStatus {
case .local:
break
case .public:
getDirectLinkCell.cellState = .disabled
uploadAndPublishCell.cellState = .completed
directLinkInstructionsLabel.text = L("unable_get_direct_link_desc")
case .private:
getDirectLinkCell.cellState = .completed
case .authorOnly:
break
case .other:
break
}
}
private func configureActionCells() {
uploadAndPublishCell.config(titles: [ .normal : L("upload_and_publish"),
.inProgress : L("upload_and_publish_progress_text"),
.updating : L("direct_link_updating_text"),
.completed : L("upload_and_publish_success") ],
image: UIImage(named: "ic24PxGlobe"),
delegate: self)
getDirectLinkCell.config(titles: [ .normal : L("upload_and_get_direct_link"),
.inProgress : L("direct_link_progress_text"),
.updating : L("direct_link_updating_text"),
.completed : L("direct_link_success"),
.disabled : L("upload_and_publish_success")],
image: UIImage(named: "ic24PxLink"),
delegate: self)
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableView.automaticDimension
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
switch section {
case publicSectionIndex:
return rowsInPublicSection
case privateSectionIndex:
return rowsInPrivateSection
case editOnWebSectionIndex:
return rowsInEditOnWebSection
default:
return 0
}
}
override func tableView(_ tableView: UITableView,
titleForHeaderInSection section: Int) -> String? {
switch section {
case 0:
return L("limited_access")
case 1:
return L("public_access")
case 2:
return L("edit_on_web")
default:
return nil
}
}
override func tableView(_ tableView: UITableView,
willSelectRowAt indexPath: IndexPath) -> IndexPath? {
let cell = tableView.cellForRow(at: indexPath)
if cell == getDirectLinkCell && getDirectLinkCell.cellState != .normal
|| cell == uploadAndPublishCell && uploadAndPublishCell.cellState != .normal {
return nil
}
return indexPath
}
override func tableView(_ tableView: UITableView,
didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
let cell = tableView.cellForRow(at: indexPath)
if cell == uploadAndPublishCell {
startUploadAndPublishFlow()
} else if cell == getDirectLinkCell {
uploadAndGetDirectLink(update: false)
} else if cell == updatePublishCell {
updatePublic()
} else if cell == updateDirectLinkCell {
updateDirectLink()
}
}
private func updatePublic() {
let updateAction = { [unowned self] in
self.performAfterValidation(anchor: self.uploadAndPublishCell) { [weak self] in
guard let self = self else { return }
if self.category.title.isEmpty || self.category.detailedAnnotation.isEmpty {
self.showMalformedDataError()
return
}
if (self.category.trackCount + self.category.bookmarksCount < 3) {
MWMAlertViewController
.activeAlert()
.presentInfoAlert(L("error_public_not_enought_title"),
text: L("error_public_not_enought_subtitle"))
return
}
self.uploadAndPublish(update: true)
}
}
MWMAlertViewController
.activeAlert()
.presentDefaultAlert(withTitle: L("any_access_update_alert_title"),
message: L("any_access_update_alert_message"),
rightButtonTitle: L("any_access_update_alert_update"),
leftButtonTitle: L("cancel"),
rightButtonAction: updateAction)
}
private func updateDirectLink() {
MWMAlertViewController.activeAlert().presentDefaultAlert(withTitle: L("any_access_update_alert_title"),
message: L("any_access_update_alert_message"),
rightButtonTitle: L("any_access_update_alert_update"),
leftButtonTitle: L("cancel")) {
self.uploadAndGetDirectLink(update: true)
}
}
private func startUploadAndPublishFlow() {
Statistics.logEvent(kStatSharingOptionsClick, withParameters: [kStatItem : kStatPublic])
let alert = EditOnWebAlertViewController(with: L("bookmark_public_upload_alert_title"),
message: L("bookmark_public_upload_alert_subtitle"),
acceptButtonTitle: L("bookmark_public_upload_alert_ok_button"))
alert.onAcceptBlock = { [unowned self] in
self.dismiss(animated: true)
self.performAfterValidation(anchor: self.uploadAndPublishCell) { [weak self] in
if let self = self {
if (self.category.trackCount + self.category.bookmarksCount > 2) {
self.showEditName()
} else {
MWMAlertViewController.activeAlert().presentInfoAlert(L("error_public_not_enought_title"),
text: L("error_public_not_enought_subtitle"))
}
}
}
}
alert.onCancelBlock = { [unowned self] in self.dismiss(animated: true) }
present(alert, animated: true)
}
private func uploadAndPublish(update: Bool) {
if !update {
guard let tags = sharingTags, let userStatus = sharingUserStatus else {
assert(false, "not enough data for public sharing")
return
}
manager.setCategory(category.categoryId, authorType: userStatus)
manager.setCategory(category.categoryId, tags: tags)
}
uploadAndPublishCell.cellState = update ? .updating : .inProgress
if update {
self.tableView.deleteRows(at: [IndexPath(row: self.publishUpdateRowIndex,
section: self.publicSectionIndex)],
with: .automatic)
}
manager.uploadAndPublishCategory(withId: category.categoryId, progress: nil) { (error) in
if let error = error as NSError? {
self.uploadAndPublishCell.cellState = .normal
self.showErrorAlert(error)
} else {
self.uploadAndPublishCell.cellState = .completed
Statistics.logEvent(kStatSharingOptionsUploadSuccess, withParameters:
[kStatTracks : self.category.trackCount,
kStatPoints : self.category.bookmarksCount])
self.getDirectLinkCell.cellState = .disabled
self.directLinkInstructionsLabel.text = L("unable_get_direct_link_desc")
self.tableView.beginUpdates()
let directLinkUpdateIndexPath = IndexPath(row: self.directLinkUpdateRowIndex,
section: self.privateSectionIndex)
if (self.tableView.cellForRow(at: directLinkUpdateIndexPath) != nil) {
self.tableView.deleteRows(at: [directLinkUpdateIndexPath], with: .automatic)
}
self.tableView.insertRows(at: [IndexPath(row: self.publishUpdateRowIndex,
section: self.publicSectionIndex)],
with: .automatic)
self.tableView.endUpdates()
if update {
Toast.toast(withText: L("direct_link_updating_success")).show()
}
}
}
}
private func uploadAndGetDirectLink(update: Bool) {
Statistics.logEvent(kStatSharingOptionsClick, withParameters: [kStatItem : kStatPrivate])
performAfterValidation(anchor: getDirectLinkCell) { [weak self] in
guard let s = self else {
assert(false, "Unexpected self == nil")
return
}
s.getDirectLinkCell.cellState = update ? .updating : .inProgress
if update {
s.tableView.deleteRows(at: [IndexPath(item: s.directLinkUpdateRowIndex,
section: s.privateSectionIndex)],
with: .automatic)
}
s.manager.uploadAndGetDirectLinkCategory(withId: s.category.categoryId, progress: nil) { (error) in
if let error = error as NSError? {
s.getDirectLinkCell.cellState = .normal
s.showErrorAlert(error)
} else {
s.getDirectLinkCell.cellState = .completed
s.delegate?.didShareCategory()
Statistics.logEvent(kStatSharingOptionsUploadSuccess, withParameters:
[kStatTracks : s.category.trackCount,
kStatPoints : s.category.bookmarksCount])
s.tableView.insertRows(at: [IndexPath(item: s.directLinkUpdateRowIndex,
section: s.privateSectionIndex)],
with: .automatic)
if update {
Toast.toast(withText: L("direct_link_updating_success")).show()
}
}
}
}
}
private func performAfterValidation(anchor: UIView, action: @escaping MWMVoidBlock) {
if FrameworkHelper.isNetworkConnected() {
signup(anchor: anchor, onComplete: { success in
if success {
action()
} else {
Statistics.logEvent(kStatSharingOptionsError, withParameters: [kStatError : 1])
}
})
} else {
Statistics.logEvent(kStatSharingOptionsError, withParameters: [kStatError : 0])
MWMAlertViewController.activeAlert().presentDefaultAlert(withTitle: L("common_check_internet_connection_dialog_title"),
message: L("common_check_internet_connection_dialog"),
rightButtonTitle: L("downloader_retry"),
leftButtonTitle: L("cancel")) {
self.performAfterValidation(anchor: anchor,
action: action)
}
}
}
private func showErrorAlert(_ error: NSError) {
guard error.code == kCategoryUploadFailedCode,
let statusCode = error.userInfo[kCategoryUploadStatusKey] as? Int,
let status = MWMCategoryUploadStatus(rawValue: statusCode) else {
assert(false)
return
}
switch (status) {
case .networkError:
Statistics.logEvent(kStatSharingOptionsUploadError, withParameters: [kStatError : 1])
self.showUploadError()
case .serverError:
Statistics.logEvent(kStatSharingOptionsUploadError, withParameters: [kStatError : 2])
self.showUploadError()
case .authError:
Statistics.logEvent(kStatSharingOptionsUploadError, withParameters: [kStatError : 3])
self.showUploadError()
case .malformedData:
Statistics.logEvent(kStatSharingOptionsUploadError, withParameters: [kStatError : 4])
self.showMalformedDataError()
case .accessError:
Statistics.logEvent(kStatSharingOptionsUploadError, withParameters: [kStatError : 5])
self.showAccessError()
case .invalidCall:
Statistics.logEvent(kStatSharingOptionsUploadError, withParameters: [kStatError : 6])
assert(false, "sharing is not available for paid bookmarks")
}
}
private func showUploadError() {
MWMAlertViewController.activeAlert().presentInfoAlert(L("unable_upload_errorr_title"),
text: L("upload_error_toast"))
}
private func showMalformedDataError() {
let alert = EditOnWebAlertViewController(with: L("html_format_error_title"),
message: L("html_format_error_subtitle"),
acceptButtonTitle: L("edit_on_web").uppercased())
alert.onAcceptBlock = {
self.dismiss(animated: true, completion: {
self.performSegue(withIdentifier: self.kEditOnWebSegueIdentifier, sender: nil)
})
}
alert.onCancelBlock = {
self.dismiss(animated: true)
}
navigationController?.present(alert, animated: true)
}
private func showAccessError() {
let alert = EditOnWebAlertViewController(with: L("public_or_limited_access_after_edit_online_error_title"),
message: L("public_or_limited_access_after_edit_online_error_message"),
acceptButtonTitle: L("edit_on_web").uppercased())
alert.onAcceptBlock = {
self.dismiss(animated: true, completion: {
self.performSegue(withIdentifier: self.kEditOnWebSegueIdentifier, sender: nil)
})
}
alert.onCancelBlock = {
self.dismiss(animated: true)
}
navigationController?.present(alert, animated: true)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == kEditOnWebSegueIdentifier {
Statistics.logEvent(kStatSharingOptionsClick, withParameters: [kStatItem : kStatEditOnWeb])
if let vc = segue.destination as? EditOnWebViewController {
vc.delegate = self
vc.category = category
}
}
}
private func showEditName() {
let storyboard = UIStoryboard.instance(.sharing)
let guideNameController = storyboard.instantiateViewController(withIdentifier: kNameControllerIdentifier)
as! GuideNameViewController
guideNameController.guideName = category.title
guideNameController.delegate = self
navigationController?.pushViewController(guideNameController, animated: true)
}
private func showEditDescr() {
let storyboard = UIStoryboard.instance(.sharing)
let guideDescrController = storyboard.instantiateViewController(withIdentifier: kDescriptionControllerIdentifier)
as! GuideDescriptionViewController
guideDescrController.guideDescription = category.detailedAnnotation
guideDescrController.delegate = self
replaceTopViewController(guideDescrController, animated: true)
}
private func showSelectTags() {
let storyboard = UIStoryboard.instance(.sharing)
let tagsController = storyboard.instantiateViewController(withIdentifier: kTagsControllerIdentifier)
as! SharingTagsViewController
tagsController.delegate = self
replaceTopViewController(tagsController, animated: true)
}
private func showSelectProperties() {
let storyboard = UIStoryboard.instance(.sharing)
let propertiesController = storyboard.instantiateViewController(withIdentifier: kPropertiesControllerIdentifier)
as! SharingPropertiesViewController
propertiesController.delegate = self
replaceTopViewController(propertiesController, animated: true)
}
private func replaceTopViewController(_ viewController: UIViewController, animated: Bool) {
guard var viewControllers = navigationController?.viewControllers else {
assert(false)
return
}
viewControllers.removeLast()
viewControllers.append(viewController)
navigationController?.setViewControllers(viewControllers, animated: animated)
}
}
extension BookmarksSharingViewController: UITextViewDelegate {
func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange) -> Bool {
let safari = SFSafariViewController(url: URL)
present(safari, animated: true, completion: nil)
return false
}
}
extension BookmarksSharingViewController: UploadActionCellDelegate {
func cellDidPressShareButton(_ cell: UploadActionCell, senderView: UIView) {
if cell == uploadAndPublishCell {
share(manager.publicLink(forCategoryId: category.categoryId), senderView: senderView)
} else if cell == getDirectLinkCell {
share(manager.deeplink(forCategoryId: category.categoryId), senderView: senderView)
} else {
assert(false, "unsupported cell")
}
}
func share(_ url: URL?, senderView: UIView) {
guard let url = url else {
assert(false, "must provide guide url")
return
}
Statistics.logEvent(kStatSharingOptionsClick, withParameters: [kStatItem : kStatCopyLink])
let message = String(coreFormat: L("share_bookmarks_email_body_link"), arguments: [url.absoluteString])
let shareController = MWMActivityViewController.share(for: nil, message: message) {
_, success, _, _ in
if success {
Statistics.logEvent(kStatSharingLinkSuccess, withParameters: [kStatFrom : kStatSharingOptions])
}
}
shareController?.present(inParentViewController: self, anchorView: senderView)
}
}
extension BookmarksSharingViewController: SharingTagsViewControllerDelegate {
func sharingTagsViewController(_ viewController: SharingTagsViewController, didSelect tags: [MWMTag]) {
navigationController?.popViewController(animated: true)
sharingTags = tags
uploadAndPublish(update: false)
}
func sharingTagsViewControllerDidCancel(_ viewController: SharingTagsViewController) {
navigationController?.popViewController(animated: true)
}
}
extension BookmarksSharingViewController: SharingPropertiesViewControllerDelegate {
func sharingPropertiesViewController(_ viewController: SharingPropertiesViewController,
didSelect userStatus: MWMCategoryAuthorType) {
sharingUserStatus = userStatus
showSelectTags()
}
}
extension BookmarksSharingViewController: EditOnWebViewControllerDelegate {
func editOnWebViewControllerDidFinish(_ viewController: EditOnWebViewController) {
navigationController?.popViewController(animated: true)
}
}
extension BookmarksSharingViewController: GuideNameViewControllerDelegate {
func viewController(_ viewController: GuideNameViewController, didFinishEditing text: String) {
category.title = text
showEditDescr()
}
}
extension BookmarksSharingViewController: GuideDescriptionViewControllerDelegate {
func viewController(_ viewController: GuideDescriptionViewController, didFinishEditing text: String) {
category.detailedAnnotation = text
showSelectProperties()
}
}
|
f8a22430e4ca7644cbcf581beb6d8657
| 39.845124 | 125 | 0.649658 | false | false | false | false |
hirohisa/RxSwift
|
refs/heads/master
|
RxExample/RxExample/Examples/WikipediaImageSearch/WikipediaAPI/WikipediaSearchResult.swift
|
mit
|
3
|
//
// WikipediaSearchResult.swift
// Example
//
// Created by Krunoslav Zaher on 3/28/15.
// Copyright (c) 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
#if !RX_NO_MODULE
import RxSwift
#endif
struct WikipediaSearchResult: Printable {
let title: String
let description: String
let URL: NSURL
init(title: String, description: String, URL: NSURL) {
self.title = title
self.description = description
self.URL = URL
}
// tedious parsing part
static func parseJSON(json: [AnyObject]) -> RxResult<[WikipediaSearchResult]> {
let rootArrayTyped = json.map { $0 as? [AnyObject] }
.filter { $0 != nil }
.map { $0! }
if rootArrayTyped.count != 3 {
return failure(WikipediaParseError)
}
let titleAndDescription = Array(Swift.Zip2(rootArrayTyped[0], rootArrayTyped[1]))
let titleDescriptionAndUrl: [((AnyObject, AnyObject), AnyObject)] = Array(Swift.Zip2(titleAndDescription, rootArrayTyped[2]))
let searchResults: [RxResult<WikipediaSearchResult>] = titleDescriptionAndUrl.map ( { result -> RxResult<WikipediaSearchResult> in
let ((title: AnyObject, description: AnyObject), url: AnyObject) = result
let titleString = title as? String,
descriptionString = description as? String,
urlString = url as? String
if titleString == nil || descriptionString == nil || urlString == nil {
return failure(WikipediaParseError)
}
let URL = NSURL(string: urlString!)
if URL == nil {
return failure(WikipediaParseError)
}
return success(WikipediaSearchResult(title: titleString!, description: descriptionString!, URL: URL!))
})
let values = (searchResults.filter { $0.isSuccess }).map { $0.get() }
return success(values)
}
}
|
1bdc2ef2ba53aef9b8f061487f4f56aa
| 32.52459 | 138 | 0.593154 | false | false | false | false |
u10int/Kinetic
|
refs/heads/master
|
Example/Kinetic/GroupTweenViewController.swift
|
mit
|
1
|
//
// GroupTweenViewController.swift
// Motion
//
// Created by Nicholas Shipes on 1/1/16.
// Copyright © 2016 Urban10 Interactive, LLC. All rights reserved.
//
import UIKit
import Kinetic
class GroupTweenViewController: ExampleViewController {
var square: UIView!
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
title = "Grouped Tween"
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.white
square = UIView()
square.frame = CGRect(x: 50, y: 50, width: 50, height: 50)
square.backgroundColor = UIColor.red
view.addSubview(square)
let moveX: Tween = Tween(target: square).to(X(200)).duration(0.5).ease(Cubic.easeInOut)
let moveY: Tween = Tween(target: square).to(Y(290)).duration(0.75).ease(Sine.easeOut)
let color: Tween = Tween(target: square).to(BackgroundColor(.yellow)).duration(0.5).ease(Sine.easeOut)
let timeline = Timeline(tweens: [moveX, moveY, color], align: .start)
timeline.yoyo().forever()
animation = timeline
}
override func reset() {
super.reset()
square.frame = CGRect(x: 50, y: 50, width: 50, height: 50)
square.backgroundColor = UIColor.red
}
}
|
f5bcf7abbd9f1391b66de4686f2670fc
| 25.705882 | 104 | 0.70558 | false | false | false | false |
Gilbertat/SYKanZhiHu
|
refs/heads/master
|
SYKanZhihu/SYKanZhihu/Class/Extensions/UIColor+kanzhihu.swift
|
mit
|
1
|
//
// UIColor+kanzhihu.swift
// SYKanZhihu
//
// Created by shiyue on 16/3/7.
// Copyright © 2016年 shiyue. All rights reserved.
//
import UIKit
extension UIColor {
convenience init(red:Int, green:Int, blue:Int) {
assert(red >= 0 && red <= 255, "Invalid red component")
assert(green >= 0 && green <= 255, "Invalid green component")
assert(blue >= 0 && blue <= 255, "Invalid blue component")
self.init(red:CGFloat(red) / 255.0, green:CGFloat(green) / 255.0, blue:CGFloat(blue) / 255.0, alpha:1.0)
}
convenience init(netHex:Int) {
self.init(red:(netHex >> 16) & 0xff, green:(netHex >> 8) & 0xff, blue:netHex & 0xff)
}
}
|
171366b6c8b7fea322a822e0eeb3f8be
| 29.130435 | 112 | 0.597403 | false | false | false | false |
lenssss/whereAmI
|
refs/heads/master
|
Whereami/Controller/Photo/PublishQuestionClassViewController.swift
|
mit
|
1
|
//
// PublishQuestionClassViewController.swift
// Whereami
//
// Created by A on 16/4/12.
// Copyright © 2016年 WuQifei. All rights reserved.
//
import UIKit
class PublishQuestionClassViewController: UIViewController,UITableViewDataSource,UITableViewDelegate {
var questionModel:QuestionModel? = nil
var tableView:UITableView? = nil
var classList:[GameKindModel]? = nil
var nameArray:[String]? = nil
var codeArray:[String]? = nil
var selectedIndex:Int? = nil
override func viewDidLoad() {
super.viewDidLoad()
self.classList = FileManager.sharedInstance.readGameKindListFromFile()
if classList != nil {
self.nameArray = GameKindModel.getNamesFromModels(classList!)
self.codeArray = GameKindModel.getCodesFromModels(classList!)
}
self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: NSLocalizedString("next",tableName:"Localizable", comment: ""), style: .Done, target: self, action: #selector(self.pushToNext))
self.setUI()
// Do any additional setup after loading the view.
}
func setUI(){
self.tableView = UITableView()
self.tableView?.delegate = self
self.tableView?.dataSource = self
self.tableView?.registerClass(UITableViewCell.self , forCellReuseIdentifier: "PublishQuestionClassViewCell")
self.view.addSubview(tableView!)
self.tableView?.autoPinEdgesToSuperviewEdgesWithInsets(UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0))
}
func pushToNext(){
if selectedIndex != nil {
let viewController = PublishQuestionRangeViewController()
viewController.questionModel = self.questionModel
self.navigationController?.pushViewController(viewController, animated: true)
}
else{
let alertController = UIAlertController(title: NSLocalizedString("warning",tableName:"Localizable", comment: ""), message: NSLocalizedString("selectRange",tableName:"Localizable", comment: ""), preferredStyle: .Alert)
let confirmAction = UIAlertAction(title: NSLocalizedString("ok",tableName:"Localizable", comment: ""), style: .Default, handler: nil)
alertController.addAction(confirmAction)
self.presentViewController(alertController, animated: true, completion: nil)
}
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if classList != nil {
return (classList?.count)!
}
return 0
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
//self.selectedRange = nameArray![indexPath.row]
self.selectedIndex = indexPath.row
self.questionModel?.classificationCode = codeArray![selectedIndex!]
self.questionModel?.classificationName = nameArray![selectedIndex!]
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("PublishQuestionClassViewCell")
if nameArray != nil {
cell?.textLabel?.text = nameArray![indexPath.row]
}
return cell!
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
|
20bc4fc3959c624b493519f0b5bbfae6
| 39.891566 | 229 | 0.677961 | false | false | false | false |
superk589/CGSSGuide
|
refs/heads/master
|
DereGuide/Unit/Simulation/View/UnitAdvanceCalculationCell.swift
|
mit
|
2
|
//
// UnitAdvanceCalculationCell.swift
// DereGuide
//
// Created by zzk on 2017/6/20.
// Copyright © 2017 zzk. All rights reserved.
//
import UIKit
import SnapKit
typealias UnitAdvanceCalculationCellVariableView = TextFieldOption
protocol UnitAdvanceCalculationCellDelegate: class {
func unitAdvanceCalculationCell(_ unitAdvanceCalculationCell: UnitAdvanceCalculationCell, didStartCalculationWith varibles: [String])
}
class UnitAdvanceCalculationCell: UITableViewCell {
let titleLabel = UILabel()
weak var delegate: UnitAdvanceCalculationCellDelegate?
var variableNames = [String]() {
didSet {
rearrangeStackView()
}
}
var inputStrings: [String] {
return stackView.arrangedSubviews.map {
return ($0 as? UnitAdvanceCalculationCellVariableView)?.textField.text ?? ""
}
}
var stackView: UIStackView!
let startButton = WideButton()
let resultView = UnitAdvanceCalculationResultView()
let startButtonIndicator = UIActivityIndicatorView(style: .white)
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
titleLabel.font = .systemFont(ofSize: 16)
titleLabel.numberOfLines = 0
contentView.addSubview(titleLabel)
titleLabel.snp.makeConstraints { (make) in
make.top.equalTo(10)
make.left.equalTo(readableContentGuide)
make.right.equalTo(readableContentGuide)
}
stackView = UIStackView()
contentView.addSubview(stackView)
stackView.distribution = .equalSpacing
stackView.axis = .vertical
stackView.spacing = 5
stackView.snp.makeConstraints { (make) in
make.left.equalTo(readableContentGuide)
make.top.equalTo(titleLabel.snp.bottom).offset(10)
make.right.equalTo(readableContentGuide)
}
contentView.addSubview(resultView)
resultView.snp.makeConstraints { (make) in
make.right.equalTo(readableContentGuide)
make.left.equalTo(readableContentGuide)
make.top.equalTo(stackView.snp.bottom).offset(10)
}
startButton.setTitle(NSLocalizedString("开始计算", comment: ""), for: .normal)
startButton.backgroundColor = .dance
startButton.addTarget(self, action: #selector(handleStartButton(_:)), for: .touchUpInside)
contentView.addSubview(startButton)
startButton.snp.makeConstraints { (make) in
make.left.equalTo(readableContentGuide)
make.right.equalTo(readableContentGuide)
make.top.equalTo(resultView.snp.bottom).offset(10)
make.bottom.equalTo(-10)
}
startButton.addSubview(startButtonIndicator)
startButtonIndicator.snp.makeConstraints { (make) in
make.right.equalTo(startButton.titleLabel!.snp.left)
make.centerY.equalTo(startButton)
}
}
private func rearrangeStackView() {
for view in stackView.arrangedSubviews {
stackView.removeArrangedSubview(view)
view.removeFromSuperview()
}
for name in variableNames {
let view = UnitAdvanceCalculationCellVariableView()
view.label.text = name
view.textField.delegate = self
stackView.addArrangedSubview(view)
}
selectionStyle = .none
}
@objc private func handleStartButton(_ button: UIButton) {
delegate?.unitAdvanceCalculationCell(self, didStartCalculationWith: inputStrings)
}
func setup(_ data: UnitAdvanceCalculationController.CalculationRow) {
titleLabel.text = data.name
variableNames = data.variableDescriptions
for view in stackView.arrangedSubviews {
if let view = view as? UnitAdvanceCalculationCellVariableView,
let index = stackView.arrangedSubviews.firstIndex(of: view),
let variables = data.variables {
view.textField.text = variables[index]
}
}
updateResult(data)
}
func updateResult(_ data: UnitAdvanceCalculationController.CalculationRow) {
if let result = data.result {
resultView.rightLabel.text = result
} else {
resultView.rightLabel.text = ""
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func stopCalculationAnimating() {
startButton.isUserInteractionEnabled = true
startButtonIndicator.stopAnimating()
startButton.setTitle(NSLocalizedString("开始计算", comment: ""), for: .normal)
}
func startCalculationAnimating() {
startButtonIndicator.startAnimating()
startButton.setTitle(NSLocalizedString("计算中...", comment: ""), for: .normal)
startButton.isUserInteractionEnabled = false
}
}
extension UnitAdvanceCalculationCell: UITextFieldDelegate {
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
func textFieldDidBeginEditing(_ textField: UITextField) {
resultView.rightLabel.text = ""
}
}
|
18e1a94548824b56ea9cc8fc2152619f
| 33.844156 | 137 | 0.654678 | false | false | false | false |
xudafeng/swifty-webview
|
refs/heads/master
|
swifty-webview/Utils.swift
|
mit
|
1
|
//
// Utils.swift
// swifty-webview
//
// Created by xdf on 9/4/15.
// Copyright (c) 2015 open source. All rights reserved.
//
import UIKit
import SwiftyJSON
class Utils: NSObject {
class func getImgView(ImgName: NSString) -> UIImage {
var image:UIImage = UIImage(named: ImgName as String)!
image = image.imageWithRenderingMode(UIImageRenderingMode.AlwaysOriginal);
return image;
}
class func parseQuery(querystring: String) -> [String: String] {
var query = [String: String]()
for qs in querystring.componentsSeparatedByString("&") {
let key = qs.componentsSeparatedByString("=")[0]
var value = qs.componentsSeparatedByString("=")[1]
value = value.stringByReplacingOccurrencesOfString("+", withString: " ")
value = value.stringByRemovingPercentEncoding!
query[key] = value
}
return query
}
class func getValueFromQueue(queryStrings: [String: String], key: String) -> String {
let data = String(queryStrings["data"]!)
let dataString = data.stringByRemovingPercentEncoding!
let _dataString = dataString.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
let json = JSON(data: _dataString!)
let value = String(json[key])
return value
}
class func getData(key: String) -> String {
let temp = NSUserDefaults.standardUserDefaults()
let value = temp.objectForKey(key)
if (value != nil) {
return String(value)
} else {
return "nil"
}
}
class func hasData(key: String) -> Bool {
let temp = self.getData(key)
return temp != "nil"
}
class func setData(key: String, value: String) {
let temp = NSUserDefaults.standardUserDefaults()
temp.setObject(value, forKey: key)
temp.synchronize()
}
class func removeData(key: String) {
let temp = NSUserDefaults.standardUserDefaults()
temp.removeObjectForKey(key)
temp.synchronize()
}
}
|
c0efdf65790bc143f311335e684dbdec
| 28.652778 | 105 | 0.613402 | false | false | false | false |
AboutObjects/Modelmatic
|
refs/heads/master
|
Example/Modelmatic/AuthorDataSource.swift
|
mit
|
1
|
//
// Copyright (C) 2015 About Objects, Inc. All Rights Reserved.
// See LICENSE.txt for this example's licensing information.
//
import UIKit
import CoreData
import Modelmatic
/// Storyboard ID for prototype cell
let cellId = "Book"
class AuthorDataSource: NSObject
{
@IBOutlet private var objectStore: AuthorObjectStore!
var authors: [Author]? { return objectStore.authors }
}
// MARK: - Persistence API
extension AuthorDataSource
{
func fetch(_ completion: @escaping () -> Void) { objectStore.fetch(completion) }
func save() { objectStore.save() }
func toggleStorageMode() { objectStore.toggleStorageMode() }
}
// MARK: - Accessing the model
extension AuthorDataSource
{
var bookEntity: NSEntityDescription { return objectStore.bookEntity }
func bookAtIndexPath(_ indexPath: IndexPath) -> Book? {
return objectStore.bookAtIndexPath(indexPath)
}
func removeBookAtIndexPath(_ indexPath: IndexPath) {
objectStore.removeBookAtIndexPath(indexPath)
}
}
// MARK: - UITableViewDataSource conformance
extension AuthorDataSource: UITableViewDataSource
{
func numberOfSections(in tableView: UITableView) -> Int {
return objectStore.numberOfSections()
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return objectStore.titleForSection(section)
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return objectStore.numberOfRows(inSection: section)
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: cellId) as? BookCell else {
fatalError("Unable to dequeue a cell with identifier \(cellId)")
}
populateCell(cell, atIndexPath: indexPath)
configureCell(cell, atIndexPath: indexPath)
return cell
}
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath)
{
if editingStyle == .delete {
removeBookAtIndexPath(indexPath)
tableView.deleteRows(at: [indexPath], with: .automatic)
save()
}
}
}
// MARK: - Configuring and populating cells
extension AuthorDataSource
{
/// Formatter for currency values
static let currencyFormatter: NumberFormatter = {
let formatter = NumberFormatter()
formatter.numberStyle = .currency
return formatter
}()
func configureCell(_ cell: BookCell, atIndexPath indexPath: IndexPath) {
guard let book = objectStore.bookAtIndexPath(indexPath) else { return }
cell.ratingLabel.alpha = book.rating == .zero ? 0.3 : 1
cell.favoriteLabel.transform = book.favorite.boolValue ? CGAffineTransform(scaleX: 1.2, y: 1.2) : CGAffineTransform.identity
}
func populateCell(_ cell: BookCell, atIndexPath indexPath: IndexPath) {
guard let book = objectStore.bookAtIndexPath(indexPath) else { return }
cell.titleLabel.text = book.title
cell.priceLabel.text = AuthorDataSource.currencyFormatter.string(from: NSNumber(value: book.retailPrice ?? 0 as Double))
cell.ratingLabel.text = book.rating.description
cell.favoriteLabel.text = book.favorite.description
}
}
// MARK: - Enums
@objc enum Heart: Int, CustomStringConvertible {
case yes, no
init(isFavorite: Bool?) {
self = (isFavorite != nil && isFavorite!) ? .yes : .no
}
var boolValue: Bool { return self == .yes }
var description: String { return self == .yes ? "♥︎" : "♡" }
mutating func toggle() {
self = self == .yes ? .no : .yes
}
}
@objc enum Stars: Int, CustomStringConvertible {
case zero, one, two, three, four, five
init(rating: Int?) {
self = Stars(rawValue: rating ?? 0) ?? .zero
}
var description: String {
switch self {
case .zero: return "☆☆☆☆☆"
case .one: return "★☆☆☆☆"
case .two: return "★★☆☆☆"
case .three: return "★★★☆☆"
case .four: return "★★★★☆"
case .five: return "★★★★★"
}
}
}
|
360c25f4809a69dbdfcf0a38db063ca4
| 32.338583 | 132 | 0.660368 | false | false | false | false |
iXieYi/Weibo_DemoTest
|
refs/heads/master
|
Weibo_DemoTest/Weibo_DemoTest/StatusCell.swift
|
mit
|
1
|
//
// StatusCell.swift
// Weibo_DemoTest
//
// Created by 谢毅 on 16/12/22.
// Copyright © 2016年 xieyi. All rights reserved.
//
import UIKit
/// 微博Cell中控件的间距数值
let StatusCellMargin:CGFloat = 12
//定义微博头像的宽度
let StatusCellIconWidth:CGFloat = 35
//微博cell
class StatusCell: UITableViewCell {
//微博的视图模型
var viewModel:StatusViewModel?{
didSet{
topView.viewModel = viewModel
contentLabel.text = viewModel?.status.text
//测试修改配图视图高度 -> cell视图存在复用,若动态的修改其约束高度会使得,cell自动计算过变得不准
//设置配置视图 - 设置视图模型之后 - 配图视图有能力计算大小
pictureView.viewModel = viewModel
pictureView.snp_updateConstraints { (make) -> Void in
// print("配图视图大小:\(pictureView.bounds)")
make.height.equalTo(pictureView.bounds.height)
//宽度约束- > 直接设置宽度数值,如果这时候其他地方再次设置,有参照的值会使得约束设置冲突
//自动布局系统不知道,该依据那个设置视图大小
make.width.equalTo(pictureView.bounds.width)
//根据配图数量,决定配图视图的顶部间距
// let offset = viewModel?.thumbnailUrls?.count > 0 ?StatusCellMargin :0
// make.top.equalTo(contentLabel.snp_bottom).offset(offset)
}
}
}
/// 根据指定的视图模型指定行高
///
/// - parameter ViewModel: 视图模型
///
/// - returns: 返回视图模型对应的行高
func rowHeight(VM:StatusViewModel)->CGFloat{
//1.记录视图模型 -> 会调用的上方didSet 设置内容和更新约束
viewModel = VM
//2.强制更新所有约束 - >所有控件都会被计算正确
contentView.layoutIfNeeded()
//3.返回底部视图的最大高度
return CGRectGetMaxY(bottonView.frame)
}
//构造函数
//style 参数可以设置系统的样式
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
setupUI()
//设置cell选中时后的样式 (快捷键查看文件属性,方法列表 ctrl + 6 支持智能搜索和匹配)
selectionStyle = .None
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
//MARK:- 懒加载控件
//顶部视图
private lazy var topView:StatusTop = StatusTop()
//微博正文
lazy var contentLabel: UILabel = UILabel(title: "微博正文", fontSize: 15, screenInset: StatusCellMargin)
//配图视图
lazy var pictureView:StatusPictureView = StatusPictureView()
//底部视图
lazy var bottonView:StatusBottom = StatusBottom()
override func awakeFromNib() {
super.awakeFromNib()
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
//MARK: - 设置界面使用
extension StatusCell{
func setupUI(){
//1.添加控件
contentView.addSubview(topView)
contentView.addSubview(contentLabel)
contentView.addSubview(pictureView)
contentView.addSubview(bottonView)
// bottonView.backgroundColor = UIColor.redColor()
//2.自动布局
//顶部视图
topView.snp_makeConstraints { (make) -> Void in
make.top.equalTo(contentView.snp_top)
make.left.equalTo(contentView.snp_left)
make.right.equalTo(contentView.snp_right)
//TODO: - 修改高度
make.height.equalTo(2*StatusCellMargin + StatusCellIconWidth)
}
//正文内容标签
contentLabel.snp_makeConstraints { (make) -> Void in
make.top.equalTo(topView.snp_bottom).offset(StatusCellMargin)
make.left.equalTo(contentView.snp_left).offset(StatusCellMargin)
// make.right.equalTo(contentView.snp_right).offset(StatusCellMargin)
}
//底部视图
bottonView.snp_makeConstraints { (make) -> Void in
make.top.equalTo(pictureView.snp_bottom).offset(StatusCellMargin)
make.left.equalTo(contentView.snp_left)
make.right.equalTo(contentView.snp_right)
make.height.equalTo(44)
//指定向下的约束
// make.bottom.equalTo(contentView.snp_bottom)
}
}
}
|
51249186f7e3fd24cd8c6976d13c9a97
| 27.543478 | 105 | 0.62757 | false | false | false | false |
pozi119/Valine
|
refs/heads/master
|
Valine/NSObject+Runtime.swift
|
gpl-2.0
|
1
|
//
// NSObject+Runtime.swift
// Valine
//
// Created by Valo on 15/12/23.
// Copyright (c) 2015年 Valo. All rights reserved.
//
import Foundation
import ObjectiveC.runtime
func method_swizzle(aClass:AnyClass?, origSelector:Selector, altSelector:Selector)->Bool{
if aClass == nil {
return false
}
var origMethod:Method?
var altMethod:Method?
func find_methods(){
var methodCount:UInt32 = 0
let methodList:UnsafeMutablePointer<Method> = class_copyMethodList(aClass, &methodCount)
origMethod = nil
altMethod = nil
if methodList != nil {
for index in 0...methodCount{
let method:Method = methodList[Int(index)]
let sel:Selector = method_getName(method)
if origSelector == sel{
origMethod = method
}
if altSelector == sel{
altMethod = method
}
}
}
free(methodList)
}
find_methods()
if origMethod == nil{
origMethod = class_getInstanceMethod(aClass, origSelector)
if origMethod == nil{
return false
}
if class_addMethod(aClass, method_getName(origMethod!), method_getImplementation(origMethod!), method_getTypeEncoding(origMethod!)) == false{
return false
}
}
if altMethod == nil{
altMethod = class_getInstanceMethod(aClass, altSelector)
if altMethod == nil{
return false
}
if class_addMethod(aClass, method_getName(altMethod!), method_getImplementation(altMethod!), method_getTypeEncoding(altMethod!)) == false{
return false
}
}
find_methods()
if origMethod == nil || altMethod == nil{
return false
}
method_exchangeImplementations(origMethod!, altMethod!)
return true;
}
func method_append(toClass:AnyClass?, fromClass:AnyClass?, aSelector:Selector?){
if toClass == nil || fromClass == nil || aSelector == nil {
return
}
let method:Method = class_getInstanceMethod(fromClass, aSelector!)
if method == nil {
return
}
class_addMethod(toClass, method_getName(method), method_getImplementation(method), method_getTypeEncoding(method))
}
func method_replace(toClass:AnyClass?, fromClass:AnyClass?, selector:Selector?){
if toClass == nil || fromClass == nil || selector == nil {
return
}
let method:Method = class_getInstanceMethod(fromClass, selector!)
if method == nil {
return
}
class_replaceMethod(toClass, method_getName(method), method_getImplementation(method), method_getTypeEncoding(method))
}
func loop_check(aClass:AnyClass?, aSelector:Selector?, stopClass:AnyClass?)->Bool{
if aClass == nil || aClass === stopClass{
return false
}
var methodCount:UInt32 = 0
let methodList:UnsafeMutablePointer<Method> = class_copyMethodList(aClass!, &methodCount)
if methodList != nil{
for i in 0...methodCount{
if method_getName(methodList[Int(i)]) == aSelector!{
return true
}
}
}
return loop_check(aClass, aSelector: aSelector, stopClass: stopClass)
}
extension NSObject{
class func swizzleMethod(origSelector:Selector, newSelector:Selector){
method_swizzle(self, origSelector: origSelector, altSelector: newSelector)
}
class func appendMethod(newSelector:Selector, fromClass aClass:AnyClass){
method_append(self, fromClass: aClass, aSelector: newSelector)
}
class func replaceMethod(aSelector:Selector, fromClass aClass:AnyClass){
method_replace(self, fromClass: aClass, selector: aSelector)
}
class func instancesRespondToSelector(aSelector:Selector, untilClass stopClass:AnyClass)->Bool {
return loop_check(self.classForCoder(), aSelector: aSelector, stopClass: stopClass)
}
func respondsToSelector(aSelector:Selector, untilClass stopClass:AnyClass)->Bool{
return self.classForCoder.instancesRespondToSelector(aSelector, untilClass: stopClass)
}
func superRespondsToSelector(aSelector:Selector)->Bool{
return self.superclass!.instancesRespondToSelector(aSelector)
}
func superRespondsToSelector(aSelector:Selector, untilClass stopClass:AnyClass)->Bool{
return self.superclass!.instancesRespondToSelector(aSelector, untilClass: stopClass)
}
}
|
30a6b792c6d232949bc7c7fce50568ae
| 30.923077 | 149 | 0.63943 | false | false | false | false |
1000copy/fin
|
refs/heads/master
|
keychain.swift
|
mit
|
1
|
import UIKit
import Security
class Keychain {
class func save(_ key: String, _ data: Data) -> Bool {
let query = [
kSecClass as String : kSecClassGenericPassword as String,
kSecAttrAccount as String : key,
kSecValueData as String : data ] as [String : Any]
SecItemDelete(query as CFDictionary)
let status: OSStatus = SecItemAdd(query as CFDictionary, nil)
return status == noErr
}
class func load(_ key: String) -> Data? {
let query = [
kSecClass as String : kSecClassGenericPassword,
kSecAttrAccount as String : key,
kSecReturnData as String : kCFBooleanTrue,
kSecMatchLimit as String : kSecMatchLimitOne ] as [String : Any]
var dataTypeRef: AnyObject?
let status = withUnsafeMutablePointer(to: &dataTypeRef) { SecItemCopyMatching(query as CFDictionary, UnsafeMutablePointer($0)) }
if status == errSecSuccess {
if let data = dataTypeRef as! Data? {
return data
}
}
return nil
}
class func delete(_ key: String) -> Bool {
let query = [
kSecClass as String : kSecClassGenericPassword,
kSecAttrAccount as String : key ] as [String : Any]
let status: OSStatus = SecItemDelete(query as CFDictionary)
return status == noErr
}
class func clear() -> Bool {
let query = [ kSecClass as String : kSecClassGenericPassword ]
let status: OSStatus = SecItemDelete(query as CFDictionary)
return status == noErr
}
}
|
f947c0dd1a7a9c7616ca1a14ced5fed8
| 38.238095 | 136 | 0.596481 | false | false | false | false |
iMetalk/TCZKit
|
refs/heads/master
|
TCZKitDemo/TCZKit/Views/StackView/TCZStackView.swift
|
mit
|
1
|
//
// TCZStackView.swift
// Dormouse
//
// Created by tczy on 2017/8/14.
// Copyright © 2017年 WangSuyan. All rights reserved.
//
import UIKit
enum TCZStackItemType {
//纯文字
case Title
//纯图片
case Image
//左边文字,右边图片
case LeftTitleRightImage
//左边图片,右边文字
case LeftImageRightTitle
//上边图片,下边文字
case TopImageBottomTitle
}
struct TCZStackItem {
var itemTitle: NSString?
var itemColorNormal: UIColor?
var itemColorHighLighted: UIColor?
var itemColorSelected: UIColor?
var itemImageNormal: UIImage?
var itemImageHighLighted: UIImage?
var itemImageSelected: UIImage?
/// The item type
var itemType: TCZStackItemType
init(type: TCZStackItemType) {
self.itemType = type
}
}
class TCZStackView: UIView {
var stackItems: NSArray = []
var stackViewButtonClickBlock: ((_ index: Int) -> ())?
//MARK: - LifeCycle
convenience init(frame: CGRect, items: NSArray) {
self.init(frame: frame)
stackItems = items
self.backgroundColor = UIColor.black
self.createStackSubviews()
}
//MARK: - Click Action
func stackViewButtonClickAction(button: UIButton) {
if stackViewButtonClickBlock != nil {
stackViewButtonClickBlock!(button.tag)
}
}
//MARK: - Methond
func setIsSelectedAtIndex(index: Int, isSelected: Bool) {
if index > stackItems.count {
return
}
let stackCollectionCell: TCZStackCollectionCell = collectionView.cellForItem(at: IndexPath.init(row: index, section: 0)) as! TCZStackCollectionCell
stackCollectionCell.button.isSelected = isSelected
}
func setIsEnabledAtIndex(index: Int, isEnabled: Bool) {
if index > stackItems.count {
return
}
let stackCollectionCell: TCZStackCollectionCell = collectionView.cellForItem(at: IndexPath.init(row: index, section: 0)) as! TCZStackCollectionCell
stackCollectionCell.button.isEnabled = isEnabled
}
func setTitleAtIndex(index: Int, title: NSString) {
if index > stackItems.count {
return
}
let item: TCZStackItem = stackItems[index] as! TCZStackItem
if item.itemType == .Image {
return
}
let stackCollectionCell: TCZStackCollectionCell = collectionView.cellForItem(at: IndexPath.init(row: index, section: 0)) as! TCZStackCollectionCell
stackCollectionCell.button.setTitle(title as String, for: .normal)
if (item.itemType == .LeftImageRightTitle) {
stackCollectionCell.button.ajustImagePosition(position: .left, offset: 5)
}else if (item.itemType == .LeftTitleRightImage) {
stackCollectionCell.button.ajustImagePosition(position: .right, offset: 5)
}else if (item.itemType == .TopImageBottomTitle) {
stackCollectionCell.button.ajustImagePosition(position: .top, offset: 5)
}
}
//MARK: - CreateUI
func createStackSubviews() {
self.addSubview(collectionView)
collectionView.snp.makeConstraints { (make) in
make.edges.equalToSuperview()
}
}
lazy var collectionView: UICollectionView = {
let layout = UICollectionViewFlowLayout()
layout.scrollDirection = .horizontal
layout.minimumLineSpacing = 0
layout.minimumInteritemSpacing = 0
let aCollection = UICollectionView(frame: self.frame, collectionViewLayout: layout)
aCollection.backgroundColor = UIColor.clear
aCollection.delegate = self
aCollection.dataSource = self
aCollection.isScrollEnabled = false
aCollection.showsHorizontalScrollIndicator = false
aCollection.register(TCZStackCollectionCell.self, forCellWithReuseIdentifier: NSStringFromClass(TCZStackCollectionCell.self))
return aCollection
}()
}
extension TCZStackView: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return stackItems.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: NSStringFromClass(TCZStackCollectionCell.self), for: indexPath) as! TCZStackCollectionCell
cell.button.tag = indexPath.row
cell.button.addTarget(self, action: #selector(stackViewButtonClickAction(button:)), for: .touchUpInside)
cell.loadStackCollectionCellData(item: stackItems[indexPath.row] as! TCZStackItem)
return cell
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let width: CGFloat = self.bounds.width / CGFloat(stackItems.count)
return CGSize(width:width, height:self.bounds.height)
}
}
class TCZStackCollectionCell: UICollectionViewCell {
//MARK: - LifeCycle
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override init(frame: CGRect) {
super.init(frame: frame)
self.backgroundColor = UIColor.clear
contentView.backgroundColor = UIColor.clear
contentView.addSubview(button)
button.snp.makeConstraints { (make) in
make.edges.equalTo(UIEdgeInsetsMake(5, 5, 5, 5))
}
}
//MARK: - Data
func loadStackCollectionCellData(item: TCZStackItem) {
button.setTitle(item.itemTitle as String?, for: .normal)
button.setTitleColor(item.itemColorNormal, for: .normal)
button.setTitleColor(item.itemColorHighLighted, for: .highlighted)
button.setTitleColor(item.itemColorSelected, for: .selected)
button.setImage(item.itemImageNormal, for: .normal)
button.setImage(item.itemImageHighLighted, for: .highlighted)
button.setImage(item.itemImageSelected, for: .selected)
switch item.itemType {
case .Title:
button.imageEdgeInsets = UIEdgeInsets.zero
button.titleEdgeInsets = UIEdgeInsets.zero
break
case .Image:
button.imageEdgeInsets = UIEdgeInsets.zero
button.titleEdgeInsets = UIEdgeInsets.zero
break
case .LeftTitleRightImage:
button.ajustImagePosition(position: .right, offset: 5)
break
case .LeftImageRightTitle:
button.ajustImagePosition(position: .left, offset: 5)
break
case .TopImageBottomTitle:
button.ajustImagePosition(position: .top, offset: 5)
break
}
}
//MARK: - create
lazy var button: UIButton = {
let button: UIButton = UIButton.tczButton()
button.backgroundColor = UIColor.clear
button.setTitleColor(UIColor.white, for: .normal)
button.titleLabel?.font = UIFont.tcz_systemFontWithSize(size: 13.0)
return button
}()
}
|
87681689d61545dcac1911893a782857
| 31.304348 | 165 | 0.648183 | false | false | false | false |
na4lapy/Na4LapyAPI
|
refs/heads/master
|
Sources/Na4LapyCore/PhotoBackend_oldapi.swift
|
apache-2.0
|
2
|
//
// PhotoBackend.swift
// Na4lapyAPI
//
// Created by Andrzej Butkiewicz on 24.12.2016.
// Copyright © 2016 Stowarzyszenie Na4Łapy. All rights reserved.
//
import Foundation
public class PhotoBackend_oldapi: Model {
let db: DBLayer
public init(db: DBLayer) {
self.db = db
}
/**
Usunięcie wszystkich zdjęć dla id zwierzaka
- Parameter id
*/
public func deleteAll(byId id: Int) throws -> [String] {
return try db.deleteAllPhotos(byAnimalId: id)
}
/**
Usunięcie zdjęcia o zadanym id
- Parameter id
*/
public func delete(byId id: Int) throws -> String {
return try db.deletePhoto(byId: id)
}
/**
Pobranie zdjęć dla obiektu o zadanym id
- Parameter id
*/
public func get(byId id: Int) throws -> JSONDictionary {
let dbresult = try db.fetch(byId: id, table: Config.phototable, idname: PhotoDBKey.animalid)
if dbresult.count == 0 {
// throw ResultCode.PhotoBackendNoData
}
var photos: [JSONDictionary] = []
for entry in dbresult {
guard let photo = Photo_oldapi(dictionary: entry) else {
throw ResultCode.PhotoBackendBadParameters
}
var photodictionary = photo.dictionaryRepresentation()
if let filename = photodictionary[PhotoJSON.url] as? String {
photodictionary[PhotoJSON.url] = (db.config.oldapiUrl + filename) as Any
}
photos.append(photodictionary)
}
return [AnimalJSON.photos : photos]
}
public func get(byPage page: Int, size: Int, shelterid: Int?, withParameters params: ParamDictionary) throws -> JSONDictionary {
return [:]
}
public func getall(shelterid: Int?) throws -> JSONDictionary {
return [:]
}
public func add(withDictionary dictionary: JSONDictionary) throws -> Int {
return 0
}
public func edit(withDictionary dictionary: JSONDictionary) throws -> Int {
return 0
}
public func get(byIds ids: [Int]) throws -> JSONDictionary {
return [:]
}
}
|
cea383d9b2c3367545fd7f5b44376bbe
| 26.4125 | 132 | 0.599635 | false | false | false | false |
Jnosh/swift
|
refs/heads/master
|
test/SILGen/objc_bridging.swift
|
apache-2.0
|
2
|
// RUN: rm -rf %t && mkdir -p %t
// RUN: %build-silgen-test-overlays
// RUN: %target-swift-frontend(mock-sdk: -sdk %S/Inputs -I %t) -emit-module -o %t -I %S/../Inputs/ObjCBridging %S/../Inputs/ObjCBridging/Appliances.swift
// RUN: %target-swift-frontend(mock-sdk: -sdk %S/Inputs -I %t) -I %S/../Inputs/ObjCBridging -Xllvm -sil-full-demangle -emit-silgen %s | %FileCheck %s --check-prefix=CHECK --check-prefix=CHECK-%target-cpu --check-prefix=CHECK-%target-os-%target-cpu
// REQUIRES: objc_interop
import Foundation
import Appliances
func getDescription(_ o: NSObject) -> String {
return o.description
}
// CHECK-LABEL: sil hidden @_T013objc_bridging14getDescription{{.*}}F
// CHECK: bb0([[ARG:%.*]] : $NSObject):
// CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]]
// CHECK: [[DESCRIPTION:%.*]] = class_method [volatile] [[BORROWED_ARG]] : $NSObject, #NSObject.description!getter.1.foreign
// CHECK: [[OPT_BRIDGED:%.*]] = apply [[DESCRIPTION]]([[BORROWED_ARG]])
// CHECK: switch_enum [[OPT_BRIDGED]] : $Optional<NSString>, case #Optional.some!enumelt.1: [[SOME_BB:bb[0-9]+]], case #Optional.none!enumelt: [[NONE_BB:bb[0-9]+]]
//
// CHECK: [[SOME_BB]]([[BRIDGED:%.*]] : $NSString):
// CHECK-NOT: unchecked_enum_data
// CHECK: [[NSSTRING_TO_STRING:%.*]] = function_ref @_T0SS10FoundationE36_unconditionallyBridgeFromObjectiveCSSSo8NSStringCSgFZ
// CHECK: [[BRIDGED_BOX:%.*]] = enum $Optional<NSString>, #Optional.some!enumelt.1, [[BRIDGED]]
// CHECK: [[NATIVE:%.*]] = apply [[NSSTRING_TO_STRING]]([[BRIDGED_BOX]],
// CHECK: [[OPT_NATIVE:%.*]] = enum $Optional<String>, #Optional.some!enumelt.1, [[NATIVE]]
// CHECK: br [[CONT_BB:bb[0-9]+]]([[OPT_NATIVE]] : $Optional<String>)
//
// CHECK: [[NONE_BB]]:
// CHECK: [[OPT_NATIVE:%.*]] = enum $Optional<String>, #Optional.none!enumelt
// CHECK: br [[CONT_BB]]([[OPT_NATIVE]] : $Optional<String>)
//
// CHECK: [[CONT_BB]]([[OPT_NATIVE:%.*]] : $Optional<String>):
// CHECK: switch_enum [[OPT_NATIVE]] : $Optional<String>, case #Optional.some!enumelt.1: [[SOME_BB:bb[0-9]+]], case #Optional.none!enumelt: [[NONE_BB:bb[0-9]+]]
//
// CHECK: [[NONE_BB]]:
// CHECK: unreachable
//
// CHECK: [[SOME_BB]]([[NATIVE:%.*]] : $String):
// CHECK: end_borrow [[BORROWED_ARG]] from [[ARG]]
// CHECK: destroy_value [[ARG]]
// CHECK: return [[NATIVE]]
// CHECK:}
func getUppercaseString(_ s: NSString) -> String {
return s.uppercase()
}
// CHECK-LABEL: sil hidden @_T013objc_bridging18getUppercaseString{{.*}}F
// CHECK: bb0([[ARG:%.*]] : $NSString):
// -- The 'self' argument of NSString methods doesn't bridge.
// CHECK-NOT: function_ref @_T0SS10FoundationE36_unconditionallyBridgeFromObjectiveCSSSo8NSStringCSgFZ
// CHECK-NOT: function_ref @swift_StringToNSString
// CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]]
// CHECK: [[UPPERCASE_STRING:%.*]] = class_method [volatile] [[BORROWED_ARG]] : $NSString, #NSString.uppercase!1.foreign
// CHECK: [[OPT_BRIDGED:%.*]] = apply [[UPPERCASE_STRING]]([[BORROWED_ARG]]) : $@convention(objc_method) (NSString) -> @autoreleased Optional<NSString>
// CHECK: switch_enum [[OPT_BRIDGED]] : $Optional<NSString>, case #Optional.some!enumelt.1: [[SOME_BB:bb[0-9]+]], case #Optional.none!enumelt: [[NONE_BB:bb[0-9]+]]
//
//
// CHECK: [[SOME_BB]]([[BRIDGED:%.*]] :
// CHECK-NOT: unchecked_enum_data
// CHECK: [[NSSTRING_TO_STRING:%.*]] = function_ref @_T0SS10FoundationE36_unconditionallyBridgeFromObjectiveCSSSo8NSStringCSgFZ
// CHECK: [[BRIDGED_BOX:%.*]] = enum $Optional<NSString>, #Optional.some!enumelt.1, [[BRIDGED]]
// CHECK: [[NATIVE:%.*]] = apply [[NSSTRING_TO_STRING]]([[BRIDGED_BOX]]
// CHECK: [[OPT_NATIVE:%.*]] = enum $Optional<String>, #Optional.some!enumelt.1, [[NATIVE]]
// CHECK: br [[CONT_BB:bb[0-9]+]]([[OPT_NATIVE]] : $Optional<String>)
//
// CHECK: [[NONE_BB]]:
// CHECK: [[OPT_NATIVE:%.*]] = enum $Optional<String>, #Optional.none!enumelt
// CHECK: br [[CONT_BB]]([[OPT_NATIVE]] : $Optional<String>)
//
// CHECK: [[CONT_BB]]([[OPT_NATIVE:%.*]] : $Optional<String>):
// CHECK: switch_enum [[OPT_NATIVE]] : $Optional<String>, case #Optional.some!enumelt.1: [[SOME_BB:bb[0-9]+]], case #Optional.none!enumelt: [[NONE_BB:bb[0-9]+]]
//
// CHECK: [[NONE_BB]]:
// CHECK: unreachable
//
// CHECK: [[SOME_BB]]([[NATIVE:%.*]] : $String):
// CHECK: return [[NATIVE]]
// CHECK: }
// @interface Foo -(void) setFoo: (NSString*)s; @end
func setFoo(_ f: Foo, s: String) {
var s = s
f.setFoo(s)
}
// CHECK-LABEL: sil hidden @_T013objc_bridging6setFoo{{.*}}F
// CHECK: bb0([[ARG0:%.*]] : $Foo, {{%.*}} : $String):
// CHECK: [[BORROWED_ARG0:%.*]] = begin_borrow [[ARG0]]
// CHECK: [[SET_FOO:%.*]] = class_method [volatile] [[BORROWED_ARG0]] : $Foo, #Foo.setFoo!1.foreign
// CHECK: [[NV:%.*]] = load
// CHECK: [[OPT_NATIVE:%.*]] = enum $Optional<String>, #Optional.some!enumelt.1, [[NV]]
// CHECK: switch_enum [[OPT_NATIVE]] : $Optional<String>, case #Optional.some!enumelt.1: [[SOME_BB:bb[0-9]+]], case #Optional.none!enumelt: [[NONE_BB:bb[0-9]+]]
//
// CHECK: [[SOME_BB]]([[NATIVE:%.*]] : $String):
// CHECK-NOT: unchecked_enum_data
// CHECK: [[STRING_TO_NSSTRING:%.*]] = function_ref @_T0SS10FoundationE19_bridgeToObjectiveCSo8NSStringCyF
// CHECK: [[BORROWED_NATIVE:%.*]] = begin_borrow [[NATIVE]]
// CHECK: [[BRIDGED:%.*]] = apply [[STRING_TO_NSSTRING]]([[BORROWED_NATIVE]])
// CHECK: [[OPT_BRIDGED:%.*]] = enum $Optional<NSString>, #Optional.some!enumelt.1, [[BRIDGED]]
// CHECK: end_borrow [[BORROWED_NATIVE]] from [[NATIVE]]
// CHECK: destroy_value [[NATIVE]]
// CHECK: br [[CONT_BB:bb[0-9]+]]([[OPT_BRIDGED]] : $Optional<NSString>)
//
// CHECK: [[NONE_BB]]:
// CHECK: [[OPT_BRIDGED:%.*]] = enum $Optional<NSString>, #Optional.none!enumelt
// CHECK: br [[CONT_BB]]([[OPT_BRIDGED]] : $Optional<NSString>)
//
// CHECK: [[CONT_BB]]([[OPT_BRIDGED:%.*]] : $Optional<NSString>):
// CHECK: apply [[SET_FOO]]([[OPT_BRIDGED]], [[BORROWED_ARG0]]) : $@convention(objc_method) (Optional<NSString>, Foo) -> ()
// CHECK: destroy_value [[OPT_BRIDGED]]
// CHECK: end_borrow [[BORROWED_ARG0]] from [[ARG0]]
// CHECK: destroy_value [[ARG0]]
// CHECK: }
// @interface Foo -(BOOL) zim; @end
func getZim(_ f: Foo) -> Bool {
return f.zim()
}
// CHECK-ios-i386-LABEL: sil hidden @_T013objc_bridging6getZim{{.*}}F
// CHECK-ios-i386: bb0([[SELF:%.*]] : $Foo):
// CHECK-ios-i386: [[BORROWED_SELF:%.*]] = begin_borrow [[SELF]]
// CHECK-ios-i386: [[METHOD:%.*]] = class_method [volatile] [[BORROWED_SELF]] : $Foo, #Foo.zim!1.foreign : (Foo) -> () -> Bool
// CHECK-ios-i386: [[OBJC_BOOL:%.*]] = apply [[METHOD]]([[BORROWED_SELF]]) : $@convention(objc_method) (Foo) -> ObjCBool
// CHECK-ios-i386: [[CONVERT:%.*]] = function_ref @swift_ObjCBoolToBool : $@convention(thin) (ObjCBool) -> Bool
// CHECK-ios-i386: [[SWIFT_BOOL:%.*]] = apply [[CONVERT]]([[OBJC_BOOL]]) : $@convention(thin) (ObjCBool) -> Bool
// CHECK-ios-i386: end_borrow [[BORROWED_SELF]] from [[SELF]]
// CHECK-ios-i386: return [[SWIFT_BOOL]] : $Bool
// CHECK-ios-i386: }
// CHECK-watchos-i386-LABEL: sil hidden @_T013objc_bridging6getZim{{.*}}F
// CHECK-watchos-i386: bb0([[SELF:%.*]] : $Foo):
// CHECK-watchos-i386: [[BORROWED_SELF:%.*]] = begin_borrow [[SELF]]
// CHECK-watchos-i386: [[METHOD:%.*]] = class_method [volatile] [[BORROWED_SELF]] : $Foo, #Foo.zim!1.foreign : (Foo) -> () -> Boo
// CHECK-watchos-i386: [[BOOL:%.*]] = apply [[METHOD]]([[BORROWED_SELF]]) : $@convention(objc_method) (Foo) -> Bool
// CHECK-watchos-i386: end_borrow [[BORROWED_SELF]] from [[SELF]]
// CHECK-watchos-i386: return [[BOOL]] : $Bool
// CHECK-watchos-i386: }
// CHECK-macosx-x86_64-LABEL: sil hidden @_T013objc_bridging6getZim{{.*}}F
// CHECK-macosx-x86_64: bb0([[SELF:%.*]] : $Foo):
// CHECK-macosx-x86_64: [[BORROWED_SELF:%.*]] = begin_borrow [[SELF]]
// CHECK-macosx-x86_64: [[METHOD:%.*]] = class_method [volatile] [[BORROWED_SELF]] : $Foo, #Foo.zim!1.foreign : (Foo) -> () -> Bool
// CHECK-macosx-x86_64: [[OBJC_BOOL:%.*]] = apply [[METHOD]]([[BORROWED_SELF]]) : $@convention(objc_method) (Foo) -> ObjCBool
// CHECK-macosx-x86_64: [[CONVERT:%.*]] = function_ref @swift_ObjCBoolToBool : $@convention(thin) (ObjCBool) -> Bool
// CHECK-macosx-x86_64: [[SWIFT_BOOL:%.*]] = apply [[CONVERT]]([[OBJC_BOOL]]) : $@convention(thin) (ObjCBool) -> Bool
// CHECK-macosx-x86_64: end_borrow [[BORROWED_SELF]] from [[SELF]]
// CHECK-macosx-x86_64: return [[SWIFT_BOOL]] : $Bool
// CHECK-macosx-x86_64: }
// CHECK-ios-x86_64-LABEL: sil hidden @_T013objc_bridging6getZim{{.*}}F
// CHECK-ios-x86_64: bb0([[SELF:%.*]] : $Foo):
// CHECK-ios-x86_64: [[BORROWED_SELF:%.*]] = begin_borrow [[SELF]]
// CHECK-ios-x86_64: [[METHOD:%.*]] = class_method [volatile] [[BORROWED_SELF]] : $Foo, #Foo.zim!1.foreign : (Foo) -> () -> Boo
// CHECK-ios-x86_64: [[BOOL:%.*]] = apply [[METHOD]]([[BORROWED_SELF]]) : $@convention(objc_method) (Foo) -> Bool
// CHECK-ios-x86_64: end_borrow [[BORROWED_SELF]] from [[SELF]]
// CHECK-ios-x86_64: return [[BOOL]] : $Bool
// CHECK-ios-x86_64: }
// CHECK-arm64-LABEL: sil hidden @_T013objc_bridging6getZim{{.*}}F
// CHECK-arm64: bb0([[SELF:%.*]] : $Foo):
// CHECK-arm64: [[BORROWED_SELF:%.*]] = begin_borrow [[SELF]]
// CHECK-arm64: [[METHOD:%.*]] = class_method [volatile] [[BORROWED_SELF]] : $Foo, #Foo.zim!1.foreign : (Foo) -> () -> Boo
// CHECK-arm64: [[BOOL:%.*]] = apply [[METHOD]]([[BORROWED_SELF]]) : $@convention(objc_method) (Foo) -> Bool
// CHECK-arm64: end_borrow [[BORROWED_SELF]] from [[SELF]]
// CHECK-arm64: return [[BOOL]] : $Bool
// CHECK-arm64: }
// @interface Foo -(void) setZim: (BOOL)b; @end
func setZim(_ f: Foo, b: Bool) {
f.setZim(b)
}
// CHECK-ios-i386-LABEL: sil hidden @_T013objc_bridging6setZim{{.*}}F
// CHECK-ios-i386: bb0([[ARG0:%.*]] : $Foo, [[ARG1:%.*]] : $Bool):
// CHECK-ios-i386: [[BORROWED_ARG0:%.*]] = begin_borrow [[ARG0]]
// CHECK-ios-i386: [[METHOD:%.*]] = class_method [volatile] [[BORROWED_ARG0]] : $Foo, #Foo.setZim!1.foreign
// CHECK-ios-i386: [[CONVERT:%.*]] = function_ref @swift_BoolToObjCBool : $@convention(thin) (Bool) -> ObjCBool
// CHECK-ios-i386: [[OBJC_BOOL:%.*]] = apply [[CONVERT]]([[ARG1]]) : $@convention(thin) (Bool) -> ObjCBool
// CHECK-ios-i386: apply [[METHOD]]([[OBJC_BOOL]], [[BORROWED_ARG0]]) : $@convention(objc_method) (ObjCBool, Foo) -> ()
// CHECK-ios-i386: end_borrow [[BORROWED_ARG0]] from [[ARG0]]
// CHECK-ios-i386: destroy_value [[ARG0]]
// CHECK-ios-i386: }
// CHECK-macosx-x86_64-LABEL: sil hidden @_T013objc_bridging6setZim{{.*}}F
// CHECK-macosx-x86_64: bb0([[ARG0:%.*]] : $Foo, [[ARG1:%.*]] : $Bool):
// CHECK-macosx-x86_64: [[BORROWED_ARG0:%.*]] = begin_borrow [[ARG0]]
// CHECK-macosx-x86_64: [[METHOD:%.*]] = class_method [volatile] [[BORROWED_ARG0]] : $Foo, #Foo.setZim!1.foreign
// CHECK-macosx-x86_64: [[CONVERT:%.*]] = function_ref @swift_BoolToObjCBool : $@convention(thin) (Bool) -> ObjCBool
// CHECK-macosx-x86_64: [[OBJC_BOOL:%.*]] = apply [[CONVERT]]([[ARG1]]) : $@convention(thin) (Bool) -> ObjCBool
// CHECK-macosx-x86_64: apply [[METHOD]]([[OBJC_BOOL]], [[BORROWED_ARG0]]) : $@convention(objc_method) (ObjCBool, Foo) -> ()
// CHECK-macosx-x86_64: end_borrow [[BORROWED_ARG0]] from [[ARG0]]
// CHECK-macosx-x86_64: destroy_value [[ARG0]]
// CHECK-macosx-x86_64: }
// CHECK-ios-x86_64-LABEL: sil hidden @_T013objc_bridging6setZim{{.*}}F
// CHECK-ios-x86_64: bb0([[ARG0:%.*]] : $Foo, [[ARG1:%.*]] : $Bool):
// CHECK-ios-x86_64: [[BORROWED_ARG0:%.*]] = begin_borrow [[ARG0]]
// CHECK-ios-x86_64: [[METHOD:%.*]] = class_method [volatile] [[BORROWED_ARG0]] : $Foo, #Foo.setZim!1.foreign
// CHECK-ios-x86_64: apply [[METHOD]]([[ARG1]], [[BORROWED_ARG0]]) : $@convention(objc_method) (Bool, Foo) -> ()
// CHECK-ios-x86_64: end_borrow [[BORROWED_ARG0]] from [[ARG0]]
// CHECK-ios-x86_64: destroy_value [[ARG0]]
// CHECK-ios-x86_64: }
// CHECK-arm64-LABEL: sil hidden @_T013objc_bridging6setZim{{.*}}F
// CHECK-arm64: bb0([[ARG0:%.*]] : $Foo, [[ARG1:%.*]] : $Bool):
// CHECK-arm64: [[BORROWED_ARG0:%.*]] = begin_borrow [[ARG0]]
// CHECK-arm64: [[METHOD:%.*]] = class_method [volatile] [[BORROWED_ARG0]] : $Foo, #Foo.setZim!1.foreign
// CHECK-arm64: apply [[METHOD]]([[ARG1]], [[BORROWED_ARG0]]) : $@convention(objc_method) (Bool, Foo) -> ()
// CHECK-arm64: end_borrow [[BORROWED_ARG0]] from [[ARG0]]
// CHECK-arm64: destroy_value [[ARG0]]
// CHECK-arm64: }
// CHECK-watchos-i386-LABEL: sil hidden @_T013objc_bridging6setZim{{.*}}F
// CHECK-watchos-i386: bb0([[ARG0:%.*]] : $Foo, [[ARG1:%.*]] : $Bool):
// CHECK-watchos-i386: [[BORROWED_ARG0:%.*]] = begin_borrow [[ARG0]]
// CHECK-watchos-i386: [[METHOD:%.*]] = class_method [volatile] [[BORROWED_ARG0]] : $Foo, #Foo.setZim!1.foreign
// CHECK-watchos-i386: apply [[METHOD]]([[ARG1]], [[BORROWED_ARG0]]) : $@convention(objc_method) (Bool, Foo) -> ()
// CHECK-watchos-i386: end_borrow [[BORROWED_ARG0]] from [[ARG0]]
// CHECK-watchos-i386: destroy_value [[ARG0]]
// CHECK-watchos-i386: }
// @interface Foo -(_Bool) zang; @end
func getZang(_ f: Foo) -> Bool {
return f.zang()
}
// CHECK-LABEL: sil hidden @_T013objc_bridging7getZangSbSo3FooCF
// CHECK: bb0([[ARG:%.*]] : $Foo)
// CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]]
// CHECK: [[METHOD:%.*]] = class_method [volatile] [[BORROWED_ARG]] : $Foo, #Foo.zang!1.foreign
// CHECK: [[BOOL:%.*]] = apply [[METHOD]]([[BORROWED_ARG]]) : $@convention(objc_method) (Foo) -> Bool
// CHECK: end_borrow [[BORROWED_ARG]] from [[ARG]]
// CHECK: destroy_value [[ARG]]
// CHECK: return [[BOOL]]
// @interface Foo -(void) setZang: (_Bool)b; @end
func setZang(_ f: Foo, _ b: Bool) {
f.setZang(b)
}
// CHECK-LABEL: sil hidden @_T013objc_bridging7setZangySo3FooC_SbtF
// CHECK: bb0([[ARG0:%.*]] : $Foo, [[ARG1:%.*]] : $Bool):
// CHECK: [[BORROWED_ARG0:%.*]] = begin_borrow [[ARG0]]
// CHECK: [[METHOD:%.*]] = class_method [volatile] [[BORROWED_ARG0]] : $Foo, #Foo.setZang!1.foreign
// CHECK: apply [[METHOD]]([[ARG1]], [[BORROWED_ARG0]]) : $@convention(objc_method) (Bool, Foo) -> ()
// CHECK: end_borrow [[BORROWED_ARG0]] from [[ARG0]]
// CHECK: destroy_value [[ARG0]]
// CHECK: } // end sil function '_T013objc_bridging7setZangySo3FooC_SbtF'
// NSString *bar(void);
func callBar() -> String {
return bar()
}
// CHECK-LABEL: sil hidden @_T013objc_bridging7callBar{{.*}}F
// CHECK: bb0:
// CHECK: [[BAR:%.*]] = function_ref @bar
// CHECK: [[OPT_BRIDGED:%.*]] = apply [[BAR]]() : $@convention(c) () -> @autoreleased Optional<NSString>
// CHECK: switch_enum [[OPT_BRIDGED]] : $Optional<NSString>, case #Optional.some!enumelt.1: [[SOME_BB:bb[0-9]+]], case #Optional.none!enumelt: [[NONE_BB:bb[0-9]+]]
// CHECK: [[SOME_BB]]([[BRIDGED:%.*]] : $NSString):
// CHECK: [[NSSTRING_TO_STRING:%.*]] = function_ref @_T0SS10FoundationE36_unconditionallyBridgeFromObjectiveCSSSo8NSStringCSgFZ
// CHECK: [[BRIDGED_BOX:%.*]] = enum $Optional<NSString>, #Optional.some!enumelt.1, [[BRIDGED]]
// CHECK: [[NATIVE:%.*]] = apply [[NSSTRING_TO_STRING]]([[BRIDGED_BOX]]
// CHECK: [[OPT_NATIVE:%.*]] = enum $Optional<String>, #Optional.some!enumelt.1, [[NATIVE]]
// CHECK: bb5([[NATIVE:%.*]] : $String):
// CHECK: return [[NATIVE]]
// CHECK: }
// void setBar(NSString *s);
func callSetBar(_ s: String) {
var s = s
setBar(s)
}
// CHECK-LABEL: sil hidden @_T013objc_bridging10callSetBar{{.*}}F
// CHECK: bb0({{%.*}} : $String):
// CHECK: [[SET_BAR:%.*]] = function_ref @setBar
// CHECK: [[NV:%.*]] = load
// CHECK: [[OPT_NATIVE:%.*]] = enum $Optional<String>, #Optional.some!enumelt.1, [[NV]]
// CHECK: switch_enum [[OPT_NATIVE]] : $Optional<String>, case #Optional.some!enumelt.1: [[SOME_BB:bb[0-9]+]], case #Optional.none!enumelt: [[NONE_BB:bb[0-9]+]]
// CHECK: [[SOME_BB]]([[NATIVE:%.*]] : $String):
// CHECK-NOT: unchecked_enum_data
// CHECK: [[STRING_TO_NSSTRING:%.*]] = function_ref @_T0SS10FoundationE19_bridgeToObjectiveCSo8NSStringCyF
// CHECK: [[BORROWED_NATIVE:%.*]] = begin_borrow [[NATIVE]]
// CHECK: [[BRIDGED:%.*]] = apply [[STRING_TO_NSSTRING]]([[BORROWED_NATIVE]])
// CHECK: = enum $Optional<NSString>, #Optional.some!enumelt.1, [[BRIDGED]]
// CHECK: end_borrow [[BORROWED_NATIVE]] from [[NATIVE]]
// CHECK: bb3([[OPT_BRIDGED:%.*]] : $Optional<NSString>):
// CHECK: apply [[SET_BAR]]([[OPT_BRIDGED]])
// CHECK: destroy_value [[OPT_BRIDGED]]
// CHECK: }
var NSS: NSString
// -- NSString methods don't convert 'self'
extension NSString {
var nsstrFakeProp: NSString {
get { return NSS }
set {}
}
// CHECK-LABEL: sil hidden [thunk] @_T0So8NSStringC13objc_bridgingE13nsstrFakePropABfgTo
// CHECK-NOT: swift_StringToNSString
// CHECK-NOT: _T0SS10FoundationE36_unconditionallyBridgeFromObjectiveCSSSo8NSStringCSgFZ
// CHECK: }
// CHECK-LABEL: sil hidden [thunk] @_T0So8NSStringC13objc_bridgingE13nsstrFakePropABfsTo
// CHECK-NOT: swift_StringToNSString
// CHECK-NOT: _T0SS10FoundationE36_unconditionallyBridgeFromObjectiveCSSSo8NSStringCSgFZ
// CHECK: }
func nsstrResult() -> NSString { return NSS }
// CHECK-LABEL: sil hidden [thunk] @_T0So8NSStringC13objc_bridgingE11nsstrResultAByFTo
// CHECK-NOT: swift_StringToNSString
// CHECK-NOT: _T0SS10FoundationE36_unconditionallyBridgeFromObjectiveCSSSo8NSStringCSgFZ
// CHECK: }
func nsstrArg(_ s: NSString) { }
// CHECK-LABEL: sil hidden [thunk] @_T0So8NSStringC13objc_bridgingE8nsstrArgyABFTo
// CHECK-NOT: swift_StringToNSString
// CHECK-NOT: _T0SS10FoundationE36_unconditionallyBridgeFromObjectiveCSSSo8NSStringCSgFZ
// CHECK: }
}
class Bas : NSObject {
// -- Bridging thunks for String properties convert between NSString
var strRealProp: String = "Hello"
// CHECK-LABEL: sil hidden [thunk] @_T013objc_bridging3BasC11strRealPropSSfgTo : $@convention(objc_method) (Bas) -> @autoreleased NSString {
// CHECK: bb0([[THIS:%.*]] : $Bas):
// CHECK: [[THIS_COPY:%.*]] = copy_value [[THIS]] : $Bas
// CHECK: [[BORROWED_THIS_COPY:%.*]] = begin_borrow [[THIS_COPY]]
// CHECK: // function_ref objc_bridging.Bas.strRealProp.getter
// CHECK: [[PROPIMPL:%.*]] = function_ref @_T013objc_bridging3BasC11strRealPropSSfg
// CHECK: [[PROP_COPY:%.*]] = apply [[PROPIMPL]]([[BORROWED_THIS_COPY]]) : $@convention(method) (@guaranteed Bas) -> @owned String
// CHECK: end_borrow [[BORROWED_THIS_COPY]] from [[THIS_COPY]]
// CHECK: destroy_value [[THIS_COPY]]
// CHECK: [[STRING_TO_NSSTRING:%.*]] = function_ref @_T0SS10FoundationE19_bridgeToObjectiveCSo8NSStringCyF
// CHECK: [[BORROWED_PROP_COPY:%.*]] = begin_borrow [[PROP_COPY]]
// CHECK: [[NSSTR:%.*]] = apply [[STRING_TO_NSSTRING]]([[BORROWED_PROP_COPY]])
// CHECK: end_borrow [[BORROWED_PROP_COPY]] from [[PROP_COPY]]
// CHECK: destroy_value [[PROP_COPY]]
// CHECK: return [[NSSTR]]
// CHECK: }
// CHECK-LABEL: sil hidden @_T013objc_bridging3BasC11strRealPropSSfg
// CHECK: [[PROP_ADDR:%.*]] = ref_element_addr %0 : {{.*}}, #Bas.strRealProp
// CHECK: [[PROP:%.*]] = load [copy] [[PROP_ADDR]]
// CHECK-LABEL: sil hidden [thunk] @_T013objc_bridging3BasC11strRealPropSSfsTo : $@convention(objc_method) (NSString, Bas) -> () {
// CHECK: bb0([[VALUE:%.*]] : $NSString, [[THIS:%.*]] : $Bas):
// CHECK: [[VALUE_COPY:%.*]] = copy_value [[VALUE]]
// CHECK: [[THIS_COPY:%.*]] = copy_value [[THIS]]
// CHECK: [[NSSTRING_TO_STRING:%.*]] = function_ref @_T0SS10FoundationE36_unconditionallyBridgeFromObjectiveCSSSo8NSStringCSgFZ
// CHECK: [[VALUE_BOX:%.*]] = enum $Optional<NSString>, #Optional.some!enumelt.1, [[VALUE_COPY]]
// CHECK: [[STR:%.*]] = apply [[NSSTRING_TO_STRING]]([[VALUE_BOX]]
// CHECK: [[BORROWED_THIS_COPY:%.*]] = begin_borrow [[THIS_COPY]]
// CHECK: [[SETIMPL:%.*]] = function_ref @_T013objc_bridging3BasC11strRealPropSSfs
// CHECK: apply [[SETIMPL]]([[STR]], [[BORROWED_THIS_COPY]])
// CHECK: end_borrow [[BORROWED_THIS_COPY]] from [[THIS_COPY]]
// CHECK: destroy_value [[THIS_COPY]]
// CHECK: } // end sil function '_T013objc_bridging3BasC11strRealPropSSfsTo'
// CHECK-LABEL: sil hidden @_T013objc_bridging3BasC11strRealPropSSfs
// CHECK: bb0(%0 : $String, %1 : $Bas):
// CHECK: [[STR_ADDR:%.*]] = ref_element_addr %1 : {{.*}}, #Bas.strRealProp
// CHECK: assign {{.*}} to [[STR_ADDR]]
// CHECK: }
var strFakeProp: String {
get { return "" }
set {}
}
// CHECK-LABEL: sil hidden [thunk] @_T013objc_bridging3BasC11strFakePropSSfgTo : $@convention(objc_method) (Bas) -> @autoreleased NSString {
// CHECK: bb0([[THIS:%.*]] : $Bas):
// CHECK: [[THIS_COPY:%.*]] = copy_value [[THIS]]
// CHECK: [[BORROWED_THIS_COPY:%.*]] = begin_borrow [[THIS_COPY]]
// CHECK: [[GETTER:%.*]] = function_ref @_T013objc_bridging3BasC11strFakePropSSfg
// CHECK: [[STR:%.*]] = apply [[GETTER]]([[BORROWED_THIS_COPY]])
// CHECK: end_borrow [[BORROWED_THIS_COPY]] from [[THIS_COPY]]
// CHECK: destroy_value [[THIS_COPY]]
// CHECK: [[STRING_TO_NSSTRING:%.*]] = function_ref @_T0SS10FoundationE19_bridgeToObjectiveCSo8NSStringCyF
// CHECK: [[BORROWED_STR:%.*]] = begin_borrow [[STR]]
// CHECK: [[NSSTR:%.*]] = apply [[STRING_TO_NSSTRING]]([[BORROWED_STR]])
// CHECK: end_borrow [[BORROWED_STR]] from [[STR]]
// CHECK: destroy_value [[STR]]
// CHECK: return [[NSSTR]]
// CHECK: }
// CHECK-LABEL: sil hidden [thunk] @_T013objc_bridging3BasC11strFakePropSSfsTo : $@convention(objc_method) (NSString, Bas) -> () {
// CHECK: bb0([[NSSTR:%.*]] : $NSString, [[THIS:%.*]] : $Bas):
// CHECK: [[NSSTR_COPY:%.*]] = copy_value [[NSSTR]]
// CHECK: [[THIS_COPY:%.*]] = copy_value [[THIS]]
// CHECK: [[NSSTRING_TO_STRING:%.*]] = function_ref @_T0SS10FoundationE36_unconditionallyBridgeFromObjectiveCSSSo8NSStringCSgFZ
// CHECK: [[NSSTR_BOX:%.*]] = enum $Optional<NSString>, #Optional.some!enumelt.1, [[NSSTR_COPY]]
// CHECK: [[STR:%.*]] = apply [[NSSTRING_TO_STRING]]([[NSSTR_BOX]]
// CHECK: [[BORROWED_THIS_COPY:%.*]] = begin_borrow [[THIS_COPY]]
// CHECK: [[SETTER:%.*]] = function_ref @_T013objc_bridging3BasC11strFakePropSSfs
// CHECK: apply [[SETTER]]([[STR]], [[BORROWED_THIS_COPY]])
// CHECK: end_borrow [[BORROWED_THIS_COPY]] from [[THIS_COPY]]
// CHECK: destroy_value [[THIS_COPY]]
// CHECK: } // end sil function '_T013objc_bridging3BasC11strFakePropSSfsTo'
// -- Bridging thunks for explicitly NSString properties don't convert
var nsstrRealProp: NSString
var nsstrFakeProp: NSString {
get { return NSS }
set {}
}
// CHECK-LABEL: sil hidden [thunk] @_T013objc_bridging3BasC13nsstrRealPropSo8NSStringCfgTo : $@convention(objc_method) (Bas) -> @autoreleased NSString {
// CHECK-NOT: swift_StringToNSString
// CHECK-NOT: _T0SS10FoundationE36_unconditionallyBridgeFromObjectiveCSSSo8NSStringCSgFZ
// CHECK: }
// CHECK-LABEL: sil hidden [thunk] @_T013objc_bridging3BasC13nsstrRealPropSo8NSStringCfsTo : $@convention(objc_method) (NSString, Bas) ->
// CHECK-NOT: swift_StringToNSString
// CHECK-NOT: _T0SS10FoundationE36_unconditionallyBridgeFromObjectiveCSSSo8NSStringCSgFZ
// CHECK: }
// -- Bridging thunks for String methods convert between NSString
func strResult() -> String { return "" }
// CHECK-LABEL: sil hidden [thunk] @_T013objc_bridging3BasC9strResultSSyFTo
// CHECK: bb0([[THIS:%.*]] : $Bas):
// CHECK: [[THIS_COPY:%.*]] = copy_value [[THIS]]
// CHECK: [[BORROWED_THIS_COPY:%.*]] = begin_borrow [[THIS_COPY]]
// CHECK: [[METHOD:%.*]] = function_ref @_T013objc_bridging3BasC9strResultSSyF
// CHECK: [[STR:%.*]] = apply [[METHOD]]([[BORROWED_THIS_COPY]])
// CHECK: end_borrow [[BORROWED_THIS_COPY]] from [[THIS_COPY]]
// CHECK: destroy_value [[THIS_COPY]]
// CHECK: [[STRING_TO_NSSTRING:%.*]] = function_ref @_T0SS10FoundationE19_bridgeToObjectiveCSo8NSStringCyF
// CHECK: [[BORROWED_STR:%.*]] = begin_borrow [[STR]]
// CHECK: [[NSSTR:%.*]] = apply [[STRING_TO_NSSTRING]]([[BORROWED_STR]])
// CHECK: end_borrow [[BORROWED_STR]] from [[STR]]
// CHECK: destroy_value [[STR]]
// CHECK: return [[NSSTR]]
// CHECK: }
func strArg(_ s: String) { }
// CHECK-LABEL: sil hidden [thunk] @_T013objc_bridging3BasC6strArgySSFTo
// CHECK: bb0([[NSSTR:%.*]] : $NSString, [[THIS:%.*]] : $Bas):
// CHECK: [[NSSTR_COPY:%.*]] = copy_value [[NSSTR]]
// CHECK: [[THIS_COPY:%.*]] = copy_value [[THIS]]
// CHECK: [[NSSTRING_TO_STRING:%.*]] = function_ref @_T0SS10FoundationE36_unconditionallyBridgeFromObjectiveCSSSo8NSStringCSgFZ
// CHECK: [[NSSTR_BOX:%.*]] = enum $Optional<NSString>, #Optional.some!enumelt.1, [[NSSTR_COPY]]
// CHECK: [[STR:%.*]] = apply [[NSSTRING_TO_STRING]]([[NSSTR_BOX]]
// CHECK: [[BORROWED_THIS_COPY:%.*]] = begin_borrow [[THIS_COPY]]
// CHECK: [[METHOD:%.*]] = function_ref @_T013objc_bridging3BasC6strArgySSF
// CHECK: apply [[METHOD]]([[STR]], [[BORROWED_THIS_COPY]])
// CHECK: end_borrow [[BORROWED_THIS_COPY]] from [[THIS_COPY]]
// CHECK: destroy_value [[THIS_COPY]]
// CHECK: } // end sil function '_T013objc_bridging3BasC6strArgySSFTo'
// -- Bridging thunks for explicitly NSString properties don't convert
func nsstrResult() -> NSString { return NSS }
// CHECK-LABEL: sil hidden [thunk] @_T013objc_bridging3BasC11nsstrResultSo8NSStringCyFTo
// CHECK-NOT: swift_StringToNSString
// CHECK-NOT: _T0SS10FoundationE36_unconditionallyBridgeFromObjectiveCSSSo8NSStringCSgFZ
// CHECK: }
func nsstrArg(_ s: NSString) { }
// CHECK-LABEL: sil hidden @_T013objc_bridging3BasC8nsstrArgySo8NSStringCF
// CHECK-NOT: swift_StringToNSString
// CHECK-NOT: _T0SS10FoundationE36_unconditionallyBridgeFromObjectiveCSSSo8NSStringCSgFZ
// CHECK: }
init(str: NSString) {
nsstrRealProp = str
super.init()
}
// CHECK-LABEL: sil hidden [thunk] @_T013objc_bridging3BasC8arrayArgySayyXlGFTo : $@convention(objc_method) (NSArray, Bas) -> ()
// CHECK: bb0([[NSARRAY:%[0-9]+]] : $NSArray, [[SELF:%[0-9]+]] : $Bas):
// CHECK: [[NSARRAY_COPY:%.*]] = copy_value [[NSARRAY]] : $NSArray
// CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]] : $Bas
// CHECK: [[CONV_FN:%[0-9]+]] = function_ref @_T0Sa10FoundationE36_unconditionallyBridgeFromObjectiveCSayxGSo7NSArrayCSgFZ
// CHECK: [[OPT_NSARRAY:%[0-9]+]] = enum $Optional<NSArray>, #Optional.some!enumelt.1, [[NSARRAY_COPY]] : $NSArray
// CHECK: [[ARRAY_META:%[0-9]+]] = metatype $@thin Array<AnyObject>.Type
// CHECK: [[ARRAY:%[0-9]+]] = apply [[CONV_FN]]<AnyObject>([[OPT_NSARRAY]], [[ARRAY_META]])
// CHECK: [[BORROWED_SELF_COPY:%.*]] = begin_borrow [[SELF_COPY]]
// CHECK: [[SWIFT_FN:%[0-9]+]] = function_ref @_T013objc_bridging3BasC8arrayArgySayyXlGF : $@convention(method) (@owned Array<AnyObject>, @guaranteed Bas) -> ()
// CHECK: [[RESULT:%[0-9]+]] = apply [[SWIFT_FN]]([[ARRAY]], [[BORROWED_SELF_COPY]]) : $@convention(method) (@owned Array<AnyObject>, @guaranteed Bas) -> ()
// CHECK: end_borrow [[BORROWED_SELF_COPY]] from [[SELF_COPY]]
// CHECK: destroy_value [[SELF_COPY]] : $Bas
// CHECK: return [[RESULT]] : $()
func arrayArg(_ array: [AnyObject]) { }
// CHECK-LABEL: sil hidden [thunk] @_T013objc_bridging3BasC11arrayResultSayyXlGyFTo : $@convention(objc_method) (Bas) -> @autoreleased NSArray
// CHECK: bb0([[SELF:%[0-9]+]] : $Bas):
// CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]] : $Bas
// CHECK: [[BORROWED_SELF_COPY:%.*]] = begin_borrow [[SELF_COPY]]
// CHECK: [[SWIFT_FN:%[0-9]+]] = function_ref @_T013objc_bridging3BasC11arrayResultSayyXlGyF : $@convention(method) (@guaranteed Bas) -> @owned Array<AnyObject>
// CHECK: [[ARRAY:%[0-9]+]] = apply [[SWIFT_FN]]([[BORROWED_SELF_COPY]]) : $@convention(method) (@guaranteed Bas) -> @owned Array<AnyObject>
// CHECK: end_borrow [[BORROWED_SELF_COPY]] from [[SELF_COPY]]
// CHECK: destroy_value [[SELF_COPY]]
// CHECK: [[CONV_FN:%[0-9]+]] = function_ref @_T0Sa10FoundationE19_bridgeToObjectiveCSo7NSArrayCyF
// CHECK: [[BORROWED_ARRAY:%.*]] = begin_borrow [[ARRAY]]
// CHECK: [[NSARRAY:%[0-9]+]] = apply [[CONV_FN]]<AnyObject>([[BORROWED_ARRAY]]) : $@convention(method) <τ_0_0> (@guaranteed Array<τ_0_0>) -> @owned NSArray
// CHECK: end_borrow [[BORROWED_ARRAY]] from [[ARRAY]]
// CHECK: destroy_value [[ARRAY]]
// CHECK: return [[NSARRAY]]
func arrayResult() -> [AnyObject] { return [] }
// CHECK-LABEL: sil hidden [thunk] @_T013objc_bridging3BasC9arrayPropSaySSGfgTo : $@convention(objc_method) (Bas) -> @autoreleased NSArray
// CHECK-LABEL: sil hidden [thunk] @_T013objc_bridging3BasC9arrayPropSaySSGfsTo : $@convention(objc_method) (NSArray, Bas) -> ()
var arrayProp: [String] = []
}
// CHECK-LABEL: sil hidden @_T013objc_bridging16applyStringBlockS3SXB_SS1xtF
func applyStringBlock(_ f: @convention(block) (String) -> String, x: String) -> String {
// CHECK: bb0([[BLOCK:%.*]] : $@convention(block) (NSString) -> @autoreleased NSString, [[STRING:%.*]] : $String):
// CHECK: [[BLOCK_COPY:%.*]] = copy_block [[BLOCK]]
// CHECK: [[BORROWED_BLOCK_COPY:%.*]] = begin_borrow [[BLOCK_COPY]]
// CHECK: [[BLOCK_COPY_COPY:%.*]] = copy_value [[BORROWED_BLOCK_COPY]]
// CHECK: [[BORROWED_STRING:%.*]] = begin_borrow [[STRING]]
// CHECK: [[STRING_COPY:%.*]] = copy_value [[BORROWED_STRING]]
// CHECK: [[STRING_TO_NSSTRING:%.*]] = function_ref @_T0SS10FoundationE19_bridgeToObjectiveCSo8NSStringCyF
// CHECK: [[BORROWED_STRING_COPY:%.*]] = begin_borrow [[STRING_COPY]]
// CHECK: [[NSSTR:%.*]] = apply [[STRING_TO_NSSTRING]]([[BORROWED_STRING_COPY]]) : $@convention(method) (@guaranteed String)
// CHECK: end_borrow [[BORROWED_STRING_COPY]] from [[STRING_COPY]]
// CHECK: destroy_value [[STRING_COPY]]
// CHECK: [[RESULT_NSSTR:%.*]] = apply [[BLOCK_COPY_COPY]]([[NSSTR]]) : $@convention(block) (NSString) -> @autoreleased NSString
// CHECK: destroy_value [[NSSTR]]
// CHECK: [[FINAL_BRIDGE:%.*]] = function_ref @_T0SS10FoundationE36_unconditionallyBridgeFromObjectiveCSSSo8NSStringCSgFZ
// CHECK: [[OPTIONAL_NSSTR:%.*]] = enum $Optional<NSString>, #Optional.some!enumelt.1, [[RESULT_NSSTR]]
// CHECK: [[RESULT:%.*]] = apply [[FINAL_BRIDGE]]([[OPTIONAL_NSSTR]], {{.*}}) : $@convention(method) (@owned Optional<NSString>, @thin String.Type) -> @owned String
// CHECK: destroy_value [[BLOCK_COPY_COPY]]
// CHECK: destroy_value [[STRING]]
// CHECK: destroy_value [[BLOCK_COPY]]
// CHECK: destroy_value [[BLOCK]]
// CHECK: return [[RESULT]] : $String
return f(x)
}
// CHECK: } // end sil function '_T013objc_bridging16applyStringBlockS3SXB_SS1xtF'
// CHECK-LABEL: sil hidden @_T013objc_bridging15bridgeCFunction{{.*}}F
func bridgeCFunction() -> (String!) -> (String!) {
// CHECK: [[THUNK:%.*]] = function_ref @_T0SC18NSStringFromStringSQySSGABFTO : $@convention(thin) (@owned Optional<String>) -> @owned Optional<String>
// CHECK: [[THICK:%.*]] = thin_to_thick_function [[THUNK]]
// CHECK: return [[THICK]]
return NSStringFromString
}
func forceNSArrayMembers() -> (NSArray, NSArray) {
let x = NSArray(objects: nil, count: 0)
return (x, x)
}
// Check that the allocating initializer shim for initializers that take pointer
// arguments lifetime-extends the bridged pointer for the right duration.
// <rdar://problem/16738050>
// CHECK-LABEL: sil shared [serializable] @_T0So7NSArrayCABSQySPyyXlSgGG7objects_s5Int32V5counttcfC
// CHECK: [[SELF:%.*]] = alloc_ref_dynamic
// CHECK: [[METHOD:%.*]] = function_ref @_T0So7NSArrayCABSQySPyyXlSgGG7objects_s5Int32V5counttcfcTO
// CHECK: [[RESULT:%.*]] = apply [[METHOD]]
// CHECK: return [[RESULT]]
// Check that type lowering preserves the bool/BOOL distinction when bridging
// imported C functions.
// CHECK-ios-i386-LABEL: sil hidden @_T013objc_bridging5boolsSb_SbtSbF
// CHECK-ios-i386: function_ref @useBOOL : $@convention(c) (ObjCBool) -> ()
// CHECK-ios-i386: function_ref @useBool : $@convention(c) (Bool) -> ()
// CHECK-ios-i386: function_ref @getBOOL : $@convention(c) () -> ObjCBool
// CHECK-ios-i386: function_ref @getBool : $@convention(c) () -> Bool
// CHECK-macosx-x86_64-LABEL: sil hidden @_T013objc_bridging5boolsSb_SbtSbF
// CHECK-macosx-x86_64: function_ref @useBOOL : $@convention(c) (ObjCBool) -> ()
// CHECK-macosx-x86_64: function_ref @useBool : $@convention(c) (Bool) -> ()
// CHECK-macosx-x86_64: function_ref @getBOOL : $@convention(c) () -> ObjCBool
// CHECK-macosx-x86_64: function_ref @getBool : $@convention(c) () -> Bool
// FIXME: no distinction on x86_64, arm64 or watchos-i386, since SILGen looks
// at the underlying Clang decl of the bridged decl to decide whether it needs
// bridging.
//
// CHECK-watchos-i386-LABEL: sil hidden @_T013objc_bridging5boolsSb_SbtSbF
// CHECK-watchos-i386: function_ref @useBOOL : $@convention(c) (Bool) -> ()
// CHECK-watchos-i386: function_ref @useBool : $@convention(c) (Bool) -> ()
// CHECK-watchos-i386: function_ref @getBOOL : $@convention(c) () -> Bool
// CHECK-watchos-i386: function_ref @getBool : $@convention(c) () -> Bool
// CHECK-ios-x86_64-LABEL: sil hidden @_T013objc_bridging5boolsSb_SbtSbF
// CHECK-ios-x86_64: function_ref @useBOOL : $@convention(c) (Bool) -> ()
// CHECK-ios-x86_64: function_ref @useBool : $@convention(c) (Bool) -> ()
// CHECK-ios-x86_64: function_ref @getBOOL : $@convention(c) () -> Bool
// CHECK-ios-x86_64: function_ref @getBool : $@convention(c) () -> Bool
// CHECK-arm64-LABEL: sil hidden @_T013objc_bridging5boolsSb_SbtSbF
// CHECK-arm64: function_ref @useBOOL : $@convention(c) (Bool) -> ()
// CHECK-arm64: function_ref @useBool : $@convention(c) (Bool) -> ()
// CHECK-arm64: function_ref @getBOOL : $@convention(c) () -> Bool
// CHECK-arm64: function_ref @getBool : $@convention(c) () -> Bool
func bools(_ x: Bool) -> (Bool, Bool) {
useBOOL(x)
useBool(x)
return (getBOOL(), getBool())
}
// CHECK-LABEL: sil hidden @_T013objc_bridging9getFridge{{.*}}F
// CHECK: bb0([[HOME:%[0-9]+]] : $APPHouse):
func getFridge(_ home: APPHouse) -> Refrigerator {
// CHECK: [[BORROWED_HOME:%.*]] = begin_borrow [[HOME]]
// CHECK: [[GETTER:%[0-9]+]] = class_method [volatile] [[BORROWED_HOME]] : $APPHouse, #APPHouse.fridge!getter.1.foreign
// CHECK: [[OBJC_RESULT:%[0-9]+]] = apply [[GETTER]]([[BORROWED_HOME]])
// CHECK: [[BRIDGE_FN:%[0-9]+]] = function_ref @_T010Appliances12RefrigeratorV36_unconditionallyBridgeFromObjectiveCACSo15APPRefrigeratorCSgFZ
// CHECK: [[REFRIGERATOR_META:%[0-9]+]] = metatype $@thin Refrigerator.Type
// CHECK: [[RESULT:%[0-9]+]] = apply [[BRIDGE_FN]]([[OBJC_RESULT]], [[REFRIGERATOR_META]])
// CHECK: end_borrow [[BORROWED_HOME]] from [[HOME]]
// CHECK: destroy_value [[HOME]] : $APPHouse
// CHECK: return [[RESULT]] : $Refrigerator
return home.fridge
}
// FIXME(integers): the following checks should be updated for the new integer
// protocols. <rdar://problem/29939484>
// XCHECK-LABEL: sil hidden @_T013objc_bridging16updateFridgeTemp{{.*}}F
// XCHECK: bb0([[HOME:%[0-9]+]] : $APPHouse, [[DELTA:%[0-9]+]] : $Double):
func updateFridgeTemp(_ home: APPHouse, delta: Double) {
// +=
// XCHECK: [[PLUS_EQ:%[0-9]+]] = function_ref @_T0s2peoiySdz_SdtF
// Borrowed home
// CHECK: [[BORROWED_HOME:%.*]] = begin_borrow [[HOME]]
// Temporary fridge
// XCHECK: [[TEMP_FRIDGE:%[0-9]+]] = alloc_stack $Refrigerator
// Get operation
// CHECK: [[GETTER:%[0-9]+]] = class_method [volatile] [[BORROWED_HOME]] : $APPHouse, #APPHouse.fridge!getter.1.foreign
// CHECK: [[OBJC_FRIDGE:%[0-9]+]] = apply [[GETTER]]([[BORROWED_HOME]])
// CHECK: [[BRIDGE_FROM_FN:%[0-9]+]] = function_ref @_T010Appliances12RefrigeratorV36_unconditionallyBridgeFromObjectiveCACSo15APPRefrigeratorCSgFZ
// CHECK: [[REFRIGERATOR_META:%[0-9]+]] = metatype $@thin Refrigerator.Type
// CHECK: [[FRIDGE:%[0-9]+]] = apply [[BRIDGE_FROM_FN]]([[OBJC_FRIDGE]], [[REFRIGERATOR_META]])
// Addition
// XCHECK: [[TEMP:%[0-9]+]] = struct_element_addr [[TEMP_FRIDGE]] : $*Refrigerator, #Refrigerator.temperature
// XCHECK: apply [[PLUS_EQ]]([[TEMP]], [[DELTA]])
// Setter
// XCHECK: [[FRIDGE:%[0-9]+]] = load [trivial] [[TEMP_FRIDGE]] : $*Refrigerator
// XCHECK: [[SETTER:%[0-9]+]] = class_method [volatile] [[BORROWED_HOME]] : $APPHouse, #APPHouse.fridge!setter.1.foreign
// XCHECK: [[BRIDGE_TO_FN:%[0-9]+]] = function_ref @_T010Appliances12RefrigeratorV19_bridgeToObjectiveCSo15APPRefrigeratorCyF
// XCHECK: [[OBJC_ARG:%[0-9]+]] = apply [[BRIDGE_TO_FN]]([[FRIDGE]])
// XCHECK: apply [[SETTER]]([[OBJC_ARG]], [[BORROWED_HOME]]) : $@convention(objc_method) (APPRefrigerator, APPHouse) -> ()
// XCHECK: destroy_value [[OBJC_ARG]]
// XCHECK: end_borrow [[BORROWED_HOME]] from [[HOME]]
// XCHECK: destroy_value [[HOME]]
home.fridge.temperature += delta
}
|
6a785e8806370eacf7f9d9ae69da730a
| 55.643625 | 247 | 0.633627 | false | false | false | false |
ccrama/Slide-iOS
|
refs/heads/master
|
Slide for Reddit/Collections.swift
|
apache-2.0
|
1
|
//
// Collections.swift
// Slide for Reddit
//
// Created by Carlos Crane on 9/15/19.
// Copyright © 2019 Haptic Apps. All rights reserved.
//
import reddift
import UIKit
protocol CollectionsDelegate: class {
func didUpdate()
}
class Collections {
public static var collectionIDs: NSMutableDictionary = NSMutableDictionary() {
didSet {
delegate?.didUpdate()
}
}
public static weak var delegate: CollectionsDelegate?
public static func getAllCollectionIDs() -> [Link] {
var toReturn = [Link]()
for value in collectionIDs.allKeys {
if value is String {
var id = value as! String
if id.contains("_") {
id = id.substring(3, length: id.length - 3)
}
toReturn.append(Link(id: id))
}
}
return toReturn
}
public static func getAllCollections() -> [String] {
var collections = [String]()
for item in collectionIDs.allValues {
if item is String && !collections.contains(item as! String) {
collections.append(item as! String)
}
}
return collections
}
public static func getCollectionIDs(title: String = "NONE") -> [Link] {
var toReturn = [Link]()
for value in collectionIDs.allKeys {
if value is String && ((collectionIDs[value] as! String).lowercased() == title.lowercased()) {
var id = value as! String
if id.contains("_") {
id = id.substring(3, length: id.length - 3)
}
toReturn.append(Link(id: id))
}
}
return toReturn
}
public static func isSavedCollectionAny(link: RSubmission) -> Bool {
return isSavedCollectionAny(id: link.getId())
}
public static func isSavedCollectionAny(link: RSubmission, title: String) -> Bool {
return isSavedCollection(id: link.getId(), title: title)
}
public static func isSavedCollectionAny(id: String) -> Bool {
return collectionIDs.object(forKey: id) != nil
}
public static func isSavedCollection(id: String, title: String) -> Bool {
return Collections.getCollectionIDs(title: title).contains(where: { (link) -> Bool in
return link.getId() == id
})
}
@discardableResult
public static func toggleSavedCollection(link: RSubmission, title: String) -> Bool {
let isMarkedReadLater = isSavedCollection(id: link.getId(), title: title)
if isMarkedReadLater {
Collections.removeFromCollection(link: link, title: title)
return false
} else {
Collections.addToCollection(link: link, title: title)
return true
}
}
public static func addToCollection(link: RSubmission, title: String) {
addToCollection(id: link.getId(), title: title)
}
public static func addToCollection(id: String, title: String) {
collectionIDs.setValue(title, forKey: id)
AppDelegate.removeDict.removeObject(forKey: id)
delegate?.didUpdate()
}
public static func addToCollectionCreate(id: String, title: String) {
collectionIDs.setValue(title, forKey: id)
AppDelegate.removeDict.removeObject(forKey: id)
delegate?.didUpdate()
}
public static func removeFromCollection(link: RSubmission, title: String) {
removeFromCollection(id: link.getId(), title: title)
delegate?.didUpdate()
}
public static func removeFromCollection(id: String, title: String) {
var shortId = id
if shortId.contains("_") {
shortId = shortId.substring(3, length: id.length - 3)
collectionIDs.removeObject(forKey: shortId)
}
collectionIDs.removeObject(forKey: id)
AppDelegate.removeDict[id] = 0
}
}
|
225e330690cac2f5e702b379b93d4737
| 31.260163 | 106 | 0.598286 | false | false | false | false |
Djecksan/MobiTask
|
refs/heads/master
|
Example/Pods/ObjectMapper/ObjectMapper/Core/Operators.swift
|
apache-2.0
|
20
|
//
// Operators.swift
// ObjectMapper
//
// Created by Tristan Himmelman on 2014-10-09.
// Copyright (c) 2014 hearst. All rights reserved.
//
/**
* This file defines a new operator which is used to create a mapping between an object and a JSON key value.
* There is an overloaded operator definition for each type of object that is supported in ObjectMapper.
* This provides a way to add custom logic to handle specific types of objects
*/
infix operator <- {}
// MARK:- Objects with Basic types
/// Object of Basic type
public func <- <T>(inout left: T, right: Map) {
if right.mappingType == MappingType.FromJSON {
FromJSON.basicType(&left, object: right.value())
} else {
ToJSON.basicType(left, key: right.currentKey!, dictionary: &right.JSONDictionary)
}
}
/// Optional object of basic type
public func <- <T>(inout left: T?, right: Map) {
if right.mappingType == MappingType.FromJSON {
FromJSON.optionalBasicType(&left, object: right.value())
} else {
ToJSON.optionalBasicType(left, key: right.currentKey!, dictionary: &right.JSONDictionary)
}
}
/// Implicitly unwrapped optional object of basic type
public func <- <T>(inout left: T!, right: Map) {
if right.mappingType == MappingType.FromJSON {
FromJSON.optionalBasicType(&left, object: right.value())
} else {
ToJSON.optionalBasicType(left, key: right.currentKey!, dictionary: &right.JSONDictionary)
}
}
// MARK:- Raw Representable types
/// Object of Raw Representable type
public func <- <T: RawRepresentable>(inout left: T, right: Map) {
left <- (right, EnumTransform())
}
/// Optional Object of Raw Representable type
public func <- <T: RawRepresentable>(inout left: T?, right: Map) {
left <- (right, EnumTransform())
}
/// Implicitly Unwrapped Optional Object of Raw Representable type
public func <- <T: RawRepresentable>(inout left: T!, right: Map) {
left <- (right, EnumTransform())
}
// MARK:- Arrays of Raw Representable type
/// Array of Raw Representable object
public func <- <T: RawRepresentable>(inout left: [T], right: Map) {
left <- (right, EnumTransform())
}
/// Array of Raw Representable object
public func <- <T: RawRepresentable>(inout left: [T]?, right: Map) {
left <- (right, EnumTransform())
}
/// Array of Raw Representable object
public func <- <T: RawRepresentable>(inout left: [T]!, right: Map) {
left <- (right, EnumTransform())
}
// MARK:- Dictionaries of Raw Representable type
/// Dictionary of Raw Representable object
public func <- <T: RawRepresentable>(inout left: [String: T], right: Map) {
left <- (right, EnumTransform())
}
/// Dictionary of Raw Representable object
public func <- <T: RawRepresentable>(inout left: [String: T]?, right: Map) {
left <- (right, EnumTransform())
}
/// Dictionary of Raw Representable object
public func <- <T: RawRepresentable>(inout left: [String: T]!, right: Map) {
left <- (right, EnumTransform())
}
// MARK:- Transforms
/// Object of Basic type with Transform
public func <- <T, Transform: TransformType where Transform.Object == T>(inout left: T, right: (Map, Transform)) {
if right.0.mappingType == MappingType.FromJSON {
var value: T? = right.1.transformFromJSON(right.0.currentValue)
FromJSON.basicType(&left, object: value)
} else {
var value: Transform.JSON? = right.1.transformToJSON(left)
ToJSON.optionalBasicType(value, key: right.0.currentKey!, dictionary: &right.0.JSONDictionary)
}
}
/// Optional object of basic type with Transform
public func <- <T, Transform: TransformType where Transform.Object == T>(inout left: T?, right: (Map, Transform)) {
if right.0.mappingType == MappingType.FromJSON {
var value: T? = right.1.transformFromJSON(right.0.currentValue)
FromJSON.optionalBasicType(&left, object: value)
} else {
var value: Transform.JSON? = right.1.transformToJSON(left)
ToJSON.optionalBasicType(value, key: right.0.currentKey!, dictionary: &right.0.JSONDictionary)
}
}
/// Implicitly unwrapped optional object of basic type with Transform
public func <- <T, Transform: TransformType where Transform.Object == T>(inout left: T!, right: (Map, Transform)) {
if right.0.mappingType == MappingType.FromJSON {
var value: T? = right.1.transformFromJSON(right.0.currentValue)
FromJSON.optionalBasicType(&left, object: value)
} else {
var value: Transform.JSON? = right.1.transformToJSON(left)
ToJSON.optionalBasicType(value, key: right.0.currentKey!, dictionary: &right.0.JSONDictionary)
}
}
/// Array of Basic type with Transform
public func <- <T: TransformType>(inout left: [T.Object], right: (Map, T)) {
let (map, transform) = right
if map.mappingType == MappingType.FromJSON {
let values = fromJSONArrayWithTransform(map.currentValue, transform)
FromJSON.basicType(&left, object: values)
} else {
let values = toJSONArrayWithTransform(left, transform)
ToJSON.optionalBasicType(values, key: map.currentKey!, dictionary: &map.JSONDictionary)
}
}
/// Optional array of Basic type with Transform
public func <- <T: TransformType>(inout left: [T.Object]?, right: (Map, T)) {
let (map, transform) = right
if map.mappingType == MappingType.FromJSON {
let values = fromJSONArrayWithTransform(map.currentValue, transform)
FromJSON.optionalBasicType(&left, object: values)
} else {
let values = toJSONArrayWithTransform(left, transform)
ToJSON.optionalBasicType(values, key: map.currentKey!, dictionary: &map.JSONDictionary)
}
}
/// Implicitly unwrapped optional array of Basic type with Transform
public func <- <T: TransformType>(inout left: [T.Object]!, right: (Map, T)) {
let (map, transform) = right
if map.mappingType == MappingType.FromJSON {
let values = fromJSONArrayWithTransform(map.currentValue, transform)
FromJSON.optionalBasicType(&left, object: values)
} else {
let values = toJSONArrayWithTransform(left, transform)
ToJSON.optionalBasicType(values, key: map.currentKey!, dictionary: &map.JSONDictionary)
}
}
/// Dictionary of Basic type with Transform
public func <- <T: TransformType>(inout left: [String: T.Object], right: (Map, T)) {
let (map, transform) = right
if map.mappingType == MappingType.FromJSON {
let values = fromJSONDictionaryWithTransform(map.currentValue, transform)
FromJSON.basicType(&left, object: values)
} else {
let values = toJSONDictionaryWithTransform(left, transform)
ToJSON.optionalBasicType(values, key: map.currentKey!, dictionary: &map.JSONDictionary)
}
}
/// Optional dictionary of Basic type with Transform
public func <- <T: TransformType>(inout left: [String: T.Object]?, right: (Map, T)) {
let (map, transform) = right
if map.mappingType == MappingType.FromJSON {
let values = fromJSONDictionaryWithTransform(map.currentValue, transform)
FromJSON.optionalBasicType(&left, object: values)
} else {
let values = toJSONDictionaryWithTransform(left, transform)
ToJSON.optionalBasicType(values, key: map.currentKey!, dictionary: &map.JSONDictionary)
}
}
/// Implicitly unwrapped optional dictionary of Basic type with Transform
public func <- <T: TransformType>(inout left: [String: T.Object]!, right: (Map, T)) {
let (map, transform) = right
if map.mappingType == MappingType.FromJSON {
let values = fromJSONDictionaryWithTransform(map.currentValue, transform)
FromJSON.optionalBasicType(&left, object: values)
} else {
let values = toJSONDictionaryWithTransform(left, transform)
ToJSON.optionalBasicType(values, key: map.currentKey!, dictionary: &map.JSONDictionary)
}
}
private func fromJSONArrayWithTransform<T: TransformType>(input: AnyObject?, transform: T) -> [T.Object] {
if let values = input as? [AnyObject] {
return values.filterMap { value in
return transform.transformFromJSON(value)
}
} else {
return []
}
}
private func fromJSONDictionaryWithTransform<T: TransformType>(input: AnyObject?, transform: T) -> [String: T.Object] {
if let values = input as? [String: AnyObject] {
return values.filterMap { value in
return transform.transformFromJSON(value)
}
} else {
return [:]
}
}
private func toJSONArrayWithTransform<T: TransformType>(input: [T.Object]?, transform: T) -> [T.JSON]? {
return input?.filterMap { value in
return transform.transformToJSON(value)
}
}
private func toJSONDictionaryWithTransform<T: TransformType>(input: [String: T.Object]?, transform: T) -> [String: T.JSON]? {
return input?.filterMap { value in
return transform.transformToJSON(value)
}
}
// MARK:- Mappable Objects - <T: Mappable>
/// Object conforming to Mappable
public func <- <T: Mappable>(inout left: T, right: Map) {
if right.mappingType == MappingType.FromJSON {
FromJSON.object(&left, object: right.currentValue)
} else {
ToJSON.object(left, key: right.currentKey!, dictionary: &right.JSONDictionary)
}
}
/// Optional Mappable objects
public func <- <T: Mappable>(inout left: T?, right: Map) {
if right.mappingType == MappingType.FromJSON {
FromJSON.optionalObject(&left, object: right.currentValue)
} else {
ToJSON.optionalObject(left, key: right.currentKey!, dictionary: &right.JSONDictionary)
}
}
/// Implicitly unwrapped optional Mappable objects
public func <- <T: Mappable>(inout left: T!, right: Map) {
if right.mappingType == MappingType.FromJSON {
FromJSON.optionalObject(&left, object: right.currentValue)
} else {
ToJSON.optionalObject(left, key: right.currentKey!, dictionary: &right.JSONDictionary)
}
}
// MARK:- Dictionary of Mappable objects - Dictionary<String, T: Mappable>
/// Dictionary of Mappable objects <String, T: Mappable>
public func <- <T: Mappable>(inout left: Dictionary<String, T>, right: Map) {
if right.mappingType == MappingType.FromJSON {
FromJSON.objectDictionary(&left, object: right.currentValue)
} else {
ToJSON.objectDictionary(left, key: right.currentKey!, dictionary: &right.JSONDictionary)
}
}
/// Optional Dictionary of Mappable object <String, T: Mappable>
public func <- <T: Mappable>(inout left: Dictionary<String, T>?, right: Map) {
if right.mappingType == MappingType.FromJSON {
FromJSON.optionalObjectDictionary(&left, object: right.currentValue)
} else {
ToJSON.optionalObjectDictionary(left, key: right.currentKey!, dictionary: &right.JSONDictionary)
}
}
/// Implicitly unwrapped Optional Dictionary of Mappable object <String, T: Mappable>
public func <- <T: Mappable>(inout left: Dictionary<String, T>!, right: Map) {
if right.mappingType == MappingType.FromJSON {
FromJSON.optionalObjectDictionary(&left, object: right.currentValue)
} else {
ToJSON.optionalObjectDictionary(left, key: right.currentKey!, dictionary: &right.JSONDictionary)
}
}
/// Dictionary of Mappable objects <String, T: Mappable>
public func <- <T: Mappable>(inout left: Dictionary<String, [T]>, right: Map) {
if right.mappingType == MappingType.FromJSON {
FromJSON.objectDictionaryOfArrays(&left, object: right.currentValue)
} else {
ToJSON.objectDictionaryOfArrays(left, key: right.currentKey!, dictionary: &right.JSONDictionary)
}
}
/// Optional Dictionary of Mappable object <String, T: Mappable>
public func <- <T: Mappable>(inout left: Dictionary<String, [T]>?, right: Map) {
if right.mappingType == MappingType.FromJSON {
FromJSON.optionalObjectDictionaryOfArrays(&left, object: right.currentValue)
} else {
ToJSON.optionalObjectDictionaryOfArrays(left, key: right.currentKey!, dictionary: &right.JSONDictionary)
}
}
/// Implicitly unwrapped Optional Dictionary of Mappable object <String, T: Mappable>
public func <- <T: Mappable>(inout left: Dictionary<String, [T]>!, right: Map) {
if right.mappingType == MappingType.FromJSON {
FromJSON.optionalObjectDictionaryOfArrays(&left, object: right.currentValue)
} else {
ToJSON.optionalObjectDictionaryOfArrays(left, key: right.currentKey!, dictionary: &right.JSONDictionary)
}
}
// MARK:- Array of Mappable objects - Array<T: Mappable>
/// Array of Mappable objects
public func <- <T: Mappable>(inout left: Array<T>, right: Map) {
if right.mappingType == MappingType.FromJSON {
FromJSON.objectArray(&left, object: right.currentValue)
} else {
ToJSON.objectArray(left, key: right.currentKey!, dictionary: &right.JSONDictionary)
}
}
/// Optional array of Mappable objects
public func <- <T: Mappable>(inout left: Array<T>?, right: Map) {
if right.mappingType == MappingType.FromJSON {
FromJSON.optionalObjectArray(&left, object: right.currentValue)
} else {
ToJSON.optionalObjectArray(left, key: right.currentKey!, dictionary: &right.JSONDictionary)
}
}
/// Implicitly unwrapped Optional array of Mappable objects
public func <- <T: Mappable>(inout left: Array<T>!, right: Map) {
if right.mappingType == MappingType.FromJSON {
FromJSON.optionalObjectArray(&left, object: right.currentValue)
} else {
ToJSON.optionalObjectArray(left, key: right.currentKey!, dictionary: &right.JSONDictionary)
}
}
|
f4300a42a84979cd8a2a687a9f743632
| 36.353448 | 125 | 0.719188 | false | false | false | false |
Ivacker/swift
|
refs/heads/master
|
stdlib/public/core/RangeReplaceableCollectionType.swift
|
apache-2.0
|
10
|
//===--- RangeReplaceableCollectionType.swift -----------------*- swift -*-===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// A Collection protocol with replaceRange
//
//===----------------------------------------------------------------------===//
/// A *collection* that supports replacement of an arbitrary subRange
/// of elements with the elements of another collection.
public protocol RangeReplaceableCollectionType : CollectionType {
//===--- Fundamental Requirements ---------------------------------------===//
/// Create an empty instance.
init()
/// Replace the given `subRange` of elements with `newElements`.
///
/// Invalidates all indices with respect to `self`.
///
/// - Complexity: O(`subRange.count`) if
/// `subRange.endIndex == self.endIndex` and `newElements.isEmpty`,
/// O(`self.count` + `newElements.count`) otherwise.
mutating func replaceRange<
C : CollectionType where C.Generator.Element == Generator.Element
>(
subRange: Range<Index>, with newElements: C
)
/*
We could have these operators with default implementations, but the compiler
crashes:
<rdar://problem/16566712> Dependent type should have been substituted by Sema
or SILGen
func +<
S : SequenceType
where S.Generator.Element == Generator.Element
>(_: Self, _: S) -> Self
func +<
S : SequenceType
where S.Generator.Element == Generator.Element
>(_: S, _: Self) -> Self
func +<
S : CollectionType
where S.Generator.Element == Generator.Element
>(_: Self, _: S) -> Self
func +<
RC : RangeReplaceableCollectionType
where RC.Generator.Element == Generator.Element
>(_: Self, _: S) -> Self
*/
/// A non-binding request to ensure `n` elements of available storage.
///
/// This works as an optimization to avoid multiple reallocations of
/// linear data structures like `Array`. Conforming types may
/// reserve more than `n`, exactly `n`, less than `n` elements of
/// storage, or even ignore the request completely.
mutating func reserveCapacity(n: Index.Distance)
//===--- Derivable Requirements -----------------------------------------===//
/// Creates a collection instance that contains `elements`.
init<
S : SequenceType where S.Generator.Element == Generator.Element
>(_ elements: S)
/// Append `x` to `self`.
///
/// Applying `successor()` to the index of the new element yields
/// `self.endIndex`.
///
/// - Complexity: Amortized O(1).
mutating func append(x: Generator.Element)
/*
The 'appendContentsOf' requirement should be an operator, but the compiler crashes:
<rdar://problem/16566712> Dependent type should have been substituted by Sema
or SILGen
func +=<
S : SequenceType
where S.Generator.Element == Generator.Element
>(inout _: Self, _: S)
*/
/// Append the elements of `newElements` to `self`.
///
/// - Complexity: O(*length of result*).
mutating func appendContentsOf<
S : SequenceType
where S.Generator.Element == Generator.Element
>(newElements: S)
/// Insert `newElement` at index `i`.
///
/// Invalidates all indices with respect to `self`.
///
/// - Complexity: O(`self.count`).
mutating func insert(newElement: Generator.Element, atIndex i: Index)
/// Insert `newElements` at index `i`.
///
/// Invalidates all indices with respect to `self`.
///
/// - Complexity: O(`self.count + newElements.count`).
mutating func insertContentsOf<
S : CollectionType where S.Generator.Element == Generator.Element
>(newElements: S, at i: Index)
/// Remove the element at index `i`.
///
/// Invalidates all indices with respect to `self`.
///
/// - Complexity: O(`self.count`).
mutating func removeAtIndex(i: Index) -> Generator.Element
/// Customization point for `removeLast()`. Implement this function if you
/// want to replace the default implementation.
///
/// - Returns: A non-nil value if the operation was performed.
@warn_unused_result
mutating func _customRemoveLast() -> Generator.Element?
/// Customization point for `removeLast(_:)`. Implement this function if you
/// want to replace the default implementation.
///
/// - Returns: True if the operation was performed.
@warn_unused_result
mutating func _customRemoveLast(n: Int) -> Bool
/// Remove the element at `startIndex` and return it.
///
/// - Complexity: O(`self.count`)
/// - Requires: `!self.isEmpty`.
mutating func removeFirst() -> Generator.Element
/// Remove the first `n` elements.
///
/// - Complexity: O(`self.count`)
/// - Requires: `n >= 0 && self.count >= n`.
mutating func removeFirst(n: Int)
/// Remove the indicated `subRange` of elements.
///
/// Invalidates all indices with respect to `self`.
///
/// - Complexity: O(`self.count`).
mutating func removeRange(subRange: Range<Index>)
/// Remove all elements.
///
/// Invalidates all indices with respect to `self`.
///
/// - parameter keepCapacity: If `true`, is a non-binding request to
/// avoid releasing storage, which can be a useful optimization
/// when `self` is going to be grown again.
///
/// - Complexity: O(`self.count`).
mutating func removeAll(keepCapacity keepCapacity: Bool /*= false*/)
}
//===----------------------------------------------------------------------===//
// Default implementations for RangeReplaceableCollectionType
//===----------------------------------------------------------------------===//
extension RangeReplaceableCollectionType {
public init<
S : SequenceType where S.Generator.Element == Generator.Element
>(_ elements: S) {
self.init()
appendContentsOf(elements)
}
public mutating func append(newElement: Generator.Element) {
insert(newElement, atIndex: endIndex)
}
public mutating func appendContentsOf<
S : SequenceType where S.Generator.Element == Generator.Element
>(newElements: S) {
for element in newElements {
append(element)
}
}
public mutating func insert(
newElement: Generator.Element, atIndex i: Index
) {
replaceRange(i..<i, with: CollectionOfOne(newElement))
}
public mutating func insertContentsOf<
C : CollectionType where C.Generator.Element == Generator.Element
>(newElements: C, at i: Index) {
replaceRange(i..<i, with: newElements)
}
public mutating func removeAtIndex(index: Index) -> Generator.Element {
_precondition(!isEmpty, "can't remove from an empty collection")
let result: Generator.Element = self[index]
replaceRange(index...index, with: EmptyCollection())
return result
}
public mutating func removeRange(subRange: Range<Index>) {
replaceRange(subRange, with: EmptyCollection())
}
public mutating func removeFirst(n: Int) {
if n == 0 { return }
_precondition(n >= 0, "number of elements to remove should be non-negative")
_precondition(count >= numericCast(n),
"can't remove more items from a collection than it has")
let end = startIndex.advancedBy(numericCast(n))
removeRange(startIndex..<end)
}
public mutating func removeFirst() -> Generator.Element {
_precondition(!isEmpty,
"can't remove first element from an empty collection")
let firstElement = first!
removeFirst(1)
return firstElement
}
public mutating func removeAll(keepCapacity keepCapacity: Bool = false) {
if !keepCapacity {
self = Self()
}
else {
replaceRange(indices, with: EmptyCollection())
}
}
public mutating func reserveCapacity(n: Index.Distance) {}
}
extension RangeReplaceableCollectionType where SubSequence == Self {
/// Remove the element at `startIndex` and return it.
///
/// - Complexity: O(1)
/// - Requires: `!self.isEmpty`.
public mutating func removeFirst() -> Generator.Element {
_precondition(!isEmpty, "can't remove items from an empty collection")
let element = first!
self = self[startIndex.successor()..<endIndex]
return element
}
/// Remove the first `n` elements.
///
/// - Complexity: O(1)
/// - Requires: `self.count >= n`.
public mutating func removeFirst(n: Int) {
if n == 0 { return }
_precondition(n >= 0, "number of elements to remove should be non-negative")
_precondition(count >= numericCast(n),
"can't remove more items from a collection than it contains")
self = self[startIndex.advancedBy(numericCast(n))..<endIndex]
}
}
extension RangeReplaceableCollectionType {
@warn_unused_result
public mutating func _customRemoveLast() -> Generator.Element? {
return nil
}
@warn_unused_result
public mutating func _customRemoveLast(n: Int) -> Bool {
return false
}
}
extension RangeReplaceableCollectionType
where
Index : BidirectionalIndexType,
SubSequence == Self {
@warn_unused_result
public mutating func _customRemoveLast() -> Generator.Element? {
let element = last!
self = self[startIndex..<endIndex.predecessor()]
return element
}
@warn_unused_result
public mutating func _customRemoveLast(n: Int) -> Bool {
self = self[startIndex..<endIndex.advancedBy(numericCast(-n))]
return true
}
}
extension RangeReplaceableCollectionType where Index : BidirectionalIndexType {
/// Remove an element from the end.
///
/// - Complexity: O(1)
/// - Requires: `!self.isEmpty`
public mutating func removeLast() -> Generator.Element {
_precondition(!isEmpty, "can't remove last element from an empty collection")
if let result = _customRemoveLast() {
return result
}
return removeAtIndex(endIndex.predecessor())
}
/// Remove the last `n` elements.
///
/// - Complexity: O(`self.count`)
/// - Requires: `n >= 0 && self.count >= n`.
public mutating func removeLast(n: Int) {
if n == 0 { return }
_precondition(n >= 0, "number of elements to remove should be non-negative")
_precondition(count >= numericCast(n),
"can't remove more items from a collection than it contains")
if _customRemoveLast(n) {
return
}
let end = endIndex
removeRange(end.advancedBy(numericCast(-n))..<end)
}
}
/// Insert `newElement` into `x` at index `i`.
///
/// Invalidates all indices with respect to `x`.
///
/// - Complexity: O(`x.count`).
@available(*, unavailable, message="call the 'insert()' method on the collection")
public func insert<
C: RangeReplaceableCollectionType
>(inout x: C, _ newElement: C.Generator.Element, atIndex i: C.Index) {
fatalError("unavailable function can't be called")
}
/// Insert `newElements` into `x` at index `i`.
///
/// Invalidates all indices with respect to `x`.
///
/// - Complexity: O(`x.count + newElements.count`).
@available(*, unavailable, message="call the 'insertContentsOf()' method on the collection")
public func splice<
C: RangeReplaceableCollectionType,
S : CollectionType where S.Generator.Element == C.Generator.Element
>(inout x: C, _ newElements: S, atIndex i: C.Index) {
fatalError("unavailable function can't be called")
}
/// Remove from `x` and return the element at index `i`.
///
/// Invalidates all indices with respect to `x`.
///
/// - Complexity: O(`x.count`).
@available(*, unavailable, message="call the 'removeAtIndex()' method on the collection")
public func removeAtIndex<
C: RangeReplaceableCollectionType
>(inout x: C, _ index: C.Index) -> C.Generator.Element {
fatalError("unavailable function can't be called")
}
/// Remove from `x` the indicated `subRange` of elements.
///
/// Invalidates all indices with respect to `x`.
///
/// - Complexity: O(`x.count`).
@available(*, unavailable, message="call the 'removeRange()' method on the collection")
public func removeRange<
C: RangeReplaceableCollectionType
>(inout x: C, _ subRange: Range<C.Index>) {
fatalError("unavailable function can't be called")
}
/// Remove all elements from `x`.
///
/// Invalidates all indices with respect to `x`.
///
/// - parameter keepCapacity: If `true`, is a non-binding request to
/// avoid releasing storage, which can be a useful optimization
/// when `x` is going to be grown again.
///
/// - Complexity: O(`x.count`).
@available(*, unavailable, message="call the 'removeAll()' method on the collection")
public func removeAll<
C: RangeReplaceableCollectionType
>(inout x: C, keepCapacity: Bool = false) {
fatalError("unavailable function can't be called")
}
/// Append elements from `newElements` to `x`.
///
/// - Complexity: O(N).
@available(*, unavailable, message="call the 'appendContentsOf()' method on the collection")
public func extend<
C: RangeReplaceableCollectionType,
S : SequenceType where S.Generator.Element == C.Generator.Element
>(inout x: C, _ newElements: S) {
fatalError("unavailable function can't be called")
}
extension RangeReplaceableCollectionType {
@available(*, unavailable, renamed="appendContentsOf")
public mutating func extend<
S : SequenceType
where S.Generator.Element == Generator.Element
>(newElements: S) {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed="insertContentsOf")
public mutating func splice<
S : CollectionType where S.Generator.Element == Generator.Element
>(newElements: S, atIndex i: Index) {
fatalError("unavailable function can't be called")
}
}
/// Remove an element from the end of `x` in O(1).
///
/// - Requires: `x` is nonempty.
@available(*, unavailable, message="call the 'removeLast()' method on the collection")
public func removeLast<
C: RangeReplaceableCollectionType where C.Index : BidirectionalIndexType
>(inout x: C) -> C.Generator.Element {
fatalError("unavailable function can't be called")
}
@warn_unused_result
public func +<
C : RangeReplaceableCollectionType,
S : SequenceType
where S.Generator.Element == C.Generator.Element
>(lhs: C, rhs: S) -> C {
var lhs = lhs
// FIXME: what if lhs is a reference type? This will mutate it.
lhs.appendContentsOf(rhs)
return lhs
}
@warn_unused_result
public func +<
C : RangeReplaceableCollectionType,
S : SequenceType
where S.Generator.Element == C.Generator.Element
>(lhs: S, rhs: C) -> C {
var result = C()
result.reserveCapacity(rhs.count + numericCast(rhs.underestimateCount()))
result.appendContentsOf(lhs)
result.appendContentsOf(rhs)
return result
}
@warn_unused_result
public func +<
C : RangeReplaceableCollectionType,
S : CollectionType
where S.Generator.Element == C.Generator.Element
>(lhs: C, rhs: S) -> C {
var lhs = lhs
// FIXME: what if lhs is a reference type? This will mutate it.
lhs.reserveCapacity(lhs.count + numericCast(rhs.count))
lhs.appendContentsOf(rhs)
return lhs
}
@warn_unused_result
public func +<
RRC1 : RangeReplaceableCollectionType,
RRC2 : RangeReplaceableCollectionType
where RRC1.Generator.Element == RRC2.Generator.Element
>(lhs: RRC1, rhs: RRC2) -> RRC1 {
var lhs = lhs
// FIXME: what if lhs is a reference type? This will mutate it.
lhs.reserveCapacity(lhs.count + numericCast(rhs.count))
lhs.appendContentsOf(rhs)
return lhs
}
@available(*, unavailable, renamed="RangeReplaceableCollectionType")
public typealias ExtensibleCollectionType = RangeReplaceableCollectionType
|
0e0444268835a36ee8f80ed548d7d3fe
| 30.632323 | 92 | 0.667071 | false | false | false | false |
audrl1010/EasyMakePhotoPicker
|
refs/heads/master
|
Example/EasyMakePhotoPicker/NumberLabel.swift
|
mit
|
1
|
//
// NumberLabel.swift
// KaKaoChatInputView
//
// Created by myung gi son on 2017. 5. 25..
// Copyright © 2017년 grutech. All rights reserved.
//
import UIKit
class NumberLabel: BaseView {
struct Color {
static let labelTextColor = UIColor.black
static let backgroundColor = UIColor(
red: 255/255,
green: 255/255,
blue: 0/255,
alpha: 1.0)
}
struct Font {
static let labelFont = UIFont.systemFont(ofSize: 12)
}
var number: Int = 0 {
didSet {
label.text = "\(number)"
}
}
var font: UIFont = Font.labelFont {
didSet {
label.font = font
}
}
var label = UILabel().then {
$0.font = Font.labelFont
$0.textColor = Color.labelTextColor
}
override func layoutSubviews() {
super.layoutSubviews()
layer.cornerRadius = frame.height / 2
}
override func setupViews() {
super.setupViews()
addSubview(label)
backgroundColor = Color.backgroundColor
}
override func setupConstraints() {
super.setupConstraints()
label
.fs_centerXAnchor(equalTo: centerXAnchor)
.fs_centerYAnchor(equalTo: centerYAnchor)
.fs_endSetup()
}
}
|
ead2eb5762271caca0f06fd5be6d1cf1
| 16.028571 | 56 | 0.619966 | false | false | false | false |
hfutrell/BezierKit
|
refs/heads/master
|
BezierKit/Library/RootFinding.swift
|
mit
|
1
|
//
// RootFinding.swift
// GraphicsPathNearest
//
// Created by Holmes Futrell on 2/23/21.
//
#if canImport(CoreGraphics)
import CoreGraphics
#endif
import Foundation
struct RootFindingConfiguration {
static let defaultErrorThreshold: CGFloat = 1e-5
static let minimumErrorThreshold: CGFloat = 1e-12
private(set) var errorThreshold: CGFloat
init(errorThreshold: CGFloat) {
precondition(errorThreshold >= RootFindingConfiguration.minimumErrorThreshold)
self.errorThreshold = errorThreshold
}
static var `default`: RootFindingConfiguration {
return Self(errorThreshold: RootFindingConfiguration.defaultErrorThreshold)
}
}
extension BernsteinPolynomialN {
/// Returns the unique, ordered real roots of the curve that fall within the unit interval `0 <= t <= 1`
/// the roots are unique and ordered so that for `i < j` they satisfy `root[i] < root[j]`
/// - Returns: the array of roots
func distinctRealRootsInUnitInterval(configuration: RootFindingConfiguration = .default) -> [CGFloat] {
guard coefficients.contains(where: { $0 != .zero }) else { return [] }
let result = BernsteinPolynomialN.rootsOfCurveMappedToRange(self, start: 0, end: 1, configuration: configuration)
guard result.isEmpty == false else { return [] }
assert(result == result.sorted())
// eliminate non-unique roots by comparing against neighbors
return result.indices.compactMap { i in
guard i == 0 || result[i] != result[i - 1] else { return nil }
return result[i]
}
}
private static func rootsOfCurveMappedToRange(_ curve: BernsteinPolynomialN, start rangeStart: CGFloat, end rangeEnd: CGFloat, configuration: RootFindingConfiguration) -> [CGFloat] {
let n = curve.order
// find the range where the convex hull of `curve2D` intersects the x-Axis
var lowerBound = CGFloat.infinity
var upperBound = -CGFloat.infinity
for i in 0..<n {
for j in i+1...n {
let p1 = CGPoint(x: CGFloat(i) / CGFloat(n), y: curve.coefficients[i])
let p2 = CGPoint(x: CGFloat(j) / CGFloat(n), y: curve.coefficients[j])
guard p1.y != 0 || p2.y != 0 else {
assert(p2.x >= p1.x)
if p1.x < lowerBound { lowerBound = p1.x }
if p2.x > upperBound { upperBound = p2.x }
continue
}
let tLine = -p1.y / (p2.y - p1.y)
if tLine >= 0, tLine <= 1 {
let t = Utils.linearInterpolate(p1.x, p2.x, tLine)
if t < lowerBound { lowerBound = t }
if t > upperBound { upperBound = t }
}
}
}
// if the range is empty then convex hull doesn't intersect x-Axis, so we're done.
guard lowerBound.isFinite, upperBound.isFinite else { return [] }
// if the range is small enough that it's within the accuracy threshold
// we've narrowed it down to a root and we're done
let nextRangeStart = Utils.linearInterpolate(rangeStart, rangeEnd, lowerBound)
let nextRangeEnd = Utils.linearInterpolate(rangeStart, rangeEnd, upperBound)
guard nextRangeEnd - nextRangeStart > configuration.errorThreshold else {
let nextRangeMid = Utils.linearInterpolate(nextRangeStart, nextRangeEnd, 0.5)
return [nextRangeMid]
}
// if the range where the convex hull intersects the x-Axis is too large
// we aren't converging quickly, perhaps due to multiple roots.
// split the curve in half and handle each half separately.
guard upperBound - lowerBound < 0.8 else {
let rangeMid = Utils.linearInterpolate(rangeStart, rangeEnd, 0.5)
var curveRoots: [CGFloat] = []
let (left, right) = curve.split(at: 0.5)
curveRoots += rootsOfCurveMappedToRange(left, start: rangeStart, end: rangeMid, configuration: configuration)
curveRoots += rootsOfCurveMappedToRange(right, start: rangeMid, end: rangeEnd, configuration: configuration)
return curveRoots
}
// split the curve over the range where the convex hull intersected the
// x-Axis and iterate.
var curveRoots: [CGFloat] = []
let subcurve = curve.split(from: lowerBound, to: upperBound)
func skippedRoot(between first: CGFloat, and second: CGFloat) -> Bool {
// due to floating point roundoff, it is possible (although rare)
// for the algorithm to sneak past a root. To avoid this problem
// we make sure the curve doesn't change sign between the
// boundaries of the current and next range
return first > 0 && second < 0 || first < 0 && second > 0
}
if skippedRoot(between: curve.coefficients.first!, and: subcurve.coefficients.first!) {
curveRoots.append(nextRangeStart)
}
curveRoots += rootsOfCurveMappedToRange(subcurve, start: nextRangeStart, end: nextRangeEnd, configuration: configuration)
if skippedRoot(between: subcurve.coefficients.last!, and: curve.coefficients.last!) {
curveRoots.append(nextRangeEnd)
}
return curveRoots
}
}
|
61ae8fd443eea6f1cffdf0b60d89471f
| 49.885714 | 186 | 0.632603 | false | true | false | false |
iWeslie/Ant
|
refs/heads/master
|
Ant/Ant/Tools/MyTimePickerVC.swift
|
apache-2.0
|
2
|
//
// MyTimePickerVC.swift
// Ant
//
// Created by LiuXinQiang on 2017/7/12.
// Copyright © 2017年 LiuXinQiang. All rights reserved.
//
import UIKit
typealias TimeClouseType = (String?) -> ()
typealias CloseClouseType = () -> ()
class MyTimePickerVC: UIViewController{
//定义时间闭包
var timeClouse : TimeClouseType?
//定义关闭闭包
var closeClouse : CloseClouseType?
//closeBtn
var closeBtn : UIButton?
override func viewDidLoad() {
let closeBtn = UIButton(type: .custom)
closeBtn.frame = CGRect.init(x: 20, y: 0, width: 20, height: 20)
closeBtn.setImage(UIImage.init(named: "icon_nav_quxiao_normal"), for: .normal)
closeBtn.addTarget(self, action:#selector(MyTimePickerVC.closeView), for: .touchUpInside)
self.view.addSubview(closeBtn)
//创建日期选择器
let datePicker = UIDatePicker(frame: CGRect(x:0, y: 30, width:screenWidth, height:220))
//将日期选择器区域设置为中文,则选择器日期显示为中文
datePicker.locale = Locale(identifier: "zh_CN")
datePicker.datePickerMode = .date
//注意:action里面的方法名后面需要加个冒号“:”
datePicker.addTarget(self, action: #selector(dateChanged),for: .valueChanged)
self.view.backgroundColor = UIColor.white
self.view.addSubview(datePicker)
}
//日期选择器响应方法
func dateChanged(datePicker : UIDatePicker){
//更新提醒时间文本框
let formatter = DateFormatter()
//日期样式
formatter.dateFormat = "yyyy年MM月dd日"
if timeClouse != nil {
timeClouse!(formatter.string(from: datePicker.date))
}
}
func closeView() -> () {
if closeClouse != nil {
closeClouse!()
}
}
}
|
c8393485ae7a5b25c00c3f415a6af32b
| 24.705882 | 97 | 0.608124 | false | false | false | false |
CodaFi/swift
|
refs/heads/master
|
test/ModuleInterface/access-filter.swift
|
apache-2.0
|
14
|
// RUN: %target-swift-frontend -typecheck -emit-module-interface-path %t.swiftinterface %s -module-name AccessFilter
// RUN: %FileCheck %s < %t.swiftinterface
// RUN: %FileCheck -check-prefix NEGATIVE %s < %t.swiftinterface
// NEGATIVE-NOT: BAD
// CHECK: public func publicFn(){{$}}
public func publicFn() {}
internal func internalFn_BAD() {}
private func privateFn_BAD() {}
// CHECK: @usableFromInline
// CHECK-NEXT: internal func ufiFn(){{$}}
@usableFromInline internal func ufiFn() {}
// CHECK: public struct PublicStruct {{[{]$}}
public struct PublicStruct {
// CHECK: public func publicMethod(){{$}}
public func publicMethod() {}
internal func internalMethod_BAD() {}
// CHECK: @usableFromInline
// CHECK-NEXT: internal func ufiMethod(){{$}}
@usableFromInline internal func ufiMethod() {}
} // CHECK: {{^[}]$}}
internal struct InternalStruct_BAD {
public func publicMethod_BAD() {}
internal func internalMethod_BAD() {}
@usableFromInline internal func ufiMethod_BAD() {}
}
// CHECK: @usableFromInline
// CHECK-NEXT: internal struct UFIStruct {{[{]$}}
@usableFromInline
internal struct UFIStruct {
// FIXME: Arguably this should be downgraded to "@usableFromInline internal".
// CHECK: public func publicMethod(){{$}}
public func publicMethod() {}
internal func internalMethod_BAD() {}
// CHECK: @usableFromInline
// CHECK-NEXT: internal func ufiMethod(){{$}}
@usableFromInline internal func ufiMethod() {}
} // CHECK: {{^[}]$}}
// CHECK: public protocol PublicProto {{[{]$}}
public protocol PublicProto {
// CHECK-NEXT: associatedtype Assoc = Swift.Int
associatedtype Assoc = Int
// CHECK-NEXT: func requirement()
func requirement()
} // CHECK-NEXT: {{^[}]$}}
// CHECK: extension PublicProto {{[{]$}}
extension PublicProto {
// CHECK: public func publicMethod(){{$}}
public func publicMethod() {}
internal func internalMethod_BAD() {}
// CHECK: @usableFromInline
// CHECK-NEXT: internal func ufiMethod(){{$}}
@usableFromInline internal func ufiMethod() {}
} // CHECK: {{^[}]$}}
// CHECK: {{^}}extension PublicProto {{[{]$}}
public extension PublicProto {
// CHECK: public func publicExtPublicMethod(){{$}}
func publicExtPublicMethod() {}
internal func publicExtInternalMethod_BAD() {}
// CHECK: @usableFromInline
// CHECK-NEXT: internal func publicExtUFIMethod(){{$}}
@usableFromInline internal func publicExtUFIMethod() {}
}
internal protocol InternalProto_BAD {
associatedtype AssocBAD = Int
func requirementBAD()
}
extension InternalProto_BAD {
public func publicMethod_BAD() {}
internal func internalMethod_BAD() {}
@usableFromInline internal func ufiMethod_BAD() {}
}
// CHECK: @usableFromInline
// CHECK-NEXT: internal protocol UFIProto {{[{]$}}
@usableFromInline
internal protocol UFIProto {
// CHECK-NEXT: associatedtype Assoc = Swift.Int
associatedtype Assoc = Int
// CHECK-NEXT: func requirement()
func requirement()
} // CHECK-NEXT: {{^[}]$}}
// CHECK: extension UFIProto {{[{]$}}
extension UFIProto {
// CHECK: public func publicMethod(){{$}}
public func publicMethod() {}
internal func internalMethod_BAD() {}
// CHECK: @usableFromInline
// CHECK-NEXT: internal func ufiMethod(){{$}}
@usableFromInline internal func ufiMethod() {}
} // CHECK: {{^[}]$}}
// CHECK: extension PublicStruct {{[{]$}}
extension PublicStruct {
// CHECK: @_hasInitialValue public static var secretlySettable: Swift.Int {
// CHECK-NEXT: get
// CHECK-NEXT: }
public private(set) static var secretlySettable: Int = 0
} // CHECK: {{^[}]$}}
extension InternalStruct_BAD: PublicProto {
func requirement() {}
internal static var dummy: Int { return 0 }
}
// CHECK: extension UFIStruct : AccessFilter.PublicProto {{[{]$}}
extension UFIStruct: PublicProto {
// CHECK-NEXT: @usableFromInline
// CHECK-NEXT: internal typealias Assoc = Swift.Int
// FIXME: Is it okay for this non-@usableFromInline implementation to satisfy
// the protocol?
func requirement() {}
internal static var dummy: Int { return 0 }
} // CHECK-NEXT: {{^[}]$}}
// CHECK: public enum PublicEnum {{[{]$}}
public enum PublicEnum {
// CHECK-NEXT: case x
case x
// CHECK-NEXT: case y(Swift.Int)
case y(Int)
} // CHECK-NEXT: {{^[}]$}}
enum InternalEnum_BAD {
case xBAD
}
// CHECK: @usableFromInline
// CHECK-NEXT: internal enum UFIEnum {{[{]$}}
@usableFromInline enum UFIEnum {
// CHECK-NEXT: case x
case x
// CHECK-NEXT: case y(Swift.Int)
case y(Int)
} // CHECK-NEXT: {{^[}]$}}
// CHECK: public class PublicClass {{[{]$}}
public class PublicClass {
} // CHECK: {{^[}]$}}
class InternalClass_BAD {
}
// CHECK: @usableFromInline
// CHECK-NEXT: internal class UFIClass {{[{]$}}
@usableFromInline class UFIClass {
} // CHECK: {{^[}]$}}
// CHECK: public struct GenericStruct<T>
public struct GenericStruct<T> {}
// CHECK: extension GenericStruct where T == AccessFilter.PublicStruct {{[{]$}}
extension GenericStruct where T == AccessFilter.PublicStruct {
// CHECK-NEXT: public func constrainedToPublicStruct(){{$}}
public func constrainedToPublicStruct() {}
} // CHECK-NEXT: {{^[}]$}}
// CHECK: extension GenericStruct where T == AccessFilter.UFIStruct {{[{]$}}
extension GenericStruct where T == AccessFilter.UFIStruct {
// CHECK-NEXT: @usableFromInline{{$}}
// CHECK-NEXT: internal func constrainedToUFIStruct(){{$}}
@usableFromInline internal func constrainedToUFIStruct() {}
} // CHECK-NEXT: {{^[}]$}}
extension GenericStruct where T == InternalStruct_BAD {
@usableFromInline internal func constrainedToInternalStruct_BAD() {}
}
// CHECK: extension GenericStruct where T == AccessFilter.PublicStruct {{[{]$}}
extension GenericStruct where PublicStruct == T {
// CHECK-NEXT: public func constrainedToPublicStruct2(){{$}}
public func constrainedToPublicStruct2() {}
} // CHECK-NEXT: {{^[}]$}}
// CHECK: extension GenericStruct where T == AccessFilter.UFIStruct {{[{]$}}
extension GenericStruct where UFIStruct == T {
// CHECK-NEXT: @usableFromInline{{$}}
// CHECK-NEXT: internal func constrainedToUFIStruct2(){{$}}
@usableFromInline internal func constrainedToUFIStruct2() {}
} // CHECK-NEXT: {{^[}]$}}
extension GenericStruct where InternalStruct_BAD == T {
@usableFromInline internal func constrainedToInternalStruct2_BAD() {}
}
// CHECK: extension GenericStruct where T : AccessFilter.PublicProto {{[{]$}}
extension GenericStruct where T: PublicProto {
// CHECK-NEXT: public func constrainedToPublicProto(){{$}}
public func constrainedToPublicProto() {}
} // CHECK-NEXT: {{^[}]$}}
// CHECK: extension GenericStruct where T : AccessFilter.UFIProto {{[{]$}}
extension GenericStruct where T: UFIProto {
// CHECK-NEXT: @usableFromInline{{$}}
// CHECK-NEXT: internal func constrainedToUFIProto(){{$}}
@usableFromInline internal func constrainedToUFIProto() {}
} // CHECK-NEXT: {{^[}]$}}
extension GenericStruct where T: InternalProto_BAD {
@usableFromInline internal func constrainedToInternalProto_BAD() {}
}
// CHECK: extension GenericStruct where T : AccessFilter.PublicClass {{[{]$}}
extension GenericStruct where T: PublicClass {
// CHECK-NEXT: public func constrainedToPublicClass(){{$}}
public func constrainedToPublicClass() {}
} // CHECK-NEXT: {{^[}]$}}
// CHECK: extension GenericStruct where T : AccessFilter.UFIClass {{[{]$}}
extension GenericStruct where T: UFIClass {
// CHECK-NEXT: @usableFromInline{{$}}
// CHECK-NEXT: internal func constrainedToUFIClass(){{$}}
@usableFromInline internal func constrainedToUFIClass() {}
} // CHECK-NEXT: {{^[}]$}}
extension GenericStruct where T: InternalClass_BAD {
@usableFromInline internal func constrainedToInternalClass_BAD() {}
}
// CHECK: extension GenericStruct where T : AnyObject {{[{]$}}
extension GenericStruct where T: AnyObject {
// CHECK-NEXT: public func constrainedToAnyObject(){{$}}
public func constrainedToAnyObject() {}
} // CHECK-NEXT: {{^[}]$}}
public struct PublicAliasBase {}
internal struct ReallyInternalAliasBase_BAD {}
// CHECK: public typealias PublicAlias = AccessFilter.PublicAliasBase
public typealias PublicAlias = PublicAliasBase
internal typealias InternalAlias_BAD = PublicAliasBase
// CHECK: @usableFromInline
// CHECK-NEXT: internal typealias UFIAlias = AccessFilter.PublicAliasBase
@usableFromInline internal typealias UFIAlias = PublicAliasBase
internal typealias ReallyInternalAlias_BAD = ReallyInternalAliasBase_BAD
// CHECK: extension GenericStruct where T == AccessFilter.PublicAlias {{[{]$}}
extension GenericStruct where T == PublicAlias {
// CHECK-NEXT: public func constrainedToPublicAlias(){{$}}
public func constrainedToPublicAlias() {}
} // CHECK-NEXT: {{^[}]$}}
// CHECK: extension GenericStruct where T == AccessFilter.UFIAlias {{[{]$}}
extension GenericStruct where T == UFIAlias {
// CHECK-NEXT: @usableFromInline{{$}}
// CHECK-NEXT: internal func constrainedToUFIAlias(){{$}}
@usableFromInline internal func constrainedToUFIAlias() {}
} // CHECK-NEXT: {{^[}]$}}
extension GenericStruct where T == InternalAlias_BAD {
// FIXME: We could print this one by desugaring; it is indeed public.
@usableFromInline internal func constrainedToInternalAlias() {}
}
extension GenericStruct where T == ReallyInternalAlias_BAD {
@usableFromInline internal func constrainedToPrivateAlias() {}
}
extension GenericStruct {
// For the next extension's test.
public func requirement() {}
}
extension GenericStruct: PublicProto where T: InternalProto_BAD {
@usableFromInline internal func conformance_BAD() {}
}
public struct MultiGenericStruct<First, Second> {}
// CHECK: extension MultiGenericStruct where First == AccessFilter.PublicStruct, Second == AccessFilter.PublicStruct {{[{]$}}
extension MultiGenericStruct where First == PublicStruct, Second == PublicStruct {
// CHECK-NEXT: public func publicPublic(){{$}}
public func publicPublic() {}
} // CHECK-NEXT: {{^[}]$}}
extension MultiGenericStruct where First == PublicStruct, Second == InternalStruct_BAD {
@usableFromInline internal func publicInternal_BAD() {}
}
extension MultiGenericStruct where First == InternalStruct_BAD, Second == PublicStruct {
@usableFromInline internal func internalPublic_BAD() {}
}
|
6abf8e0e763635030f4f1d8aa5ca255c
| 34.16609 | 125 | 0.707763 | false | false | false | false |
grandiere/box
|
refs/heads/master
|
box/View/Help/VHelp.swift
|
mit
|
1
|
import UIKit
class VHelp:VView, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout
{
private weak var controller:CHelp!
private weak var collectionView:VCollection!
private weak var pageControl:UIPageControl!
private weak var layoutButtonLeft:NSLayoutConstraint!
private let kControlHeight:CGFloat = 50
private let kButtonWidth:CGFloat = 120
private let kButtonHeight:CGFloat = 34
private let kButtonBottom:CGFloat = -20
private let kCornerRadius:CGFloat = 17
override init(controller:CController)
{
super.init(controller:controller)
self.controller = controller as? CHelp
let button:UIButton = UIButton()
button.backgroundColor = UIColor.gridBlue
button.translatesAutoresizingMaskIntoConstraints = false
button.clipsToBounds = true
button.setTitle(
NSLocalizedString("VHelp_button", comment:""),
for:UIControlState.normal)
button.setTitleColor(
UIColor.white,
for:UIControlState.normal)
button.setTitleColor(
UIColor(white:1, alpha:0.2),
for:UIControlState.highlighted)
button.titleLabel!.font = UIFont.bold(size:16)
button.layer.cornerRadius = kCornerRadius
button.addTarget(
self,
action:#selector(actionButton(sender:)),
for:UIControlEvents.touchUpInside)
let collectionView:VCollection = VCollection()
collectionView.alwaysBounceHorizontal = true
collectionView.isPagingEnabled = true
collectionView.registerCell(cell:VHelpCell.self)
collectionView.delegate = self
collectionView.dataSource = self
self.collectionView = collectionView
if let flow:VCollectionFlow = collectionView.collectionViewLayout as? VCollectionFlow
{
flow.scrollDirection = UICollectionViewScrollDirection.horizontal
}
let pageControl:UIPageControl = UIPageControl()
pageControl.isUserInteractionEnabled = false
pageControl.translatesAutoresizingMaskIntoConstraints = false
pageControl.clipsToBounds = true
pageControl.numberOfPages = self.controller.model.items.count
pageControl.currentPage = 0
pageControl.currentPageIndicatorTintColor = UIColor.gridOrange
pageControl.pageIndicatorTintColor = UIColor(white:1, alpha:0.4)
self.pageControl = pageControl
addSubview(collectionView)
addSubview(pageControl)
addSubview(button)
NSLayoutConstraint.equals(
view:collectionView,
toView:self)
NSLayoutConstraint.bottomToBottom(
view:button,
toView:self,
constant:kButtonBottom)
NSLayoutConstraint.height(
view:button,
constant:kButtonHeight)
layoutButtonLeft = NSLayoutConstraint.leftToLeft(
view:button,
toView:self)
NSLayoutConstraint.width(
view:button,
constant:kButtonWidth)
NSLayoutConstraint.bottomToTop(
view:pageControl,
toView:button)
NSLayoutConstraint.height(
view:pageControl,
constant:kControlHeight)
NSLayoutConstraint.equalsHorizontal(
view:pageControl,
toView:self)
}
required init?(coder:NSCoder)
{
return nil
}
override func layoutSubviews()
{
let width:CGFloat = bounds.maxX
let remain:CGFloat = width - kButtonWidth
let margin:CGFloat = remain / 2.0
layoutButtonLeft.constant = margin
collectionView.contentOffset = CGPoint.zero
collectionView.collectionViewLayout.invalidateLayout()
super.layoutSubviews()
}
//MARK: actions
func actionButton(sender button:UIButton)
{
controller.back()
}
//MARK: private
private func modelAtIndex(index:IndexPath) -> MHelpProtocol
{
let item:MHelpProtocol = controller.model.items[index.item]
return item
}
//MARK: collectionView delegate
func scrollViewDidScroll(_ scrollView:UIScrollView)
{
let midX:CGFloat = scrollView.bounds.size.width / 2.0
let midY:CGFloat = scrollView.bounds.midY
let offsetX:CGFloat = scrollView.contentOffset.x
let centerX:CGFloat = midX + offsetX
let pointCenter:CGPoint = CGPoint(
x:centerX,
y:midY)
guard
let indexPath:IndexPath = collectionView.indexPathForItem(
at:pointCenter)
else
{
return
}
let indexItem:Int = indexPath.item
pageControl.currentPage = indexItem
}
func collectionView(_ collectionView:UICollectionView, layout collectionViewLayout:UICollectionViewLayout, sizeForItemAt indexPath:IndexPath) -> CGSize
{
let width:CGFloat = collectionView.bounds.maxX
let height:CGFloat = collectionView.bounds.maxY
let size:CGSize = CGSize(width:width, height:height)
return size
}
func numberOfSections(in collectionView:UICollectionView) -> Int
{
return 1
}
func collectionView(_ collectionView:UICollectionView, numberOfItemsInSection section:Int) -> Int
{
let count:Int = controller.model.items.count
return count
}
func collectionView(_ collectionView:UICollectionView, cellForItemAt indexPath:IndexPath) -> UICollectionViewCell
{
let item:MHelpProtocol = modelAtIndex(index:indexPath)
let cell:VHelpCell = collectionView.dequeueReusableCell(
withReuseIdentifier:
VHelpCell.reusableIdentifier,
for:indexPath) as! VHelpCell
cell.config(model:item)
return cell
}
func collectionView(_ collectionView:UICollectionView, shouldSelectItemAt indexPath:IndexPath) -> Bool
{
return false
}
func collectionView(_ collectionView:UICollectionView, shouldDeselectItemAt indexPath:IndexPath) -> Bool
{
return false
}
}
|
678256e726cfe4482683d84fd9f82ae3
| 31.365482 | 155 | 0.641154 | false | false | false | false |
RedRoster/rr-ios
|
refs/heads/master
|
RedRoster/Model/Subject.swift
|
apache-2.0
|
1
|
//
// Subject.swift
// RedRoster
//
// Created by Daniel Li on 3/24/16.
// Copyright © 2016 dantheli. All rights reserved.
//
import Foundation
import SwiftyJSON
import RealmSwift
/** A Subject represents a group of courses in a field of study. Its abbreviation (AEM, INFO, CS, etc.) is often used course. */
class Subject: Object {
/// Name of the subject, e.g. "Engineering Introduction"
dynamic var name: String = ""
/// Abbreviation of the Subject, e.g. "ENGRI"
dynamic var abbreviation: String = ""
/// Unique serial of the Subject which is abbreviation + slug of the Term it is in
dynamic var id: String = ""
/// The list of Courses in this Subject
let courses = List<Course>()
/// The Term to which this Subject belongs
fileprivate let terms = LinkingObjects(fromType: Term.self, property: "subjects")
var term: Term? {
return terms.first
}
override static func primaryKey() -> String? {
return "id"
}
override static func ignoredProperties() -> [String] {
return ["term"]
}
static func create(_ json: JSON, termSlug: String) -> Subject {
guard let abbreviation = json["value"].string else { fatalError() }
let id = abbreviation + termSlug
let subject: Subject = try! Realm().object(ofType: Subject.self, forPrimaryKey: id) ?? Subject(value: ["id" : id, "abbreviation" : abbreviation])
if let name = json["descrformal"].string { subject.name = name }
return subject
}
}
|
6f3d9c2736238431ff7794078b1c3119
| 30.28 | 153 | 0.631074 | false | false | false | false |
cruisediary/Diving
|
refs/heads/master
|
Diving/Services/Travels/TravelsRealmService.swift
|
mit
|
1
|
//
// TravelRealmStore.swift
// Diving
//
// Created by CruzDiary on 7/5/16.
// Copyright © 2016 DigitalNomad. All rights reserved.
//
import UIKit
import RealmSwift
class TravelsRealmService: TravelsServiceProtocol {
var realm: Realm!
init() {
realm = try! Realm()
}
func createTravel(travelToCreate: Travel,completionHandler: TravelsCreateTravelCompletionHandler) {
let realmTravel = RealmTravel()
realmTravel.id = travelToCreate.id
realmTravel.title = travelToCreate.title
realmTravel.createdAt = travelToCreate.createAt
realmTravel.startDate = travelToCreate.startDate
realmTravel.endDate = travelToCreate.endDate
try! realm.write {
realm.add(realmTravel)
}
}
func fetchTravels(completionHandler: TravelsFetchTravelsCompletionHandler) {
let travels = Array(realm.objects(RealmTravel.self)).map { $0.toStruct() }
return completionHandler(result: TravelsServiceResult<[Travel]>.success(result: travels))
}
func fetchTravel(id: String, completionHandler: TravelsFetchTravelCompletionHandler) {
if let travel = realm.objectForPrimaryKey(RealmTravel.self, key: id) {
return completionHandler(result: TravelsServiceResult<Travel>.success(result:travel.toStruct()))
} else {
return completionHandler(result: TravelsServiceResult<Travel>.failure(error: TravelsServiceError.cannotFetch("Cannot fetch travel")))
}
}
func updateTravel(travelToUpdate: Travel, completionHandler: TravelsUpdateTravelCompletionHandler) {
}
func deleteTravel(id: String, completionHandler: TravelsDeleteTravelCompletionHandler) {
}
}
|
e8c7a5164cd3bce8fee22106e108c53d
| 30.684211 | 145 | 0.677741 | false | false | false | false |
RMizin/PigeonMessenger-project
|
refs/heads/main
|
FalconMessenger/ChatsControllers/NewChatControllers/GroupProfileTableHeaderContainer.swift
|
gpl-3.0
|
1
|
//
// GroupProfileTableHeaderContainer.swift
// Pigeon-project
//
// Created by Roman Mizin on 3/13/18.
// Copyright © 2018 Roman Mizin. All rights reserved.
//
import UIKit
class GroupProfileTableHeaderContainer: UIView {
lazy var profileImageView: FalconProfileImageView = {
let profileImageView = FalconProfileImageView()
profileImageView.translatesAutoresizingMaskIntoConstraints = false
profileImageView.contentMode = .scaleAspectFill
profileImageView.layer.masksToBounds = true
profileImageView.layer.borderWidth = 1
profileImageView.layer.borderColor = ThemeManager.currentTheme().generalSubtitleColor.cgColor
profileImageView.layer.cornerRadius = 48
profileImageView.isUserInteractionEnabled = true
return profileImageView
}()
let addPhotoLabelAdminText = "Add\nphoto"
let addPhotoLabelRegularText = "No photo\nprovided"
let addPhotoLabel: UILabel = {
let addPhotoLabel = UILabel()
addPhotoLabel.translatesAutoresizingMaskIntoConstraints = false
addPhotoLabel.numberOfLines = 2
addPhotoLabel.textAlignment = .center
return addPhotoLabel
}()
var name: PasteRestrictedTextField = {
let name = PasteRestrictedTextField()
name.enablesReturnKeyAutomatically = true
name.font = UIFont.systemFont(ofSize: 20)
name.translatesAutoresizingMaskIntoConstraints = false
name.textAlignment = .center
let attributes = [NSAttributedString.Key.foregroundColor: ThemeManager.currentTheme().generalSubtitleColor]
name.attributedPlaceholder = NSAttributedString(string:"Group name", attributes: attributes)
name.borderStyle = .none
name.autocorrectionType = .no
name.returnKeyType = .done
name.keyboardAppearance = ThemeManager.currentTheme().keyboardAppearance
return name
}()
let userData: UIView = {
let userData = UIView()
userData.translatesAutoresizingMaskIntoConstraints = false
userData.layer.cornerRadius = 30
userData.layer.borderWidth = 1
userData.layer.borderColor = ThemeManager.currentTheme().generalSubtitleColor.cgColor
return userData
}()
override init(frame: CGRect) {
super.init(frame: frame)
addSubview(addPhotoLabel)
addSubview(profileImageView)
addSubview(userData)
userData.addSubview(name)
backgroundColor = ThemeManager.currentTheme().generalBackgroundColor
addPhotoLabel.text = addPhotoLabelAdminText
addPhotoLabel.textColor = ThemeManager.currentTheme().tintColor
NotificationCenter.default.addObserver(self, selector: #selector(profilePictureDidSet), name: .profilePictureDidSet, object: nil)
NSLayoutConstraint.activate([
profileImageView.topAnchor.constraint(equalTo: topAnchor, constant: 30),
profileImageView.widthAnchor.constraint(equalToConstant: 100),
profileImageView.heightAnchor.constraint(equalToConstant: 100),
addPhotoLabel.centerXAnchor.constraint(equalTo: profileImageView.centerXAnchor),
addPhotoLabel.centerYAnchor.constraint(equalTo: profileImageView.centerYAnchor),
addPhotoLabel.widthAnchor.constraint(equalToConstant: 100),
addPhotoLabel.heightAnchor.constraint(equalToConstant: 100),
userData.topAnchor.constraint(equalTo: profileImageView.topAnchor, constant: 0),
userData.leftAnchor.constraint(equalTo: profileImageView.rightAnchor, constant: 10),
userData.bottomAnchor.constraint(equalTo: profileImageView.bottomAnchor, constant: 0),
name.centerYAnchor.constraint(equalTo: userData.centerYAnchor, constant: 0),
name.leftAnchor.constraint(equalTo: userData.leftAnchor, constant: 0),
name.rightAnchor.constraint(equalTo: userData.rightAnchor, constant: 0),
name.heightAnchor.constraint(equalToConstant: 50)
])
if #available(iOS 11.0, *) {
NSLayoutConstraint.activate([
profileImageView.leadingAnchor.constraint(equalTo: safeAreaLayoutGuide.leadingAnchor, constant: 10),
userData.trailingAnchor.constraint(equalTo: safeAreaLayoutGuide.trailingAnchor, constant: -10)
])
} else {
NSLayoutConstraint.activate([
profileImageView.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 10),
userData.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -10)
])
}
}
deinit {
NotificationCenter.default.removeObserver(self)
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)!
}
@objc fileprivate func profilePictureDidSet() {
if profileImageView.image == nil {
addPhotoLabel.isHidden = false
} else {
addPhotoLabel.isHidden = true
}
}
}
|
c791d00e98f10e36dc978c850dca237c
| 35.296875 | 131 | 0.752475 | false | false | false | false |
guillermo-ag-95/App-Development-with-Swift-for-Students
|
refs/heads/master
|
4 - Tables and Persistence/3 - Model View Controller/lab/FavoriteAthlete/FavoriteAthlete/AthleteTableViewController.swift
|
mit
|
1
|
import UIKit
class AthleteTableViewController: UITableViewController {
struct PropertyKeys {
static let athleteCell = "AthleteCell"
static let editAthleteSegue = "EditAthlete"
}
var athletes: [Athlete] = []
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
tableView.reloadData()
}
// MARK: - Table view data source
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return athletes.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: PropertyKeys.athleteCell, for: indexPath)
let athlete = athletes[indexPath.row]
cell.textLabel?.text = athlete.name
cell.detailTextLabel?.text = athlete.description
return cell
}
/*
// MARK: - Navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
}
*/
}
|
2f0efb352522dcd2ae1e8c96cba643eb
| 24 | 109 | 0.648182 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.