repo_name
stringlengths
6
91
path
stringlengths
8
968
copies
stringclasses
210 values
size
stringlengths
2
7
content
stringlengths
61
1.01M
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6
99.8
line_max
int64
12
1k
alpha_frac
float64
0.3
0.91
ratio
float64
2
9.89
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
CoderLiLe/Swift
属性/main.swift
1
7004
// // main.swift // 属性 // // Created by LiLe on 15/4/4. // Copyright (c) 2015年 LiLe. All rights reserved. // import Foundation /* 存储属性 其实Swift中的存储属性就是以前学习OC中的普通属性, 在结构体或者类中定义的属性, 默认就是存储属性 */ struct Person { var name: String var age: Int } var p:Person = Person(name: "lnj", age: 30) p.name = "hm" p.age = 50 /* 常量存储属性 常量存储属性只能在定义时或构造时修改, 构造好一个对象之后不能对常量存储属性进行修改 */ struct Person2 { var name: String var age: Int let card: String // 身份证 } var p2: Person2 = Person2(name: "lnj", age: 30, card: "123456") p2.name = "hm" p2.age = 50 // 构造好对象之后不能修改常量存储属性 //p2.card = "56789" /* 结构体和类常量与存储属性的关系 结构体和枚举是值类型 类是引用类型 */ struct Person3 { var name: String var age: Int } let p3: Person3 = Person3(name: "lnj", age: 30) // 因为结构体是值类型, 所以不能修改结构体常量中的属性 // 不能修改结构体/枚举常量对象中的值, 因为他指向的对象是一个常量 //p3.name = "hm" // 不能修改结构体常量对象的值 //p3 = Person(name: "hm", age: 50) class Person4 { var name: String = "lnj" var age: Int = 30 } let p4:Person4 = Person4() // 可以修改类常量中的值, 因为他指向的对象不是一个常量 p4.name = "hm" // 不可以修改类常量的指向 //p4 = Person4() /* 延迟存储属性 Swift语言中所有的存储属性必须有初始值, 也就是当构造完一个对象后, 对象中所有的存储属性必须有初始值, 但是也有例外, 其中延迟存储属性可以将属性的初始化推迟到该属性第一次被调用的时候 懒加载应用场景: 1.有可能不会用到 2.依赖于其它值 */ class Line { var start:Double = 0.0 var end: Double = 0.0 // 如果不是lazy属性, 定义的时候对象还没有初始化, 所以不能访问self // 如果加上lazy, 代表使用时才会加载, 也就是使用到length属性时才会调用self, // 而访问一个类的属性必须通过对象方法, 所以访问时对象已经初始化完成了, 可以使用self lazy var length: Double = self.getLenght() // 通过闭包懒加载 lazy var container: Array<AnyObject> = { print("懒加载") // return self.end - self.start var arrM = [] return arrM as [AnyObject] }() func getLenght() ->Double { print("懒加载") return end - start } } var line = Line() line.end = 150.0 //print(line.getLenght()) print("创建对象完毕") print(line.length) var arrM = line.container arrM.append("1") arrM.append(5) print(arrM) /* 计算属性 1.Swift中的计算属性不直接存储值, 跟存储属性不同, 没有任何的"后端存储与之对应" 2.计算属性用于计算, 可以实现setter和getter这两种计算方法 3.枚举不可以有存储属性, 但是允许有计算属性 setter 对象.属性 = 值 getter var value = 对象.属性 */ struct Rect { var origion: (x: Double, y: Double) = (0, 0) var size: (w: Double, h: Double) = (0, 0) // 由于center的值是通过起点和宽高计算出来的, 所以没有必要提供一个存储属性 // var center: (x: Double, y: Double) = (0, 0) var center: (x: Double, y: Double) { get{ // print("get") return (origion.x + size.w/2, origion.y + size.h/2) } // set(newCenter){ set{ // print("set \(newCenter)") // 注意: 计算属性不具备存储功能, 所以不能给计算属性赋值, 如果赋值会发生运行时错误 // 注意: setter可以自己传递一个参数, 也可以使用系统默认的参数newValue // 如果要使用系统自带的参数, 必须删除自定义参数 // origion.x = newCenter.x - size.w / 2 // origion.y = newCenter.y - size.h / 2 origion.x = newValue.x - size.w / 2 origion.y = newValue.y - size.h / 2 } } } var r = Rect() r.origion = (0, 0) r.size = (100, 100) //r.center = ((r.origion.x + r.size.w) / 2, (r.origion.y + r.size.h) / 2) print("center.x = \(r.center.x) center.y = \(r.center.y)") r.center = (100, 100) print("origion.x = \(r.origion.x) origion.y = \(r.origion.y)") print("center.x = \(r.center.x) center.y = \(r.center.y)") /* 只读计算属性 对应OC中的readonly属性, 所谓的只读属性就是只提供了getter方法, 没有提供setter方法 */ class Line2 { var start:Double = 0.0 var end: Double = 0.0 // 只读属性, 只读属性必须是变量var, 不能是常量let // 例如想获取长度, 只能通过计算获得, 而不需要外界设置, 可以设置为只读计算属性 var length: Double{ // 只读属性的简写, 可以省略get{} // get{ return end - start // } } } var line2 = Line2() line2.end = 100 print(line2.length) /* 属性观察器,类似OC中的KVO, 可以用于监听属性什么时候被修改, 只有属性被修改才会调用 有两种属性观察器: 1.willSet, 在设置新值之前调用 2.didSet, 在设置新值之后调用 可以直接为除计算属性和lazy属性之外的存储属性添加属性观察器, 但是可以在继承类中为父类的计算属性提供属性观察器 因为在计算属性中也可以监听到属性的改变, 所以给计算属性添加属性观察器没有任何意义 */ class Line3 { var start:Double = 0.0{ willSet{ print("willSet newValue = \(newValue)") } didSet{ print("didSet oldValue = \(oldValue)") } } var end: Double = 0.0 } var l = Line3() l.start = 10.0 /* 类属性 在结构体和枚举中用static 在类中使用class, 并且类中不允许将存储属性设置为类属性 */ struct Person5 { // 普通的属性是每个对象一份 var name: String = "lnj" // 类属性是素有对象共用一份 static var gender:String = "man" static var age:Int{ return 30 } func show() { print("gender = \(Person5.gender) name = \(name)") } } var p5 = Person5() //print("gender = \(p.gender)") print("gender = \(Person5.gender)") var p6 = Person5() // 类属性是所有对象共用一份 print("gender = \(Person5.gender)") p5.show() // 可以将计算属性设置为类属性 print("age = \(Person5.age)") class Person6 { // 普通的属性是每个对象一份 var name: String = "lnj" // 类中不允许将存储属性定义为类属性 // class var gender:String = "man" // 类中只能将计算属性定义为类属性 class var age:Int{ return 30 } func show() { print("age = \(Person6.age)") } } var p7 = Person6() print("age = \(Person6.age)") p7.show()
mit
8093e820ca7b32c9019c57c901460ab4
19.097561
95
0.608617
2.557682
false
false
false
false
pubnub/SwiftConsole
PubNubSwiftConsole/Classes/UI/NavigationController.swift
1
4529
// // NavigationController.swift // Pods // // Created by Jordan Zucker on 7/25/16. // // import UIKit import PubNub @objc(PNCNavigationController) public class NavigationController: UINavigationController, UINavigationControllerDelegate { // MARK: - Constructors public required init?(coder aDecoder: NSCoder) { fatalError() } public override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) } public required init(pubNubViewController: ViewController, showsToolbar: Bool = false) { super.init(rootViewController: pubNubViewController) self.delegate = self self.toolbarHidden = (!showsToolbar) } public enum PubNubRootViewControllerType { case ClientCreation case Console(client: PubNub) case Publish(client: PubNub) func create() -> ViewController { switch self { case .ClientCreation: return ClientCreationViewController() case .Console(let client): return ConsoleViewController(client: client) case .Publish(let client): return PublishViewController(client: client) } } } public convenience init(rootViewControllerType: PubNubRootViewControllerType) { self.init(pubNubViewController: rootViewControllerType.create()) } public static func clientCreationNavigationController() -> NavigationController { return NavigationController(rootViewControllerType: .ClientCreation) } public static func consoleNavigationController(client: PubNub) -> NavigationController { return NavigationController(rootViewControllerType: .Console(client: client)) } public static func publishNavigationController(client: PubNub) -> NavigationController { return NavigationController(rootViewControllerType: .Publish(client: client)) } // MARK: - Toolbar Items public func publishBarButtonItem() -> UIBarButtonItem { return UIBarButtonItem(title: "Publish", style: .Plain, target: self, action: #selector(self.publishBarButtonItemTapped(_:))) } // MARK: - Actions public func close(sender: UIBarButtonItem!) { self.dismissViewControllerAnimated(true, completion: nil) } public func publishBarButtonItemTapped(sender: UIBarButtonItem!) { guard let currentClient = self.client else { return } pushPublishViewController(currentClient) } public func pushPublishViewController(client: PubNub) { let publishViewController = PublishViewController(client: client) if let viewController = topViewController as? PublishViewControllerDelegate { publishViewController.publishDelegate = viewController } self.pushViewController(publishViewController, animated: true) } // MARK: - Properties public var client: PubNub? { guard let topViewController = topViewController as? ViewController else { return nil } return topViewController.client } // can use this for the publish? public var firstClient: PubNub? { for viewController in viewControllers.reverse() { guard let pubNubViewController = viewController as? ViewController, let client = pubNubViewController.client else { continue } return client } return nil } // MARK: - UINavigationControllerDelegate public func navigationController(navigationController: UINavigationController, willShowViewController viewController: UIViewController, animated: Bool) { guard let pubNubViewController = viewController as? ViewController else { return } // hide toolbar if !pubNubViewController.showsToolbar { navigationController.setToolbarHidden(true, animated: true) } } public func navigationController(navigationController: UINavigationController, didShowViewController viewController: UIViewController, animated: Bool) { guard let pubNubViewController = viewController as? ViewController else { return } // show toolbar if pubNubViewController.showsToolbar { navigationController.setToolbarHidden(false, animated: true) } } }
mit
f5ead84ee1fedf9e92a7a7ac1c93f8fd
34.108527
157
0.671451
5.959211
false
false
false
false
einsteinx2/iSub
Classes/Data Model/MediaFolderRepository.swift
1
3991
// // MediaFolderRepository.swift // iSub // // Created by Benjamin Baron on 1/15/17. // Copyright © 2017 Ben Baron. All rights reserved. // import Foundation struct MediaFolderRepository: ItemRepository { static let si = MediaFolderRepository() fileprivate let gr = GenericItemRepository.si let table = "mediaFolders" let cachedTable = "cachedMediaFolders" let itemIdField = "mediaFolderId" func mediaFolder(mediaFolderId: Int64, serverId: Int64, loadSubItems: Bool = false) -> MediaFolder? { return gr.item(repository: self, itemId: mediaFolderId, serverId: serverId, loadSubItems: loadSubItems) } func allMediaFolders(serverId: Int64?, isCachedTable: Bool = false) -> [MediaFolder] { return gr.allItems(repository: self, serverId: serverId, isCachedTable: isCachedTable) } @discardableResult func deleteAllMediaFolders(serverId: Int64?) -> Bool { return gr.deleteAllItems(repository: self, serverId: serverId) } func isPersisted(mediaFolder: MediaFolder, isCachedTable: Bool = false) -> Bool { return gr.isPersisted(repository: self, item: mediaFolder, isCachedTable: isCachedTable) } func hasCachedSubItems(mediaFolder: MediaFolder) -> Bool { return gr.hasCachedSubItems(repository: self, item: mediaFolder) } func delete(mediaFolder: MediaFolder, isCachedTable: Bool = false) -> Bool { return gr.delete(repository: self, item: mediaFolder, isCachedTable: isCachedTable) } func replace(mediaFolder: MediaFolder, isCachedTable: Bool = false) -> Bool { var success = true Database.si.write.inDatabase { db in do { let table = tableName(repository: self, isCachedTable: isCachedTable) let query = "REPLACE INTO \(table) VALUES (?, ?, ?)" try db.executeUpdate(query, mediaFolder.mediaFolderId, mediaFolder.serverId, mediaFolder.name) } catch { success = false printError(error) } } return success } func loadSubItems(mediaFolder: MediaFolder) { mediaFolder.folders = FolderRepository.si.rootFolders(mediaFolderId: mediaFolder.mediaFolderId, serverId: mediaFolder.serverId) mediaFolder.songs = SongRepository.si.rootSongs(mediaFolderId: mediaFolder.mediaFolderId, serverId: mediaFolder.serverId) } } extension MediaFolder: PersistedItem { convenience init(result: FMResultSet, repository: ItemRepository = MediaFolderRepository.si) { let mediaFolderId = result.longLongInt(forColumnIndex: 0) let serverId = result.longLongInt(forColumnIndex: 1) let name = result.string(forColumnIndex: 2) ?? "" let repository = repository as! MediaFolderRepository self.init(mediaFolderId: mediaFolderId, serverId: serverId, name: name, repository: repository) } class func item(itemId: Int64, serverId: Int64, repository: ItemRepository = MediaFolderRepository.si) -> Item? { return (repository as? MediaFolderRepository)?.mediaFolder(mediaFolderId: itemId, serverId: serverId) } var isPersisted: Bool { return repository.isPersisted(mediaFolder: self) } var hasCachedSubItems: Bool { return repository.hasCachedSubItems(mediaFolder: self) } @discardableResult func replace() -> Bool { return repository.replace(mediaFolder: self) } @discardableResult func cache() -> Bool { return repository.replace(mediaFolder: self, isCachedTable: true) } @discardableResult func delete() -> Bool { return repository.delete(mediaFolder: self) } @discardableResult func deleteCache() -> Bool { return repository.delete(mediaFolder: self, isCachedTable: true) } func loadSubItems() { repository.loadSubItems(mediaFolder: self) } }
gpl-3.0
9e93f162c9ebb1c731d46dbcb07d25bf
37
135
0.672431
4.677608
false
false
false
false
sachin004/firefox-ios
Client/Frontend/Home/HomePanelViewController.swift
9
11384
/* 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 import Shared import SnapKit import UIKit import Storage // For VisitType. private struct HomePanelViewControllerUX { // Height of the top panel switcher button toolbar. static let ButtonContainerHeight: CGFloat = 40 static let ButtonContainerBorderColor = UIColor.blackColor().colorWithAlphaComponent(0.1) static let BackgroundColor = UIConstants.PanelBackgroundColor static let EditDoneButtonRightPadding: CGFloat = -12 } protocol HomePanelViewControllerDelegate: class { func homePanelViewController(homePanelViewController: HomePanelViewController, didSelectURL url: NSURL, visitType: VisitType) func homePanelViewController(HomePanelViewController: HomePanelViewController, didSelectPanel panel: Int) func homePanelViewControllerDidRequestToSignIn(homePanelViewController: HomePanelViewController) func homePanelViewControllerDidRequestToCreateAccount(homePanelViewController: HomePanelViewController) } @objc protocol HomePanel: class { weak var homePanelDelegate: HomePanelDelegate? { get set } optional func endEditing() } struct HomePanelUX { static let EmptyTabContentOffset = -180 } @objc protocol HomePanelDelegate: class { func homePanelDidRequestToSignIn(homePanel: HomePanel) func homePanelDidRequestToCreateAccount(homePanel: HomePanel) func homePanel(homePanel: HomePanel, didSelectURL url: NSURL, visitType: VisitType) optional func homePanelWillEnterEditingMode(homePanel: HomePanel) } class HomePanelViewController: UIViewController, UITextFieldDelegate, HomePanelDelegate { var profile: Profile! var notificationToken: NSObjectProtocol! var panels: [HomePanelDescriptor]! var url: NSURL? weak var delegate: HomePanelViewControllerDelegate? private var buttonContainerView: UIView! private var buttonContainerBottomBorderView: UIView! private var controllerContainerView: UIView! private var buttons: [UIButton] = [] private var finishEditingButton: UIButton? private var editingPanel: HomePanel? override func viewDidLoad() { view.backgroundColor = HomePanelViewControllerUX.BackgroundColor let blur: UIVisualEffectView? = DeviceInfo.isBlurSupported() ? UIVisualEffectView(effect: UIBlurEffect(style: UIBlurEffectStyle.Light)) : nil if let blur = blur { view.addSubview(blur) } buttonContainerView = UIView() buttonContainerView.backgroundColor = HomePanelViewControllerUX.BackgroundColor buttonContainerView.clipsToBounds = true buttonContainerView.accessibilityNavigationStyle = .Combined buttonContainerView.accessibilityLabel = NSLocalizedString("Panel Chooser", comment: "Accessibility label for the Home panel's top toolbar containing list of the home panels (top sites, bookmarsk, history, remote tabs, reading list).") view.addSubview(buttonContainerView) self.buttonContainerBottomBorderView = UIView() buttonContainerView.addSubview(buttonContainerBottomBorderView) buttonContainerBottomBorderView.backgroundColor = HomePanelViewControllerUX.ButtonContainerBorderColor controllerContainerView = UIView() view.addSubview(controllerContainerView) blur?.snp_makeConstraints { make in make.edges.equalTo(self.view) } buttonContainerView.snp_makeConstraints { make in make.top.left.right.equalTo(self.view) make.height.equalTo(HomePanelViewControllerUX.ButtonContainerHeight) } buttonContainerBottomBorderView.snp_makeConstraints { make in make.top.equalTo(self.buttonContainerView.snp_bottom).offset(-1) make.left.right.bottom.equalTo(self.buttonContainerView) } controllerContainerView.snp_makeConstraints { make in make.top.equalTo(self.buttonContainerView.snp_bottom) make.left.right.bottom.equalTo(self.view) } self.panels = HomePanels().enabledPanels updateButtons() // Gesture recognizer to dismiss the keyboard in the URLBarView when the buttonContainerView is tapped let dismissKeyboardGestureRecognizer = UITapGestureRecognizer(target: self, action: "SELhandleDismissKeyboardGestureRecognizer:") dismissKeyboardGestureRecognizer.cancelsTouchesInView = false buttonContainerView.addGestureRecognizer(dismissKeyboardGestureRecognizer) } func SELhandleDismissKeyboardGestureRecognizer(gestureRecognizer: UITapGestureRecognizer) { view.window?.rootViewController?.view.endEditing(true) } var selectedButtonIndex: Int? = nil { didSet { if oldValue == selectedButtonIndex { // Prevent flicker, allocations, and disk access: avoid duplicate view controllers. return } if let index = oldValue { if index < buttons.count { let currentButton = buttons[index] currentButton.selected = false } } hideCurrentPanel() if let index = selectedButtonIndex { if index < buttons.count { let newButton = buttons[index] newButton.selected = true } if index < panels.count { let panel = self.panels[index].makeViewController(profile: profile) let accessibilityLabel = self.panels[index].accessibilityLabel if let panelController = panel as? UINavigationController, let rootPanel = panelController.viewControllers.first { setupHomePanel(rootPanel, accessibilityLabel: accessibilityLabel) self.showPanel(panelController) } else { setupHomePanel(panel, accessibilityLabel: accessibilityLabel) self.showPanel(panel) } } } } } func setupHomePanel(panel: UIViewController, accessibilityLabel: String) { (panel as? HomePanel)?.homePanelDelegate = self panel.view.accessibilityNavigationStyle = .Combined panel.view.accessibilityLabel = accessibilityLabel } override func preferredStatusBarStyle() -> UIStatusBarStyle { return UIStatusBarStyle.LightContent } private func hideCurrentPanel() { if let panel = childViewControllers.first { panel.willMoveToParentViewController(nil) panel.view.removeFromSuperview() panel.removeFromParentViewController() } } private func showPanel(panel: UIViewController) { addChildViewController(panel) controllerContainerView.addSubview(panel.view) panel.view.snp_makeConstraints { make in make.top.equalTo(self.buttonContainerView.snp_bottom) make.left.right.bottom.equalTo(self.view) } panel.didMoveToParentViewController(self) } func SELtappedButton(sender: UIButton!) { for (index, button) in buttons.enumerate() { if (button == sender) { selectedButtonIndex = index delegate?.homePanelViewController(self, didSelectPanel: index) break } } } func endEditing(sender: UIButton!) { toggleEditingMode(false) editingPanel?.endEditing?() editingPanel = nil } private func updateButtons() { // Remove any existing buttons if we're rebuilding the toolbar. for button in buttons { button.removeFromSuperview() } buttons.removeAll() var prev: UIView? = nil for panel in panels { let button = UIButton() buttonContainerView.addSubview(button) button.addTarget(self, action: "SELtappedButton:", forControlEvents: UIControlEvents.TouchUpInside) if let image = UIImage(named: "panelIcon\(panel.imageName)") { button.setImage(image, forState: UIControlState.Normal) } if let image = UIImage(named: "panelIcon\(panel.imageName)Selected") { button.setImage(image, forState: UIControlState.Selected) } button.accessibilityLabel = panel.accessibilityLabel buttons.append(button) button.snp_remakeConstraints { make in let left = prev?.snp_right ?? self.view.snp_left make.left.equalTo(left) make.height.centerY.equalTo(self.buttonContainerView) make.width.equalTo(self.buttonContainerView).dividedBy(self.panels.count) } prev = button } } func homePanel(homePanel: HomePanel, didSelectURL url: NSURL, visitType: VisitType) { delegate?.homePanelViewController(self, didSelectURL: url, visitType: visitType) dismissViewControllerAnimated(true, completion: nil) } func homePanelDidRequestToCreateAccount(homePanel: HomePanel) { delegate?.homePanelViewControllerDidRequestToCreateAccount(self) } func homePanelDidRequestToSignIn(homePanel: HomePanel) { delegate?.homePanelViewControllerDidRequestToSignIn(self) } func homePanelWillEnterEditingMode(homePanel: HomePanel) { editingPanel = homePanel toggleEditingMode(true) } func toggleEditingMode(editing: Bool) { let translateDown = CGAffineTransformMakeTranslation(0, UIConstants.ToolbarHeight) let translateUp = CGAffineTransformMakeTranslation(0, -UIConstants.ToolbarHeight) if editing { let button = UIButton(type: UIButtonType.System) button.setTitle(NSLocalizedString("Done", comment: "Done editing button"), forState: UIControlState.Normal) button.addTarget(self, action: "endEditing:", forControlEvents: UIControlEvents.TouchUpInside) button.transform = translateDown button.titleLabel?.textAlignment = .Right self.buttonContainerView.addSubview(button) button.snp_makeConstraints { make in make.right.equalTo(self.buttonContainerView).offset(HomePanelViewControllerUX.EditDoneButtonRightPadding) make.centerY.equalTo(self.buttonContainerView) } self.buttonContainerView.layoutIfNeeded() finishEditingButton = button } UIView.animateWithDuration(0.4, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 0, options: [UIViewAnimationOptions.AllowUserInteraction, UIViewAnimationOptions.CurveEaseInOut], animations: { () -> Void in self.buttons.forEach { $0.transform = editing ? translateUp : CGAffineTransformIdentity } self.finishEditingButton?.transform = editing ? CGAffineTransformIdentity : translateDown }, completion: { _ in if !editing { self.finishEditingButton?.removeFromSuperview() self.finishEditingButton = nil } }) } }
mpl-2.0
d54ab2509c854c788235bd851b436233
40.4
243
0.680692
5.907628
false
false
false
false
bsantanas/Twitternator2
Twitternator2/StreamingTwitterAuth.swift
1
3318
// // StreamingTwitterAuth.swift // Twitternator2 // // Created by Bernardo Santana on 9/9/15. // Copyright (c) 2015 Bernardo Santana. All rights reserved. // import Foundation //MARK: StreamingAPI class StreamingAPI: NSObject { var swifter:Swifter? var authenticationRequired = false func authorizeStreaming() { if authenticationRequired { var oauthToken : String? = NSUserDefaults.standardUserDefaults().valueForKey("oauth_token") as? String var oauthTokenSecret : String? = NSUserDefaults.standardUserDefaults().valueForKey("oauth_secret") as? String if oauthToken != nil && oauthTokenSecret != nil { self.swifter = Swifter(consumerKey: "lTDvE17axNaFEtl5lLzm11Pdj", consumerSecret: "AmRqfhJ7mz0anqIb3NkPuDHogIJcDMWVeH6qA1uagtHYyBTR6V", oauthToken: oauthToken!, oauthTokenSecret: oauthTokenSecret!) self.startStreamingWithFilters(["Saints"]) } else { // Get oauth secret and token swifter = Swifter(consumerKey: "lTDvE17axNaFEtl5lLzm11Pdj", consumerSecret: "AmRqfhJ7mz0anqIb3NkPuDHogIJcDMWVeH6qA1uagtHYyBTR6V") let callbackURL = NSURL(string: "swifter://success")! swifter!.authorizeWithCallbackURL(callbackURL, success: { (accessToken: SwifterCredential.OAuthAccessToken?, response: NSURLResponse) in // println("Access Token key \(accessToken?.key)") println("userId\(accessToken?.userID)") // println("userName\(accessToken?.screenName)") println("Access Token secret\(accessToken?.secret)") //Save the values that you need in NSUserDefaults let defaults = NSUserDefaults.standardUserDefaults() defaults.setObject(accessToken!.key, forKey: "oauth_token") defaults.setObject(accessToken!.secret, forKey: "oauth_secret") defaults.synchronize() self.swifter = Swifter(consumerKey: "lTDvE17axNaFEtl5lLzm11Pdj", consumerSecret: "AmRqfhJ7mz0anqIb3NkPuDHogIJcDMWVeH6qA1uagtHYyBTR6V", oauthToken: accessToken!.key, oauthTokenSecret: accessToken!.secret) self.startStreamingWithFilters(["RCTV"]) }, failure: { (error: NSError) in // Handle error: TODO }) } } } func startStreamingWithFilters(tracks:[String]) { swifter!.postStatusesFilterWithFollow(follow: nil, track: tracks, locations:["50.87, -1.47,50.95, -1.33"], delimited: false, stallWarnings: true, progress: { (status: Dictionary<String, JSONValue>?) in println(status) }, stallWarningHandler: { (code: String?, message: String?, percentFull: Int?) in print(percentFull) }, failure: { error in println(error) }) } }
mit
55fe18883b10e821922d62322cece969
43.24
223
0.56088
4.872247
false
false
false
false
jflinter/SVGPath
SVGPath/SVGPath.swift
1
8678
// // SVGPath.swift // SVGPath // // Created by Tim Wood on 1/21/15. // Copyright (c) 2015 Tim Wood. All rights reserved. // import Foundation import CoreGraphics // MARK: UIBezierPath public extension UIBezierPath { convenience init (svgPath: String) { self.init() applyCommands(svgPath, path: self) } } private func applyCommands (svgPath: String, path: UIBezierPath) { for command in SVGPath(svgPath).commands { switch command.type { case .Move: path.moveToPoint(command.point) case .Line: path.addLineToPoint(command.point) case .QuadCurve: path.addQuadCurveToPoint(command.point, controlPoint: command.control1) case .CubeCurve: path.addCurveToPoint(command.point, controlPoint1: command.control1, controlPoint2: command.control2) case .Close: path.closePath() } } } // MARK: Enums private enum Coordinates { case Absolute case Relative } // MARK: Class public class SVGPath { public var commands: [SVGCommand] = [] private var builder: SVGCommandBuilder = moveTo private var coords: Coordinates = .Absolute private var stride: Int = 2 private var numbers = "" public init (_ string: String) { for char in string.characters { switch char { case "M": use(.Absolute, 2, moveTo) case "m": use(.Relative, 2, moveTo) case "L": use(.Absolute, 2, lineTo) case "l": use(.Relative, 2, lineTo) case "V": use(.Absolute, 1, lineToVertical) case "v": use(.Relative, 1, lineToVertical) case "H": use(.Absolute, 1, lineToHorizontal) case "h": use(.Relative, 1, lineToHorizontal) case "Q": use(.Absolute, 4, quadBroken) case "q": use(.Relative, 4, quadBroken) case "T": use(.Absolute, 2, quadSmooth) case "t": use(.Relative, 2, quadSmooth) case "C": use(.Absolute, 6, cubeBroken) case "c": use(.Relative, 6, cubeBroken) case "S": use(.Absolute, 4, cubeSmooth) case "s": use(.Relative, 4, cubeSmooth) case "Z": use(.Absolute, 1, close) case "z": use(.Absolute, 1, close) default: numbers.append(char) } } finishLastCommand() } private func use (coords: Coordinates, _ stride: Int, _ builder: SVGCommandBuilder) { finishLastCommand() self.builder = builder self.coords = coords self.stride = stride } private func finishLastCommand () { for command in take(SVGPath.parseNumbers(numbers), stride: stride, coords: coords, last: commands.last, callback: builder) { commands.append(coords == .Relative ? command.relativeTo(commands.last) : command) } numbers = "" } } // MARK: Numbers private let numberSet = NSCharacterSet(charactersInString: "-.0123456789eE") private let locale = NSLocale(localeIdentifier: "en_US") public extension SVGPath { class func parseNumbers (numbers: String) -> [CGFloat] { var all:[String] = [] var curr = "" var last = "" for char in numbers.unicodeScalars { let next = String(char) if next == "-" && last != "" && last != "E" && last != "e" { if curr.utf16.count > 0 { all.append(curr) } curr = next } else if numberSet.longCharacterIsMember(char.value) { curr += next } else if curr.utf16.count > 0 { all.append(curr) curr = "" } last = next } all.append(curr) return all.map { CGFloat(NSDecimalNumber(string: $0, locale: locale)) } } } // MARK: Commands public struct SVGCommand { public var point:CGPoint public var control1:CGPoint public var control2:CGPoint public var type:Kind public enum Kind { case Move case Line case CubeCurve case QuadCurve case Close } public init () { let point = CGPoint() self.init(point, point, point, type: .Close) } public init (_ x: CGFloat, _ y: CGFloat, type: Kind) { let point = CGPoint(x: x, y: y) self.init(point, point, point, type: type) } public init (_ cx: CGFloat, _ cy: CGFloat, _ x: CGFloat, _ y: CGFloat) { let control = CGPoint(x: cx, y: cy) self.init(control, control, CGPoint(x: x, y: y), type: .QuadCurve) } public init (_ cx1: CGFloat, _ cy1: CGFloat, _ cx2: CGFloat, _ cy2: CGFloat, _ x: CGFloat, _ y: CGFloat) { self.init(CGPoint(x: cx1, y: cy1), CGPoint(x: cx2, y: cy2), CGPoint(x: x, y: y), type: .CubeCurve) } public init (_ control1: CGPoint, _ control2: CGPoint, _ point: CGPoint, type: Kind) { self.point = point self.control1 = control1 self.control2 = control2 self.type = type } private func relativeTo (other:SVGCommand?) -> SVGCommand { if let otherPoint = other?.point { return SVGCommand(control1 + otherPoint, control2 + otherPoint, point + otherPoint, type: type) } return self } } // MARK: CGPoint helpers private func +(a:CGPoint, b:CGPoint) -> CGPoint { return CGPoint(x: a.x + b.x, y: a.y + b.y) } private func -(a:CGPoint, b:CGPoint) -> CGPoint { return CGPoint(x: a.x - b.x, y: a.y - b.y) } // MARK: Command Builders private typealias SVGCommandBuilder = ([CGFloat], SVGCommand?, Coordinates) -> SVGCommand private func take (numbers: [CGFloat], stride: Int, coords: Coordinates, last: SVGCommand?, callback: SVGCommandBuilder) -> [SVGCommand] { var out: [SVGCommand] = [] var lastCommand:SVGCommand? = last let count = (numbers.count / stride) * stride var nums:[CGFloat] = [0, 0, 0, 0, 0, 0]; for var i = 0; i < count; i += stride { for var j = 0; j < stride; j++ { nums[j] = numbers[i + j] } lastCommand = callback(nums, lastCommand, coords) out.append(lastCommand!) } return out } // MARK: Mm - Move private func moveTo (numbers: [CGFloat], last: SVGCommand?, coords: Coordinates) -> SVGCommand { return SVGCommand(numbers[0], numbers[1], type: .Move) } // MARK: Ll - Line private func lineTo (numbers: [CGFloat], last: SVGCommand?, coords: Coordinates) -> SVGCommand { return SVGCommand(numbers[0], numbers[1], type: .Line) } // MARK: Vv - Vertical Line private func lineToVertical (numbers: [CGFloat], last: SVGCommand?, coords: Coordinates) -> SVGCommand { return SVGCommand(coords == .Absolute ? last?.point.x ?? 0 : 0, numbers[0], type: .Line) } // MARK: Hh - Horizontal Line private func lineToHorizontal (numbers: [CGFloat], last: SVGCommand?, coords: Coordinates) -> SVGCommand { return SVGCommand(numbers[0], coords == .Absolute ? last?.point.y ?? 0 : 0, type: .Line) } // MARK: Qq - Quadratic Curve To private func quadBroken (numbers: [CGFloat], last: SVGCommand?, coords: Coordinates) -> SVGCommand { return SVGCommand(numbers[0], numbers[1], numbers[2], numbers[3]) } // MARK: Tt - Smooth Quadratic Curve To private func quadSmooth (numbers: [CGFloat], last: SVGCommand?, coords: Coordinates) -> SVGCommand { var lastControl = last?.control1 ?? CGPoint() let lastPoint = last?.point ?? CGPoint() if (last?.type ?? .Line) != .QuadCurve { lastControl = lastPoint } var control = lastPoint - lastControl if coords == .Absolute { control = control + lastPoint } return SVGCommand(control.x, control.y, numbers[0], numbers[1]) } // MARK: Cc - Cubic Curve To private func cubeBroken (numbers: [CGFloat], last: SVGCommand?, coords: Coordinates) -> SVGCommand { return SVGCommand(numbers[0], numbers[1], numbers[2], numbers[3], numbers[4], numbers[5]) } // MARK: Ss - Smooth Cubic Curve To private func cubeSmooth (numbers: [CGFloat], last: SVGCommand?, coords: Coordinates) -> SVGCommand { var lastControl = last?.control2 ?? CGPoint() let lastPoint = last?.point ?? CGPoint() if (last?.type ?? .Line) != .CubeCurve { lastControl = lastPoint } var control = lastPoint - lastControl if coords == .Absolute { control = control + lastPoint } return SVGCommand(control.x, control.y, numbers[0], numbers[1], numbers[2], numbers[3]) } // MARK: Zz - Close Path private func close (numbers: [CGFloat], last: SVGCommand?, coords: Coordinates) -> SVGCommand { return SVGCommand() }
mit
c21fadeedc2f81d9ffa31525436f9078
30.32852
138
0.601175
3.884512
false
false
false
false
slicedev/slice-ios
SliceSDK/Framework/Source/Public/SliceClient.swift
1
4143
// // SliceClient.swift // SliceSDK // import Foundation import UIKit import KeychainAccess public struct SliceSettings { internal let clientID: String internal let clientSecret: String public init(clientID: String, clientSecret: String) { self.clientID = clientID self.clientSecret = clientSecret } } public typealias AuthorizationResult = (String?, NSError?) -> () public class SliceClient { private let networkManager = NetworkManager() private let serverEndpoint = ProductionEndpoint() private let keychain: Keychain private let settings: SliceSettings private let URLScheme: String private let redirectURI: String public init(settings: SliceSettings) { self.settings = settings self.URLScheme = "com.slice.developer." + settings.clientID self.redirectURI = self.URLScheme + "://auth" self.keychain = Keychain(service: self.URLScheme) } // MARK: Authorization private var authorizationURL: NSURL { let parameters = [ "client_id" : settings.clientID , "response_type" : "code" , "redirect_uri" : redirectURI ] let baseURL = serverEndpoint.oauthURL.URLByAppendingPathComponent("authorize") let authorizationURL = baseURL.URLByAppendingQueryParameters(parameters, encode: false)! return authorizationURL } private var authorizationResult: AuthorizationResult? public func authorize(application: UIApplication, result: AuthorizationResult?) { let authorizationURL = self.authorizationURL if application.canOpenURL(authorizationURL) { authorizationResult = result application.openURL(authorizationURL) } } public func unauthorize() { currentAccessToken = nil } // MARK: Open URL public func application(application: UIApplication, openURL url: NSURL, sourceApplication: String?, annotation: AnyObject?) -> Bool { var handled = false if let scheme = url.scheme { if scheme == URLScheme { handled = true if let queryParameters = url.queryParameters, let code = queryParameters["code"] { self.authorizeCode(code) } } } return handled } // MARK: Access Token private func authorizeCode(code: String) { let codeURL = serverEndpoint.oauthURL.URLByAppendingPathComponent("token") let parameters = [ "client_id" : settings.clientID , "client_secret": settings.clientSecret , "grant_type" : "authorization_code" , "code" : code , "redirect_uri" : redirectURI ] let codeRequest = NetworkRequest(method: .POST, URL: codeURL, queryParameters: parameters, bodyParameters: nil, accessToken: nil) networkManager.requestJSON(codeRequest) { (response, error) in if let dictionary = response as? JSONDictionary, let accessToken = dictionary["access_token"] as? String { self.currentAccessToken = accessToken self.authorizationResult?(accessToken, nil) self.authorizationResult = nil } } } public private(set) var currentAccessToken: String? { get { return keychain["currentAccessToken"] } set { keychain["currentAccessToken"] = newValue } } // MARK: Resources public func resources(name: String, parameters: [String : AnyObject]?, result: JSONResult?) { if let accessToken = currentAccessToken { let resourcesURL = serverEndpoint.apiURL.URLByAppendingPathComponent(name) let resourceRequest = NetworkRequest(method: .GET, URL: resourcesURL, queryParameters: parameters, bodyParameters: nil, accessToken: accessToken) networkManager.requestJSON(resourceRequest, result: result) } } }
mit
697d31857ae2641bedbf817322626e4c
33.815126
157
0.620323
5.465699
false
false
false
false
ksco/swift-algorithm-club-cn
Tree/Tree.playground/Contents.swift
1
1960
//: Playground - noun: a place where people can play public class TreeNode<T> { public var value: T public var parent: TreeNode? public var children = [TreeNode<T>]() public init(value: T) { self.value = value } public func addChild(node: TreeNode<T>) { children.append(node) node.parent = self } } extension TreeNode: CustomStringConvertible { public var description: String { var s = "\(value)" if !children.isEmpty { s += " {" + children.map { $0.description }.joinWithSeparator(", ") + "}" } return s } } let tree = TreeNode<String>(value: "beverages") let hotNode = TreeNode<String>(value: "hot") let coldNode = TreeNode<String>(value: "cold") let teaNode = TreeNode<String>(value: "tea") let coffeeNode = TreeNode<String>(value: "coffee") let chocolateNode = TreeNode<String>(value: "cocoa") let blackTeaNode = TreeNode<String>(value: "black") let greenTeaNode = TreeNode<String>(value: "green") let chaiTeaNode = TreeNode<String>(value: "chai") let sodaNode = TreeNode<String>(value: "soda") let milkNode = TreeNode<String>(value: "milk") let gingerAleNode = TreeNode<String>(value: "ginger ale") let bitterLemonNode = TreeNode<String>(value: "bitter lemon") tree.addChild(hotNode) tree.addChild(coldNode) hotNode.addChild(teaNode) hotNode.addChild(coffeeNode) hotNode.addChild(chocolateNode) coldNode.addChild(sodaNode) coldNode.addChild(milkNode) teaNode.addChild(blackTeaNode) teaNode.addChild(greenTeaNode) teaNode.addChild(chaiTeaNode) sodaNode.addChild(gingerAleNode) sodaNode.addChild(bitterLemonNode) tree teaNode.parent teaNode.parent!.parent extension TreeNode where T: Equatable { func search(value: T) -> TreeNode? { if value == self.value { return self } for child in children { if let found = child.search(value) { return found } } return nil } } tree.search("cocoa") tree.search("chai") tree.search("bubbly")
mit
eef949ff02c0e0df7b3ff0deec16fcd8
21.022472
79
0.69898
3.350427
false
false
false
false
SwiftFS/Swift-FS-China
Sources/SwiftFSChina/configuration/Routes.swift
1
6352
// // Routes.swift // Perfect-App-Template // // Created by Jonathan Guthrie on 2017-02-20. // Copyright (C) 2017 PerfectlySoft, Inc. // //===----------------------------------------------------------------------===// // // This source file is part of the Perfect.org open source project // // Copyright (c) 2015 - 2016 PerfectlySoft Inc. and the Perfect project authors // Licensed under Apache License v2.0 // // See http://perfect.org/licensing.html for license information // //===----------------------------------------------------------------------===// // import PerfectHTTPServer import PerfectLib import PerfectHTTP import OAuth2 func mainRoutes() -> [[String: Any]] { let dic = ApplicationConfiguration() GitHubConfig.appid = dic.appid GitHubConfig.secret = dic.secret GitHubConfig.endpointAfterAuth = dic.endpointAfterAuth GitHubConfig.redirectAfterAuth = dic.redirectAfterAuth var routes: [[String: Any]] = [[String: Any]]() routes.append(["method":"get", "uri":"/**", "handler":PerfectHTTPServer.HTTPHandler.staticFiles, "documentRoot":"./webroot", "allowRequestFilter":false, "allowResponseFilters":true]) //github routes.append(["method":"get", "uri":"/to/github", "handler":OAuth.sendToProvider]) // routes.append(["method":"get", "uri":"/auth/response/github", "handler":OAuth.authResponse]) //Handler for home page routes.append(["method":"get", "uri":"/", "handler":Handlers.index]) routes.append(["method":"get", "uri":"/index", "handler":Handlers.index]) routes.append(["method":"get", "uri":"/share", "handler":Handlers.share]) routes.append(["method":"get", "uri":"/ask", "handler":Handlers.ask]) routes.append(["method":"get", "uri":"/settings", "handler":Handlers.settings]) routes.append(["method":"get", "uri":"/about", "handler":Handlers.about]) routes.append(["method":"get", "uri":"/login", "handler":Handlers.login]) routes.append(["method":"get", "uri":"/register", "handler":Handlers.register]) routes.append(["method":"get", "uri":"/notification/**", "handler":Notification.index]) //wiki routes.append(["method":"get", "uri":"/wiki/{path}", "handler":Wiki.index]) routes.append(["method":"get", "uri":"/wiki", "handler":Wiki.index]) routes.append(["method":"get", "uri":"/wiki/", "handler":Wiki.index]) //wiki-api routes.append(["method":"post", "uri":"/wiki/new", "handler":Wiki.newWiki]) //user routes.append(["method":"get", "uri":"/user/{username}/index", "handler":User.index]) routes.append(["method":"get", "uri":"/user/{username}/hot_topics", "handler":User.hotTopics]) routes.append(["method":"get", "uri":"/user/{username}/like_topics", "handler":User.likeTopics]) routes.append(["method":"get", "uri":"/user/{username}/topics", "handler":User.topics]) routes.append(["method":"get", "uri":"/user/{username}/comments", "handler":User.comments]) routes.append(["method":"get", "uri":"/user/{username}/collects", "handler":User.collects]) routes.append(["method":"get", "uri":"/user/{username}/follows", "handler":User.follows]) routes.append(["method":"post", "uri":"/user/follow", "handler":User.follow]) routes.append(["method":"post", "uri":"/user/cancel_follow", "handler":User.cancelFollow]) routes.append(["method":"get", "uri":"/user/{username}/fans", "handler":User.fans]) routes.append(["method":"post", "uri":"/user/edit", "handler":User.edit]) routes.append(["method":"post", "uri":"/user/change_pwd", "handler":User.changePwd]) //notification routes.append(["method":"get", "uri":"/notification/all", "handler":Notification.requiredDate]) //topic routes.append(["method":"get", "uri":"topic/{topic_id}/view", "handler":Topic.get]) routes.append(["method":"get", "uri":"topic/new", "handler":Topic.new]) routes.append(["method":"post", "uri":"topic/new", "handler":Topic.newTopic]) routes.append(["method":"post", "uri":"topic/edit", "handler":Topic.edit]) routes.append(["method":"get", "uri":"topic/{topic_id}/query", "handler":Topic.getQuery]) routes.append(["method":"get", "uri":"topic/{topic_id}/edit", "handler":Topic.editTopic]) routes.append(["method":"get", "uri":"topic/{topic_id}/delete", "handler":Topic.deleteTopic]) routes.append(["method":"post", "uri":"topic/collect", "handler":Topic.collect]) routes.append(["method":"post", "uri":"topic/like", "handler":Topic.like]) routes.append(["method":"get", "uri":"topic/cancel_like", "handler":Topic.cancleLike]) routes.append(["method":"post", "uri":"topic/cancel_collect", "handler":Topic.cancelCollect]) //comments routes.append(["method":"get", "uri":"comments/all", "handler":Comments.getComments]) routes.append(["method":"post", "uri":"comment/new", "handler":Comments.newComment]) routes.append(["method":"get", "uri":"comment/{comment_id}/delete", "handler":Comments.delete]) //auth routes.append(["method":"post", "uri":"/auth/sign_up", "handler":Auth.signUp]) routes.append(["method":"post", "uri":"/auth/login", "handler":Auth.login]) routes.append(["method":"get", "uri":"/auth/logout", "handler":Auth.logout]) routes.append(["method":"get", "uri":"/topics/all", "handler":Topics.topics]) //upload routes.append(["method":"post", "uri":"/upload/avatar", "handler":Upload.avatar]) routes.append(["method":"post", "uri":"/upload/file", "handler":Upload.file]) //notification routes.append(["method":"post", "uri":"notification/delete_all", "handler":Notification.deleteAll]) routes.append(["method":"post", "uri":"notification/mark", "handler":Notification.mark]) routes.append(["method":"post", "uri":"notification/{id}/delete", "handler":Notification.delete]) //search routes.append(["method":"get", "uri":"search/*", "handler":Search.query]) //email routes.append(["method":"get", "uri":"verification/{secret}", "handler":EmailAuth.verification]) routes.append(["method":"get", "uri":"email-verification", "handler":EmailAuth.emailVerification]) routes.append(["method":"post", "uri":"send-verification-mail", "handler":EmailAuth.sendVerificationMail]) return routes }
mit
225ab839ee82fb27bdc1c97fc3dad852
47.121212
110
0.627361
3.885015
false
false
false
false
OscarSwanros/swift
stdlib/public/core/StringUnicodeScalarView.swift
2
21945
//===----------------------------------------------------------------------===// // // 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.index(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 { @_inlineable // FIXME(sil-serialize-all) @_versioned // FIXME(sil-serialize-all) internal init(_ _core: _StringCore, coreOffset: Int = 0) { self._core = _core self._coreOffset = coreOffset } @_fixed_layout // FIXME(sil-serialize-all) @_versioned // FIXME(sil-serialize-all) internal struct _ScratchIterator : IteratorProtocol { @_versioned internal var core: _StringCore @_versioned // FIXME(sil-serialize-all) internal var idx: Int @_inlineable // FIXME(sil-serialize-all) @_versioned // FIXME(sil-serialize-all) internal init(_ core: _StringCore, _ pos: Int) { self.idx = pos self.core = core } @_inlineable // FIXME(sil-serialize-all) @_versioned // FIXME(sil-serialize-all) @inline(__always) internal mutating func next() -> UTF16.CodeUnit? { if idx == core.endIndex { return nil } defer { idx += 1 } return self.core[idx] } } public typealias Index = String.Index public typealias IndexDistance = Int /// Translates a `_core` index into a `UnicodeScalarIndex` using this view's /// `_coreOffset`. @_inlineable // FIXME(sil-serialize-all) @_versioned // FIXME(sil-serialize-all) internal func _fromCoreIndex(_ i: Int) -> Index { return Index(encodedOffset: i + _coreOffset) } /// Translates a `UnicodeScalarIndex` into a `_core` index using this view's /// `_coreOffset`. @_inlineable // FIXME(sil-serialize-all) @_versioned // 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`. @_inlineable // FIXME(sil-serialize-all) public var startIndex: Index { return _fromCoreIndex(_core.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`. @_inlineable // FIXME(sil-serialize-all) public var endIndex: Index { return _fromCoreIndex(_core.endIndex) } /// Returns the next consecutive location after `i`. /// /// - Precondition: The next location exists. @_inlineable // FIXME(sil-serialize-all) public func index(after i: Index) -> Index { let i = _toCoreIndex(i) var scratch = _ScratchIterator(_core, i) var decoder = UTF16() let (_, length) = decoder._decodeOne(&scratch) return _fromCoreIndex(i + length) } /// Returns the previous consecutive location before `i`. /// /// - Precondition: The previous location exists. @_inlineable // FIXME(sil-serialize-all) public func index(before i: Index) -> Index { var i = _toCoreIndex(i) - 1 let codeUnit = _core[i] if _slowPath((codeUnit >> 10) == 0b1101_11) { if i != 0 && (_core[i - 1] >> 10) == 0b1101_10 { i -= 1 } } return _fromCoreIndex(i) } /// 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.index(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. @_inlineable // FIXME(sil-serialize-all) public subscript(position: Index) -> Unicode.Scalar { var scratch = _ScratchIterator(_core, _toCoreIndex(position)) var decoder = UTF16() switch decoder.decode(&scratch) { case .scalarValue(let us): return us case .emptyInput: _sanityCheckFailure("cannot subscript using an endIndex") case .error: return Unicode.Scalar(0xfffd)! } } /// An iterator over the Unicode scalars that make up a `UnicodeScalarView` /// collection. @_fixed_layout // FIXME(sil-serialize-all) public struct Iterator : IteratorProtocol { @_inlineable // FIXME(sil-serialize-all) @_versioned // FIXME(sil-serialize-all) internal init(_ _base: _StringCore) { self._iterator = _base.makeIterator() if _base.hasContiguousStorage { self._baseSet = true if _base.isASCII { self._ascii = true self._asciiBase = UnsafeBufferPointer( start: _base._baseAddress?.assumingMemoryBound( to: UTF8.CodeUnit.self), count: _base.count).makeIterator() } else { self._ascii = false self._base = UnsafeBufferPointer<UInt16>( start: _base._baseAddress?.assumingMemoryBound( to: UTF16.CodeUnit.self), count: _base.count).makeIterator() } } else { self._ascii = false self._baseSet = false } } /// 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. @_inlineable // FIXME(sil-serialize-all) public mutating func next() -> Unicode.Scalar? { var result: UnicodeDecodingResult if _baseSet { if _ascii { switch self._asciiBase.next() { case let x?: result = .scalarValue(Unicode.Scalar(x)) case nil: result = .emptyInput } } else { result = _decoder.decode(&(self._base!)) } } else { result = _decoder.decode(&(self._iterator)) } switch result { case .scalarValue(let us): return us case .emptyInput: return nil case .error: return Unicode.Scalar(0xfffd) } } @_versioned // FIXME(sil-serialize-all) internal var _decoder: UTF16 = UTF16() @_versioned // FIXME(sil-serialize-all) internal let _baseSet: Bool @_versioned // FIXME(sil-serialize-all) internal let _ascii: Bool @_versioned // FIXME(sil-serialize-all) internal var _asciiBase: UnsafeBufferPointerIterator<UInt8>! @_versioned // FIXME(sil-serialize-all) internal var _base: UnsafeBufferPointerIterator<UInt16>! @_versioned // FIXME(sil-serialize-all) internal var _iterator: IndexingIterator<_StringCore> } /// Returns an iterator over the Unicode scalars that make up this view. /// /// - Returns: An iterator over this collection's `Unicode.Scalar` elements. @_inlineable // FIXME(sil-serialize-all) public func makeIterator() -> Iterator { return Iterator(_core) } @_inlineable // FIXME(sil-serialize-all) public var description: String { return String(_core) } @_inlineable // FIXME(sil-serialize-all) public var debugDescription: String { return "StringUnicodeScalarView(\(self.description.debugDescription))" } @_versioned // FIXME(sil-serialize-all) internal var _core: _StringCore /// The offset of this view's `_core` from an original core. This works /// around the fact that `_StringCore` is always zero-indexed. /// `_coreOffset` should be subtracted from `UnicodeScalarIndex.encodedOffset` /// before that value is used as a `_core` index. @_versioned // FIXME(sil-serialize-all) internal var _coreOffset: Int } /// 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.index(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. @_inlineable // FIXME(sil-serialize-all) public init(_ unicodeScalars: UnicodeScalarView) { self.init(unicodeScalars._core) } /// The index type for a string's `unicodeScalars` view. public typealias UnicodeScalarIndex = UnicodeScalarView.Index } extension String.UnicodeScalarView : _SwiftStringView { @_inlineable // FIXME(sil-serialize-all) @_versioned // FIXME(sil-serialize-all) internal var _persistentContent : String { return String(_core) } } extension String { /// The string's value represented as a collection of Unicode scalar values. @_inlineable // FIXME(sil-serialize-all) public var unicodeScalars: UnicodeScalarView { get { return UnicodeScalarView(_core) } set { _core = newValue._core } } } extension String.UnicodeScalarView : RangeReplaceableCollection { /// Creates an empty view instance. @_inlineable // FIXME(sil-serialize-all) public init() { self = String.UnicodeScalarView(_StringCore()) } /// 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. @_inlineable // FIXME(sil-serialize-all) public mutating func reserveCapacity(_ n: Int) { _core.reserveCapacity(n) } /// Appends the given Unicode scalar to the view. /// /// - Parameter c: The character to append to the string. @_inlineable // FIXME(sil-serialize-all) public mutating func append(_ x: Unicode.Scalar) { _core.append(x) } /// 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. @_inlineable // FIXME(sil-serialize-all) public mutating func append<S : Sequence>(contentsOf newElements: S) where S.Element == Unicode.Scalar { _core.append(contentsOf: newElements.lazy.flatMap { $0.utf16 }) } /// 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`. @_inlineable // FIXME(sil-serialize-all) 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 } _core.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.index(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. @_inlineable // 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.index(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`. @_inlineable // FIXME(sil-serialize-all) public func samePosition(in characters: String) -> String.Index? { return String.Index(self, within: characters) } } extension String.UnicodeScalarView { @_inlineable // FIXME(sil-serialize-all) @_versioned // FIXME(sil-serialize-all) internal func _isOnUnicodeScalarBoundary(_ i: Index) -> Bool { if _fastPath(_core.isASCII) { return true } if i == startIndex || i == endIndex { return true } if i._transcodedOffset != 0 { return false } let i2 = _toCoreIndex(i) if _fastPath(_core[i2] & 0xFC00 != 0xDC00) { return true } return _core[i2 &- 1] & 0xFC00 != 0xD800 } // NOTE: Don't make this function inlineable. Grapheme cluster // segmentation uses a completely different algorithm in Unicode 9.0. @_inlineable // FIXME(sil-serialize-all) @_versioned // 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(_core) 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. @_inlineable // FIXME(sil-serialize-all) public var customMirror: Mirror { return Mirror(self, unlabeledChildren: self) } } extension String.UnicodeScalarView : CustomPlaygroundQuickLookable { @_inlineable // FIXME(sil-serialize-all) public var customPlaygroundQuickLook: PlaygroundQuickLook { return .text(description) } } // backward compatibility for index interchange. extension String.UnicodeScalarView { @_inlineable // 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!) } @_inlineable // 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: IndexDistance) -> Index { return index(i!, offsetBy: n) } @_inlineable // 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?) -> IndexDistance { return distance(from: i!, to: j!) } @_inlineable // 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 @_inlineable // 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.index(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). @_inlineable // FIXME(sil-serialize-all) @available(swift, obsoleted: 4) public subscript(r: Range<Index>) -> String.UnicodeScalarView { let rawSubRange = _toCoreIndex(r.lowerBound)..<_toCoreIndex(r.upperBound) return String.UnicodeScalarView( _core[rawSubRange], coreOffset: r.lowerBound.encodedOffset) } @_inlineable // FIXME(sil-serialize-all) @available(swift, obsoleted: 4) public subscript(bounds: ClosedRange<Index>) -> String.UnicodeScalarView { return self[bounds.relative(to: self)] } }
apache-2.0
fa566f37b32f2e5e08aad56b92ae0505
35.826891
104
0.63253
4.254757
false
false
false
false
corey-lin/swift-tasks
Task2-MapKit/Task2-MapKit/ETAMapViewController.swift
1
4589
// // ETAMapViewController.swift // Task2-MapKit // // Created by coreylin on 4/12/16. // Copyright © 2016 coreylin. All rights reserved. // import UIKit import MapKit class ETAMapViewController: UIViewController { @IBOutlet var mapView: MKMapView! var currentDestinationIndex = 0 let coordinates = [ [37.4848474,-122.1505746], [37.4220005,-122.0845547] ] let names = ["Facebook HQ", "Google HQ"] var images: [UIImage]! var locationManager: CLLocationManager! override func viewDidLoad() { images = [UIImage(named: "FacebookIcon")!, UIImage(named: "GoogleIcon")!] locationManager = CLLocationManager() locationManager.requestWhenInUseAuthorization() mapView.showsUserLocation = true mapView.delegate = self } @IBAction func nextPlace(sender: AnyObject) { if currentDestinationIndex > names.count - 1 { currentDestinationIndex = 0; } let coordinate = coordinates[currentDestinationIndex] let latitude = coordinate[0] let longitude = coordinate[1] let locationCoordinate = CLLocationCoordinate2D(latitude: latitude, longitude: longitude) var annotation = CompanyAnnotation(coordinate: locationCoordinate) annotation.title = names[currentDestinationIndex] annotation.image = images[currentDestinationIndex] let request = MKDirectionsRequest() let sourceItem = MKMapItem(placemark: MKPlacemark(coordinate: mapView.userLocation.coordinate, addressDictionary: nil)) request.source = sourceItem let destinationItem = MKMapItem(placemark: MKPlacemark(coordinate: locationCoordinate, addressDictionary: nil)) request.destination = destinationItem request.requestsAlternateRoutes = false request.transportType = .Transit mapView.setCenterCoordinate(locationCoordinate, animated: true) let directions = MKDirections(request: request) directions.calculateETAWithCompletionHandler() { (response: MKETAResponse?, error: NSError?) in if let error = error { print("Error while requesting ETA:\(error.localizedDescription)") annotation.eta = error.localizedDescription } else { let etaTime = Int((response?.expectedTravelTime)! / 60) annotation.eta = "\(etaTime) min" } var isExist = false for a in self.mapView.annotations { if a.coordinate.latitude == locationCoordinate.latitude && a.coordinate.longitude == locationCoordinate.longitude { isExist = true annotation = a as! CompanyAnnotation } } if !isExist { self.mapView.addAnnotation(annotation) } self.mapView.selectAnnotation(annotation, animated: true) self.currentDestinationIndex++ } } } extension ETAMapViewController: MKMapViewDelegate { func mapView(mapView: MKMapView, didUpdateUserLocation userLocation: MKUserLocation) { let region = MKCoordinateRegion(center: userLocation.coordinate, span: MKCoordinateSpanMake(2, 2)) mapView.setRegion(region, animated: true) } func mapView(mapView: MKMapView, viewForAnnotation annotation: MKAnnotation) -> MKAnnotationView? { guard annotation is CompanyAnnotation else { return nil } var annotationView = mapView.dequeueReusableAnnotationViewWithIdentifier("Pin") if annotationView == nil { annotationView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: "Pin") annotationView?.canShowCallout = true } else { annotationView?.annotation = annotation } let companyAnnotation = annotation as! CompanyAnnotation annotationView?.detailCalloutAccessoryView = UIImageView(image: companyAnnotation.image) let leftAccessory = UILabel(frame: CGRectMake(0, 0, 50, 30)) leftAccessory.text = companyAnnotation.eta leftAccessory.font = UIFont(name: "Verdana", size: 10) annotationView?.leftCalloutAccessoryView = leftAccessory let image = UIImage(named: "Bus") let button = UIButton(type: .Custom) button.frame = CGRectMake(0, 0, 30, 30) button.setImage(image, forState: .Normal) annotationView?.rightCalloutAccessoryView = button return annotationView } func mapView(mapView: MKMapView, annotationView view: MKAnnotationView, calloutAccessoryControlTapped control: UIControl) { let placemark = MKPlacemark(coordinate: view.annotation!.coordinate, addressDictionary: nil) let mapItem = MKMapItem(placemark: placemark) let launchOptions = [MKLaunchOptionsDirectionsModeKey:MKLaunchOptionsDirectionsModeTransit] mapItem.openInMapsWithLaunchOptions(launchOptions) } }
mit
aa02fa2e83bf04e11f995ef59fb146ba
37.554622
125
0.732127
4.949299
false
false
false
false
flowsprenger/RxLifx-Swift
RxLifx/RxLifxTests/RxLifxTests.swift
1
3598
/* Copyright 2017 Florian Sprenger 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 XCTest import RxSwift @testable import RxLifx class RxLifxTests: XCTestCase { var disposables:CompositeDisposable! var broadcastAddr = sockaddr.broadcastTo(port: 56701) override func setUp() { super.setUp() disposables = CompositeDisposable() } override func tearDown() { disposables.dispose() super.tearDown() } func testReceiveMessage(){ let expectation = XCTestExpectation(description: "received broadcasted message") let testData = Data(bytes: [1, 3, 2, 5]) let socket = UdpSocket() let result = socket.connect(port: "56700") switch(result){ case .Success(let handle): let transport = UdpTransport(port: "56701", generator: TestMessageGenerator()) _ = disposables.insert(transport.messages.subscribe{ event in switch(event){ case .next(let data): XCTAssertEqual(data, testData) expectation.fulfill() break default: () } }) DispatchQueue.main.asyncAfter(deadline: .now() + 2) { let result = socket.writeMessage(socketDescriptor: handle, addr: &self.broadcastAddr, data: testData) XCTAssertEqual(result, testData.count) } break case .Failure: XCTAssertTrue(false) } wait(for: [expectation], timeout: 5) } func testSendMessage(){ let expectation = XCTestExpectation(description: "received broadcasted message") let testData = Data(bytes: [1, 3, 2, 5]) let transport = UdpTransport(port: "56701", generator: TestMessageGenerator()) _ = disposables.insert(transport.messages.subscribe{ event in switch(event){ case .next(let data): XCTAssertEqual(data, testData) expectation.fulfill() break default: () } }) DispatchQueue.main.asyncAfter(deadline: .now() + 2) { let result = transport.sendMessage(target: self.broadcastAddr, data: testData) XCTAssertEqual(result, true) } wait(for: [expectation], timeout: 5) } } class TestMessageGenerator : MessageGenerator{ public func generate(from: sockaddr, data:Data) -> Data?{ return data } }
mit
4427c84bc60ac48b49cababec0e006ce
35.353535
121
0.629238
5.011142
false
true
false
false
therealbnut/swift
test/decl/func/dynamic_self.swift
9
8453
// RUN: %target-typecheck-verify-swift // ---------------------------------------------------------------------------- // DynamicSelf is only allowed on the return type of class and // protocol methods. func global() -> Self { } // expected-error{{global function cannot return 'Self'}} func inFunction() { func local() -> Self { } // expected-error{{local function cannot return 'Self'}} } struct S0 { func f() -> Self { } // expected-error{{struct method cannot return 'Self'; did you mean to use the struct type 'S0'?}}{{15-19=S0}} func g(_ ds: Self) { } // expected-error{{'Self' is only available in a protocol or as the result of a method in a class; did you mean 'S0'?}}{{16-20=S0}} } enum E0 { func f() -> Self { } // expected-error{{enum method cannot return 'Self'; did you mean to use the enum type 'E0'?}}{{15-19=E0}} func g(_ ds: Self) { } // expected-error{{'Self' is only available in a protocol or as the result of a method in a class; did you mean 'E0'?}}{{16-20=E0}} } class C0 { func f() -> Self { } // okay func g(_ ds: Self) { } // expected-error{{'Self' is only available in a protocol or as the result of a method in a class; did you mean 'C0'?}}{{16-20=C0}} func h(_ ds: Self) -> Self { } // expected-error{{'Self' is only available in a protocol or as the result of a method in a class; did you mean 'C0'?}}{{16-20=C0}} } protocol P0 { func f() -> Self // okay func g(_ ds: Self) // okay } extension P0 { func h() -> Self { // okay func g(_ t : Self) -> Self { // okay return t } return g(self) } } protocol P1: class { func f() -> Self // okay func g(_ ds: Self) // okay } extension P1 { func h() -> Self { // okay func g(_ t : Self) -> Self { // okay return t } return g(self) } } // ---------------------------------------------------------------------------- // The 'self' type of a Self method is based on Self class C1 { required init(int i: Int) {} // Instance methods have a self of type Self. func f(_ b: Bool) -> Self { // FIXME: below diagnostic should complain about C1 -> Self conversion if b { return C1(int: 5) } // expected-error{{cannot convert return expression of type 'C1' to return type 'Self'}} // One can use `type(of:)` to attempt to construct an object of type Self. if !b { return type(of: self).init(int: 5) } // Can't utter Self within the body of a method. var _: Self = self // expected-error{{'Self' is only available in a protocol or as the result of a method in a class; did you mean 'C1'?}} {{12-16=C1}} // Okay to return 'self', because it has the appropriate type. return self // okay } // Type methods have a self of type Self.Type. class func factory(_ b: Bool) -> Self { // Check directly. var x: Int = self // expected-error{{cannot convert value of type 'Self.Type' to specified type 'Int'}} // Can't utter Self within the body of a method. var c1 = C1(int: 5) as Self // expected-error{{'Self' is only available in a protocol or as the result of a method in a class; did you mean 'C1'?}} {{28-32=C1}} if b { return self.init(int: 5) } return Self() // expected-error{{use of unresolved identifier 'Self'}} expected-note {{did you mean 'self'?}} } } // ---------------------------------------------------------------------------- // Using a method with a Self result carries the receiver type. class X { func instance() -> Self { } class func factory() -> Self { } func produceX() -> X { } } class Y : X { func produceY() -> Y { } } func testInvokeInstanceMethodSelf() { // Trivial case: invoking on the declaring class. var x = X() var x2 = x.instance() x = x2 // at least an X x2 = x // no more than an X // Invoking on a subclass. var y = Y() var y2 = y.instance(); y = y2 // at least a Y y2 = y // no more than a Y } func testInvokeTypeMethodSelf() { // Trivial case: invoking on the declaring class. var x = X() var x2 = X.factory() x = x2 // at least an X x2 = x // no more than an X // Invoking on a subclass. var y = Y() var y2 = Y.factory() y = y2 // at least a Y y2 = y // no more than a Y } func testCurryInstanceMethodSelf() { // Trivial case: currying on the declaring class. var produceX = X.produceX var produceX2 = X.instance produceX = produceX2 produceX2 = produceX // Currying on a subclass. var produceY = Y.produceY var produceY2 = Y.instance produceY = produceY2 produceY2 = produceY } class GX<T> { func instance() -> Self { } class func factory() -> Self { } func produceGX() -> GX { } } class GY<T> : GX<[T]> { func produceGY() -> GY { } } func testInvokeInstanceMethodSelfGeneric() { // Trivial case: invoking on the declaring class. var x = GX<Int>() var x2 = x.instance() x = x2 // at least an GX<Int> x2 = x // no more than an GX<Int> // Invoking on a subclass. var y = GY<Int>() var y2 = y.instance(); y = y2 // at least a GY<Int> y2 = y // no more than a GY<Int> } func testInvokeTypeMethodSelfGeneric() { // Trivial case: invoking on the declaring class. var x = GX<Int>() var x2 = GX<Int>.factory() x = x2 // at least an GX<Int> x2 = x // no more than an GX<Int> // Invoking on a subclass. var y = GY<Int>() var y2 = GY<Int>.factory(); y = y2 // at least a GY<Int> y2 = y // no more than a GY<Int> } func testCurryInstanceMethodSelfGeneric() { // Trivial case: currying on the declaring class. var produceGX = GX<Int>.produceGX var produceGX2 = GX<Int>.instance produceGX = produceGX2 produceGX2 = produceGX // Currying on a subclass. var produceGY = GY<Int>.produceGY var produceGY2 = GY<Int>.instance produceGY = produceGY2 produceGY2 = produceGY } // ---------------------------------------------------------------------------- // Overriding a method with a Self class Z : Y { override func instance() -> Self { } override class func factory() -> Self { } } func testOverriddenMethodSelfGeneric() { var z = Z() var z2 = z.instance(); z = z2 z2 = z var z3 = Z.factory() z = z3 z3 = z } // ---------------------------------------------------------------------------- // Generic uses of Self methods. protocol P { func f() -> Self } func testGenericCall<T: P>(_ t: T) { var t = t var t2 = t.f() t2 = t t = t2 } // ---------------------------------------------------------------------------- // Existential uses of Self methods. func testExistentialCall(_ p: P) { _ = p.f() } // ---------------------------------------------------------------------------- // Dynamic lookup of Self methods. @objc class SomeClass { @objc func method() -> Self { return self } } func testAnyObject(_ ao: AnyObject) { var ao = ao var result : AnyObject = ao.method!() result = ao ao = result } // ---------------------------------------------------------------------------- // Name lookup on Self values extension Y { func testInstance() -> Self { if false { return self.instance() } return instance() } class func testFactory() -> Self { if false { return self.factory() } return factory() } } // ---------------------------------------------------------------------------- // Optional Self returns extension X { func tryToClone() -> Self? { return nil } func cloneOrFail() -> Self { return self } func cloneAsObjectSlice() -> X? { return self } } extension Y { func operationThatOnlyExistsOnY() {} } func testOptionalSelf(_ y : Y) { if let clone = y.tryToClone() { clone.operationThatOnlyExistsOnY() } // Sanity-checking to make sure that the above succeeding // isn't coincidental. if let clone = y.cloneOrFail() { // expected-error {{initializer for conditional binding must have Optional type, not 'Y'}} clone.operationThatOnlyExistsOnY() } // Sanity-checking to make sure that the above succeeding // isn't coincidental. if let clone = y.cloneAsObjectSlice() { clone.operationThatOnlyExistsOnY() // expected-error {{value of type 'X' has no member 'operationThatOnlyExistsOnY'}} } } // ---------------------------------------------------------------------------- // Conformance lookup on Self protocol Runcible { } extension Runcible { func runce() {} } func wantsRuncible<T : Runcible>(_: T) {} class Runce : Runcible { func getRunced() -> Self { runce() wantsRuncible(self) return self } }
apache-2.0
f24f5cf73c059b851f76f81d3c9f4452
25.009231
164
0.570212
3.736958
false
false
false
false
joshdholtz/Few.swift
FewDemo/AppDelegate.swift
5
1884
// // AppDelegate.swift // Few // // Created by Josh Abernathy on 7/22/14. // Copyright (c) 2014 Josh Abernathy. All rights reserved. // import Cocoa import Few enum ActiveComponent { case Demo case Converter case Counter } func renderApp(component: Component<ActiveComponent>, state: ActiveComponent) -> Element { var contentComponent: Element! switch state { case .Demo: contentComponent = Demo() case .Converter: contentComponent = TemperatureConverter() case .Counter: contentComponent = Counter() } return Element() .justification(.Center) .childAlignment(.Center) .direction(.Column) .children([ contentComponent, CustomButton(title: "Show me more!") { component.updateState(toggleDisplay) } .margin(Edges(top: 20)) ]) // return Element() // .direction(.Column) // .justification(.Center) // .children([ // Element().height(90).children([ // View(backgroundColor: .grayColor()).width(32), // View(backgroundColor: .blackColor(), cornerRadius: 20).width(40).height(40).margin(Edges(left: -10)).selfAlignment(.Center), // Element().selfAlignment(.Center).direction(.Column).flex(1).children([ // Label("Lorem Ipsum"), // Label("Dolor"), // ]), // View(backgroundColor: .blackColor()).width(30).height(30).selfAlignment(.Center).margin(Edges(right: 10)) // ]) // ]) } func toggleDisplay(display: ActiveComponent) -> ActiveComponent { switch display { case .Demo: return .Converter case .Converter: return .Counter case .Counter: return .Demo } } class AppDelegate: NSObject, NSApplicationDelegate { @IBOutlet weak var window: NSWindow! private let appComponent = Component(initialState: .Converter, render: renderApp) func applicationDidFinishLaunching(notification: NSNotification) { let contentView = window.contentView as! NSView appComponent.addToView(contentView) } }
mit
1cf909e235eb5a5e77beb9e50a9126dd
23.467532
130
0.703822
3.431694
false
false
false
false
Drakken-Engine/GameEngine
DrakkenEngine/dAnimator.swift
1
1877
// // dAnimator.swift // DrakkenEngine // // Created by Allison Lindner on 01/09/16. // Copyright © 2016 Drakken Studio. All rights reserved. // fileprivate class dAnimationState { internal var currentFrameId: Int = 0 internal var timeStamp: Float = 0.0 } public class dAnimator: dComponent { private var _sprite: dSprite internal var sprite: dSprite { get { return _sprite } } private var _states: [String : dAnimationState] = [:] private var _defaultAnimation: String private var _currentAnimation: String private var _currentIndex: Int = 0 internal var playing: Bool = false internal var frame: Int32 = 0 internal init(sprite: dSprite, defaultAnimation: String) { self._sprite = sprite self._defaultAnimation = defaultAnimation self._currentAnimation = defaultAnimation for animation in self._sprite.animations { self._states[animation.key] = dAnimationState() } let sequence = _sprite.animations[_currentAnimation]!.sequence frame = sequence[_currentIndex].frame super.init() } internal func play() { playing = true } internal func stop() { playing = false } internal func update(deltaTime: Float) { if playing { let state = _states[_currentAnimation] let sequence = _sprite.animations[_currentAnimation]!.sequence state!.timeStamp += deltaTime if state!.timeStamp >= sequence[_currentIndex].time { _currentIndex += 1 if _currentIndex >= sequence.count { _currentIndex = 0 } state!.timeStamp = 0.0 } frame = sequence[_currentIndex].frame _sprite.frame = frame } else { frame = _sprite.frame } } internal func set(animation name: String) { if _sprite.animations[name] != nil { self._currentAnimation = name } else { self._currentAnimation = _defaultAnimation } } }
gpl-3.0
dfcc8cd5b336e7fd638853a39ce5cc90
21.60241
65
0.666311
3.820774
false
false
false
false
JGiola/swift
stdlib/public/core/Range.swift
1
36903
//===--- Range.swift ------------------------------------------*- swift -*-===// // // 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 // //===----------------------------------------------------------------------===// /// A type that can be used to slice a collection. /// /// A type that conforms to `RangeExpression` can convert itself to a /// `Range<Bound>` of indices within a given collection. public protocol RangeExpression<Bound> { /// The type for which the expression describes a range. associatedtype Bound: Comparable /// Returns the range of indices described by this range expression within /// the given collection. /// /// You can use the `relative(to:)` method to convert a range expression, /// which could be missing one or both of its endpoints, into a concrete /// range that is bounded on both sides. The following example uses this /// method to convert a partial range up to `4` into a half-open range, /// using an array instance to add the range's lower bound. /// /// let numbers = [10, 20, 30, 40, 50, 60, 70] /// let upToFour = ..<4 /// /// let r1 = upToFour.relative(to: numbers) /// // r1 == 0..<4 /// /// The `r1` range is bounded on the lower end by `0` because that is the /// starting index of the `numbers` array. When the collection passed to /// `relative(to:)` starts with a different index, that index is used as the /// lower bound instead. The next example creates a slice of `numbers` /// starting at index `2`, and then uses the slice with `relative(to:)` to /// convert `upToFour` to a concrete range. /// /// let numbersSuffix = numbers[2...] /// // numbersSuffix == [30, 40, 50, 60, 70] /// /// let r2 = upToFour.relative(to: numbersSuffix) /// // r2 == 2..<4 /// /// Use this method only if you need the concrete range it produces. To /// access a slice of a collection using a range expression, use the /// collection's generic subscript that uses a range expression as its /// parameter. /// /// let numbersPrefix = numbers[upToFour] /// // numbersPrefix == [10, 20, 30, 40] /// /// - Parameter collection: The collection to evaluate this range expression /// in relation to. /// - Returns: A range suitable for slicing `collection`. The returned range /// is *not* guaranteed to be inside the bounds of `collection`. Callers /// should apply the same preconditions to the return value as they would /// to a range provided directly by the user. func relative<C: Collection>( to collection: C ) -> Range<Bound> where C.Index == Bound /// Returns a Boolean value indicating whether the given element is contained /// within the range expression. /// /// - Parameter element: The element to check for containment. /// - Returns: `true` if `element` is contained in the range expression; /// otherwise, `false`. func contains(_ element: Bound) -> Bool } extension RangeExpression { /// Returns a Boolean value indicating whether a value is included in a /// range. /// /// You can use the pattern-matching operator (`~=`) to test whether a value /// is included in a range. The pattern-matching operator is used /// internally in `case` statements for pattern matching. The following /// example uses the `~=` operator to test whether an integer is included in /// a range of single-digit numbers: /// /// let chosenNumber = 3 /// if 0..<10 ~= chosenNumber { /// print("\(chosenNumber) is a single digit.") /// } /// // Prints "3 is a single digit." /// /// - Parameters: /// - pattern: A range. /// - bound: A value to match against `pattern`. @inlinable public static func ~= (pattern: Self, value: Bound) -> Bool { return pattern.contains(value) } } /// A half-open interval from a lower bound up to, but not including, an upper /// bound. /// /// You create a `Range` instance by using the half-open range operator /// (`..<`). /// /// let underFive = 0.0..<5.0 /// /// You can use a `Range` instance to quickly check if a value is contained in /// a particular range of values. For example: /// /// underFive.contains(3.14) /// // true /// underFive.contains(6.28) /// // false /// underFive.contains(5.0) /// // false /// /// `Range` instances can represent an empty interval, unlike `ClosedRange`. /// /// let empty = 0.0..<0.0 /// empty.contains(0.0) /// // false /// empty.isEmpty /// // true /// /// Using a Range as a Collection of Consecutive Values /// ---------------------------------------------------- /// /// When a range uses integers as its lower and upper bounds, or any other type /// that conforms to the `Strideable` protocol with an integer stride, you can /// use that range in a `for`-`in` loop or with any sequence or collection /// method. The elements of the range are the consecutive values from its /// lower bound up to, but not including, its upper bound. /// /// for n in 3..<5 { /// print(n) /// } /// // Prints "3" /// // Prints "4" /// /// Because floating-point types such as `Float` and `Double` are their own /// `Stride` types, they cannot be used as the bounds of a countable range. If /// you need to iterate over consecutive floating-point values, see the /// `stride(from:to:by:)` function. @frozen public struct Range<Bound: Comparable> { /// The range's lower bound. /// /// In an empty range, `lowerBound` is equal to `upperBound`. public let lowerBound: Bound /// The range's upper bound. /// /// In an empty range, `upperBound` is equal to `lowerBound`. A `Range` /// instance does not contain its upper bound. public let upperBound: Bound // This works around _debugPrecondition() impacting the performance of // optimized code. (rdar://72246338) @_alwaysEmitIntoClient @inline(__always) internal init(_uncheckedBounds bounds: (lower: Bound, upper: Bound)) { self.lowerBound = bounds.lower self.upperBound = bounds.upper } /// Creates an instance with the given bounds. /// /// Because this initializer does not perform any checks, it should be used /// as an optimization only when you are absolutely certain that `lower` is /// less than or equal to `upper`. Using the half-open range operator /// (`..<`) to form `Range` instances is preferred. /// /// - Parameter bounds: A tuple of the lower and upper bounds of the range. @inlinable public init(uncheckedBounds bounds: (lower: Bound, upper: Bound)) { _debugPrecondition(bounds.lower <= bounds.upper, "Range requires lowerBound <= upperBound") self.init(_uncheckedBounds: (lower: bounds.lower, upper: bounds.upper)) } /// Returns a Boolean value indicating whether the given element is contained /// within the range. /// /// Because `Range` represents a half-open range, a `Range` instance does not /// contain its upper bound. `element` is contained in the range if it is /// greater than or equal to the lower bound and less than the upper bound. /// /// - Parameter element: The element to check for containment. /// - Returns: `true` if `element` is contained in the range; otherwise, /// `false`. @inlinable public func contains(_ element: Bound) -> Bool { return lowerBound <= element && element < upperBound } /// A Boolean value indicating whether the range contains no elements. /// /// An empty `Range` instance has equal lower and upper bounds. /// /// let empty: Range = 10..<10 /// print(empty.isEmpty) /// // Prints "true" @inlinable public var isEmpty: Bool { return lowerBound == upperBound } } extension Range: Sequence where Bound: Strideable, Bound.Stride: SignedInteger { public typealias Element = Bound public typealias Iterator = IndexingIterator<Range<Bound>> } extension Range: Collection, BidirectionalCollection, RandomAccessCollection where Bound: Strideable, Bound.Stride: SignedInteger { /// A type that represents a position in the range. public typealias Index = Bound public typealias Indices = Range<Bound> public typealias SubSequence = Range<Bound> @inlinable public var startIndex: Index { return lowerBound } @inlinable public var endIndex: Index { return upperBound } @inlinable public func index(after i: Index) -> Index { _failEarlyRangeCheck(i, bounds: startIndex..<endIndex) return i.advanced(by: 1) } @inlinable public func index(before i: Index) -> Index { _precondition(i > lowerBound) _precondition(i <= upperBound) return i.advanced(by: -1) } @inlinable public func index(_ i: Index, offsetBy n: Int) -> Index { let r = i.advanced(by: numericCast(n)) _precondition(r >= lowerBound) _precondition(r <= upperBound) return r } @inlinable public func distance(from start: Index, to end: Index) -> Int { return numericCast(start.distance(to: end)) } /// Accesses the subsequence bounded by the given range. /// /// - Parameter bounds: A range of the range's indices. The upper and lower /// bounds of the `bounds` range must be valid indices of the collection. @inlinable public subscript(bounds: Range<Index>) -> Range<Bound> { return bounds } /// The indices that are valid for subscripting the range, in ascending /// order. @inlinable public var indices: Indices { return self } @inlinable public func _customContainsEquatableElement(_ element: Element) -> Bool? { return lowerBound <= element && element < upperBound } @inlinable public func _customIndexOfEquatableElement(_ element: Bound) -> Index?? { return lowerBound <= element && element < upperBound ? element : nil } @inlinable public func _customLastIndexOfEquatableElement(_ element: Bound) -> Index?? { // The first and last elements are the same because each element is unique. return _customIndexOfEquatableElement(element) } /// Accesses the element at specified position. /// /// You can subscript a collection with any valid index other than the /// collection's end index. The end index refers to the position one past /// the last element of a collection, so it doesn't correspond with an /// element. /// /// - Parameter position: The position of the element to access. `position` /// must be a valid index of the range, and must not equal the range's end /// index. @inlinable public subscript(position: Index) -> Element { // FIXME: swift-3-indexing-model: tests for the range check. _debugPrecondition(self.contains(position), "Index out of range") return position } } extension Range where Bound: Strideable, Bound.Stride: SignedInteger { /// Creates an instance equivalent to the given `ClosedRange`. /// /// - Parameter other: A closed range to convert to a `Range` instance. /// /// An equivalent range must be representable as an instance of Range<Bound>. /// For example, passing a closed range with an upper bound of `Int.max` /// triggers a runtime error, because the resulting half-open range would /// require an upper bound of `Int.max + 1`, which is not representable as /// an `Int`. @inlinable // trivial-implementation public init(_ other: ClosedRange<Bound>) { let upperBound = other.upperBound.advanced(by: 1) self.init(_uncheckedBounds: (lower: other.lowerBound, upper: upperBound)) } } extension Range: RangeExpression { /// Returns the range of indices described by this range expression within /// the given collection. /// /// - Parameter collection: The collection to evaluate this range expression /// in relation to. /// - Returns: A range suitable for slicing `collection`. The returned range /// is *not* guaranteed to be inside the bounds of `collection`. Callers /// should apply the same preconditions to the return value as they would /// to a range provided directly by the user. @inlinable // trivial-implementation public func relative<C: Collection>(to collection: C) -> Range<Bound> where C.Index == Bound { self } } extension Range { /// Returns a copy of this range clamped to the given limiting range. /// /// The bounds of the result are always limited to the bounds of `limits`. /// For example: /// /// let x: Range = 0..<20 /// print(x.clamped(to: 10..<1000)) /// // Prints "10..<20" /// /// If the two ranges do not overlap, the result is an empty range within the /// bounds of `limits`. /// /// let y: Range = 0..<5 /// print(y.clamped(to: 10..<1000)) /// // Prints "10..<10" /// /// - Parameter limits: The range to clamp the bounds of this range. /// - Returns: A new range clamped to the bounds of `limits`. @inlinable // trivial-implementation @inline(__always) public func clamped(to limits: Range) -> Range { let lower = limits.lowerBound > self.lowerBound ? limits.lowerBound : limits.upperBound < self.lowerBound ? limits.upperBound : self.lowerBound let upper = limits.upperBound < self.upperBound ? limits.upperBound : limits.lowerBound > self.upperBound ? limits.lowerBound : self.upperBound return Range(_uncheckedBounds: (lower: lower, upper: upper)) } } extension Range: CustomStringConvertible { /// A textual representation of the range. @inlinable // trivial-implementation public var description: String { return "\(lowerBound)..<\(upperBound)" } } extension Range: CustomDebugStringConvertible { /// A textual representation of the range, suitable for debugging. public var debugDescription: String { return "Range(\(String(reflecting: lowerBound))" + "..<\(String(reflecting: upperBound)))" } } #if SWIFT_ENABLE_REFLECTION extension Range: CustomReflectable { public var customMirror: Mirror { return Mirror( self, children: ["lowerBound": lowerBound, "upperBound": upperBound]) } } #endif extension Range: Equatable { /// Returns a Boolean value indicating whether two ranges are equal. /// /// Two ranges are equal when they have the same lower and upper bounds. /// That requirement holds even for empty ranges. /// /// let x = 5..<15 /// print(x == 5..<15) /// // Prints "true" /// /// let y = 5..<5 /// print(y == 15..<15) /// // Prints "false" /// /// - Parameters: /// - lhs: A range to compare. /// - rhs: Another range to compare. @inlinable public static func == (lhs: Range<Bound>, rhs: Range<Bound>) -> Bool { return lhs.lowerBound == rhs.lowerBound && lhs.upperBound == rhs.upperBound } } extension Range: Hashable where Bound: Hashable { /// Hashes the essential components of this value by feeding them into the /// given hasher. /// /// - Parameter hasher: The hasher to use when combining the components /// of this instance. @inlinable public func hash(into hasher: inout Hasher) { hasher.combine(lowerBound) hasher.combine(upperBound) } } extension Range: Decodable where Bound: Decodable { public init(from decoder: Decoder) throws { var container = try decoder.unkeyedContainer() let lowerBound = try container.decode(Bound.self) let upperBound = try container.decode(Bound.self) guard lowerBound <= upperBound else { throw DecodingError.dataCorrupted( DecodingError.Context( codingPath: decoder.codingPath, debugDescription: "Cannot initialize \(Range.self) with a lowerBound (\(lowerBound)) greater than upperBound (\(upperBound))")) } self.init(_uncheckedBounds: (lower: lowerBound, upper: upperBound)) } } extension Range: Encodable where Bound: Encodable { public func encode(to encoder: Encoder) throws { var container = encoder.unkeyedContainer() try container.encode(self.lowerBound) try container.encode(self.upperBound) } } /// A partial half-open interval up to, but not including, an upper bound. /// /// You create `PartialRangeUpTo` instances by using the prefix half-open range /// operator (prefix `..<`). /// /// let upToFive = ..<5.0 /// /// You can use a `PartialRangeUpTo` instance to quickly check if a value is /// contained in a particular range of values. For example: /// /// upToFive.contains(3.14) // true /// upToFive.contains(6.28) // false /// upToFive.contains(5.0) // false /// /// You can use a `PartialRangeUpTo` instance of a collection's indices to /// represent the range from the start of the collection up to, but not /// including, the partial range's upper bound. /// /// let numbers = [10, 20, 30, 40, 50, 60, 70] /// print(numbers[..<3]) /// // Prints "[10, 20, 30]" @frozen public struct PartialRangeUpTo<Bound: Comparable> { public let upperBound: Bound @inlinable // trivial-implementation public init(_ upperBound: Bound) { self.upperBound = upperBound } } extension PartialRangeUpTo: RangeExpression { @_transparent public func relative<C: Collection>(to collection: C) -> Range<Bound> where C.Index == Bound { return collection.startIndex..<self.upperBound } @_transparent public func contains(_ element: Bound) -> Bool { return element < upperBound } } extension PartialRangeUpTo: Decodable where Bound: Decodable { public init(from decoder: Decoder) throws { var container = try decoder.unkeyedContainer() try self.init(container.decode(Bound.self)) } } extension PartialRangeUpTo: Encodable where Bound: Encodable { public func encode(to encoder: Encoder) throws { var container = encoder.unkeyedContainer() try container.encode(self.upperBound) } } /// A partial interval up to, and including, an upper bound. /// /// You create `PartialRangeThrough` instances by using the prefix closed range /// operator (prefix `...`). /// /// let throughFive = ...5.0 /// /// You can use a `PartialRangeThrough` instance to quickly check if a value is /// contained in a particular range of values. For example: /// /// throughFive.contains(4.0) // true /// throughFive.contains(5.0) // true /// throughFive.contains(6.0) // false /// /// You can use a `PartialRangeThrough` instance of a collection's indices to /// represent the range from the start of the collection up to, and including, /// the partial range's upper bound. /// /// let numbers = [10, 20, 30, 40, 50, 60, 70] /// print(numbers[...3]) /// // Prints "[10, 20, 30, 40]" @frozen public struct PartialRangeThrough<Bound: Comparable> { public let upperBound: Bound @inlinable // trivial-implementation public init(_ upperBound: Bound) { self.upperBound = upperBound } } extension PartialRangeThrough: RangeExpression { @_transparent public func relative<C: Collection>(to collection: C) -> Range<Bound> where C.Index == Bound { return collection.startIndex..<collection.index(after: self.upperBound) } @_transparent public func contains(_ element: Bound) -> Bool { return element <= upperBound } } extension PartialRangeThrough: Decodable where Bound: Decodable { public init(from decoder: Decoder) throws { var container = try decoder.unkeyedContainer() try self.init(container.decode(Bound.self)) } } extension PartialRangeThrough: Encodable where Bound: Encodable { public func encode(to encoder: Encoder) throws { var container = encoder.unkeyedContainer() try container.encode(self.upperBound) } } /// A partial interval extending upward from a lower bound. /// /// You create `PartialRangeFrom` instances by using the postfix range operator /// (postfix `...`). /// /// let atLeastFive = 5... /// /// You can use a partial range to quickly check if a value is contained in a /// particular range of values. For example: /// /// atLeastFive.contains(4) /// // false /// atLeastFive.contains(5) /// // true /// atLeastFive.contains(6) /// // true /// /// You can use a partial range of a collection's indices to represent the /// range from the partial range's lower bound up to the end of the /// collection. /// /// let numbers = [10, 20, 30, 40, 50, 60, 70] /// print(numbers[3...]) /// // Prints "[40, 50, 60, 70]" /// /// Using a Partial Range as a Sequence /// ----------------------------------- /// /// When a partial range uses integers as its lower and upper bounds, or any /// other type that conforms to the `Strideable` protocol with an integer /// stride, you can use that range in a `for`-`in` loop or with any sequence /// method that doesn't require that the sequence is finite. The elements of /// a partial range are the consecutive values from its lower bound continuing /// upward indefinitely. /// /// func isTheMagicNumber(_ x: Int) -> Bool { /// return x == 3 /// } /// /// for x in 1... { /// if isTheMagicNumber(x) { /// print("\(x) is the magic number!") /// break /// } else { /// print("\(x) wasn't it...") /// } /// } /// // "1 wasn't it..." /// // "2 wasn't it..." /// // "3 is the magic number!" /// /// Because a `PartialRangeFrom` sequence counts upward indefinitely, do not /// use one with methods that read the entire sequence before returning, such /// as `map(_:)`, `filter(_:)`, or `suffix(_:)`. It is safe to use operations /// that put an upper limit on the number of elements they access, such as /// `prefix(_:)` or `dropFirst(_:)`, and operations that you can guarantee /// will terminate, such as passing a closure you know will eventually return /// `true` to `first(where:)`. /// /// In the following example, the `asciiTable` sequence is made by zipping /// together the characters in the `alphabet` string with a partial range /// starting at 65, the ASCII value of the capital letter A. Iterating over /// two zipped sequences continues only as long as the shorter of the two /// sequences, so the iteration stops at the end of `alphabet`. /// /// let alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" /// let asciiTable = zip(65..., alphabet) /// for (code, letter) in asciiTable { /// print(code, letter) /// } /// // "65 A" /// // "66 B" /// // "67 C" /// // ... /// // "89 Y" /// // "90 Z" /// /// The behavior of incrementing indefinitely is determined by the type of /// `Bound`. For example, iterating over an instance of /// `PartialRangeFrom<Int>` traps when the sequence's next value would be /// above `Int.max`. @frozen public struct PartialRangeFrom<Bound: Comparable> { public let lowerBound: Bound @inlinable // trivial-implementation public init(_ lowerBound: Bound) { self.lowerBound = lowerBound } } extension PartialRangeFrom: RangeExpression { @_transparent public func relative<C: Collection>( to collection: C ) -> Range<Bound> where C.Index == Bound { return self.lowerBound..<collection.endIndex } @inlinable // trivial-implementation public func contains(_ element: Bound) -> Bool { return lowerBound <= element } } extension PartialRangeFrom: Sequence where Bound: Strideable, Bound.Stride: SignedInteger { public typealias Element = Bound /// The iterator for a `PartialRangeFrom` instance. @frozen public struct Iterator: IteratorProtocol { @usableFromInline internal var _current: Bound @inlinable public init(_current: Bound) { self._current = _current } /// 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`. /// /// - Returns: The next element in the underlying sequence, if a next /// element exists; otherwise, `nil`. @inlinable public mutating func next() -> Bound? { defer { _current = _current.advanced(by: 1) } return _current } } /// Returns an iterator for this sequence. @inlinable public __consuming func makeIterator() -> Iterator { return Iterator(_current: lowerBound) } } extension PartialRangeFrom: Decodable where Bound: Decodable { public init(from decoder: Decoder) throws { var container = try decoder.unkeyedContainer() try self.init(container.decode(Bound.self)) } } extension PartialRangeFrom: Encodable where Bound: Encodable { public func encode(to encoder: Encoder) throws { var container = encoder.unkeyedContainer() try container.encode(self.lowerBound) } } extension Comparable { /// Returns a half-open range that contains its lower bound but not its upper /// bound. /// /// Use the half-open range operator (`..<`) to create a range of any type /// that conforms to the `Comparable` protocol. This example creates a /// `Range<Double>` from zero up to, but not including, 5.0. /// /// let lessThanFive = 0.0..<5.0 /// print(lessThanFive.contains(3.14)) // Prints "true" /// print(lessThanFive.contains(5.0)) // Prints "false" /// /// - Parameters: /// - minimum: The lower bound for the range. /// - maximum: The upper bound for the range. /// /// - Precondition: `minimum <= maximum`. @_transparent public static func ..< (minimum: Self, maximum: Self) -> Range<Self> { _precondition(minimum <= maximum, "Range requires lowerBound <= upperBound") return Range(_uncheckedBounds: (lower: minimum, upper: maximum)) } /// Returns a partial range up to, but not including, its upper bound. /// /// Use the prefix half-open range operator (prefix `..<`) to create a /// partial range of any type that conforms to the `Comparable` protocol. /// This example creates a `PartialRangeUpTo<Double>` instance that includes /// any value less than `5.0`. /// /// let upToFive = ..<5.0 /// /// upToFive.contains(3.14) // true /// upToFive.contains(6.28) // false /// upToFive.contains(5.0) // false /// /// You can use this type of partial range of a collection's indices to /// represent the range from the start of the collection up to, but not /// including, the partial range's upper bound. /// /// let numbers = [10, 20, 30, 40, 50, 60, 70] /// print(numbers[..<3]) /// // Prints "[10, 20, 30]" /// /// - Parameter maximum: The upper bound for the range. /// /// - Precondition: `maximum` must compare equal to itself (i.e. cannot be NaN). @_transparent public static prefix func ..< (maximum: Self) -> PartialRangeUpTo<Self> { _precondition(maximum == maximum, "Range cannot have an unordered upper bound.") return PartialRangeUpTo(maximum) } /// Returns a partial range up to, and including, its upper bound. /// /// Use the prefix closed range operator (prefix `...`) to create a partial /// range of any type that conforms to the `Comparable` protocol. This /// example creates a `PartialRangeThrough<Double>` instance that includes /// any value less than or equal to `5.0`. /// /// let throughFive = ...5.0 /// /// throughFive.contains(4.0) // true /// throughFive.contains(5.0) // true /// throughFive.contains(6.0) // false /// /// You can use this type of partial range of a collection's indices to /// represent the range from the start of the collection up to, and /// including, the partial range's upper bound. /// /// let numbers = [10, 20, 30, 40, 50, 60, 70] /// print(numbers[...3]) /// // Prints "[10, 20, 30, 40]" /// /// - Parameter maximum: The upper bound for the range. /// /// - Precondition: `maximum` must compare equal to itself (i.e. cannot be NaN). @_transparent public static prefix func ... (maximum: Self) -> PartialRangeThrough<Self> { _precondition(maximum == maximum, "Range cannot have an unordered upper bound.") return PartialRangeThrough(maximum) } /// Returns a partial range extending upward from a lower bound. /// /// Use the postfix range operator (postfix `...`) to create a partial range /// of any type that conforms to the `Comparable` protocol. This example /// creates a `PartialRangeFrom<Double>` instance that includes any value /// greater than or equal to `5.0`. /// /// let atLeastFive = 5.0... /// /// atLeastFive.contains(4.0) // false /// atLeastFive.contains(5.0) // true /// atLeastFive.contains(6.0) // true /// /// You can use this type of partial range of a collection's indices to /// represent the range from the partial range's lower bound up to the end /// of the collection. /// /// let numbers = [10, 20, 30, 40, 50, 60, 70] /// print(numbers[3...]) /// // Prints "[40, 50, 60, 70]" /// /// - Parameter minimum: The lower bound for the range. /// /// - Precondition: `minimum` must compare equal to itself (i.e. cannot be NaN). @_transparent public static postfix func ... (minimum: Self) -> PartialRangeFrom<Self> { _precondition(minimum == minimum, "Range cannot have an unordered lower bound.") return PartialRangeFrom(minimum) } } /// A range expression that represents the entire range of a collection. /// /// You can use the unbounded range operator (`...`) to create a slice of a /// collection that contains all of the collection's elements. Slicing with an /// unbounded range is essentially a conversion of a collection instance into /// its slice type. /// /// For example, the following code declares `countLetterChanges(_:_:)`, a /// function that finds the number of changes required to change one /// word or phrase into another. The function uses a recursive approach to /// perform the same comparisons on smaller and smaller pieces of the original /// strings. In order to use recursion without making copies of the strings at /// each step, `countLetterChanges(_:_:)` uses `Substring`, a string's slice /// type, for its parameters. /// /// func countLetterChanges(_ s1: Substring, _ s2: Substring) -> Int { /// if s1.isEmpty { return s2.count } /// if s2.isEmpty { return s1.count } /// /// let cost = s1.first == s2.first ? 0 : 1 /// /// return min( /// countLetterChanges(s1.dropFirst(), s2) + 1, /// countLetterChanges(s1, s2.dropFirst()) + 1, /// countLetterChanges(s1.dropFirst(), s2.dropFirst()) + cost) /// } /// /// To call `countLetterChanges(_:_:)` with two strings, use an unbounded /// range in each string's subscript. /// /// let word1 = "grizzly" /// let word2 = "grisly" /// let changes = countLetterChanges(word1[...], word2[...]) /// // changes == 2 @frozen // namespace public enum UnboundedRange_ { // FIXME: replace this with a computed var named `...` when the language makes // that possible. /// Creates an unbounded range expression. /// /// The unbounded range operator (`...`) is valid only within a collection's /// subscript. public static postfix func ... (_: UnboundedRange_) -> () { // This function is uncallable } } /// The type of an unbounded range operator. public typealias UnboundedRange = (UnboundedRange_)->() extension Collection { /// Accesses the contiguous subrange of the collection's elements specified /// by a range expression. /// /// The range expression is converted to a concrete subrange relative to this /// collection. For example, using a `PartialRangeFrom` range expression /// with an array accesses the subrange from the start of the range /// expression until the end of the array. /// /// let streets = ["Adams", "Bryant", "Channing", "Douglas", "Evarts"] /// let streetsSlice = streets[2...] /// print(streetsSlice) /// // ["Channing", "Douglas", "Evarts"] /// /// The accessed slice uses the same indices for the same elements as the /// original collection uses. This example searches `streetsSlice` for one /// of the strings in the slice, and then uses that index in the original /// array. /// /// let index = streetsSlice.firstIndex(of: "Evarts") // 4 /// print(streets[index!]) /// // "Evarts" /// /// Always use the slice's `startIndex` property instead of assuming that its /// indices start at a particular value. Attempting to access an element by /// using an index outside the bounds of the slice's indices may result in a /// runtime error, even if that index is valid for the original collection. /// /// print(streetsSlice.startIndex) /// // 2 /// print(streetsSlice[2]) /// // "Channing" /// /// print(streetsSlice[0]) /// // error: Index out of bounds /// /// - Parameter bounds: A range of the collection's indices. The bounds of /// the range must be valid indices of the collection. /// /// - Complexity: O(1) @inlinable public subscript<R: RangeExpression>(r: R) -> SubSequence where R.Bound == Index { return self[r.relative(to: self)] } @inlinable public subscript(x: UnboundedRange) -> SubSequence { return self[startIndex...] } } extension MutableCollection { @inlinable public subscript<R: RangeExpression>(r: R) -> SubSequence where R.Bound == Index { get { return self[r.relative(to: self)] } set { self[r.relative(to: self)] = newValue } } @inlinable public subscript(x: UnboundedRange) -> SubSequence { get { return self[startIndex...] } set { self[startIndex...] = newValue } } } // TODO: enhance RangeExpression to make this generic and available on // any expression. extension Range { /// Returns a Boolean value indicating whether this range and the given range /// contain an element in common. /// /// This example shows two overlapping ranges: /// /// let x: Range = 0..<20 /// print(x.overlaps(10...1000)) /// // Prints "true" /// /// Because a half-open range does not include its upper bound, the ranges /// in the following example do not overlap: /// /// let y = 20..<30 /// print(x.overlaps(y)) /// // Prints "false" /// /// - Parameter other: A range to check for elements in common. /// - Returns: `true` if this range and `other` have at least one element in /// common; otherwise, `false`. @inlinable public func overlaps(_ other: Range<Bound>) -> Bool { // Disjoint iff the other range is completely before or after our range. // Additionally either `Range` (unlike a `ClosedRange`) could be empty, in // which case it is disjoint with everything as overlap is defined as having // an element in common. let isDisjoint = other.upperBound <= self.lowerBound || self.upperBound <= other.lowerBound || self.isEmpty || other.isEmpty return !isDisjoint } @inlinable public func overlaps(_ other: ClosedRange<Bound>) -> Bool { // Disjoint iff the other range is completely before or after our range. // Additionally the `Range` (unlike the `ClosedRange`) could be empty, in // which case it is disjoint with everything as overlap is defined as having // an element in common. let isDisjoint = other.upperBound < self.lowerBound || self.upperBound <= other.lowerBound || self.isEmpty return !isDisjoint } } // Note: this is not for compatibility only, it is considered a useful // shorthand. TODO: Add documentation public typealias CountableRange<Bound: Strideable> = Range<Bound> where Bound.Stride: SignedInteger // Note: this is not for compatibility only, it is considered a useful // shorthand. TODO: Add documentation public typealias CountablePartialRangeFrom<Bound: Strideable> = PartialRangeFrom<Bound> where Bound.Stride: SignedInteger extension Range: Sendable where Bound: Sendable { } extension PartialRangeUpTo: Sendable where Bound: Sendable { } extension PartialRangeThrough: Sendable where Bound: Sendable { } extension PartialRangeFrom: Sendable where Bound: Sendable { } extension PartialRangeFrom.Iterator: Sendable where Bound: Sendable { } extension Range where Bound == String.Index { @_alwaysEmitIntoClient // Swift 5.7 internal var _encodedOffsetRange: Range<Int> { _internalInvariant( (lowerBound._canBeUTF8 && upperBound._canBeUTF8) || (lowerBound._canBeUTF16 && upperBound._canBeUTF16)) return Range<Int>( _uncheckedBounds: (lowerBound._encodedOffset, upperBound._encodedOffset)) } }
apache-2.0
267a3732f827abb5c0851340d8b23d49
34.483654
137
0.656261
4.23151
false
false
false
false
Hearsayer/YLDrawer
Drawer/MenuViewController.swift
1
1529
// // MenuViewController.swift // Drawer // // Created by he on 2017/7/13. // Copyright © 2017年 hezongjiang. All rights reserved. // import UIKit class MenuViewController: UIViewController { fileprivate lazy var tableView: UITableView = { let tableView = UITableView(frame: self.view.bounds) tableView.dataSource = self tableView.delegate = self tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell") tableView.backgroundColor = .clear tableView.tableFooterView = UIView() return tableView }() fileprivate lazy var vi = UIView() override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = .clear view.addSubview(tableView) vi.backgroundColor = .red vi.frame = CGRect(x: 0, y: 0, width: 100, height: 100) vi.center = view.center view.addSubview(vi) } } extension MenuViewController: UITableViewDelegate, UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 5 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) cell.backgroundColor = .clear cell.textLabel?.text = "\(indexPath.row)" cell.textLabel?.textColor = .white return cell } }
mit
00ebb0cb7cb5b27b4ac6400935c7e139
26.25
100
0.638925
5.003279
false
false
false
false
nickfrey/knightsapp
Newman Knights/EventCalendar.swift
1
11487
// // EventCalendar.swift // Newman Knights // // Created by Nick Frey on 12/21/15. // Copyright © 2015 Nick Frey. All rights reserved. // import Foundation class EventCalendar { let calendar: Calendar fileprivate var datesBeingFetched: Set<Date> fileprivate var datesAlreadyFetched: Dictionary<Date, Date> fileprivate var datesContainingEvents: Set<Date> init() { self.calendar = Calendar(identifier: .gregorian) self.datesBeingFetched = Set() self.datesAlreadyFetched = Dictionary() self.datesContainingEvents = Set() } // MARK: Class Methods class func fetchEvents(_ date: Date, completionHandler: @escaping (_ events: Array<Event>?, _ error: Error?) -> Void) -> (() -> Void)? { let monthYearFormatter = DateFormatter() monthYearFormatter.dateFormat = "MM-yyyy" let dayFormatter = DateFormatter() dayFormatter.dateFormat = "dd" return self.fetchEvents([ "ff_month_year": monthYearFormatter.string(from: date), "ffDay": dayFormatter.string(from: date) ], completionHandler: completionHandler) } class func fetchEvents(_ query: String, completionHandler: @escaping (_ events: Array<Event>?, _ error: Error?) -> Void) -> (() -> Void)? { return self.fetchEvents([ "G5statusflag": "view", "vw_schoolyear": "1", "search_text": query ], completionHandler: completionHandler) } fileprivate class func fetchEvents(_ parameters: Dictionary<String, String>, completionHandler: @escaping (_ events: Array<Event>?, _ error: Error?) -> Void) -> (() -> Void)? { var queryItems = [ URLQueryItem(name: "G5genie", value: "97"), URLQueryItem(name: "school_id", value: "5"), URLQueryItem(name: "XMLCalendar", value: "6") ] for (key, value) in parameters { queryItems.append(URLQueryItem(name: key, value: value)) } var fetchURLComponents = URLComponents(string: "http://www.northiowaconference.org/g5-bin/client.cgi")! fetchURLComponents.queryItems = queryItems guard let fetchURL = fetchURLComponents.url else { completionHandler(nil, NSError(domain: NSURLErrorDomain, code: NSURLErrorBadURL, userInfo: nil)) return nil } let dataTask = URLSession.shared.dataTask(with: fetchURL, completionHandler: { (data, response, error) -> Void in guard let data = data, error == nil else { return completionHandler(nil, error) } let xml = SWXMLHash.config({ config in config.shouldProcessNamespaces = true }).parse(data) var events = Array<Event>() for eventIndexer in xml["schema"]["element"].all { guard let eventElement = eventIndexer.element, eventElement.attribute(by: "name")?.text == "event" else { continue } var event = Event() var eventType: String? var eventDate: String? var startTime: String? var endTime: String? var comments = [String]() for detailIndexer in eventIndexer["complexType"]["sequence"]["element"].all { guard let detailElement = detailIndexer.element else { continue } let name = detailElement.attribute(by: "name")?.text let text = detailElement.text if name == "game_date" { eventDate = text } else if name == "start_time" { startTime = text } else if name == "end_time" { endTime = text } else if name == "type" { eventType = text } else if name == "identifier" { event.identifier = text } else if name == "sport" { event.title = text } else if name == "level" { event.gradeLevel = text } else if name == "gender" { event.gender = text.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines) } else if name == "status" { event.status = text.replacingOccurrences(of: "(", with: "").replacingOccurrences(of: ")", with: "") } else if name == "homeaway" { event.away = (text == "Away") } else if name == "location" { for locationIndexer in detailIndexer["complexType"]["sequence"]["element"].all { guard let locationElement = locationIndexer.element, locationElement.attribute(by: "name")?.text == "name" else { continue } event.location = locationElement.text.replacingOccurrences(of: "@ ", with: "") } } else if name == "opponent" { if detailElement.attribute(by: "type")?.text == "xsd:string" { event.opponents = text.components(separatedBy: ",").flatMap({ opponent -> String? in let trimmedOpponent = opponent.trimmingCharacters(in: .whitespacesAndNewlines) if trimmedOpponent.count > 0 { return opponent } else { return nil } }) } } else if name == "comment" { for commentIndexer in detailIndexer["complexType"]["sequence"]["element"].all { guard let commentElement = commentIndexer.element else { continue } let commentText = commentElement.text.trimmingCharacters(in: .whitespacesAndNewlines) guard commentText.count > 0 else { continue } if !comments.contains(commentText) { comments.append(commentText) } } } } if let eventType = eventType { if let title = event.title { event.title = title + " " + eventType } else { event.title = eventType } } event.details = comments.joined(separator: "\n\n") // Start & end dates let dateFormatter = DateFormatter() let dateFormat = (parameters["G5statusflag"] == "view" ? "MM-dd-yy" : "yyyy-MM-dd") if var startDate = eventDate { dateFormatter.dateFormat = dateFormat if let startTime = startTime, startTime.range(of: ":") != nil { startDate += " " + startTime dateFormatter.dateFormat = dateFormat + " hh:mma" } event.startDate = dateFormatter.date(from: startDate) } if var endDate = eventDate { dateFormatter.dateFormat = dateFormat if let endTime = endTime, endTime.range(of: ":") != nil { endDate += " " + endTime dateFormatter.dateFormat = dateFormat + " hh:mma" } event.endDate = dateFormatter.date(from: endDate) } // Append the event events.append(event) } completionHandler(events, nil) }) dataTask.resume() return { dataTask.cancel() } } // MARK: Instance Methods func fetchEventOccurrences(_ month: Date, completionHandler: @escaping (_ fetched: Bool, _ error: Error?) -> Void) { guard let beginningOfMonth = self.calendar.date(bySetting: .day, value: 1, of: month) else { return completionHandler(false, nil) } let fromDate = self.calendar.startOfDay(for: beginningOfMonth) if let lastFetchDate = self.datesAlreadyFetched[fromDate] { if Date().timeIntervalSince(lastFetchDate) < 60 * 10 { // If this month was fetched within last 10 minutes, use cache return completionHandler(false, nil) } } if self.datesBeingFetched.contains(fromDate) { return completionHandler(false, nil) } else { self.datesBeingFetched.insert(fromDate) } let dateFormatter = DateFormatter() dateFormatter.dateFormat = "yyyy-MM-dd" let fetchURL = URL(string: String(format: "http://srv2.advancedview.rschooltoday.com/public/conference/calendar/type/xml/G5genie/97/G5button/13/school_id/5/preview/no/vw_activity/0/vw_conference_events/1/vw_non_conference_events/1/vw_homeonly/1/vw_awayonly/1/vw_schoolonly/1/vw_gender/1/vw_type/0/vw_level/0/vw_opponent/0/opt_show_location/1/opt_show_comments/1/opt_show_bus_times/1/vw_location/0/vw_period/month-yr/vw_month2/%@/vw_monthCnt/01/vw_school_year/0/sortType/time/expandView/1/listact/0/dontshowlocation/1/", dateFormatter.string(from: fromDate)))! URLSession.shared.dataTask(with: fetchURL, completionHandler: { (data, response, error) -> Void in self.datesBeingFetched.remove(fromDate) guard let data = data, error == nil else { return completionHandler(true, error) } dateFormatter.dateFormat = "EEE, dd MMMM yyyy HH:mm:ss Z" dateFormatter.locale = Locale(identifier: "en") // Fetch succeeded let xml = SWXMLHash.parse(data) for eventIndexer in xml["rss"]["channel"]["item"].all { guard let eventElement = eventIndexer.element else { continue } for childElement in eventElement.xmlChildren { if childElement.name == "pubDate" { if let pubDate = dateFormatter.date(from: childElement.text) { self.datesContainingEvents.insert(self.calendar.startOfDay(for: pubDate)) } break } } } self.datesAlreadyFetched[fromDate] = Date() completionHandler(true, nil) }).resume() } func eventsOccurOnDate(_ date: Date) -> Bool { return self.datesContainingEvents.contains(self.calendar.startOfDay(for: date)) } }
mit
a4ac09e286c9586b4320fc564f20d1ad
44.579365
567
0.502264
5.327458
false
false
false
false
informmegp2/inform-me
InformME/UpdateEventViewController.swift
1
10788
// // UpdateEventViewController.swift // InformME // // Created by Amal Ibrahim on 2/9/16. // Copyright © 2016 King Saud University. All rights reserved. // import Foundation // // EventDetailsViewController.swift // InformME // // Created by Amal Ibrahim on 2/9/16. // Copyright © 2016 King Saud University. All rights reserved. // import Foundation import UIKit class UpdateEventViewController: UIViewController, UITextFieldDelegate, UIImagePickerControllerDelegate,UINavigationControllerDelegate { var evid: Int=1; var evname: String="" var evwebsite: String="" var evdate: String="" var evlogo: UIImage? @IBOutlet var EventLogo: UIButton! @IBOutlet var EventDate: UITextField! @IBOutlet var EventWebsite: UITextField! @IBOutlet var EventName: UITextField! override func viewDidLoad() { super.viewDidLoad() EventDate.text = evdate EventWebsite.text = evwebsite EventName.text = evname EventLogo.setBackgroundImage(evlogo, forState: .Normal) EventDate.delegate = self EventWebsite.delegate = self EventName.delegate = self // Do any additional setup after loading the view. } @IBAction func uploadImage(sender: AnyObject) { print("button pressed") let myPickerController = UIImagePickerController() myPickerController.delegate = self; myPickerController.sourceType = UIImagePickerControllerSourceType.PhotoLibrary self.presentViewController(myPickerController, animated: true, completion: nil) } func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) { EventLogo.setBackgroundImage(info[UIImagePickerControllerOriginalImage] as? UIImage, forState: .Normal) self.dismissViewControllerAnimated(true, completion: nil) } @IBAction func dp(sender: UITextField) { let inputView = UIView(frame: CGRectMake(0, 0, self.view.frame.width, 240)) let datePickerView : UIDatePicker = UIDatePicker(frame: CGRectMake(0, 40, 0, 0)) datePickerView.datePickerMode = UIDatePickerMode.Date inputView.addSubview(datePickerView) // add date picker to UIView let doneButton = UIButton(frame: CGRectMake((self.view.frame.size.width/2) - (100/2), 0, 100, 50)) doneButton.setTitle("Done", forState: UIControlState.Normal) doneButton.setTitle("Done", forState: UIControlState.Highlighted) doneButton.setTitleColor(UIColor.blackColor(), forState: UIControlState.Normal) doneButton.setTitleColor(UIColor.grayColor(), forState: UIControlState.Highlighted) inputView.addSubview(doneButton) // add Button to UIView doneButton.addTarget(self, action: #selector(UpdateEventViewController.doneButton(_:)), forControlEvents: UIControlEvents.TouchUpInside) // set button click event sender.inputView = inputView datePickerView.addTarget(self, action: #selector(UpdateEventViewController.handleDatePicker(_:)), forControlEvents: UIControlEvents.ValueChanged) handleDatePicker(datePickerView) // Set the date on start. } func doneButton(sender:UIButton) { EventDate.resignFirstResponder() // To resign the inputView on clicking done. } func handleDatePicker(sender: UIDatePicker) { let dateFormatter = NSDateFormatter() dateFormatter.dateFormat = "yyyy-MM-dd" sender.minimumDate = NSDate() EventDate.text = dateFormatter.stringFromDate(sender.date) } func checkDate (ddate: String) -> Bool { let dateFormatter = NSDateFormatter() dateFormatter.dateFormat = "yyyy-MM-dd" let todaysDate:NSDate = NSDate() let dayWothFormat = dateFormatter.stringFromDate(todaysDate) print(dayWothFormat) let date = dateFormatter.dateFromString(dayWothFormat) let date1 = dateFormatter.dateFromString(ddate) if date1!.compare(date!) == NSComparisonResult.OrderedDescending { print("date1 after date2"); return true } else if date1!.compare(date!) == NSComparisonResult.OrderedAscending { return false } else { return true } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBOutlet var scrollView: UIScrollView! func textFieldDidBeginEditing(textField: UITextField) { scrollView.setContentOffset((CGPointMake(0, 150)), animated: true) } func textFieldDidEndEditing(textField: UITextField) { scrollView.setContentOffset((CGPointMake(0, 0)), animated: true) } override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { self.view.endEditing(true) } func textFieldShouldReturn(textField: UITextField) -> Bool { textField.resignFirstResponder() return true } @IBAction func save(sender: AnyObject) { let name = EventName.text! let website = EventWebsite.text! let date = EventDate.text! let dateValidation = checkDate(date) if (EventName.text == "" || EventDate.text == "") { displayMessage("", message: "يرجى إدخال كافة الحقول") } else if(EventDate.text != "" && !dateValidation){ displayMessage("", message: "يرجى إدخال تاريخ الحدث بشكل الصحيح") } else { let alertController = UIAlertController(title: "", message: " هل أنت متأكد من رغبتك بحفظ التغييرات؟", preferredStyle: .Alert) // Create the actions let okAction = UIAlertAction(title: "موافق", style: UIAlertActionStyle.Default) { UIAlertAction in NSLog("OK Pressed") let e : Event = Event() if(Reachability.isConnectedToNetwork()){ e.updateEvent (self.evid,name: name, web: website, date: date, logo: self.EventLogo.backgroundImageForState(.Normal)!){ (flag:Bool) in //we should perform all segues in the main thread dispatch_async(dispatch_get_main_queue()) { print("Heeeeello") self.performSegueWithIdentifier("alertPressedOK", sender:sender) }} } else { self.displayMessage("", message: "الرجاء الاتصال بالانترنت") } // e.updateEvent (self.evid,name: name, web: website, date: date, logo: self.EventLogo.backgroundImageForState(.Normal)!) // self.performSegueWithIdentifier("alertPressedOK", sender:sender) } let cancelAction = UIAlertAction(title: "إلغاء الأمر", style: UIAlertActionStyle.Cancel) { UIAlertAction in NSLog("Cancel Pressed") } //Add the actions alertController.addAction(okAction) alertController.addAction(cancelAction) // Present the controller self.presentViewController(alertController, animated: true, completion: nil) } } @IBAction func deleteEvent(sender: AnyObject) { let alertController = UIAlertController(title: "", message: "هل أنت متأكد من رغبتك بالحذف", preferredStyle: .Alert) // Create the actions let okAction = UIAlertAction(title: "موافق", style: UIAlertActionStyle.Default) { UIAlertAction in NSLog("OK Pressed") let e: Event = Event() e.DeleteEvent(self.evid) self.performSegueWithIdentifier("deleteok", sender:sender) } let cancelAction = UIAlertAction(title: "إلغاء الأمر", style: UIAlertActionStyle.Cancel) { UIAlertAction in NSLog("Cancel Pressed") } // Add the actions alertController.addAction(okAction) alertController.addAction(cancelAction) // Present the controller self.presentViewController(alertController, animated: true, completion: nil) } func displayMessage(title: String, message: String){ let alert = UIAlertController(title:title, message: message, preferredStyle: UIAlertControllerStyle.Alert) alert.addAction(UIAlertAction(title: "موافق", style: .Default, handler: { (action) -> Void in // self.dismissViewControllerAnimated(true, completion: nil) })) self.presentViewController(alert, animated: true, completion: nil) } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) { if (segue.identifier == "alertPressedOK") { print("segue") let detailVC = segue.destinationViewController as! EventDetailsViewController; detailVC.evid = evid detailVC.evname=EventName.text! detailVC.evwebsite=EventWebsite.text! detailVC.evdate=EventDate.text! detailVC.evlogo=self.EventLogo.backgroundImageForState(.Normal) } else if (segue.identifier == "deleteok"){ var window:UIWindow! window = UIWindow(frame: UIScreen.mainScreen().bounds) let containerViewController = ContainerViewController() containerViewController.centerViewController = mainStoryboard().instantiateViewControllerWithIdentifier("eventsMng") as? CenterViewController print(window!.rootViewController) window!.rootViewController = containerViewController print(window!.rootViewController) window!.makeKeyAndVisible() containerViewController.centerViewController.delegate?.collapseSidePanels!() } } func mainStoryboard() -> UIStoryboard { return UIStoryboard(name: "Main", bundle: NSBundle.mainBundle()) } }
mit
fecfe567d5f7fc2df28008224099dccc
35.39726
170
0.61419
5.216986
false
false
false
false
creatubbles/ctb-api-swift
CreatubblesAPIClient/Sources/Model/UserAccountDetails.swift
1
4154
// // UserAccountDetails.swift // CreatubblesAPIClient // // Copyright (c) 2017 Creatubbles Pte. Ltd. // // 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 @objc open class UserAccountDetails: NSObject { open let identifier: String open let username: String open let displayName: String open let email: String? open let role: Role open let birthYear: Int? open let birthMonth: Int? open let ageDisplayType: String open let gender: Gender open let uiLocale: String? open let pendingAvatarUrl: String? open let groupList: Array<String>? open let ownedGroups: Array<String>? open let preapproveComments: Bool open let whatDoYouTeach: String? open let interests: String? open let interestsList: Array<String>? open let managedCreatorsCount: Int open let countryCode: String? open let receiveNotifications: Bool open let receiveNewsletter: Bool open let passwordUpdatedAt: Date? open let currentSignInAt: Date? open let createdAt: Date open let updatedAt: Date open let abilities: Array<Ability> open let requiresGuardianApproval: Bool? open let lastGuardianApprovalEmail: String? open let addedBubblesCount: Int open let addedCommentsCount: Int open let creationsCount: Int open let personalizedAvatarSourceUrl: String? open let credit: Int public init(mapper: UserAccountDetailsMapper, metadata: Metadata?) { identifier = mapper.identifier! username = mapper.username! displayName = mapper.displayName! email = mapper.email role = mapper.role birthYear = mapper.birthYear birthMonth = mapper.birthMonth ageDisplayType = mapper.ageDisplayType! gender = mapper.gender uiLocale = mapper.uiLocale pendingAvatarUrl = mapper.pendingAvatarUrl groupList = mapper.groupList ?? [] ownedGroups = mapper.ownedGroups ?? [] preapproveComments = mapper.preapproveComments! whatDoYouTeach = mapper.whatDoYouTeach interests = mapper.interests interestsList = mapper.interestsList managedCreatorsCount = mapper.managedCreatorsCount! countryCode = mapper.countryCode receiveNotifications = mapper.receiveNotifications! receiveNewsletter = mapper.receiveNewsletter! passwordUpdatedAt = mapper.passwordUpdatedAt as Date? currentSignInAt = mapper.currentSignInAt as Date? createdAt = mapper.createdAt! as Date updatedAt = mapper.updatedAt! as Date addedBubblesCount = mapper.addedBubblesCount ?? 0 addedCommentsCount = mapper.addedCommentsCount ?? 0 creationsCount = mapper.creationsCount ?? 0 personalizedAvatarSourceUrl = mapper.personalizedAvatarSourceUrl credit = mapper.credit ?? 0 abilities = MappingUtils.abilitiesFrom(metadata: metadata, forObjectWithIdentifier: identifier) requiresGuardianApproval = mapper.requiresGuardianApproval lastGuardianApprovalEmail = mapper.lastGuardianApprovalEmail } }
mit
188b8ef2082a50c7bfc16311c71d8fdb
40.128713
103
0.722436
4.736602
false
false
false
false
blstream/mEatUp
mEatUp/mEatUp/LoginViewController.swift
1
4547
// // LoginViewController.swift // mEatUp // // Created by Maciej Plewko on 08.04.2016. // Copyright © 2016 BLStream. All rights reserved. // import UIKit import FBSDKCoreKit import FBSDKLoginKit class LoginViewController: UIViewController { @IBOutlet weak var loginButton: UIButton! let userSettings = UserSettings() override func viewDidLoad() { super.viewDidLoad() //configure loginButton appearance loginButton.layer.cornerRadius = 12 loginButton.backgroundColor = UIColor.loginButtonBackgroundColor() loginButton.layer.borderWidth = 1 loginButton.layer.borderColor = UIColor.loginButtonBorderColor().CGColor loginButton.setTitleColor(UIColor.loginButtonTitleColorNormal(), forState: .Normal) loginButton.setTitleColor(UIColor.loginButtonTitleColorHighlited(), forState: .Highlighted) } override func viewDidAppear(animated: Bool) { super.viewDidAppear(true) if FBSDKAccessToken.currentAccessToken() != nil { requestFacebookUserData() loginButton.hidden = true performSegueWithIdentifier("ShowRoomListSegue", sender: nil) } } @IBAction func loginButtonClicked(sender: UIButton) { FBSDKLoginManager().logInWithReadPermissions(["public_profile"], fromViewController: self, handler: { (result: FBSDKLoginManagerLoginResult!, error: NSError!) -> Void in if (error == nil && result.grantedPermissions != nil){ if(result.grantedPermissions.contains("public_profile")) { self.createUser() } } }) } func requestFacebookUserData() { FBSDKGraphRequest.init(graphPath: "me", parameters: ["fields":"id, first_name, last_name, picture.type(small)"]).startWithCompletionHandler { (connection, result, error) -> Void in if error != nil { } else { self.saveUserDefaults(result) } } } private func saveUserDefaults(fbRequestResult: AnyObject) { if let fbID = (fbRequestResult.objectForKey("id") as? String) { let firstName: String? = (fbRequestResult.objectForKey("first_name") as? String) let lastName: String? = (fbRequestResult.objectForKey("last_name") as? String) let pictureURL: String? = (fbRequestResult.objectForKey("picture")?.objectForKey("data")?.objectForKey("url") as? String) self.userSettings.saveUserDetails(fbID, firstName: firstName, lastName: lastName, pictureURL: pictureURL) } } func createUser() { FBSDKGraphRequest.init(graphPath: "me", parameters: ["fields":"id, first_name, last_name, picture.type(small)"]).startWithCompletionHandler { (connection, result, error) -> Void in if error != nil { } else { if let fbID = (result.objectForKey("id") as? String) { let firstName: String? = (result.objectForKey("first_name") as? String) let lastName: String? = (result.objectForKey("last_name") as? String) let pictureURL: String? = (result.objectForKey("picture")?.objectForKey("data")?.objectForKey("url") as? String) self.userSettings.saveUserDetails(fbID, firstName: firstName, lastName: lastName, pictureURL: pictureURL) let cloud = CloudKitHelper() cloud.loadUserRecordWithFbId(fbID, completionHandler: { user in if user.recordID == nil { let newUser = User() newUser.fbID = fbID newUser.name = firstName newUser.surname = lastName newUser.photo = pictureURL cloud.saveUserRecord(newUser, completionHandler: nil, errorHandler: nil) } }, errorHandler: { error in let newUser = User() newUser.fbID = fbID newUser.name = firstName newUser.surname = lastName newUser.photo = pictureURL cloud.saveUserRecord(newUser, completionHandler: nil, errorHandler: nil) }) } } } } }
apache-2.0
27077209f5d4368796f98aff07b28d2f
42.711538
188
0.576331
5.457383
false
false
false
false
therealbnut/PeekSequence
PeekSequence.swift
1
1243
// // PeekSequence.swift // PeekSequence // // Created by Andrew Bennett on 26/01/2016. // Copyright © 2016 Andrew Bennett. All rights reserved. // public struct PeekSequence<T>: SequenceType { public typealias Generator = AnyGenerator<T> private var _sequence: AnySequence<T> private var _peek: T? public init<S: SequenceType where S.Generator.Element == T>( _ sequence: S ) { _sequence = AnySequence(sequence) _peek = nil } public func generate() -> AnyGenerator<T> { var peek = _peek, generator = _sequence.generate() return anyGenerator { let element = peek ?? generator.next() peek = nil return element } } public func underestimateCount() -> Int { return _peek == nil ? 0 : 1 } public mutating func peek() -> T? { if let element = _peek { return element } _peek = _sequence.generate().next() return _peek } } public func nonEmptySequence<S: SequenceType>(sequence: S) -> AnySequence<S.Generator.Element>? { var sequence = PeekSequence(sequence) if sequence.peek() != nil { return AnySequence(sequence) } else { return nil } }
mit
3b635346ce38d6e3fd94ea592cb93350
24.346939
97
0.594203
4.238908
false
false
false
false
rasmusth/BluetoothKit
Example/Vendor/CryptoSwift/Sources/CryptoSwift/Collection+Extension.swift
1
2717
// // Collection+Extension.swift // CryptoSwift // // Created by Marcin Krzyzanowski on 02/08/16. // Copyright © 2016 Marcin Krzyzanowski. All rights reserved. // extension Collection where Self.Iterator.Element == UInt8, Self.Index == Int { func toUInt32Array() -> Array<UInt32> { var result = Array<UInt32>() result.reserveCapacity(16) for idx in stride(from: self.startIndex, to: self.endIndex, by: MemoryLayout<UInt32>.size) { var val: UInt32 = 0 val |= self.count > 3 ? UInt32(self[idx.advanced(by: 3)]) << 24 : 0 val |= self.count > 2 ? UInt32(self[idx.advanced(by: 2)]) << 16 : 0 val |= self.count > 1 ? UInt32(self[idx.advanced(by: 1)]) << 8 : 0 val |= self.count > 0 ? UInt32(self[idx]) : 0 result.append(val) } return result } func toUInt64Array() -> Array<UInt64> { var result = Array<UInt64>() result.reserveCapacity(32) for idx in stride(from: self.startIndex, to: self.endIndex, by: MemoryLayout<UInt64>.size) { var val:UInt64 = 0 val |= self.count > 7 ? UInt64(self[idx.advanced(by: 7)]) << 56 : 0 val |= self.count > 6 ? UInt64(self[idx.advanced(by: 6)]) << 48 : 0 val |= self.count > 5 ? UInt64(self[idx.advanced(by: 5)]) << 40 : 0 val |= self.count > 4 ? UInt64(self[idx.advanced(by: 4)]) << 32 : 0 val |= self.count > 3 ? UInt64(self[idx.advanced(by: 3)]) << 24 : 0 val |= self.count > 2 ? UInt64(self[idx.advanced(by: 2)]) << 16 : 0 val |= self.count > 1 ? UInt64(self[idx.advanced(by: 1)]) << 8 : 0 val |= self.count > 0 ? UInt64(self[idx.advanced(by: 0)]) << 0 : 0 result.append(val) } return result } /// Initialize integer from array of bytes. Caution: may be slow! @available(*, deprecated: 0.6.0, message: "Dont use it. Too generic to be fast") func toInteger<T:Integer>() -> T where T: ByteConvertible, T: BitshiftOperationsType { if self.count == 0 { return 0; } let size = MemoryLayout<T>.size var bytes = self.reversed() //FIXME: check it this is equivalent of Array(...) if bytes.count < size { let paddingCount = size - bytes.count if (paddingCount > 0) { bytes += Array<UInt8>(repeating: 0, count: paddingCount) } } if size == 1 { return T(truncatingBitPattern: UInt64(bytes[0])) } var result: T = 0 for byte in bytes.reversed() { result = result << 8 | T(byte) } return result } }
mit
0f5a2e45814202f3cfef21cf224e5cd9
37.8
100
0.546392
3.67027
false
false
false
false
julienbodet/wikipedia-ios
WMF Framework/ColumarCollectionViewLayoutSection.swift
1
9196
class ColumnarCollectionViewLayoutSection { private class ColumnarCollectionViewLayoutColumn { var frame: CGRect init(frame: CGRect) { self.frame = frame } func addItem(_ attributes: ColumnarCollectionViewLayoutAttributes) { frame.size.height += attributes.frame.height } var widthForNextItem: CGFloat { return frame.width } var originForNextItem: CGPoint { return CGPoint(x: frame.minX, y: frame.maxY) } func addSpace(_ space: CGFloat) { frame.size.height += space } } let sectionIndex: Int var frame: CGRect = .zero let metrics: ColumnarCollectionViewLayoutMetrics var headers: [ColumnarCollectionViewLayoutAttributes] = [] var items: [ColumnarCollectionViewLayoutAttributes] = [] var footers: [ColumnarCollectionViewLayoutAttributes] = [] private let columns: [ColumnarCollectionViewLayoutColumn] private var columnIndexByItemIndex: [Int: Int] = [:] private var shortestColumnIndex: Int = 0 init(sectionIndex: Int, frame: CGRect, metrics: ColumnarCollectionViewLayoutMetrics, countOfItems: Int) { let countOfColumns = metrics.countOfColumns let columnSpacing = metrics.interColumnSpacing let columnWidth: CGFloat = floor((frame.size.width - (columnSpacing * CGFloat(countOfColumns - 1))) / CGFloat(countOfColumns)) var columns: [ColumnarCollectionViewLayoutColumn] = [] columns.reserveCapacity(countOfColumns) var x: CGFloat = frame.origin.x for _ in 0..<countOfColumns { columns.append(ColumnarCollectionViewLayoutColumn(frame: CGRect(x: x, y: frame.origin.y, width: columnWidth, height: 0))) x += columnWidth + columnSpacing } self.columns = columns self.frame = frame self.sectionIndex = sectionIndex self.metrics = metrics items.reserveCapacity(countOfItems) } private func columnForItem(at itemIndex: Int) -> ColumnarCollectionViewLayoutColumn? { guard let columnIndex = columnIndexByItemIndex[itemIndex] else { return nil } return columns[columnIndex] } private var columnForNextItem: ColumnarCollectionViewLayoutColumn { let itemIndex = items.count let columnIndex = shortestColumnIndex columnIndexByItemIndex[itemIndex] = columnIndex return columns[columnIndex] } var widthForNextItem: CGFloat { return columnForNextItem.widthForNextItem } var widthForNextSupplementaryView: CGFloat { return frame.size.width } var originForNextSupplementaryView: CGPoint { return CGPoint(x: frame.minX, y: frame.minY) } var originForNextItem: CGPoint { return columnForNextItem.originForNextItem } var widthForSupplementaryViews: CGFloat { return frame.width } func addHeader(_ attributes: ColumnarCollectionViewLayoutAttributes) { headers.append(attributes) frame.size.height += attributes.frame.size.height for column in columns { column.addSpace(attributes.frame.size.height) } } func addItem(_ attributes: ColumnarCollectionViewLayoutAttributes) { let column = columnForNextItem if metrics.interItemSpacing > 0 && items.count >= columns.count { column.addSpace(metrics.interItemSpacing) } column.addItem(attributes) items.append(attributes) if column.frame.height > frame.height { frame.size.height = column.frame.height } updateShortestColumnIndex() } func updateShortestColumnIndex() { guard columns.count > 1 else { return } var minHeight: CGFloat = CGFloat.greatestFiniteMagnitude for (index, column) in columns.enumerated() { guard column.frame.height < minHeight else { continue } minHeight = column.frame.height shortestColumnIndex = index } } func addFooter(_ attributes: ColumnarCollectionViewLayoutAttributes) { footers.append(attributes) frame.size.height += attributes.frame.size.height } func updateAttributes(at index: Int, in array: [ColumnarCollectionViewLayoutAttributes], with attributes: ColumnarCollectionViewLayoutAttributes) -> CGFloat { guard index < array.count else { return 0 } let oldAttributes = array[index] oldAttributes.frame = attributes.frame return attributes.frame.height - oldAttributes.frame.height } func translateAttributesBy(_ deltaY: CGFloat, at index: Int, in array: [ColumnarCollectionViewLayoutAttributes]) -> [IndexPath] { guard !deltaY.isEqual(to: 0), index < array.count else { return [] } var invalidatedIndexPaths: [IndexPath] = [] for (index, attributes) in array[index..<array.count].enumerated() { attributes.frame.origin.y += deltaY invalidatedIndexPaths.append(IndexPath(item: index, section: sectionIndex)) } return invalidatedIndexPaths } func invalidate(_ originalAttributes: ColumnarCollectionViewLayoutAttributes, with attributes: ColumnarCollectionViewLayoutAttributes) -> ColumnarCollectionViewLayoutSectionInvalidationResults { let index = originalAttributes.indexPath.item switch originalAttributes.representedElementCategory { case UICollectionElementCategory.cell: var invalidatedItemIndexPaths: [IndexPath] = [] let deltaY = updateAttributes(at: index, in: items, with: attributes) guard let column = columnForItem(at: index) else { return ColumnarCollectionViewLayoutSectionInvalidationResults.empty } column.frame.size.height += deltaY if column.frame.height > frame.height { frame.size.height = column.frame.height } var affectedIndex = index + columns.count // next item in the column while affectedIndex < items.count { items[affectedIndex].frame.origin.y += deltaY invalidatedItemIndexPaths.append(IndexPath(item: affectedIndex, section: sectionIndex)) affectedIndex += columns.count } updateShortestColumnIndex() let invalidatedFooterIndexPaths = translateAttributesBy(deltaY, at: 0, in: footers) return ColumnarCollectionViewLayoutSectionInvalidationResults(invalidatedHeaderIndexPaths: [], invalidatedItemIndexPaths: invalidatedItemIndexPaths, invalidatedFooterIndexPaths: invalidatedFooterIndexPaths) case UICollectionElementCategory.decorationView: return ColumnarCollectionViewLayoutSectionInvalidationResults.empty case UICollectionElementCategory.supplementaryView: switch originalAttributes.representedElementKind { case UICollectionElementKindSectionHeader: let deltaY = updateAttributes(at: index, in: headers, with: attributes) frame.size.height += deltaY let invalidatedHeaderIndexPaths = translateAttributesBy(deltaY, at: index + 1, in: items) let invalidatedItemIndexPaths = translateAttributesBy(deltaY, at: 0, in: items) let invalidatedFooterIndexPaths = translateAttributesBy(deltaY, at: 0, in: footers) return ColumnarCollectionViewLayoutSectionInvalidationResults(invalidatedHeaderIndexPaths: invalidatedHeaderIndexPaths, invalidatedItemIndexPaths: invalidatedItemIndexPaths, invalidatedFooterIndexPaths: invalidatedFooterIndexPaths) case UICollectionElementKindSectionFooter: let deltaY = updateAttributes(at: index, in: footers, with: attributes) frame.size.height += deltaY let invalidatedFooterIndexPaths = translateAttributesBy(deltaY, at: index + 1, in: footers) return ColumnarCollectionViewLayoutSectionInvalidationResults(invalidatedHeaderIndexPaths: [], invalidatedItemIndexPaths: [], invalidatedFooterIndexPaths: invalidatedFooterIndexPaths) default: return ColumnarCollectionViewLayoutSectionInvalidationResults.empty } } } func translate(deltaY: CGFloat) -> ColumnarCollectionViewLayoutSectionInvalidationResults { let invalidatedHeaderIndexPaths = translateAttributesBy(deltaY, at: 0, in: headers) let invalidatedItemIndexPaths = translateAttributesBy(deltaY, at: 0, in: items) let invalidatedFooterIndexPaths = translateAttributesBy(deltaY, at: 0, in: footers) frame.origin.y += deltaY return ColumnarCollectionViewLayoutSectionInvalidationResults(invalidatedHeaderIndexPaths: invalidatedHeaderIndexPaths, invalidatedItemIndexPaths: invalidatedItemIndexPaths, invalidatedFooterIndexPaths: invalidatedFooterIndexPaths) } }
mit
3d81687cf6a02e7d8068f21e36a934f8
44.524752
247
0.677033
5.580097
false
false
false
false
FilipLukac/makac
SidebarMenu/DetailViewController.swift
1
3665
// // ActivityViewController.swift // Makac // // Created by Filip Lukac on 13/12/15. // Copyright © 2015 Hardsun. All rights reserved. // import UIKit import Social class DetailViewController: UIViewController { @IBOutlet weak var detailDescriptionLabel: UILabel! @IBOutlet weak var durationLabel: UILabel! @IBOutlet weak var distanceLabel: UILabel! @IBAction func shareTwitter(sender: UIButton) { if SLComposeViewController.isAvailableForServiceType(SLServiceTypeTwitter){ let twitterSheet:SLComposeViewController = SLComposeViewController(forServiceType: SLServiceTypeTwitter) if let detail = self.detailItem { let name = detail["name"] as! String let distance = detail["distance"] as! String let duration = detail["duration"] as! String let string = "[" + name + "] I ran " + distance + " and my time was " + duration; twitterSheet.setInitialText(string) self.presentViewController(twitterSheet, animated: true, completion: nil) } } else { let alert = UIAlertController(title: "Accounts", message: "Please login to a Twitter account to share.", preferredStyle: UIAlertControllerStyle.Alert) alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil)) self.presentViewController(alert, animated: true, completion: nil) } } @IBAction func shareFacebook(sender: UIButton) { if SLComposeViewController.isAvailableForServiceType(SLServiceTypeFacebook){ let facebookSheet:SLComposeViewController = SLComposeViewController(forServiceType: SLServiceTypeFacebook) if let detail = self.detailItem { let name = detail["name"] as! String let distance = detail["distance"] as! String let duration = detail["duration"] as! String let string = "[" + name + "] I ran " + distance + " and my time was " + duration; facebookSheet.setInitialText(string) self.presentViewController(facebookSheet, animated: true, completion: nil) } } else { let alert = UIAlertController(title: "Accounts", message: "Please login to a Facebook account to share.", preferredStyle: UIAlertControllerStyle.Alert) alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil)) self.presentViewController(alert, animated: true, completion: nil) } } var detailItem: AnyObject? { didSet { self.configureView() } } func configureView() { // Update the user interface for the detail item. if let detail = self.detailItem { let name = detail["name"] as! String let distance = detail["distance"] as! String let duration = detail["duration"] as! String self.title = name self.detailDescriptionLabel?.text = name self.durationLabel?.text = duration self.distanceLabel?.text = distance } } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. self.configureView() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
f9027e680e1b32a3088fa081f955fe17
37.989362
163
0.611354
5.509774
false
false
false
false
Skrapit/ALCameraViewController
ALCameraViewController/ViewController/PhotoLibraryViewController.swift
1
5112
// // ALImagePickerViewController.swift // ALImagePickerViewController // // Created by Alex Littlejohn on 2015/06/09. // Copyright (c) 2015 zero. All rights reserved. // import UIKit import Photos internal let ImageCellIdentifier = "ImageCell" internal let defaultItemSpacing: CGFloat = 1 public typealias PhotoLibraryViewSelectionComplete = (PHAsset?) -> Void public class PhotoLibraryViewController: UIViewController { internal var assets: PHFetchResult<PHAsset>? = nil public var onSelectionComplete: PhotoLibraryViewSelectionComplete? lazy var backBarButtonItem: UIBarButtonItem = { let buttonImage = UIImage(named: "nav_back", in: CameraGlobals.shared.bundle, compatibleWith: nil) var item = UIBarButtonItem(image: buttonImage, style: .plain, target: self, action: #selector(dismissLibrary)) return item }() private lazy var collectionView: UICollectionView = { let layout = UICollectionViewFlowLayout() layout.itemSize = CameraGlobals.shared.photoLibraryThumbnailSize layout.minimumInteritemSpacing = defaultItemSpacing layout.minimumLineSpacing = defaultItemSpacing layout.sectionInset = UIEdgeInsets.zero let collectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: layout) collectionView.translatesAutoresizingMaskIntoConstraints = false collectionView.backgroundColor = UIColor.clear return collectionView }() public override func viewDidLoad() { super.viewDidLoad() setNeedsStatusBarAppearanceUpdate() self.title = localizedString("libray.title") navigationItem.leftBarButtonItem = self.backBarButtonItem view.backgroundColor = #colorLiteral(red: 0.9450980392, green: 0.9490196078, blue: 0.9647058824, alpha: 1) view.addSubview(collectionView) _ = ImageFetcher() .onFailure(onFailure) .onSuccess(onSuccess) .fetch() } public override func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() collectionView.frame = view.bounds } public override var preferredStatusBarStyle: UIStatusBarStyle { return UIStatusBarStyle.lightContent } public func present(_ inViewController: UIViewController, animated: Bool) { let navigationController = UINavigationController(rootViewController: self) navigationController.navigationBar.barTintColor = UIColor.black navigationController.navigationBar.tintColor = UIColor.black navigationController.navigationBar.barStyle = UIBarStyle.black navigationController.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.black] inViewController.present(navigationController, animated: animated, completion: nil) } public func dismissLibrary() { // onSelectionComplete?(nil) self.navigationController?.popViewController(animated: true) } private func onSuccess(_ photos: PHFetchResult<PHAsset>) { assets = photos configureCollectionView() } private func onFailure(_ error: NSError) { let permissionsView = PermissionsView(frame: view.bounds) permissionsView.titleLabel.text = localizedString("permissions.library.title") permissionsView.descriptionLabel.text = localizedString("permissions.library.description") view.addSubview(permissionsView) } private func configureCollectionView() { collectionView.register(ImageCell.self, forCellWithReuseIdentifier: ImageCellIdentifier) collectionView.delegate = self collectionView.dataSource = self } internal func itemAtIndexPath(_ indexPath: IndexPath) -> PHAsset? { return assets?[(indexPath as NSIndexPath).row] } } // MARK: - UICollectionViewDataSource - extension PhotoLibraryViewController : UICollectionViewDataSource { public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return assets?.count ?? 0 } @objc(collectionView:willDisplayCell:forItemAtIndexPath:) public func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) { if cell is ImageCell { if let model = itemAtIndexPath(indexPath) { (cell as! ImageCell).configureWithModel(model) } } } public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { return collectionView.dequeueReusableCell(withReuseIdentifier: ImageCellIdentifier, for: indexPath) } } // MARK: - UICollectionViewDelegate - extension PhotoLibraryViewController : UICollectionViewDelegateFlowLayout { public func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { onSelectionComplete?(itemAtIndexPath(indexPath)) } }
mit
df3b2fa746aa476edf186860f7bebbbc
37.43609
198
0.713615
6.007051
false
false
false
false
mapsme/omim
iphone/Maps/Core/Theme/Renderers/UITableViewRenderer.swift
5
811
extension UITableView { @objc override func applyTheme() { if styleName.isEmpty { styleName = "TableView" } for style in StyleManager.shared.getStyle(styleName) where !style.isEmpty && !style.hasExclusion(view: self) { UITableViewRenderer.render(self, style: style) } } } class UITableViewRenderer: UIViewRenderer { class func render(_ control: UITableView, style: Style) { super.render(control, style: style) if let backgroundColor = style.backgroundColor { control.backgroundView = UIImageView(image: backgroundColor.getImage()) } if let separatorColor = style.separatorColor { control.separatorColor = separatorColor } UIViewRenderer.renderBorder(control, style: style) UIViewRenderer.renderShadow(control, style: style) } }
apache-2.0
b90fd8f01d715d7510cdd07fd8cbe218
31.44
77
0.710234
4.480663
false
false
false
false
knehez/edx-app-ios
Source/NetworkManager.swift
2
9018
// // CourseOutline.swift // edX // // Created by Jake Lim on 5/09/15. // Copyright (c) 2015 edX. All rights reserved. // import Foundation public enum HTTPMethod: String { case GET = "GET" case POST = "POST" case PUT = "PUT" case DELETE = "DELETE" case PATCH = "PATCH" } public enum RequestBody { case JSONBody(JSON) case DataBody(data : NSData, contentType : String) case EmptyBody } public struct NetworkRequest<Out> { let method : HTTPMethod let path : String // Absolute URL or URL relative to the API base let requiresAuth : Bool let body : RequestBody let query: [String:JSON] let deserializer : (NSHTTPURLResponse?, NSData?) -> Result<Out> public init(method : HTTPMethod, path : String, requiresAuth : Bool = false, body : RequestBody = .EmptyBody, query : [String:JSON] = [:], deserializer : (NSHTTPURLResponse?, NSData?) -> Result<Out>) { self.method = method self.path = path self.requiresAuth = requiresAuth self.body = body self.query = query self.deserializer = deserializer } } public struct NetworkResult<Out> { public let request: NSURLRequest? public let response: NSHTTPURLResponse? public let data: Out? public let baseData : NSData? public let error: NSError? public init(request : NSURLRequest?, response : NSHTTPURLResponse?, data : Out?, baseData : NSData?, error : NSError?) { self.request = request self.response = response self.data = data self.error = error self.baseData = baseData } } public class NetworkTask : Removable { let request : Request private init(request : Request) { self.request = request } public func remove() { request.cancel() } } @objc public protocol AuthorizationHeaderProvider { var authorizationHeaders : [String:String] { get } } public class NetworkManager : NSObject { private let authorizationHeaderProvider: AuthorizationHeaderProvider? private let baseURL : NSURL private let cache : ResponseCache public init(authorizationHeaderProvider: AuthorizationHeaderProvider? = nil, baseURL : NSURL, cache : ResponseCache) { self.authorizationHeaderProvider = authorizationHeaderProvider self.baseURL = baseURL self.cache = cache } public func URLRequestWithRequest<Out>(request : NetworkRequest<Out>) -> Result<NSURLRequest> { return NSURL(string: request.path, relativeToURL: baseURL).toResult().flatMap { url -> Result<NSURLRequest> in let URLRequest = NSURLRequest(URL: url) if request.query.count == 0 { return Success(URLRequest) } var queryParams : [String:String] = [:] for (key, value) in request.query { value.rawString(options : NSJSONWritingOptions()).map {stringValue -> Void in queryParams[key] = stringValue } } // Alamofire has a kind of contorted API where you can encode parameters over URLs // or through the POST body, but you can't do both at the same time. // // So first we encode the get parameters let (paramRequest, error) = ParameterEncoding.URL.encode(URLRequest, parameters: queryParams) if let error = error { return Failure(error) } else { return Success(paramRequest) } } .flatMap { URLRequest in let mutableURLRequest = URLRequest.mutableCopy() as! NSMutableURLRequest if request.requiresAuth { for (key, value) in self.authorizationHeaderProvider?.authorizationHeaders ?? [:] { mutableURLRequest.setValue(value, forHTTPHeaderField: key) } } mutableURLRequest.HTTPMethod = request.method.rawValue // Now we encode the body switch request.body { case .EmptyBody: return Success(mutableURLRequest) case let .DataBody(data: data, contentType: contentType): mutableURLRequest.HTTPBody = data mutableURLRequest.setValue(contentType, forHTTPHeaderField: "Content-Type") return Success(mutableURLRequest) case let .JSONBody(json): let (bodyRequest, error) = ParameterEncoding.JSON.encode(mutableURLRequest, parameters: json.dictionaryObject ?? [:]) if let error = error { return Failure(error) } else { return Success(bodyRequest) } } } } public func taskForRequest<Out>(request : NetworkRequest<Out>, handler: NetworkResult<Out> -> Void) -> Removable { #if DEBUG // Don't let network requests happen when testing if NSClassFromString("XCTestCase") != nil { dispatch_async(dispatch_get_main_queue()) { handler(NetworkResult(request: nil, response: nil, data: nil, baseData: nil, error: NSError.oex_courseContentLoadError())) } return BlockRemovable {} } #endif let URLRequest = URLRequestWithRequest(request) let task = URLRequest.map {URLRequest -> NetworkTask in let task = Manager.sharedInstance.request(URLRequest) let serializer = { (URLRequest : NSURLRequest, response : NSHTTPURLResponse?, data : NSData?) -> (AnyObject?, NSError?) in let result = request.deserializer(response, data) return (Box((value : result.value, original : data)), result.error) } task.response(serializer: serializer) { (request, response, object, error) in let parsed = (object as? Box<(value : Out?, original : NSData?)>)?.value let result = NetworkResult<Out>(request: request, response: response, data: parsed?.value, baseData: parsed?.original, error: error) handler(result) } task.resume() return NetworkTask(request: task) } switch task { case let .Success(t): return t.value case let .Failure(error): dispatch_async(dispatch_get_main_queue()) { handler(NetworkResult(request: nil, response: nil, data: nil, baseData : nil, error: error)) } return BlockRemovable {} } } private func combineWithPersistentCacheFetch<Out>(stream : Stream<Out>, request : NetworkRequest<Out>) -> Stream<Out> { if let URLRequest = URLRequestWithRequest(request).value { let cacheStream = Sink<Out>() cache.fetchCacheEntryWithRequest(URLRequest, completion: {(entry : ResponseCacheEntry?) -> Void in if let entry = entry { dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), {[weak cacheStream] in let result = request.deserializer(entry.response, entry.data) dispatch_async(dispatch_get_main_queue()) {[weak cacheStream] in cacheStream?.close() cacheStream?.send(result) } }) } else { cacheStream.close() } }) return stream.cachedByStream(cacheStream) } else { return stream } } public func streamForRequest<Out>(request : NetworkRequest<Out>, persistResponse : Bool = false, autoCancel : Bool = true) -> Stream<Out> { let stream = Sink<NetworkResult<Out>>() let task = self.taskForRequest(request) {[weak stream, weak self] result in if let response = result.response, request = result.request where persistResponse { self?.cache.setCacheResponse(response, withData: result.baseData, forRequest: request, completion: nil) } stream?.close() stream?.send(result) } var result : Stream<Out> = stream.flatMap {[weak self] (result : NetworkResult<Out>) -> Result<Out> in if let data = result.data { return Success(data) } else { return Failure(result.error) } } if persistResponse { result = combineWithPersistentCacheFetch(result, request: request) } if autoCancel { result = result.autoCancel(task) } return result } }
apache-2.0
96d2e578aba77a0a954b9fd7a57657dc
36.111111
148
0.5723
5.203693
false
false
false
false
llb1119/LB_OCR
LB_OCR/Error.swift
1
1943
// // Error.swift // Pods // // Created by liulibo on 16/7/21. // // import Foundation /// The `Error` struct provides a convenience for creating custom LLBOCREngine NSErrors. public struct Error { /// The domain used for creating all LLBOCREngine errors. public static let Domain = "com.LB_OCR.error" /// The custom error codes generated by LLBOCREngine. public enum Code: Int { case InitEngineFailed = -6000 case RecogniseFailed = -6001 } /** Creates an `NSError` with the given error code and failure reason. - parameter code: The error code. - parameter failureReason: The failure reason. - returns: An `NSError` with the given error code and failure reason. */ public static func errorWithCode(code: Code, failureReason: String) -> NSError { return errorWithCode(code.rawValue, failureReason: failureReason) } /** Creates an `NSError` with the given error code and failure reason. - parameter code: The error code. - parameter failureReason: The failure reason. - returns: An `NSError` with the given error code and failure reason. */ public static func errorWithCode(code: Int, failureReason: String) -> NSError { let userInfo = [NSLocalizedFailureReasonErrorKey: failureReason] return NSError(domain: Domain, code: code, userInfo: userInfo) } static func error(domain domain: String = Error.Domain, code: Code, failureReason: String) -> NSError { return error(domain: domain, code: code.rawValue, failureReason: failureReason) } static func error(domain domain: String = Error.Domain, code: Int, failureReason: String) -> NSError { let userInfo = [NSLocalizedFailureReasonErrorKey: failureReason] return NSError(domain: domain, code: code, userInfo: userInfo) } }
mit
7b8f691854fce3304bc4f77a06f70a2e
33.714286
107
0.656716
4.681928
false
false
false
false
jindulys/Leetcode_Solutions_Swift
Sources/Tree/102_BinaryTreeLevelOrderTraversal.swift
1
1092
// // 102_BinaryTreeLevelOrderTraversal.swift // HRSwift // // Created by yansong li on 2016-08-04. // Copyright © 2016 yansong li. All rights reserved. // import Foundation /** Swift Knowledge: Queue, Array Algorithem Knowledge: BFS */ /** 102. Binary Tree Level Order Traversal https://leetcode.com/problems/binary-tree-level-order-traversal/ */ class BinaryTreeLevelOrderTraversal_Solution { func levelOrder(_ root: TreeNode?) -> [[Int]] { guard let node = root else { return [] } var result: [[Int]] = [] var queue = Queue<(TreeNode, Int)>() queue.enqueue((node, 0)) while !queue.isEmpty() { let (currentNode, currentLevel) = queue.dequeue()! if currentLevel >= result.count { result.append([]) } result[currentLevel].append(currentNode.val) if let left = currentNode.left { queue.enqueue((left, currentLevel + 1)) } if let right = currentNode.right { queue.enqueue((right, currentLevel + 1)) } } return result } }
mit
df41f059e1bbf2a8fca4c16966d65bab
21.265306
66
0.604033
3.967273
false
false
false
false
jindulys/Leetcode_Solutions_Swift
Sources/Array/48_RotateImage.swift
1
920
// // 48_RotateImage.swift // LeetcodeSwift // // Created by yansong li on 2016-09-07. // Copyright © 2016 YANSONG LI. All rights reserved. // import Foundation /** * Transpose Flip * 1 2 3 1 4 7 7 4 1 * 4 5 6 ----------> 2 5 8 ----------> 8 5 2 * 7 8 9 3 6 9 9 6 3 */ /** Title:48 Rotate Image URL: https://leetcode.com/problems/rotate-image/ Space: O(1) Time: O(n^2) */ class RotateImage_Solution { func rotate(_ matrix: inout [[Int]]) { for i in 0..<matrix.count { for j in i..<matrix.count { let tmp = matrix[i][j] matrix[i][j] = matrix[j][i] matrix[j][i] = tmp } } for i in 0..<matrix.count { for j in 0..<matrix.count/2 { let tmp = matrix[i][j] matrix[i][j] = matrix[i][matrix.count - 1 - j] matrix[i][matrix.count - 1 - j] = tmp } } } }
mit
b1a7f35ef35ea73b688e623f470b5c52
20.880952
54
0.490751
3.023026
false
false
false
false
qualaroo/QualarooSDKiOS
Qualaroo/Survey/Body/Question/QuestionViewFactory.swift
1
6898
// // QuestionViewFactory.swift // Qualaroo // // Copyright (c) 2018, Qualaroo, Inc. All Rights Reserved. // // Please refer to the LICENSE.md file for the terms and conditions // under which redistribution and use of this file is permitted. // import Foundation class QuestionViewFactory { let buttonHandler: SurveyButtonHandler let answerHandler: SurveyAnswerHandler let theme: Theme init(buttonHandler: SurveyButtonHandler, answerHandler: SurveyAnswerHandler, theme: Theme) { self.buttonHandler = buttonHandler self.answerHandler = answerHandler self.theme = theme } func createView(with question: Question) -> UIView? { var view: UIView? switch question.type { case .nps: view = npsQuestionView(with: question) case .text: view = textQuestionView(with: question) case .dropdown: view = dropdownQuestionView(with: question) case .binary: view = binaryQuestionView(with: question) case .radio: view = radioQuestionView(with: question) case .checkbox: view = checkboxQuestionView(with: question) case .unknown: view = nil } view?.translatesAutoresizingMaskIntoConstraints = false return view } private func npsQuestionView(with question: Question) -> AnswerNpsView? { guard let nib = Bundle.qualaroo()?.loadNibNamed("AnswerNpsView", owner: nil, options: nil), let view = nib.first as? AnswerNpsView else { return nil } let responseBuilder = SingleSelectionAnswerResponseBuilder(question: question) let validator = AnswerNpsValidator(question: question) let interactor = AnswerNpsInteractor(responseBuilder: responseBuilder, validator: validator, buttonHandler: buttonHandler, answerHandler: answerHandler, question: question) view.setupView(backgroundColor: theme.colors.background, minText: question.npsMinText ?? "", maxText: question.npsMaxText ?? "", textColor: theme.colors.text, npsColor: theme.colors.uiSelected, interactor: interactor) return view } private func textQuestionView(with question: Question) -> AnswerTextView? { guard let nib = Bundle.qualaroo()?.loadNibNamed("AnswerTextView", owner: nil, options: nil), let view = nib.first as? AnswerTextView else { return nil } let responseBuilder = AnswerTextResponseBuilder(question: question) let validator = AnswerTextValidator(question: question) let interactor = AnswerTextInteractor(responseBuilder: responseBuilder, validator: validator, buttonHandler: buttonHandler, answerHandler: answerHandler) view.setupView(backgroundColor: theme.colors.background, activeTextBorderColor: theme.colors.uiSelected, inactiveTextBorderColor: theme.colors.uiNormal, keyboardStyle: theme.keyboardStyle, interactor: interactor) return view } private func dropdownQuestionView(with question: Question) -> AnswerDropdownView? { guard let nib = Bundle.qualaroo()?.loadNibNamed("AnswerDropdownView", owner: nil, options: nil), let view = nib.first as? AnswerDropdownView else { return nil } let answers = question.answerList.map { $0.title } let responseBuilder = SingleSelectionAnswerResponseBuilder(question: question) let interactor = AnswerDropdownInteractor(responseBuilder: responseBuilder, buttonHandler: buttonHandler, answerHandler: answerHandler, question: question) view.setupView(backgroundColor: theme.colors.background, answers: answers, textColor: theme.colors.text, interactor: interactor) return view } private func binaryQuestionView(with question: Question) -> AnswerBinaryView? { guard let nib = Bundle.qualaroo()?.loadNibNamed("AnswerBinaryView", owner: nil, options: nil), let view = nib.first as? AnswerBinaryView else { return nil } let responseBuilder = SingleSelectionAnswerResponseBuilder(question: question) let interactor = AnswerBinaryInteractor(responseBuilder: responseBuilder, answerHandler: answerHandler) view.setupView(backgroundColor: theme.colors.background, buttonTextColor: theme.colors.buttonTextEnabled, buttonBackgroundColor: theme.colors.buttonEnabled, leftTitle: question.answerList[0].title, rightTitle: question.answerList[1].title, interactor: interactor) return view } private func radioQuestionView(with question: Question) -> AnswerListView? { guard let onImage = UIImage(named: "radio_button_on", in: Bundle.qualaroo(), compatibleWith: nil), let offImage = UIImage(named: "radio_button_off", in: Bundle.qualaroo(), compatibleWith: nil) else { return nil } return AnswerListView.Builder(question: question, buttonHandler: buttonHandler, answerHandler: answerHandler, selecter: AnswerRadioSelecter(), theme: theme, onImage: onImage, offImage: offImage).build() } private func checkboxQuestionView(with question: Question) -> AnswerListView? { guard let onImage = UIImage(named: "checkbox_button_on", in: Bundle.qualaroo(), compatibleWith: nil), let offImage = UIImage(named: "checkbox_button_off", in: Bundle.qualaroo(), compatibleWith: nil) else { return nil } guard let maxAnswersCount = question.maxAnswersCount else { return nil } return AnswerListView.Builder(question: question, buttonHandler: buttonHandler, answerHandler: answerHandler, selecter: AnswerCheckboxSelecter(maxAnswersCount: maxAnswersCount), theme: theme, onImage: onImage, offImage: offImage).build() } }
mit
ddaad3568911c4fab39db415086128de
44.084967
101
0.591766
5.444357
false
false
false
false
JadenGeller/Erratic
Sources/RepeatingRandomGenerator.swift
1
851
// // RepeatingRandomGenerator.swift // Erratic // // Created by Jaden Geller on 1/11/16. // Copyright © 2016 Jaden Geller. All rights reserved. // #if os(Linux) import Glibc #else import Darwin.C #endif public struct RepeatingRandomGenerator<Source: CollectionType where Source.Index.Distance == Int>: SequenceType, GeneratorType { private let source: Source public init(fromSource source: Source) { precondition(source.count <= Int(UInt32.max), "Source is too large.") self.source = source } public func next() -> Source.Generator.Element? { #if os(Linux) let distance = Int(random() % source.count) #else let distance = Int(arc4random_uniform(UInt32(source.count))) #endif return source[source.startIndex.advancedBy(distance)] } }
mit
5871e0bd624f681db3926d364f325a5b
26.419355
128
0.651765
4.028436
false
false
false
false
Bouke/HAP
Sources/HAP/Base/Predefined/Services/Service.WindowCovering.swift
1
2354
import Foundation extension Service { open class WindowCovering: Service { public init(characteristics: [AnyCharacteristic] = []) { var unwrapped = characteristics.map { $0.wrapped } currentPosition = getOrCreateAppend( type: .currentPosition, characteristics: &unwrapped, generator: { PredefinedCharacteristic.currentPosition() }) positionState = getOrCreateAppend( type: .positionState, characteristics: &unwrapped, generator: { PredefinedCharacteristic.positionState() }) targetPosition = getOrCreateAppend( type: .targetPosition, characteristics: &unwrapped, generator: { PredefinedCharacteristic.targetPosition() }) currentHorizontalTiltAngle = get(type: .currentHorizontalTiltAngle, characteristics: unwrapped) targetHorizontalTiltAngle = get(type: .targetHorizontalTiltAngle, characteristics: unwrapped) name = get(type: .name, characteristics: unwrapped) obstructionDetected = get(type: .obstructionDetected, characteristics: unwrapped) holdPosition = get(type: .holdPosition, characteristics: unwrapped) currentVerticalTiltAngle = get(type: .currentVerticalTiltAngle, characteristics: unwrapped) targetVerticalTiltAngle = get(type: .targetVerticalTiltAngle, characteristics: unwrapped) super.init(type: .windowCovering, characteristics: unwrapped) } // MARK: - Required Characteristics public let currentPosition: GenericCharacteristic<UInt8> public let positionState: GenericCharacteristic<Enums.PositionState> public let targetPosition: GenericCharacteristic<UInt8> // MARK: - Optional Characteristics public let currentHorizontalTiltAngle: GenericCharacteristic<Int>? public let targetHorizontalTiltAngle: GenericCharacteristic<Int>? public let name: GenericCharacteristic<String>? public let obstructionDetected: GenericCharacteristic<Bool>? public let holdPosition: GenericCharacteristic<Bool?>? public let currentVerticalTiltAngle: GenericCharacteristic<Int>? public let targetVerticalTiltAngle: GenericCharacteristic<Int>? } }
mit
2e6ab03000c8f5472cc3931573e6ea3f
53.744186
107
0.687766
5.899749
false
false
false
false
kaunteya/Linex
LinexTests/TestPad.swift
1
729
//----------------------------------- let name = "Kaunteya" let age = 23 let height = 6.3 //----------------------------------- let name = "Kaunteya" //Age of Person let age: Int = 23 let height: Double = 6.3 //----------------------------------- let name: String = "Kaunteya" let age: Int = 23 let height: Double = 6.3 //----------------------------------- let name: String = "Kaunteya" let age : Int = 23 //Height let height: Double = 6.3 //----------------------------------- let name: String = "Kaunteya" let age : Int = 23 let height: Double = 6.3 //-------------New Line added for alignment-------------- let age: Int = 23 let height: Double = 6.3 let name: String = "Kaunteya"
mit
b8e0620cbbc6b8950fb7a1c1930e587b
19.828571
57
0.430727
3.608911
false
false
false
false
diwu/LeetCode-Solutions-in-Swift
Solutions/Solutions/Easy/Easy_101_Symmetric_Tree.swift
1
1679
/* https://leetcode.com/problems/symmetric-tree/ #101 Symmetric Tree Level: easy Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center). For example, this binary tree is symmetric: 1 / \ 2 2 / \ / \ 3 4 4 3 But the following is not: 1 / \ 2 2 \ \ 3 3 Inspired by [@xuanaux](https://leetcode.com/discuss/456/recusive-solution-symmetric-optimal-solution-inordertraversal) */ import Foundation class Easy_101_Symmetric_Tree { class Node { var left: Node? var right: Node? var value: Int init(value: Int, left: Node?, right: Node?) { self.value = value self.left = left self.right = right } } // t = O(N), best s = O(logN), worst s = O(N) class func isSymmetric(_ root: Node?) -> Bool { if root == nil { return true } var stack_1: [Node?] = [] var stack_2: [Node?] = [] stack_1.append(root) stack_2.append(root) while stack_1.isEmpty == false && stack_2.isEmpty == false { let tmp_1: Node? = stack_1.popLast()! let tmp_2: Node? = stack_2.popLast()! if tmp_1 == nil && tmp_2 == nil { continue } if tmp_1 == nil || tmp_2 == nil { return false } if tmp_1!.value != tmp_2!.value { return false } stack_1.append(tmp_1!.right) stack_2.append(tmp_2!.left) stack_1.append(tmp_1!.left) stack_2.append(tmp_2!.right) } return true } }
mit
ac310fe13c53576dcaecfaf8c8e9505d
22.319444
118
0.504467
3.527311
false
false
false
false
NicolasKim/Roy
Example/Pods/GRDB.swift/GRDB/Core/DatabaseRegion.swift
1
11773
/// DatabaseRegion defines a region in the database. DatabaseRegion is dedicated /// to help transaction observers recognize impactful database changes in their /// `observes(eventsOfKind:)` and `databaseDidChange(with:)` methods. /// /// A database region is the union of any number of "table regions", which can /// cover a full table, or the combination of columns and rows (identified by /// their rowids): /// /// |Table1 | |Table2 | |Table3 | |Table4 | |Table5 | /// |-------| |-------| |-------| |-------| |-------| /// |x|x|x|x| |x| | | | |x|x|x|x| |x|x| |x| | | | | | /// |x|x|x|x| |x| | | | | | | | | | | | | | | |x| | | /// |x|x|x|x| |x| | | | | | | | | |x|x| |x| | | | | | /// |x|x|x|x| |x| | | | | | | | | | | | | | | | | | | /// /// You don't create a database region directly. Instead, you use one of /// those methods: /// /// - `SelectStatement.fetchedRegion`: /// /// let statement = db.makeSelectStatement("SELECT name, score FROM players") /// print(statement.fetchedRegion) /// // prints "players(name,score)" /// /// - `Request.fetchedRegion(_:)` /// /// let request = Player.filter(key: 1) /// try print(request.fetchedRegion(db)) /// // prints "players(*)[1]" /// /// Database regions returned by requests can be more precise than regions /// returned by select statements. Especially, regions returned by statements /// don't know about rowids: /// /// // A plain statement /// let statement = db.makeSelectStatement("SELECT * FROM players WHERE id = 1") /// statement.fetchedRegion // "players(*)" /// /// // A query interface request that executes the same statement: /// let request = Player.filter(key: 1) /// try request.fetchedRegion(db) // "players(*)[1]" public struct DatabaseRegion: CustomStringConvertible, Equatable { private let tableRegions: [String: TableRegion]? private init(tableRegions: [String: TableRegion]?) { self.tableRegions = tableRegions } /// Returns whether the region is empty. public var isEmpty: Bool { guard let tableRegions = tableRegions else { return false } return tableRegions.isEmpty } /// The full database: (All columns in all tables) × (all rows) static let fullDatabase = DatabaseRegion(tableRegions: nil) /// The empty database region public init() { self.init(tableRegions: [:]) } /// A full table: (all columns in the table) × (all rows) init(table: String) { self.init(tableRegions: [table: TableRegion(columns: nil, rowIds: nil)]) } /// Full columns in a table: (some columns in a table) × (all rows) init(table: String, columns: Set<String>) { self.init(tableRegions: [table: TableRegion(columns: columns, rowIds: nil)]) } /// Full rows in a table: (all columns in a table) × (some rows) init(table: String, rowIds: Set<Int64>) { self.init(tableRegions: [table: TableRegion(columns: nil, rowIds: rowIds)]) } /// Returns the intersection of this region and the given one. /// /// This method is not public because there is no known public use case for /// this intersection. It is currently only used as support for /// the isModified(byEventsOfKind:) method. func intersection(_ other: DatabaseRegion) -> DatabaseRegion { guard let tableRegions = tableRegions else { return other } guard let otherTableRegions = other.tableRegions else { return self } var tableRegionsIntersection: [String: TableRegion] = [:] for (table, tableRegion) in tableRegions { guard let otherTableRegion = otherTableRegions .first(where: { (otherTable, _) in otherTable == table })? .value else { continue } let tableRegionIntersection = tableRegion.intersection(otherTableRegion) guard !tableRegionIntersection.isEmpty else { continue } tableRegionsIntersection[table] = tableRegionIntersection } return DatabaseRegion(tableRegions: tableRegionsIntersection) } /// Only keeps those rowIds in the given table func tableIntersection(_ table: String, rowIds: Set<Int64>) -> DatabaseRegion { guard var tableRegions = tableRegions else { return DatabaseRegion(table: table, rowIds: rowIds) } guard let tableRegion = tableRegions[table] else { return self } let intersection = tableRegion.intersection(TableRegion(columns: nil, rowIds: rowIds)) if intersection.isEmpty { tableRegions.removeValue(forKey: table) } else { tableRegions[table] = intersection } return DatabaseRegion(tableRegions: tableRegions) } /// Returns the union of this region and the given one. public func union(_ other: DatabaseRegion) -> DatabaseRegion { guard let tableRegions = tableRegions else { return .fullDatabase } guard let otherTableRegions = other.tableRegions else { return .fullDatabase } var tableRegionsUnion: [String: TableRegion] = [:] let tableNames = Set(tableRegions.map { $0.key }).union(Set(otherTableRegions.map { $0.key })) for table in tableNames { let tableRegion = tableRegions[table] let otherTableRegion = otherTableRegions[table] let tableRegionUnion: TableRegion switch (tableRegion, otherTableRegion) { case (nil, nil): preconditionFailure() case (nil, let tableRegion?), (let tableRegion?, nil): tableRegionUnion = tableRegion case (let tableRegion?, let otherTableRegion?): tableRegionUnion = tableRegion.union(otherTableRegion) } tableRegionsUnion[table] = tableRegionUnion } return DatabaseRegion(tableRegions: tableRegionsUnion) } /// Inserts the given region into this region public mutating func formUnion(_ other: DatabaseRegion) { self = union(other) } } extension DatabaseRegion { // MARK: - Database Events /// Returns whether the content in the region would be impacted if the /// database were modified by an event of this kind. public func isModified(byEventsOfKind eventKind: DatabaseEventKind) -> Bool { return !intersection(eventKind.modifiedRegion).isEmpty } /// Returns whether the content in the region is impacted by this event. /// /// - precondition: event has been filtered by the same region /// in the TransactionObserver.observes(eventsOfKind:) method, by calling /// region.isModified(byEventsOfKind:) public func isModified(by event: DatabaseEvent) -> Bool { guard let tableRegions = tableRegions else { return true } switch tableRegions.count { case 1: // The precondition applies here: // // The region contains a single table. Due to the // filtering of events performed in observes(eventsOfKind:), the // event argument is guaranteed to be about the fetched table. // We thus only have to check for rowIds. assert(event.tableName == tableRegions[tableRegions.startIndex].key) // sanity check guard let rowIds = tableRegions[tableRegions.startIndex].value.rowIds else { return true } return rowIds.contains(event.rowID) default: guard let tableRegion = tableRegions[event.tableName] else { // Shouldn't happen if the precondition is met. fatalError("precondition failure: event was not filtered out in observes(eventsOfKind:) by region.isModified(byEventsOfKind:)") } guard let rowIds = tableRegion.rowIds else { return true } return rowIds.contains(event.rowID) } } } // Equatable extension DatabaseRegion { /// :nodoc: public static func == (lhs: DatabaseRegion, rhs: DatabaseRegion) -> Bool { switch (lhs.tableRegions, rhs.tableRegions) { case (nil, nil): return true case (let ltableRegions?, let rtableRegions?): let ltableNames = Set(ltableRegions.map { $0.key }) let rtableNames = Set(rtableRegions.map { $0.key }) guard ltableNames == rtableNames else { return false } for tableName in ltableNames { if ltableRegions[tableName]! != rtableRegions[tableName]! { return false } } return true default: return false } } } // CustomStringConvertible extension DatabaseRegion { /// :nodoc: public var description: String { guard let tableRegions = tableRegions else { return "full database" } if tableRegions.isEmpty { return "empty" } return tableRegions .sorted(by: { (l, r) in l.key < r.key }) .map { (table, tableRegion) in var desc = table if let columns = tableRegion.columns { desc += "(" + columns.sorted().joined(separator: ",") + ")" } else { desc += "(*)" } if let rowIds = tableRegion.rowIds { desc += "[" + rowIds.sorted().map { "\($0)" }.joined(separator: ",") + "]" } return desc } .joined(separator: ",") } } private struct TableRegion: Equatable { var columns: Set<String>? // nil means "all columns" var rowIds: Set<Int64>? // nil means "all rowids" var isEmpty: Bool { if let columns = columns, columns.isEmpty { return true } if let rowIds = rowIds, rowIds.isEmpty { return true } return false } static func == (lhs: TableRegion, rhs: TableRegion) -> Bool { if lhs.columns != rhs.columns { return false } if lhs.rowIds != rhs.rowIds { return false } return true } func intersection(_ other: TableRegion) -> TableRegion { let columnsIntersection: Set<String>? switch (self.columns, other.columns) { case (nil, let columns), (let columns, nil): columnsIntersection = columns case (let columns?, let other?): columnsIntersection = columns.intersection(other) } let rowIdsIntersection: Set<Int64>? switch (self.rowIds, other.rowIds) { case (nil, let rowIds), (let rowIds, nil): rowIdsIntersection = rowIds case (let rowIds?, let other?): rowIdsIntersection = rowIds.intersection(other) } return TableRegion(columns: columnsIntersection, rowIds: rowIdsIntersection) } func union(_ other: TableRegion) -> TableRegion { let columnsUnion: Set<String>? switch (self.columns, other.columns) { case (nil, _), (_, nil): columnsUnion = nil case (let columns?, let other?): columnsUnion = columns.union(other) } let rowIdsUnion: Set<Int64>? switch (self.rowIds, other.rowIds) { case (nil, _), (_, nil): rowIdsUnion = nil case (let rowIds?, let other?): rowIdsUnion = rowIds.union(other) } return TableRegion(columns: columnsUnion, rowIds: rowIdsUnion) } }
mit
5259acd84dd2579de00bd031d7d23fe5
37.841584
143
0.58858
4.437783
false
false
false
false
sauvikdolui/SDStateTableView
SDStateTableView/Classes/SDStateTableView.swift
1
11525
// // SDStateTableView.swift // SDStateTableView // // Created by Sauvik Dolui on 13/10/17. // import Foundation public enum SDStateTableViewState { case dataAvailable case loading(message: String) case withImage(image: UIImage?, title: String?, message: String) case withButton(errorImage: UIImage?, title: String?, message: String, buttonTitle: String, buttonConfig: (UIButton) -> Void, retryAction: () -> Void) case unknown } @IBDesignable public class SDStateTableView: UITableView { @IBInspectable public var stateViewCenterPositionOffset: CGPoint = CGPoint(x: 0.0, y: 0.0) { didSet { setUp() } } @IBInspectable public var spinnerColor: UIColor = UIColor.lightGray { didSet { setUp() } } @IBInspectable public var stateViewTitleColor: UIColor = UIColor.darkGray { didSet { setUp() } } @IBInspectable public var stateViewSubtitleColor: UIColor = UIColor.lightGray { didSet { setUp() } } @IBInspectable public var buttonColor: UIColor = UIColor.darkGray { didSet { setUp() } } @IBInspectable public var stateLabelTitleFontFamily: String = "HelveticaNeue-Bold" { didSet { setUp() } } @IBInspectable public var stateLabelSubtitleFontFamily: String = "HelveticaNeue-Light" { didSet { setUp() } } @IBInspectable public var retryButtonFontFamily: String = "HelveticaNeue-Regular" { didSet { setUp() } } @IBInspectable public var stateLabelTitleFontSize: CGFloat = 20.0 { didSet { setUp() } } @IBInspectable public var stateLabelSubtitleFontSize: CGFloat = 16.0 { didSet { setUp() } } @IBInspectable public var buttonFontSize: CGFloat = 16.0 { didSet { setUp() } } @IBInspectable public var buttonSize: CGSize = CGSize(width: 200.0, height: 44.0) { didSet { setUp() } } // MARK: Spacing @IBInspectable public var titleStackSpacing: CGFloat = 8.0 { didSet { setUp() } } @IBInspectable public var imageTitleStackSpacing: CGFloat = 16.0 { didSet { setUp() } } /// Determines whether scrolling is enabled even when there is not data /// /// Note: Default value is false, i.e. scrolling is not available when there is not data @IBInspectable public var shouldScrollWithNoData: Bool = false { didSet { setUp() } } var originalSeparatorStyle = UITableViewCell.SeparatorStyle.singleLine var spinnerView = UIActivityIndicatorView() var dataStateTitleLabel = UILabel.autolayoutView() var dataStateSubtitleLabel = UILabel.autolayoutView() var stateImageView = UIImageView.autolayoutView() var stackView: UIStackView = UIStackView.autolayoutView() var titleStackView: UIStackView = UIStackView.autolayoutView() var actionButton = UIButton.autolayoutView() var buttonAction: (() -> Void)? public var currentState: SDStateTableViewState = .unknown { didSet { if case SDStateTableViewState.dataAvailable = self.currentState { isScrollEnabled = true } else { // Data is available, let's decide according to the // value set to shouldScrollWithNoData isScrollEnabled = shouldScrollWithNoData } } } override public init(frame: CGRect, style: UITableView.Style) { super.init(frame: frame, style: style) setUp() } required public init?(coder aDecoder: NSCoder) { super.init(coder : aDecoder) setUp() } override public func layoutSubviews() { super.layoutSubviews() switch self.currentState { case .loading(let message): self.dataStateSubtitleLabel.text = message default: () } setUp() } // MARK: - Custom Setup private func setUp() { // Loading state spinnerView.translatesAutoresizingMaskIntoConstraints = false spinnerView.color = spinnerColor spinnerView.hidesWhenStopped = true dataStateTitleLabel.textColor = stateViewTitleColor dataStateTitleLabel.numberOfLines = 0 dataStateTitleLabel.textAlignment = .center dataStateTitleLabel.lineBreakMode = .byWordWrapping dataStateTitleLabel._setWidth(width: UIScreen.main.bounds.width * 0.80) dataStateTitleLabel.font = UIFont(name: stateLabelTitleFontFamily, size: stateLabelTitleFontSize) dataStateSubtitleLabel.textColor = stateViewSubtitleColor dataStateSubtitleLabel.numberOfLines = 0 dataStateSubtitleLabel.textAlignment = .center dataStateSubtitleLabel.lineBreakMode = .byWordWrapping dataStateSubtitleLabel._setWidth(width: UIScreen.main.bounds.width * 0.80) dataStateSubtitleLabel.font = UIFont(name: stateLabelSubtitleFontFamily, size: stateLabelSubtitleFontSize) titleStackView.axis = .vertical titleStackView.distribution = .equalSpacing titleStackView.alignment = .center titleStackView.spacing = titleStackSpacing titleStackView.addArrangedSubview(dataStateTitleLabel) titleStackView.addArrangedSubview(dataStateSubtitleLabel) actionButton.titleLabel?.font = UIFont(name: retryButtonFontFamily, size: buttonFontSize) actionButton.setTitleColor(buttonColor, for: .normal) actionButton.setTitleColor(buttonColor.withAlphaComponent(0.6), for: .highlighted) actionButton.setNeedsLayout() actionButton._setSize(size: CGSize(width: buttonSize.width, height: buttonSize.height)) actionButton.layer.cornerRadius = 5.0 actionButton.layer.borderWidth = 1.0 actionButton.layer.borderColor = buttonColor.cgColor actionButton.addTarget(self, action: #selector(self.retryButtonTapped(_:)), for: .touchUpInside) stackView.axis = .vertical stackView.distribution = .equalSpacing stackView.alignment = .center stackView.spacing = imageTitleStackSpacing stackView.addArrangedSubview(spinnerView) stackView.addArrangedSubview(stateImageView) stackView.addArrangedSubview(titleStackView) stackView.addArrangedSubview(actionButton) addSubview(stackView) //Constraints stackView._setCenterAlignWith(view: self, offset: stateViewCenterPositionOffset) // if case SDStateTableViewState.withButton(_, _, _, _, let configCallback, _) = currentState { actionButton.isHidden = false configCallback(actionButton) } else { actionButton.isHidden = true } // Spinner View if case SDStateTableViewState.loading(_) = currentState { spinnerView.isHidden = false } else { spinnerView.isHidden = true } } // Mark: - Deinit deinit { // Deinitialization code goes here } public func setState(_ state: SDStateTableViewState) { self.currentState = state reloadData() switch state { case .dataAvailable: configureForShowinData() case .loading(let message): configureForLoadingData(message: message) case .withImage(let image, let title, let message): configureWith(image: image, title: title, message: message) case .withButton(let errorImage, let title, let message, let buttonTitle, let buttonConfig, let buttonAction): configWithButton(image: errorImage, title: title, message: message, buttonTitle: buttonTitle, buttonConfig: buttonConfig, buttonTapAction: buttonAction) case .unknown: () } self.setNeedsLayout() } @objc func retryButtonTapped( _ sender: UIButton) { guard let action = self.buttonAction else { print("Retry Action not Found") return } action() } private func configureForLoadingData(message: String) { stateImageView.isHidden = true stackView.isHidden = false spinnerView.isHidden = false dataStateTitleLabel.isHidden = true actionButton.isHidden = true spinnerView.startAnimating() dataStateSubtitleLabel.text = message } private func configureWith(image: UIImage?, title: String?, message: String) { // Image View if let image = image { stateImageView.isHidden = false stateImageView.image = image stateImageView.contentMode = .scaleAspectFill // Updates the image width if it is too wide if image.size.width > self.bounds.width { let newSize = CGSize(width: self.bounds.width, height: image.size.height * (self.bounds.width / image.size.width)) stateImageView.image = image.imageWith(newSize: newSize) } } else { stateImageView.isHidden = true } // Title Label if let title = title { dataStateTitleLabel.isHidden = false dataStateTitleLabel.text = title } else { dataStateTitleLabel.isHidden = true } actionButton.isHidden = true spinnerView.isHidden = true stackView.isHidden = false dataStateSubtitleLabel.isHidden = false dataStateSubtitleLabel.text = message } private func configWithButton(image: UIImage?, title: String?, message: String, buttonTitle: String, buttonConfig: (UIButton) ->Void, buttonTapAction: @escaping () -> Void) { configureWith(image: image, title: title, message: message) buttonConfig(actionButton) actionButton.isHidden = false buttonAction = buttonTapAction actionButton.setTitle(buttonTitle, for: .normal) } private func configureForShowinData() { stackView.isHidden = true } } fileprivate extension UIImage { // Redraws itself to the new size func imageWith(newSize: CGSize) -> UIImage { if #available(iOS 10.0, *) { let renderer = UIGraphicsImageRenderer(size: newSize) let image = renderer.image { _ in self.draw(in: CGRect.init(origin: CGPoint.zero, size: newSize)) } return image } else { UIGraphicsBeginImageContextWithOptions(newSize, false, 0.0); self.draw(in: CGRect(x: 0, y:0, width:newSize.width, height:newSize.height)); let image = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return image ?? self; } } }
mit
7d856edb0f2cb3f95abf7ee995eb8a78
30.837017
118
0.604685
5.277015
false
false
false
false
Virpik/T
src/Foundation/[String][Localization].swift
1
2436
// // [String][Localization].swift // Pods-TDemo // // Created by Virpik on 16/10/2018. // import Foundation /// Саппорт при работе с локализацией. /// Для работы с колличественными склонениями /// Необходимо дублировать в .string файле, продублировать склоняемую фразу: /// "Значение-TOne" = "1 значение"; /// "Значение-TMany" = "2 значения"; /// "Значение-TOther" = "5 значений"; /// Типы колличественных склонений public enum StringDecline: String { case one /// Для значений, заканчивающихся на '1' кроме числа 11 case many /// Для значений от 5 до 20 и чисел оканичающихся на '0' или больше пяти case other /// Для остальных значений } extension StringDecline { /// Строковое значение public var key: String { switch self { case .one: return "TOne" case .many: return "TMany" case .other: return "TOther" } } } public extension String { /// Возвращает локализацию, ключь - текущее значение public var localize: String { return self.localize() } /// Возвращает локализацию, ключь - текущее значение. Если указан 'count' - Включается поиск склонений public func localize(comment: String? = "", count: Int? = nil) -> String { var str = self if let count = count { str += "-"+self.declension(count).key } return NSLocalizedString(str, comment: comment ?? "") } /// Возвращает тип значения по числу private func declension(_ count: Int) -> StringDecline { if (count % 10 == 1) && (count != 11) { return .one } if (count >= 5) && (count <= 20) { return .many } if (count % 10 >= 5) || (count % 10 == 0) { return .many } if (count % 10 >= 2) && (count % 10 <= 4) { return .other } return .other } }
mit
849468c446216e6623ec417dea5861d5
25.621622
106
0.556345
3.187702
false
false
false
false
Gaea-iOS/FoundationExtension
FoundationExtension/Classes/Foundation/NSAttributedString+Convinent.swift
1
2688
// // NSAttributedString+Convinent.swift // Pods // // Created by 王小涛 on 2017/7/5. // // import Foundation extension String { public func toAttributedString(attributes: [NSAttributedString.Key: Any]? = nil) -> NSAttributedString { return NSAttributedString(string: self, attributes: attributes) } } extension NSTextAttachment { public func toAttributedString() -> NSAttributedString { return NSAttributedString(attachment: self) } } extension UIImage { public func toImageTextAttachment(size: ImageTextAttachmentSize = .scale(1.0)) -> ImageTextAttachment { let attachment = ImageTextAttachment() attachment.image = self attachment.imageSize = size return attachment } public func toAttributedString(size: ImageTextAttachmentSize = .scale(1.0)) -> NSAttributedString { return toImageTextAttachment(size: size).toAttributedString() } } extension UIView { public func toImageTextAttachment(size: ImageTextAttachmentSize = .scale(1.0)) -> ImageTextAttachment { return snapshotImage.toImageTextAttachment(size: size) } public func toAttributedString(size: ImageTextAttachmentSize = .scale(1.0)) -> NSAttributedString { return toImageTextAttachment(size: size).toAttributedString() } } extension NSAttributedString { public static func padding(_ padding: CGFloat) -> NSAttributedString { let paddingAttachment = BlankTextAttachment() paddingAttachment.width = padding let paddingAttributedString = NSAttributedString(attachment: paddingAttachment) return paddingAttributedString } public func addingPadding(_ padding: CGFloat) -> NSAttributedString { return .padding(padding) + self + .padding(padding) } public func addingLeftPadding(_ padding: CGFloat) -> NSAttributedString { return .padding(padding) + self } public func addingRightPadding(_ padding: CGFloat) -> NSAttributedString { return self + .padding(padding) } } public func +(lhs: NSAttributedString, rhs: NSAttributedString) -> NSAttributedString { let mutableAttributedString = NSMutableAttributedString() mutableAttributedString.append(lhs.copy() as! NSAttributedString) mutableAttributedString.append(rhs.copy() as! NSAttributedString) return mutableAttributedString } /** Blank placeholder usded for padding */ private class BlankTextAttachment: NSTextAttachment { open var width: CGFloat { get{ return bounds.width } set { bounds.size.width = newValue bounds.size.height = 1 } } }
mit
00ab4c440bb32a368d6e435da4a90fa3
29.477273
108
0.696495
5.079545
false
false
false
false
Chaosspeeder/YourGoals
YourGoals/UI/Views/Actionable Table Cells/ActionableTableView+Reorder.swift
1
3144
// // ActionableTableView+Reorder.swift // YourGoals // // Created by André Claaßen on 11.04.18. // Copyright © 2018 André Claaßen. All rights reserved. // import Foundation import UIKit struct ReorderInfo { let startIndex:IndexPath var currentIndex:IndexPath? func offsetForDraggingRow(_ section: Int) -> Int { guard let currentIndex = self.currentIndex else { return 0 } guard currentIndex.section != startIndex.section else { return 0 } if section == startIndex.section { return -1 } if section == currentIndex.section { return +1 } return 0 } } extension ActionableTableView: LongPressReorder { func updateTaskOrder(initialIndex: IndexPath, finalIndex: IndexPath) throws { guard initialIndex != finalIndex else { NSLog("no update of order neccessary") return } guard let dataSource = self.dataSource else { assertionFailure("you need to configure the datasource first") return } guard let positioning = dataSource.positioningProtocol() else { NSLog("no repositioning protocol found") return } if initialIndex.section == finalIndex.section { let items = self.items[initialIndex.section] try positioning.updatePosition(items: items, fromPosition: initialIndex.row, toPosition: finalIndex.row) } else { // handling for empty cells var toPosition = finalIndex.row if items[finalIndex.section].count < toPosition { toPosition = items[finalIndex.section].count } try positioning.moveIntoSection(item: itemForIndexPath(path: initialIndex), section: self.sections[finalIndex.section], toPosition: toPosition) } reload() } // MARK: - Reorder handling func startReorderingRow(atIndex indexPath: IndexPath) -> Bool { self.timerPaused = true guard self.items[indexPath.section].count > 0 else { return false } self.reorderInfo = ReorderInfo(startIndex: indexPath, currentIndex: nil) return true } func reorderFinished(initialIndex: IndexPath, finalIndex: IndexPath) { do { self.reorderInfo = nil NSLog("reorder finished: init:\(initialIndex) final:\(finalIndex)") try updateTaskOrder(initialIndex: initialIndex, finalIndex: finalIndex) NSLog("core data store updateted") self.timerPaused = false } catch let error { self.delegate?.showNotification(forError: error) } } func positionChanged(currentIndex: IndexPath, newIndex: IndexPath) { self.reorderInfo?.currentIndex = newIndex } func allowChangingRow(atIndex indexPath: IndexPath) -> Bool { return true } }
lgpl-3.0
9cd689d86c7d82ec629327ca3f0e263a
27.798165
155
0.58713
5.338435
false
false
false
false
modocache/Gift
Gift/Index/Index.swift
1
2116
import LlamaKit /** A data structure representing an index, also referred to as a "staging area" for changes. The index is a temporary and dynamic binary file that describes the directory structure of the entire repository. The index captures a version of the project’s overall structure at some moment in time. The index allows a separation between incremental developmental changes and the committal of those changes. Changes are "staged" in an index, keeping those changes until they are ready to be committed. */ public class Index { internal let cIndex: COpaquePointer internal init(cIndex: COpaquePointer) { self.cIndex = cIndex } deinit { git_index_free(cIndex) } } public extension Index { /** Returns the number of entries in the index. */ public var entryCount: UInt { return git_index_entrycount(cIndex) } /** Adds the files at the specified paths to the index, using the given options. :param: paths Paths, or patterns used to match paths, of the files to be added to the index. If no patterns are specified, all files are added to the index. :param: options A set of options for adding files to the index. :returns: The result of the operation: either the index to which files have been added, or an error indicating what went wrong. */ public func add(paths: [String] = [], options: IndexAddOptions = IndexAddOptions.Default) -> Result<Index, NSError> { let count = countElements(paths) var cPaths = UnsafeMutablePointer<UnsafeMutablePointer<Int8>>.alloc(count) for i in 0..<count { cPaths[i] = UnsafeMutablePointer((paths[i] as NSString).UTF8String) } var stringArray = git_strarray(strings: cPaths, count: UInt(count)) let errorCode = git_index_add_all(cIndex, &stringArray, UInt32(options.rawValue), nil, nil) git_strarray_free(&stringArray) if errorCode == GIT_OK.value { return success(self) } else { return failure(NSError.libGit2Error(errorCode, libGit2PointOfFailure: "git_index_entrycount")) } } }
mit
5f41fe24f8cc16c205a7726f965e9744
33.096774
119
0.70246
4.186139
false
false
false
false
SwiftTools/Switt
SwittTests/UnitTests/Grammar/LexicalAnalysis/Lexer/Tokenizer/Tokenizers/RepetitionTokenizerTests.swift
1
3973
import Quick import Nimble @testable import Switt private class Helper { static func tokenizer(rule: LexerRule) -> RepetitionTokenizer { let tokenizerFactory = TokenizerFactoryImpl(lexerRules: LexerRules()) let tokenizer = RepetitionTokenizer( rule: rule, tokenizerFactory: tokenizerFactory ) return tokenizer } } class RepetitionTokenizerTests: QuickSpec, GrammarRulesBuilder { override func spec() { describe("RepetitionTokenizer") { it("1") { let tokenizer = Helper.tokenizer( LexerRule.Terminal(terminal: "a") ) let actualStates = "ab".characters.map { tokenizer.feed($0) } let expectedStates = [ TokenizerState.Complete, TokenizerState.Fail ] expect(actualStates).to(equal(expectedStates)) } it("1") { let tokenizer = Helper.tokenizer( LexerRule.Terminal(terminal: "aa") ) let actualStates = "aab".characters.map { tokenizer.feed($0) } let expectedStates = [ TokenizerState.Possible, TokenizerState.Complete, TokenizerState.Fail ] expect(actualStates).to(equal(expectedStates)) } it("2") { let tokenizer = Helper.tokenizer( LexerRule.Terminal(terminal: "a") ) let actualStates = "aab".characters.map { tokenizer.feed($0) } let expectedStates = [ TokenizerState.Complete, TokenizerState.Complete, TokenizerState.Fail ] expect(actualStates).to(equal(expectedStates)) } it("3") { let tokenizer = Helper.tokenizer( LexerRule.Terminal(terminal: "a") ) let actualStates = "aaab".characters.map { tokenizer.feed($0) } let expectedStates = [ TokenizerState.Complete, TokenizerState.Complete, TokenizerState.Complete, TokenizerState.Fail ] expect(actualStates).to(equal(expectedStates)) } it("4") { let tokenizer = Helper.tokenizer( LexerRule.Terminal(terminal: "aa") ) let actualStates = "aaaaab".characters.map { tokenizer.feed($0) } let expectedStates = [ TokenizerState.Possible, TokenizerState.Complete, TokenizerState.Possible, TokenizerState.Complete, TokenizerState.Possible, TokenizerState.Fail ] expect(actualStates).to(equal(expectedStates)) } it("5") { let tokenizer = Helper.tokenizer( LexerRule.Terminal(terminal: "aa") ) let actualStates = "aaaab".characters.map { tokenizer.feed($0) } let expectedStates = [ TokenizerState.Possible, TokenizerState.Complete, TokenizerState.Possible, TokenizerState.Complete, TokenizerState.Fail ] expect(actualStates).to(equal(expectedStates)) } } } }
mit
51966f03e358871a1f7557900de40622
32.965812
81
0.450038
6.037994
false
false
false
false
samodom/TestableUIKit
TestableUIKit/UIResponder/UIView/UIWindow/UIWindowMakeKeyAndVisibleSpy.swift
1
1652
// // UIWindowMakeKeySpy.swift // TestableUIKit // // Created by Sam Odom on 2/21/17. // Copyright © 2017 Swagger Soft. All rights reserved. // import UIKit import TestSwagger import FoundationSwagger public extension UIWindow { private static let makeKeyCalledKeyString = UUIDKeyString() private static let makeKeyCalledKey = ObjectAssociationKey(makeKeyCalledKeyString) private static let makeKeyCalledReference = SpyEvidenceReference(key: makeKeyCalledKey) private static let makeKeyCoselectors = SpyCoselectors( methodType: .instance, original: #selector(UIWindow.makeKey), spy: #selector(UIWindow.spy_makeKey) ) /// Spy controller for ensuring that a window has had `makeKey` called on it. public enum MakeKeySpyController: SpyController { public static let rootSpyableClass: AnyClass = UIWindow.self public static let vector = SpyVector.direct public static let coselectors: Set = [makeKeyCoselectors] public static let evidence: Set = [makeKeyCalledReference] public static let forwardsInvocations = true } /// Spy method that replaces the true implementation of `makeKey` dynamic public func spy_makeKey() { makeKeyCalled = true spy_makeKey() } /// Indicates whether the `makeKey` method has been called on this object. public final var makeKeyCalled: Bool { get { return loadEvidence(with: UIWindow.makeKeyCalledReference) as? Bool ?? false } set { saveEvidence(newValue, with: UIWindow.makeKeyCalledReference) } } }
mit
02b6c74c15cbb3bec20c7b838d1d9acc
27.964912
88
0.689885
4.841642
false
false
false
false
thompsonate/Shifty
Shifty/DateTime+Shifty.swift
1
1343
// // DateTime+Shifty.swift // DateTime+Shifty // // Created by Nate Thompson on 8/28/21. // import Foundation extension Time: Equatable, Comparable { init(_ date: Date) { let components = Calendar.current.dateComponents([.hour, .minute], from: date) guard let hour = components.hour, let minute = components.minute else { fatalError("Could not instantiate Time object") } self.init() self.hour = Int32(hour) self.minute = Int32(minute) } static var now: Time { return Time(Date()) } public static func ==(lhs: Time, rhs: Time) -> Bool { return lhs.hour == rhs.hour && lhs.minute == rhs.minute } public static func < (lhs: Time, rhs: Time) -> Bool { if lhs.hour == rhs.hour { return lhs.minute < rhs.minute } else { return lhs.hour < rhs.hour } } } extension Date { init(_ time: Time) { var components = Calendar.current.dateComponents([.hour, .minute], from: Date()) components.hour = Int(time.hour) components.minute = Int(time.minute) if let date = Calendar.current.date(from: components) { self = date } else { fatalError("Could not instantiate Date object") } } }
gpl-3.0
b1efcf2e73eba2d424aeec263fec04d5
25.333333
88
0.560685
4.069697
false
false
false
false
mperovic/my41
my41/Classes/KeyboardShortcuts.swift
1
20558
// // KeyboardShortcuts.swift // my41 // // Created by Miroslav Perovic on 11/26/14. // Copyright (c) 2014 iPera. All rights reserved. // import Foundation import Cocoa final class KeyboardShortcutsViewController: NSViewController { @IBOutlet weak var labelSigmaMinus: NSTextField! @IBOutlet weak var buttonCellSigmaPlus: ButtonCell! @IBOutlet weak var buttonSigmaPlus: Key! @IBOutlet weak var labelYX: NSTextField! @IBOutlet weak var buttonCellOneX: ButtonCell! @IBOutlet weak var buttonOneX: Key! @IBOutlet weak var labelXSquare: NSTextField! @IBOutlet weak var buttonCellSquareRoot: ButtonCell! @IBOutlet weak var buttonSquareRoot: Key! @IBOutlet weak var labelTenX: NSTextField! @IBOutlet weak var buttonCellLog: ButtonCell! @IBOutlet weak var buttonLog: Key! @IBOutlet weak var labelEX: NSTextField! @IBOutlet weak var buttonCellLn: ButtonCell! @IBOutlet weak var buttonLn: Key! @IBOutlet weak var labelCLSigma: NSTextField! @IBOutlet weak var buttonCellXexY: ButtonCell! @IBOutlet weak var buttonXexY: Key! @IBOutlet weak var labelPercent: NSTextField! @IBOutlet weak var buttonCellRArrrow: ButtonCell! @IBOutlet weak var buttonRArrrow: Key! @IBOutlet weak var labelSin: NSTextField! @IBOutlet weak var buttonCellSin: ButtonCell! @IBOutlet weak var buttonSin: Key! @IBOutlet weak var labelCos: NSTextField! @IBOutlet weak var buttonCellCos: ButtonCell! @IBOutlet weak var buttonCos: Key! @IBOutlet weak var labelTan: NSTextField! @IBOutlet weak var buttonCellTan: ButtonCell! @IBOutlet weak var buttonTan: Key! @IBOutlet weak var labelShift: NSTextField! @IBOutlet weak var buttonCellShift: ButtonCell! @IBOutlet weak var buttonShift: Key! @IBOutlet weak var labelASN: NSTextField! @IBOutlet weak var buttonCellXEQ: ButtonCell! @IBOutlet weak var buttonXEQ: Key! @IBOutlet weak var labelLBL: NSTextField! @IBOutlet weak var buttonCellSTO: ButtonCell! @IBOutlet weak var buttonSTO: Key! @IBOutlet weak var labelGTO: NSTextField! @IBOutlet weak var buttonCellRCL: ButtonCell! @IBOutlet weak var buttonRCL: Key! @IBOutlet weak var labelBST: NSTextField! @IBOutlet weak var buttonCellSST: ButtonCell! @IBOutlet weak var buttonSST: Key! @IBOutlet weak var labelCATALOG: NSTextField! @IBOutlet weak var buttonCellENTER: ButtonCell! @IBOutlet weak var buttonENTER: Key! @IBOutlet weak var labelISG: NSTextField! @IBOutlet weak var buttonCellCHS: ButtonCell! @IBOutlet weak var buttonCHS: Key! @IBOutlet weak var labelRTN: NSTextField! @IBOutlet weak var buttonCellEEX: ButtonCell! @IBOutlet weak var buttonEEX: Key! @IBOutlet weak var labelCLXA: NSTextField! @IBOutlet weak var buttonCellBack: ButtonCell! @IBOutlet weak var buttonBack: Key! @IBOutlet weak var labelXEQY: NSTextField! @IBOutlet weak var buttonCellMinus: ButtonCell! @IBOutlet weak var buttonMinus: Key! @IBOutlet weak var labelXLessThanY: NSTextField! @IBOutlet weak var buttonCellPlus: ButtonCell! @IBOutlet weak var buttonPlus: Key! @IBOutlet weak var labelXGreaterThanY: NSTextField! @IBOutlet weak var buttonCellMultiply: ButtonCell! @IBOutlet weak var buttonMultiply: Key! @IBOutlet weak var labelXEQ0: NSTextField! @IBOutlet weak var buttonCellDivide: ButtonCell! @IBOutlet weak var buttonDivide: Key! @IBOutlet weak var labelSF: NSTextField! @IBOutlet weak var buttonCell7: ButtonCell! @IBOutlet weak var button7: Key! @IBOutlet weak var labelCF: NSTextField! @IBOutlet weak var buttonCell8: ButtonCell! @IBOutlet weak var button8: Key! @IBOutlet weak var labelFS: NSTextField! @IBOutlet weak var buttonCell9: ButtonCell! @IBOutlet weak var button9: Key! @IBOutlet weak var labelBEEP: NSTextField! @IBOutlet weak var buttonCell4: ButtonCell! @IBOutlet weak var button4: Key! @IBOutlet weak var labelPR: NSTextField! @IBOutlet weak var buttonCell5: ButtonCell! @IBOutlet weak var button5: Key! @IBOutlet weak var labelRP: NSTextField! @IBOutlet weak var buttonCell6: ButtonCell! @IBOutlet weak var button6: Key! @IBOutlet weak var labelFIX: NSTextField! @IBOutlet weak var buttonCell1: ButtonCell! @IBOutlet weak var button1: Key! @IBOutlet weak var labelSCI: NSTextField! @IBOutlet weak var buttonCell2: ButtonCell! @IBOutlet weak var button2: Key! @IBOutlet weak var labelENG: NSTextField! @IBOutlet weak var buttonCell3: ButtonCell! @IBOutlet weak var button3: Key! @IBOutlet weak var labelPI: NSTextField! @IBOutlet weak var buttonCell0: ButtonCell! @IBOutlet weak var button0: Key! @IBOutlet weak var labelLASTX: NSTextField! @IBOutlet weak var buttonCellPoint: ButtonCell! @IBOutlet weak var buttonPoint: Key! @IBOutlet weak var labelVIEW: NSTextField! @IBOutlet weak var buttonCellRS: ButtonCell! @IBOutlet weak var buttonRS: Key! override func viewWillAppear() { self.view.layer = CALayer() self.view.layer?.backgroundColor = NSColor(calibratedRed: 0.221, green: 0.221, blue: 0.221, alpha: 1.0).cgColor self.view.wantsLayer = true let Helvetica09Font = NSFont(name: "Helvetica", size: 9.0) let Helvetica15Font = NSFont(name: "Helvetica", size: 15.0) let TimesNewRoman10Font = NSFont(name: "Times New Roman", size: 10.0) let TimesNewRoman13Font = NSFont(name: "Times New Roman", size: 13.0) // Label Σ- if let actualFont = Helvetica09Font { let sigmaMinusString = mutableAttributedStringFromString("⌘G", color: nil, fontName: "Helvetica", fontSize: 11.0) let sigmaMinusAttributes = [ NSAttributedString.Key.font : actualFont ] sigmaMinusString.addAttributes(sigmaMinusAttributes, range: NSMakeRange(1, 1)) labelSigmaMinus.attributedStringValue = sigmaMinusString } // Button Σ+ let sigmaPlusString = mutableAttributedStringFromString("Σ+", color: .white, fontName: "Helvetica", fontSize: 11.0) let sigmaPlusAttributes = [ NSAttributedString.Key.baselineOffset: 1 ] sigmaPlusString.addAttributes(sigmaPlusAttributes, range: NSMakeRange(1, 1)) buttonCellSigmaPlus.upperText = sigmaPlusString // Label yx if let actualFont = TimesNewRoman13Font { let yxString = mutableAttributedStringFromString("⌘1", color: nil, fontName: "Helvetica", fontSize: 11.0) let yxAttributes = [ NSAttributedString.Key.font : actualFont ] yxString.addAttributes(yxAttributes, range: NSMakeRange(1, 1)) labelYX.attributedStringValue = yxString } // Button 1/x if let actualFont = TimesNewRoman10Font { let oneXString = mutableAttributedStringFromString("1/x", color: .white, fontName: "Helvetica", fontSize: 11.0) let oneXAttributes = [ NSAttributedString.Key.font : actualFont, ] oneXString.addAttributes(oneXAttributes, range: NSMakeRange(2, 1)) buttonCellOneX.upperText = oneXString } // Label x^2 labelXSquare.attributedStringValue = mutableAttributedStringFromString("Q", color: nil, fontName: "Times New Roman", fontSize: 13.0) // Button √x if let actualFont = TimesNewRoman10Font { let rootXString = mutableAttributedStringFromString("√x\u{0304}", color: .white, fontName: "Helvetica", fontSize: 11.0) let rootXAttributes1 = [ NSAttributedString.Key.baselineOffset: 1 ] rootXString.addAttributes(rootXAttributes1, range: NSMakeRange(2, 1)) let rootXAttributes2 = [ NSAttributedString.Key.font : actualFont, ] rootXString.addAttributes(rootXAttributes2, range: NSMakeRange(1, 1)) buttonCellSquareRoot.upperText = rootXString } // Label 10^x labelTenX.attributedStringValue = mutableAttributedStringFromString("L", color: nil, fontName: "Times New Roman", fontSize: 13.0) // Button LOG buttonCellLog.upperText = mutableAttributedStringFromString("LOG", color: .white, fontName: "Helvetica", fontSize: 11.0) // Label e^x if let actualFont = TimesNewRoman13Font { let EXString = mutableAttributedStringFromString("⌘L", color: nil, fontName: "Helvetica", fontSize: 11.0) let EXAttributes = [ NSAttributedString.Key.font : actualFont ] EXString.addAttributes(EXAttributes, range: NSMakeRange(1, 1)) labelEX.attributedStringValue = EXString } // Button LN buttonCellLn.upperText = mutableAttributedStringFromString("LN", color: .white, fontName: "Helvetica", fontSize: 11.0) // Label CLΣ if let actualFont = TimesNewRoman13Font { let CLSigmaString = mutableAttributedStringFromString("⌘X", color: nil, fontName: "Helvetica", fontSize: 11.0) let CLSigmaAttributes = [ NSAttributedString.Key.font : actualFont ] CLSigmaString.addAttributes(CLSigmaAttributes, range: NSMakeRange(1, 1)) labelCLSigma.attributedStringValue = CLSigmaString } // Button x≷y buttonCellXexY.upperText = mutableAttributedStringFromString("x≷y", color: .white, fontName: "Times New Roman", fontSize: 14.0) // Label % if let actualFont = TimesNewRoman13Font { let percentString = mutableAttributedStringFromString("⌘A", color: nil, fontName: "Helvetica", fontSize: 11.0) let percentAttributes = [ NSAttributedString.Key.font : actualFont ] percentString.addAttributes(percentAttributes, range: NSMakeRange(1, 1)) labelPercent.attributedStringValue = percentString } // Button R↓ buttonCellRArrrow.upperText = mutableAttributedStringFromString("R↓", color: .white, fontName: "Helvetica", fontSize: 11.0) // Label SIN-1 if let actualFont = TimesNewRoman13Font { let sin1String = mutableAttributedStringFromString("I", color: nil, fontName: "Times New Roman", fontSize: 13.0) let sinAttributes = [ NSAttributedString.Key.font : actualFont, NSAttributedString.Key.baselineOffset: 4 ] as [NSAttributedString.Key : Any] sin1String.addAttributes(sinAttributes, range: NSMakeRange(0, 1)) labelSin.attributedStringValue = sin1String } // Button SIN buttonCellSin.upperText = mutableAttributedStringFromString("SIN", color: .white, fontName: "Helvetica", fontSize: 11.0) // Label COS-1 if let actualFont = TimesNewRoman13Font { let cos1String = mutableAttributedStringFromString("O", color: nil, fontName: "Times New Roman", fontSize: 13.0) let cosAttributes = [ NSAttributedString.Key.font : actualFont, NSAttributedString.Key.baselineOffset: 4 ] as [NSAttributedString.Key : Any] cos1String.addAttributes(cosAttributes, range: NSMakeRange(0, 1)) labelCos.attributedStringValue = cos1String } // Button COS buttonCellCos.upperText = mutableAttributedStringFromString("COS", color: .white, fontName: "Helvetica", fontSize: 11.0) // Label TAN-1 if let actualFont = TimesNewRoman13Font { let tan1String = mutableAttributedStringFromString("T", color: nil, fontName: "Times New Roman", fontSize: 13.0) let tanAttributes = [ NSAttributedString.Key.font : actualFont, NSAttributedString.Key.baselineOffset: 4 ] as [NSAttributedString.Key : Any] tan1String.addAttributes(tanAttributes, range: NSMakeRange(0, 1)) labelTan.attributedStringValue = tan1String } // Button TAN buttonCellTan.upperText = mutableAttributedStringFromString("TAN", color: .white, fontName: "Helvetica", fontSize: 11.0) // Label Shift labelShift.attributedStringValue = mutableAttributedStringFromString("⌘F", color: nil, fontName: "Times New Roman", fontSize: 13.0) // Label ASN labelASN.attributedStringValue = mutableAttributedStringFromString("X", color: nil, fontName: "Times New Roman", fontSize: 13.0) // Button XEQ buttonCellXEQ.upperText = mutableAttributedStringFromString("XEQ", color: .white, fontName: "Helvetica", fontSize: 11.0) // Label LBL labelLBL.attributedStringValue = mutableAttributedStringFromString("S", color: nil, fontName: "Times New Roman", fontSize: 13.0) // Button STO buttonCellSTO.upperText = mutableAttributedStringFromString("STO", color: .white, fontName: "Helvetica", fontSize: 11.0) // Label GTO labelGTO.attributedStringValue = mutableAttributedStringFromString("R", color: nil, fontName: "Times New Roman", fontSize: 13.0) // Button RCL buttonCellRCL.upperText = mutableAttributedStringFromString("RCL", color: .white, fontName: "Helvetica", fontSize: 11.0) // Label BST if let actualFont = TimesNewRoman13Font { let BSTString = mutableAttributedStringFromString("⌘S", color: nil, fontName: "Helvetica", fontSize: 11.0) let BSTAttributes = [ NSAttributedString.Key.font : actualFont ] BSTString.addAttributes(BSTAttributes, range: NSMakeRange(1, 1)) labelBST.attributedStringValue = BSTString } // Button SST buttonCellSST.upperText = mutableAttributedStringFromString("SST", color: .white, fontName: "Helvetica", fontSize: 11.0) // Label CATALOG labelCATALOG.attributedStringValue = mutableAttributedStringFromString("⏎", color: nil, fontName: "Times New Roman", fontSize: 12.0) // Button ENTER buttonCellENTER.upperText = mutableAttributedStringFromString("ENTER ↑", color: .white, fontName: "Helvetica", fontSize: 11.0) // Label ISG labelISG.attributedStringValue = mutableAttributedStringFromString("C", color: nil, fontName: "Times New Roman", fontSize: 13.0) // Button CHS buttonCellCHS.upperText = mutableAttributedStringFromString("CHS", color: .white, fontName: "Helvetica", fontSize: 11.0) // Label RTN labelRTN.attributedStringValue = mutableAttributedStringFromString("E", color: nil, fontName: "Times New Roman", fontSize: 13.0) // Button EEX buttonCellEEX.upperText = mutableAttributedStringFromString("EEX", color: .white, fontName: "Helvetica", fontSize: 11.0) // Label CL X/A labelCLXA.attributedStringValue = mutableAttributedStringFromString("←", color: nil, fontName: "Helvetica", fontSize: 11.0) // Button Back buttonCellBack.upperText = mutableAttributedStringFromString("←", color: .white, fontName: "Helvetica", fontSize: 11.0) // Label x=y ? labelXEQY.attributedStringValue = mutableAttributedStringFromString("━", color: nil, fontName: "Helvetica", fontSize: 9.0) // Button Minus if let actualFont = Helvetica09Font { let minusString = mutableAttributedStringFromString("━", color: .white, fontName: "Helvetica", fontSize: 9.0) let minusAttributes = [ NSAttributedString.Key.font : actualFont, NSAttributedString.Key.baselineOffset: -1 ] as [NSAttributedString.Key : Any] minusString.addAttributes(minusAttributes, range: NSMakeRange(0, 1)) buttonCellMinus.upperText = minusString } // Label x≤y ? labelXLessThanY.attributedStringValue = mutableAttributedStringFromString("╋", color: nil, fontName: "Helvetica", fontSize: 9.0) // Button Plus buttonCellPlus.upperText = mutableAttributedStringFromString("╋", color: .white, fontName: "Times New Roman", fontSize: 9.0) if let actualFont = Helvetica09Font { let plusString = mutableAttributedStringFromString("╋", color: .white, fontName: "Helvetica", fontSize: 9.0) let plusAttributes = [ NSAttributedString.Key.font : actualFont ] plusString.addAttributes(plusAttributes, range: NSMakeRange(0, 1)) } // Label x≥y ? labelXGreaterThanY.attributedStringValue = mutableAttributedStringFromString("*", color: nil, fontName: "Times New Roman", fontSize: 14.0) // Button Multiply if let actualFont = Helvetica15Font { let multiplyString = mutableAttributedStringFromString("×", color: .white, fontName: "Helvetica", fontSize: 15.0) let multiplyAttributes = [ NSAttributedString.Key.font : actualFont, NSAttributedString.Key.baselineOffset: 1 ] as [NSAttributedString.Key : Any] multiplyString.addAttributes(multiplyAttributes, range: NSMakeRange(0, 1)) buttonCellMultiply.upperText = multiplyString } // Label x=0 ? labelXEQ0.attributedStringValue = mutableAttributedStringFromString("/", color: nil, fontName: "Times New Roman", fontSize: 13.0) // Button Divide if let actualFont = Helvetica15Font { let divideString = mutableAttributedStringFromString("÷", color: .white, fontName: "Helvetica", fontSize: 15.0) let divideAttributes = [ NSAttributedString.Key.font : actualFont, NSAttributedString.Key.baselineOffset: 1 ] as [NSAttributedString.Key : Any] divideString.addAttributes(divideAttributes, range: NSMakeRange(0, 1)) buttonCellDivide.upperText = divideString } // Label SF labelSF.attributedStringValue = mutableAttributedStringFromString("7", color: nil, fontName: "Times New Roman", fontSize: 13.0) // Button 7 buttonCell7.upperText = mutableAttributedStringFromString("7", color: .white, fontName: "Helvetica", fontSize: 13.0) // Label CF labelCF.attributedStringValue = mutableAttributedStringFromString("8", color: nil, fontName: "Times New Roman", fontSize: 13.0) // Button 8 buttonCell8.upperText = mutableAttributedStringFromString("8", color: .white, fontName: "Helvetica", fontSize: 13.0) // Label FS? labelFS.attributedStringValue = mutableAttributedStringFromString("9", color: nil, fontName: "Times New Roman", fontSize: 13.0) // Button 9 buttonCell9.upperText = mutableAttributedStringFromString("9", color: .white, fontName: "Helvetica", fontSize: 13.0) // Label BEEP labelBEEP.attributedStringValue = mutableAttributedStringFromString("4", color: nil, fontName: "Times New Roman", fontSize: 13.0) // Button 4 buttonCell4.upperText = mutableAttributedStringFromString("4", color: .white, fontName: "Helvetica", fontSize: 13.0) // Label P→R labelPR.attributedStringValue = mutableAttributedStringFromString("5", color: nil, fontName: "Times New Roman", fontSize: 13.0) // Button 5 buttonCell5.upperText = mutableAttributedStringFromString("5", color: .white, fontName: "Helvetica", fontSize: 13.0) // Label R→P labelRP.attributedStringValue = mutableAttributedStringFromString("6", color: nil, fontName: "Times New Roman", fontSize: 13.0) // Button 6 buttonCell6.upperText = mutableAttributedStringFromString("6", color: .white, fontName: "Helvetica", fontSize: 13.0) // Label FIX labelFIX.attributedStringValue = mutableAttributedStringFromString("1", color: nil, fontName: "Times New Roman", fontSize: 13.0) // Button 1 buttonCell1.upperText = mutableAttributedStringFromString("1", color: .white, fontName: "Helvetica", fontSize: 13.0) // Label SCI labelSCI.attributedStringValue = mutableAttributedStringFromString("2", color: nil, fontName: "Times New Roman", fontSize: 13.0) // Button 2 buttonCell2.upperText = mutableAttributedStringFromString("2", color: .white, fontName: "Helvetica", fontSize: 13.0) // Label ENG labelENG.attributedStringValue = mutableAttributedStringFromString("3", color: nil, fontName: "Times New Roman", fontSize: 13.0) // Button 3 buttonCell3.upperText = mutableAttributedStringFromString("3", color: .white, fontName: "Helvetica", fontSize: 13.0) // Label PI labelPI.attributedStringValue = mutableAttributedStringFromString("0", color: nil, fontName: "Times New Roman", fontSize: 13.0) // Button 0 buttonCell0.upperText = mutableAttributedStringFromString("0", color: .white, fontName: "Helvetica", fontSize: 13.0) // Label LAST X labelLASTX.attributedStringValue = mutableAttributedStringFromString("•", color: nil, fontName: "Times New Roman", fontSize: 15.0) // Button • buttonCellPoint.upperText = mutableAttributedStringFromString("•", color: .white, fontName: "Helvetica", fontSize: 13.0) // Label VIEW if let actualFont = TimesNewRoman13Font { let viewString = mutableAttributedStringFromString("⌘R", color: nil, fontName: "Helvetica", fontSize: 11.0) let viewAttributes = [ NSAttributedString.Key.font : actualFont ] viewString.addAttributes(viewAttributes, range: NSMakeRange(1, 1)) labelVIEW.attributedStringValue = viewString } // Button R/S buttonCellRS.upperText = mutableAttributedStringFromString("R/S", color: .white, fontName: "Helvetica", fontSize: 12.0) } func mutableAttributedStringFromString(_ aString: String, color: NSColor?, fontName: String, fontSize: CGFloat) -> NSMutableAttributedString { let aFont = NSFont(name: fontName, size: fontSize) if let actualFont = aFont { if let aColor = color { return NSMutableAttributedString( string: aString, attributes: [NSAttributedString.Key.font : actualFont, NSAttributedString.Key.foregroundColor: aColor ] ) } else { return NSMutableAttributedString( string: aString, attributes: [NSAttributedString.Key.font : actualFont] ) } } else { return NSMutableAttributedString() } } }
bsd-3-clause
4a136f9093cac96765070c3c9d39ecce
41.078029
143
0.745901
3.943803
false
false
false
false
rlaferla/CLTokenInputView-Swift
CLTokenInputView/CLTokenInputView.swift
1
16842
// // CLTokenInputView.swift // CLTokenInputView // // Created by Robert La Ferla on 1/13/16 from original ObjC version by Rizwan Sattar. // Copyright © 2016 Robert La Ferla. All rights reserved. // import Foundation import UIKit protocol CLTokenInputViewDelegate: class { func tokenInputViewDidEndEditing(aView: CLTokenInputView) func tokenInputViewDidBeginEditing(aView: CLTokenInputView) func tokenInputView(aView:CLTokenInputView, didChangeText text:String) func tokenInputView(aView:CLTokenInputView, didAddToken token:CLToken) func tokenInputView(aView:CLTokenInputView, didRemoveToken token:CLToken) func tokenInputView(aView:CLTokenInputView, tokenForText text:String) -> CLToken? func tokenInputView(aView:CLTokenInputView, didChangeHeightTo height:CGFloat) } class CLTokenInputView: UIView, CLBackspaceDetectingTextFieldDelegate, CLTokenViewDelegate { weak var delegate:CLTokenInputViewDelegate? var fieldLabel:UILabel! var fieldView:UIView? { willSet { if self.fieldView != newValue { self.fieldView?.removeFromSuperview() } } didSet { if oldValue != self.fieldView { if (self.fieldView != nil) { self.addSubview(self.fieldView!) } self.repositionViews() } } } var fieldName:String? { didSet { if oldValue != self.fieldName { self.fieldLabel.text = self.fieldName self.fieldLabel.sizeToFit() let showField:Bool = self.fieldName!.characters.count > 0 self.fieldLabel.hidden = !showField if showField && self.fieldLabel.superview == nil { self.addSubview(self.fieldLabel) } else if !showField && self.fieldLabel.superview != nil { self.fieldLabel.removeFromSuperview() } if oldValue == nil || oldValue != self.fieldName { self.repositionViews() } } } } var fieldColor:UIColor? { didSet { self.fieldLabel.textColor = self.fieldColor } } var placeholderText:String? { didSet { if oldValue != self.placeholderText { self.updatePlaceholderTextVisibility() } } } var accessoryView:UIView? { willSet { if self.accessoryView != newValue { self.accessoryView?.removeFromSuperview() } } didSet { if oldValue != self.accessoryView { if (self.accessoryView != nil) { self.addSubview(self.accessoryView!) } self.repositionViews() } } } var keyboardType: UIKeyboardType! { didSet { self.textField.keyboardType = self.keyboardType; } } var autocapitalizationType: UITextAutocapitalizationType! { didSet { self.textField.autocapitalizationType = self.autocapitalizationType; } } var autocorrectionType: UITextAutocorrectionType! { didSet { self.textField.autocorrectionType = self.autocorrectionType; } } var tokenizationCharacters:Set<String> = Set<String>() var drawBottomBorder:Bool! { didSet { if oldValue != self.drawBottomBorder { self.setNeedsDisplay() } } } //var editing:Bool = false var tokens:[CLToken] = [] var tokenViews:[CLTokenView] = [] var textField:CLBackspaceDetectingTextField! var intrinsicContentHeight:CGFloat! var additionalTextFieldYOffset:CGFloat! let HSPACE:CGFloat = 0.0 let TEXT_FIELD_HSPACE:CGFloat = 4.0 // Note: Same as CLTokenView.PADDING_X let VSPACE:CGFloat = 4.0 let MINIMUM_TEXTFIELD_WIDTH:CGFloat = 56.0 let PADDING_TOP:CGFloat = 10.0 let PADDING_BOTTOM:CGFloat = 10.0 let PADDING_LEFT:CGFloat = 8.0 let PADDING_RIGHT:CGFloat = 16.0 let STANDARD_ROW_HEIGHT:CGFloat = 25.0 let FIELD_MARGIN_X:CGFloat = 4.0 func commonInit() { self.textField = CLBackspaceDetectingTextField(frame: self.bounds) self.textField.translatesAutoresizingMaskIntoConstraints = false self.textField.backgroundColor = UIColor.clearColor() self.textField.keyboardType = .EmailAddress self.textField.autocorrectionType = .No self.textField.autocapitalizationType = .None self.textField.delegate = self //self.additionalTextFieldYOffset = 0.0 self.additionalTextFieldYOffset = 1.5 self.textField.addTarget(self, action: #selector(CLTokenInputView.onTextFieldDidChange(_:)), forControlEvents: .EditingChanged) self.addSubview(self.textField) self.fieldLabel = UILabel(frame: CGRectZero) self.fieldLabel.translatesAutoresizingMaskIntoConstraints = false self.fieldLabel.font = self.textField.font self.fieldLabel.textColor = self.fieldColor self.addSubview(self.fieldLabel) self.fieldLabel.hidden = true self.fieldColor = UIColor.lightGrayColor() self.intrinsicContentHeight = STANDARD_ROW_HEIGHT self.repositionViews() } override init(frame: CGRect) { super.init(frame: frame) self.commonInit() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.commonInit() } override func intrinsicContentSize() -> CGSize { return CGSizeMake(UIViewNoIntrinsicMetric, max(45, self.intrinsicContentHeight)) } override func tintColorDidChange() { self.tokenViews.forEach { $0.tintColor = self.tintColor } } func addToken(token:CLToken) { if self.tokens.contains(token) { return } self.tokens.append(token) let tokenView:CLTokenView = CLTokenView(token: token, font: self.textField.font) tokenView.translatesAutoresizingMaskIntoConstraints = false tokenView.tintColor = self.tintColor tokenView.delegate = self let intrinsicSize:CGSize = tokenView.intrinsicContentSize() tokenView.frame = CGRect(x: 0.0, y: 0.0, width: intrinsicSize.width, height: intrinsicSize.height) self.tokenViews.append(tokenView) self.addSubview(tokenView) self.textField.text = "" self.delegate?.tokenInputView(self, didAddToken: token) self.onTextFieldDidChange(self.textField) self.updatePlaceholderTextVisibility() self.repositionViews() } func removeTokenAtIndex(index:Int) { if index == -1 { return } let tokenView = self.tokenViews[index] tokenView.removeFromSuperview() self.tokenViews.removeAtIndex(index) let removedToken = self.tokens[index] self.tokens.removeAtIndex(index) self.delegate?.tokenInputView(self, didRemoveToken: removedToken) self.updatePlaceholderTextVisibility() self.repositionViews() } func removeToken(token:CLToken) { let index:Int? = self.tokens.indexOf(token) if index != nil { self.removeTokenAtIndex(index!) } } func allTokens() -> [CLToken] { return Array(self.tokens) } func tokenizeTextfieldText() -> CLToken? { //print("tokenizeTextfieldText()") var token:CLToken? = nil let text:String = self.textField.text! if text.characters.count > 0 { token = self.delegate?.tokenInputView(self, tokenForText: text) if (token != nil) { self.addToken(token!) self.textField.text = "" self.onTextFieldDidChange(self.textField) } } return token } func repositionViews() { let bounds:CGRect = self.bounds let rightBoundary:CGFloat = CGRectGetWidth(bounds) - PADDING_RIGHT var firstLineRightBoundary:CGFloat = rightBoundary var curX:CGFloat = PADDING_LEFT var curY:CGFloat = PADDING_TOP var totalHeight:CGFloat = STANDARD_ROW_HEIGHT var isOnFirstLine:Bool = true // print("repositionViews curX=\(curX) curY=\(curY)") //print("self.frame=\(self.frame)") // Position field view (if set) if self.fieldView != nil { var fieldViewRect:CGRect = self.fieldView!.frame fieldViewRect.origin.x = curX + FIELD_MARGIN_X fieldViewRect.origin.y = curY + ((STANDARD_ROW_HEIGHT - CGRectGetHeight(fieldViewRect) / 2.0)) - PADDING_TOP self.fieldView?.frame = fieldViewRect curX = CGRectGetMaxX(fieldViewRect) + FIELD_MARGIN_X // print("fieldViewRect=\(fieldViewRect)") } // Position field label (if field name is set) if !(self.fieldLabel.hidden) { var fieldLabelRect:CGRect = self.fieldLabel.frame fieldLabelRect.origin.x = curX + FIELD_MARGIN_X fieldLabelRect.origin.y = curY + ((STANDARD_ROW_HEIGHT - CGRectGetHeight(fieldLabelRect) / 2.0)) - PADDING_TOP self.fieldLabel.frame = fieldLabelRect curX = CGRectGetMaxX(fieldLabelRect) + FIELD_MARGIN_X //print("fieldLabelRect=\(fieldLabelRect)") } // Position accessory view (if set) if self.accessoryView != nil { var accessoryRect:CGRect = self.accessoryView!.frame; accessoryRect.origin.x = CGRectGetWidth(bounds) - PADDING_RIGHT - CGRectGetWidth(accessoryRect) accessoryRect.origin.y = curY; self.accessoryView!.frame = accessoryRect; firstLineRightBoundary = CGRectGetMinX(accessoryRect) - HSPACE; } // Position token views var tokenRect:CGRect = CGRectNull for tokenView:CLTokenView in self.tokenViews { tokenRect = tokenView.frame let tokenBoundary:CGFloat = isOnFirstLine ? firstLineRightBoundary : rightBoundary if curX + CGRectGetWidth(tokenRect) > tokenBoundary { // Need a new line curX = PADDING_LEFT curY += STANDARD_ROW_HEIGHT + VSPACE totalHeight += STANDARD_ROW_HEIGHT isOnFirstLine = false } tokenRect.origin.x = curX // Center our tokenView vertically within STANDARD_ROW_HEIGHT tokenRect.origin.y = curY + ((STANDARD_ROW_HEIGHT - CGRectGetHeight(tokenRect)) / 2.0) tokenView.frame = tokenRect curX = CGRectGetMaxX(tokenRect) + HSPACE } // Always indent textfield by a little bit curX += TEXT_FIELD_HSPACE let textBoundary:CGFloat = isOnFirstLine ? firstLineRightBoundary : rightBoundary var availableWidthForTextField:CGFloat = textBoundary - curX; if availableWidthForTextField < MINIMUM_TEXTFIELD_WIDTH { isOnFirstLine = false curX = PADDING_LEFT + TEXT_FIELD_HSPACE curY += STANDARD_ROW_HEIGHT + VSPACE totalHeight += STANDARD_ROW_HEIGHT // Adjust the width availableWidthForTextField = rightBoundary - curX; } var textFieldRect:CGRect = self.textField.frame; textFieldRect.origin.x = curX textFieldRect.origin.y = curY + self.additionalTextFieldYOffset textFieldRect.size.width = availableWidthForTextField textFieldRect.size.height = STANDARD_ROW_HEIGHT self.textField.frame = textFieldRect let oldContentHeight:CGFloat = self.intrinsicContentHeight; self.intrinsicContentHeight = CGRectGetMaxY(textFieldRect)+PADDING_BOTTOM; self.invalidateIntrinsicContentSize() if oldContentHeight != self.intrinsicContentHeight { self.delegate?.tokenInputView(self, didChangeHeightTo: self.intrinsicContentSize().height) } self.setNeedsDisplay() } func updatePlaceholderTextVisibility() { if self.tokens.count > 0 { self.textField.placeholder = nil } else { self.textField.placeholder = self.placeholderText } } override func layoutSubviews() { super.layoutSubviews() self.repositionViews() } // MARK: CLBackspaceDetectingTextFieldDelegate func textFieldDidDeleteBackwards(textField: UITextField) { dispatch_async(dispatch_get_main_queue()) { () -> Void in if textField.text?.characters.count == 0 { let tokenView:CLTokenView? = self.tokenViews.last if tokenView != nil { self.selectTokenView(tokenView!, animated: true) self.textField.resignFirstResponder() } } } } //MARK: UITextFieldDelegate func textFieldDidBeginEditing(textField: UITextField) { //print("textFieldDidBeginEditing:") self.delegate?.tokenInputViewDidBeginEditing(self) self.tokenViews.last?.hideUnselectedComma = false self.unselectAllTokenViewsAnimated(true) } func textFieldDidEndEditing(textField: UITextField) { //print("textFieldDidEndEditing:") self.delegate?.tokenInputViewDidEndEditing(self) self.tokenViews.last?.hideUnselectedComma = true } func textFieldShouldReturn(textField: UITextField) -> Bool { //print("textFieldShouldReturn:") self.tokenizeTextfieldText() return false } func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool { //print("textField:shouldChangeCharactersInRange:replacementString:\(string)") if string.characters.count > 0 && self.tokenizationCharacters.contains(string) { self.tokenizeTextfieldText() return false } return true } func onTextFieldDidChange(sender:UITextField) { // print("onTextFieldDidChange") self.delegate?.tokenInputView(self, didChangeText: self.textField.text!) } func textFieldDisplayOffset() -> CGFloat { return CGRectGetMinY(self.textField.frame) - PADDING_TOP; } func text() -> String? { return self.textField.text } func tokenViewDidRequestDelete(tokenView:CLTokenView, replaceWithText replacementText:String?) { self.textField.becomeFirstResponder() if replacementText?.characters.count > 0 { self.textField.text = replacementText } let index:Int? = self.tokenViews.indexOf(tokenView) if index == nil { return } self.removeTokenAtIndex(index!) } func tokenViewDidRequestSelection(tokenView:CLTokenView) { self.selectTokenView(tokenView, animated:true) } func selectTokenView(tokenView:CLTokenView, animated aBool:Bool) { tokenView.setSelected(true, animated: aBool) for otherTokenView:CLTokenView in self.tokenViews { if otherTokenView != tokenView { otherTokenView.setSelected(false, animated: aBool) } } } func unselectAllTokenViewsAnimated(animated:Bool) { for tokenView:CLTokenView in self.tokenViews { tokenView.setSelected(false, animated: animated) } } // func isEditing() -> Bool { return self.textField.editing } func beginEditing() { self.textField.becomeFirstResponder() self.unselectAllTokenViewsAnimated(false) } func endEditing() { self.textField.resignFirstResponder() } // override func drawRect(rect: CGRect) { super.drawRect(rect) if self.drawBottomBorder == true { let context:CGContextRef? = UIGraphicsGetCurrentContext() CGContextSetStrokeColorWithColor(context, UIColor.lightGrayColor().CGColor) CGContextSetLineWidth(context, 0.5) CGContextMoveToPoint(context, CGRectGetWidth(self.bounds), self.bounds.size.height) CGContextAddLineToPoint(context, CGRectGetWidth(bounds), bounds.size.height); CGContextStrokePath(context) } } }
mit
019621eef55461d9c400020dbdbde0ef
34.014553
135
0.615047
4.911344
false
false
false
false
TrustWallet/trust-wallet-ios
Trust/Settings/ViewControllers/SettingsViewController.swift
1
13557
// Copyright DApps Platform Inc. All rights reserved. import UIKit import Eureka import StoreKit import TrustCore protocol SettingsViewControllerDelegate: class { func didAction(action: SettingsAction, in viewController: SettingsViewController) } final class SettingsViewController: FormViewController, Coordinator { var coordinators: [Coordinator] = [] struct Values { static let currencyPopularKey = "0" static let currencyAllKey = "1" static let passcodeRow = "PasscodeRow" } private var config = Config() private var lock = Lock() private let helpUsCoordinator = HelpUsCoordinator() weak var delegate: SettingsViewControllerDelegate? var isPasscodeEnabled: Bool { return lock.isPasscodeSet() } lazy var viewModel: SettingsViewModel = { return SettingsViewModel(isDebug: isDebug) }() lazy var autoLockRow: PushRow<AutoLock> = { return PushRow<AutoLock> { [weak self] in guard let strongSelf = self else { return } $0.title = strongSelf.viewModel.autoLockTitle $0.options = strongSelf.viewModel.autoLockOptions $0.value = strongSelf.lock.getAutoLockType() $0.selectorTitle = strongSelf.viewModel.autoLockTitle $0.displayValueFor = { value in return value?.displayName } $0.hidden = Condition.function([Values.passcodeRow], { form in return !((form.rowBy(tag: Values.passcodeRow) as? SwitchRow)?.value ?? false) }) }.onChange { [weak self] row in let autoLockType = row.value ?? AutoLock.immediate self?.lock.setAutoLockType(type: autoLockType) self?.lock.removeAutoLockTime() }.onPresent { _, selectorController in selectorController.enableDeselection = false }.cellSetup { cell, _ in cell.imageView?.image = R.image.settings_colorful_auto() } }() let session: WalletSession let keystore: Keystore init( session: WalletSession, keystore: Keystore ) { self.session = session self.keystore = keystore super.init(nibName: nil, bundle: nil) } override func viewDidLoad() { super.viewDidLoad() title = R.string.localizable.settingsNavigationTitle() form = Section() <<< walletsRow(for: session.account) +++ Section(R.string.localizable.settingsSecurityLabelTitle()) <<< SwitchRow(Values.passcodeRow) { [weak self] in $0.title = self?.viewModel.passcodeTitle $0.value = self?.isPasscodeEnabled }.onChange { [unowned self] row in if row.value == true { self.setPasscode { result in row.value = result row.updateCell() } } else { self.lock.deletePasscode() self.updateAutoLockRow(with: AutoLock.immediate) } }.cellSetup { cell, _ in cell.imageView?.image = R.image.settings_colorful_security() } <<< autoLockRow <<< AppFormAppearance.button { [weak self] row in row.cellStyle = .value1 row.presentationMode = .show(controllerProvider: ControllerProvider<UIViewController>.callback { let controller = NotificationsViewController() controller.didChange = { [weak self] change in self?.run(action: .pushNotifications(change)) } return controller }, onDismiss: { _ in }) }.cellUpdate { cell, _ in cell.imageView?.image = R.image.settings_colorful_notifications() cell.textLabel?.text = R.string.localizable.settingsPushNotificationsTitle() cell.accessoryType = .disclosureIndicator } +++ Section() <<< currencyRow() <<< browserRow() <<< privacyRow() +++ Section(R.string.localizable.settingsJoinCommunityLabelTitle()) <<< linkProvider(type: .twitter) <<< linkProvider(type: .telegram) <<< linkProvider(type: .facebook) <<< linkProvider(type: .discord) +++ Section() <<< linkProvider(type: .helpCenter) +++ Section() <<< shareWithFriendsRow() +++ Section() <<< aboutRow() +++ Section() <<< developersRow() } private func shareWithFriendsRow() -> ButtonRow { return AppFormAppearance.button { button in button.title = R.string.localizable.shareWithFriends() button.cell.imageView?.image = R.image.settings_colorful_share() }.onCellSelection { [unowned self] cell, _ in self.helpUsCoordinator.presentSharing(in: self, from: cell.contentView) } } private func walletsRow(for wallet: WalletInfo) -> ButtonRow { let viewModel = WalletInfoViewModel(wallet: wallet) return AppFormAppearance.button { row in row.cellStyle = .value1 }.cellUpdate { cell, _ in cell.textLabel?.textColor = .black cell.imageView?.image = R.image.settings_colorful_wallets() cell.textLabel?.text = R.string.localizable.wallets() cell.detailTextLabel?.text = String(viewModel.name.prefix(14)) cell.accessoryType = .disclosureIndicator }.onCellSelection { [weak self] (_, _) in guard let strongSelf = self else { return } strongSelf.delegate?.didAction(action: .wallets, in: strongSelf) } } private func currencyRow() -> PushRow<Currency> { return PushRow<Currency> { [weak self] in $0.title = self?.viewModel.currencyTitle $0.selectorTitle = self?.viewModel.currencyTitle $0.options = self?.viewModel.currency $0.value = self?.config.currency $0.displayValueFor = { value in let currencyCode = value?.rawValue ?? "" return currencyCode + " - " + (NSLocale.current.localizedString(forCurrencyCode: currencyCode) ?? "") } }.onChange { [weak self] row in guard let value = row.value else { return } self?.config.currency = value self?.run(action: .currency) }.onPresent { _, selectorController in selectorController.enableDeselection = false selectorController.sectionKeyForValue = { option in switch option { case .USD, .EUR, .GBP, .AUD, .RUB: return Values.currencyPopularKey default: return Values.currencyAllKey } } selectorController.sectionHeaderTitleForKey = { option in switch option { case Values.currencyPopularKey: return R.string.localizable.settingsCurrencyPopularLabelTitle() case Values.currencyAllKey: return R.string.localizable.settingsCurrencyAllLabelTitle() default: return "" } } }.cellSetup { cell, _ in cell.imageView?.image = R.image.settings_colorful_currency() } } private func aboutRow() -> ButtonRow { return AppFormAppearance.button { row in row.cellStyle = .value1 row.presentationMode = .show(controllerProvider: ControllerProvider<UIViewController>.callback { [weak self] in let controller = AboutViewController() controller.delegate = self return controller }, onDismiss: { _ in }) }.cellUpdate { cell, _ in cell.textLabel?.textColor = .black cell.imageView?.image = R.image.settings_colorful_about() cell.textLabel?.text = R.string.localizable.settingsAboutTitle() cell.accessoryType = .disclosureIndicator } } private func browserRow() -> ButtonRow { return AppFormAppearance.button { row in row.cellStyle = .value1 row.presentationMode = .show(controllerProvider:ControllerProvider<UIViewController>.callback { [weak self] in let controller = BrowserConfigurationViewController() controller.delegate = self return controller }, onDismiss: nil) }.cellUpdate { cell, _ in cell.textLabel?.textColor = .black cell.imageView?.image = R.image.settings_colorful_dappbrowser() cell.textLabel?.text = R.string.localizable.settingsBrowserTitle() cell.accessoryType = .disclosureIndicator } } private func privacyRow() -> ButtonRow { return AppFormAppearance.button { row in row.cellStyle = .value1 row.presentationMode = .show(controllerProvider:ControllerProvider<UIViewController>.callback { return PrivacyViewController() }, onDismiss: nil) }.cellUpdate { cell, _ in cell.imageView?.image = R.image.settings_colorful_privacy() cell.textLabel?.text = R.string.localizable.settingsPrivacyTitle() cell.accessoryType = .disclosureIndicator } } private func developersRow() -> ButtonRow { return AppFormAppearance.button { row in row.cellStyle = .value1 row.presentationMode = .show(controllerProvider:ControllerProvider<UIViewController>.callback {[weak self] in let controller = DeveloperViewController() controller.delegate = self return controller }, onDismiss: nil) }.cellUpdate { cell, _ in cell.imageView?.image = R.image.settings_colorful_developer() cell.textLabel?.text = R.string.localizable.developer() cell.accessoryType = .disclosureIndicator } } func setPasscode(completion: ((Bool) -> Void)? = .none) { let coordinator = LockCreatePasscodeCoordinator( model: LockCreatePasscodeViewModel() ) coordinator.delegate = self coordinator.start() coordinator.lockViewController.willFinishWithResult = { [weak self] result in if result { let type = AutoLock.immediate self?.lock.setAutoLockType(type: type) self?.updateAutoLockRow(with: type) } completion?(result) self?.navigationController?.dismiss(animated: true, completion: nil) } addCoordinator(coordinator) navigationController?.present(coordinator.navigationController, animated: true, completion: nil) } private func linkProvider( type: URLServiceProvider ) -> ButtonRow { return AppFormAppearance.button { $0.title = type.title }.onCellSelection { [weak self] _, _ in guard let `self` = self else { return } if let localURL = type.localURL, UIApplication.shared.canOpenURL(localURL) { UIApplication.shared.open(localURL, options: [:], completionHandler: .none) } else { self.openURLInBrowser(type.remoteURL) } }.cellSetup { cell, _ in cell.imageView?.image = type.image }.cellUpdate { cell, _ in cell.accessoryType = .disclosureIndicator cell.textLabel?.textAlignment = .left cell.textLabel?.textColor = .black } } private func updateAutoLockRow(with type: AutoLock) { self.autoLockRow.value = type self.autoLockRow.reload() } func run(action: SettingsAction) { delegate?.didAction(action: action, in: self) } func openURLInBrowser(_ url: URL) { self.delegate?.didAction(action: .openURL(url), in: self) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } extension SettingsViewController: LockCreatePasscodeCoordinatorDelegate { func didCancel(in coordinator: LockCreatePasscodeCoordinator) { coordinator.lockViewController.willFinishWithResult?(false) navigationController?.dismiss(animated: true, completion: nil) removeCoordinator(coordinator) } } extension SettingsViewController: AboutViewControllerDelegate { func didPressURL(_ url: URL, in controller: AboutViewController) { openURLInBrowser(url) } } extension SettingsViewController: BrowserConfigurationViewControllerDelegate { func didPressDeleteCache(in controller: BrowserConfigurationViewController) { delegate?.didAction(action: .clearBrowserCache, in: self) } } extension SettingsViewController: Scrollable { func scrollOnTop() { guard isViewLoaded else { return } tableView.scrollOnTop() } } extension SettingsViewController: DeveloperViewControllerDelegate { func didClearTransactions(in controller: DeveloperViewController) { delegate?.didAction(action: .clearTransactions, in: self) } func didClearTokens(in controller: DeveloperViewController) { delegate?.didAction(action: .clearTokens, in: self) } }
gpl-3.0
c44e4464b49d2fa7f4b19b219197e058
36.97479
123
0.601608
5.133283
false
false
false
false
mrdepth/libdgmpp
swift-wrapper/DGMGang.swift
2
3115
// // DGMGang.swift // dgmpp // // Created by Artem Shimanski on 14.12.2017. // import Foundation import cwrapper public class DGMGang: DGMType, Codable { public convenience init() throws { self.init(dgmpp_gang_create()!) } public convenience init(_ other: DGMGang) { self.init(dgmpp_gang_copy(other.handle)) } public func add(_ pilot: DGMCharacter) { willChange() dgmpp_gang_add_pilot(handle, pilot.handle) } public func remove(_ pilot: DGMCharacter) { willChange() dgmpp_gang_remove_pilot(handle, pilot.handle) } public var pilots: [DGMCharacter] { return DGMArray<DGMCharacter>(dgmpp_gang_copy_pilots(handle)).array } public var factorReload: Bool { get { return dgmpp_gang_get_factor_reload(handle) != 0 } set { willChange() dgmpp_gang_set_factor_reload(handle, newValue ? 1 : 0) } } public var area: DGMArea? { get { guard let area = dgmpp_gang_copy_area(handle) else {return nil} return DGMType.type(area) as? DGMArea } set { willChange() dgmpp_gang_set_area(handle, newValue?.handle) } } override func sendChange() { super.sendChange() pilots.forEach{$0.sendChange()} } public convenience required init(from decoder: Decoder) throws { try self.init() let container = try decoder.container(keyedBy: CodingKeys.self) let pilots = try container.decode([DGMCharacter].self, forKey: .pilots) for pilot in pilots { add(pilot) } area = try container.decodeIfPresent(DGMArea.self, forKey: .area) let links = try container.decode([Int: Int].self, forKey: .targets) let pilotsMap = Dictionary(pilots.map{($0.identifier, $0)}) {a, _ in a} for pilot in pilots { for module in pilot.ship?.modules ?? [] { guard let link = links[module.identifier] else {continue} module.target = pilotsMap[link]?.ship } for drone in pilot.ship?.drones ?? [] { guard let link = links[drone.identifier] else {continue} drone.target = pilotsMap[link]?.ship } } } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(pilots, forKey: .pilots) try container.encodeIfPresent(area, forKey: .area) var links = [Int: Int]() for pilot in pilots { for module in pilot.ship?.modules ?? [] { if let target = module.target?.parent { links[module.identifier] = target.identifier } } for drone in pilot.ship?.drones ?? [] { if let target = drone.target?.parent { links[drone.identifier] = target.identifier } } } try container.encode(links, forKey: .targets) } enum CodingKeys: String, CodingKey { case pilots case area case targets } }
mit
81fff0b450b686b7ad3ae5f85421c5f4
26.566372
79
0.58427
3.898623
false
false
false
false
ztmdsbt/tw-ios-training
storyboard-and-autolayout/json-data/json-data/MasterViewController.swift
1
4065
// // MasterViewController.swift // json-data // // Created by Kaihang An on 6/23/15. // Copyright (c) 2015 Thoughtworks. inc. All rights reserved. // import UIKit import Kingfisher class MasterViewController: UITableViewController { var detailViewController: DetailViewController? = nil var jsonTitle: NSString! = nil var jsonArray: NSArray! = nil override func awakeFromNib() { super.awakeFromNib() if UIDevice.currentDevice().userInterfaceIdiom == .Pad { self.clearsSelectionOnViewWillAppear = false self.preferredContentSize = CGSize(width: 320.0, height: 600.0) } } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. self.navigationItem.leftBarButtonItem = self.editButtonItem() let addButton = UIBarButtonItem(barButtonSystemItem: .Add, target: self, action: "insertNewObject:") self.navigationItem.rightBarButtonItem = addButton if let split = self.splitViewController { let controllers = split.viewControllers self.detailViewController = controllers[controllers.count - 1].topViewController as? DetailViewController } get_json_data() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func insertNewObject(sender: AnyObject) { } // MARK: - Segues override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "showDetail" { if let indexPath = self.tableView.indexPathForSelectedRow() { let object = jsonArray[indexPath.row] as! NSDictionary let controller = (segue.destinationViewController as! UINavigationController).topViewController as! DetailViewController controller.detailItem = object controller.navigationItem.leftBarButtonItem = self.splitViewController?.displayModeButtonItem() controller.navigationItem.leftItemsSupplementBackButton = true } } } // MARK: - Table View override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return jsonArray.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! TableViewCell let row = jsonArray[indexPath.row] as! NSDictionary cell.labelName.text = jsonArray[indexPath.row]["title"] as? String cell.labelDescription.text = jsonArray[indexPath.row]["description"] as? String if let urlString = jsonArray[indexPath.row]["imageHref"] as? String { let imageUrl = NSURL(string: urlString) if let imageData = NSData(contentsOfURL: imageUrl!) { cell.imgAvater.kf_setImageWithURL(imageUrl!, placeholderImage: nil) } } return cell } override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } else if editingStyle == .Insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view. } } func get_json_data() { var error: NSError? if let path = NSBundle.mainBundle().pathForResource("facts", ofType: "json") { let jsonData: NSData = NSData(contentsOfFile: path)! let jsonDict = NSJSONSerialization.JSONObjectWithData(jsonData, options: nil, error: &error) as! NSDictionary jsonTitle = jsonDict["title"] as! NSString jsonArray = jsonDict["rows"] as! NSArray } } }
gpl-2.0
afb0cf968cfc176c78e9024eaa6cede9
35.621622
155
0.726445
5.074906
false
false
false
false
darrarski/Messages-iOS
MessagesApp/UI/Controllers/MessagesViewController.swift
1
4199
import UIKit class MessagesViewController: UIViewController { init(messagesService: MessagesService) { self.messagesService = messagesService super.init(nibName: nil, bundle: nil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: View var messagesView: MessagesView! { return view as? MessagesView } override func loadView() { view = MessagesView() } override func viewDidLoad() { super.viewDidLoad() embed(childViewController: collectionViewController, inView: messagesView.collectionViewContainer) setupActions() loadMoreMessages() } // MARK: Child view controllers let collectionViewController = MessagesCollectionViewController() // MARK: UI Actions private func setupActions() { messagesInputAccessoryView.sendButton.addTarget(self, action: #selector(sendButtonAction), for: .touchUpInside) collectionViewController.refreshControl.addTarget(self, action: #selector(refreshControlAction), for: .valueChanged) } func sendButtonAction() { guard let text = messagesInputAccessoryView.textView.text, !text.isEmpty else { return } sendMessage(text) messagesInputAccessoryView.textView.text = nil } func refreshControlAction() { loadMoreMessages() } // MARK: Messages private let messagesPerPage = 10 private var nextMessagesPage: Int { return Int(floor(Double(collectionViewController.messages.count / messagesPerPage))) } private func loadMoreMessages() { collectionViewController.refreshControl.beginRefreshing() messagesService.fetchMessages(page: nextMessagesPage, perPage: messagesPerPage) { [weak self] result in DispatchQueue.main.async { switch result { case .success(let messages): self?.collectionViewController.appendMessages(messages.map { MessageViewModel(message: $0) }) { self?.collectionViewController.refreshControl.endRefreshing() } case .failure(let error): self?.presentError(error) } } } } private func sendMessage(_ text: String) { let outgoingMessageViewModel = OutgoingMessageViewModel(text: text) collectionViewController.insertOutgoingMessage(outgoingMessageViewModel) messagesService.sendMessage(text) { [weak self] result in DispatchQueue.main.async { self?.collectionViewController.removeOutgoingMessage(outgoingMessageViewModel) switch result { case .success(let message): let messageViewModel = MessageViewModel(message: message) self?.collectionViewController.insertMessage(messageViewModel) case .failure(let error): self?.presentError(error) } } } } // MARK: Input Accessory View override var canBecomeFirstResponder: Bool { return true } override var inputAccessoryView: UIView? { return messagesInputAccessoryView } private let messagesInputAccessoryView = MessagesInputAccessoryView() // MARK: Private private let messagesService: MessagesService private func presentError(_ error: Error) { let alertController = UIAlertController(title: "Error occured", message: error.localizedDescription, preferredStyle: .alert) alertController.addAction(UIAlertAction(title: "OK", style: .default, handler: nil)) present(alertController, animated: true) } }
mit
16470895d8dfeaa0c0512bd2e1a28e08
32.592
115
0.589188
6.175
false
false
false
false
chrisdhaan/CDYelpFusionKit
Source/CDYelpUser.swift
1
2047
// // CDYelpUser.swift // CDYelpFusionKit // // Created by Christopher de Haan on 5/7/17. // // Copyright © 2016-2022 Christopher de Haan <[email protected]> // // 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. // #if !os(OSX) import UIKit #else import Foundation #endif public struct CDYelpUser: Decodable { public let id: String? public let profileUrl: String? public let name: String? public let imageUrl: String? enum CodingKeys: String, CodingKey { case id case profileUrl = "profile_url" case name case imageUrl = "image_url" } public func profileUrlAsUrl() -> URL? { if let profileUrl = self.profileUrl, let asUrl = URL(string: profileUrl) { return asUrl } return nil } public func imageUrlAsUrl() -> URL? { if let imageUrl = self.imageUrl, let asUrl = URL(string: imageUrl) { return asUrl } return nil } }
mit
62884a2716e6c2f5fd7b9838cd6d054e
31.47619
81
0.680841
4.167006
false
false
false
false
googlearchive/science-journal-ios
ScienceJournal/UI/TriggerListDataSource.swift
1
2269
/* * Copyright 2019 Google LLC. All Rights Reserved. * * 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 /// A data source for a list of triggers for a sensor. They can be modified, deleted or added to. class TriggerListDataSource { // MARK: - Properties /// The number of items in the data source. var numberOfItems: Int { return triggers.count } /// Whether or not the data source has items. var hasItems: Bool { return numberOfItems != 0 } /// The triggers. var triggers: [SensorTrigger] // MARK: - Public /// Designated initializer. /// /// - Parameter: sensorTriggers: The triggers. init(sensorTriggers: [SensorTrigger]) { triggers = sensorTriggers } /// Returns the sensor trigger for an index path. func item(at indexPath: IndexPath) -> SensorTrigger { return triggers[indexPath.item] } /// Returns the index path of an item. func indexPathOfItem(_ item: SensorTrigger) -> IndexPath? { guard let index = triggers.firstIndex(where: { $0.triggerID == item.triggerID }) else { return nil } return IndexPath(item: index, section: 0) } /// Returns the index path of the last item. var indexPathOfLastItem: IndexPath { return IndexPath(item: numberOfItems - 1, section: 0) } /// Adds a sensor trigger to the end of the list. func addItem(_ item: SensorTrigger) { insertItem(item, atIndex: triggers.endIndex) } /// Inserts a sensor trigger at the given index. func insertItem(_ item: SensorTrigger, atIndex index: Int) { triggers.insert(item, at: index) } /// Removes a trigger. @discardableResult func removeItem(at indexPath: IndexPath) -> SensorTrigger? { return triggers.remove(at: indexPath.item) } }
apache-2.0
ff40ea71d0e116a271e389a8802f0462
28.089744
97
0.693698
4.170956
false
false
false
false
johnno1962d/swift
test/Constraints/diagnostics.swift
1
32883
// RUN: %target-parse-verify-swift protocol P { associatedtype SomeType } protocol P2 { func wonka() } extension Int : P { typealias SomeType = Int } extension Double : P { typealias SomeType = Double } func f0(_ x: Int, _ y: Float) { } func f1(_: (Int, Float) -> Int) { } func f2(_: (_: (Int) -> Int)) -> Int {} func f3(_: (_: (Int) -> Float) -> Int) {} func f4(_ x: Int) -> Int { } func f5<T : P2>(_ : T) { } func f6<T : P, U : P where T.SomeType == U.SomeType>(_ t: T, _ u: U) {} var i : Int var d : Double // Check the various forms of diagnostics the type checker can emit. // Tuple size mismatch. f1( f4 // expected-error {{cannot convert value of type '(Int) -> Int' to expected argument type '(Int, Float) -> Int'}} ) // Tuple element unused. f0(i, i, i) // expected-error{{extra argument in call}} // Position mismatch f5(f4) // expected-error {{argument type '(Int) -> Int' does not conform to expected type 'P2'}} // Tuple element not convertible. f0(i, d // expected-error {{cannot convert value of type 'Double' to expected argument type 'Float'}} ) // Function result not a subtype. f1( f0 // expected-error {{cannot convert value of type '(Int, Float) -> ()' to expected argument type '(Int, Float) -> Int'}} ) f3( f2 // expected-error {{cannot convert value of type '(((Int) -> Int)) -> Int' to expected argument type '((Int) -> Float) -> Int'}} ) f4(i, d) // expected-error {{extra argument in call}} // Missing member. i.wobble() // expected-error{{value of type 'Int' has no member 'wobble'}} // Generic member does not conform. extension Int { func wibble<T: P2>(_ x: T, _ y: T) -> T { return x } func wubble<T>(_ x: Int -> T) -> T { return x(self) } } i.wibble(3, 4) // expected-error {{argument type 'Int' does not conform to expected type 'P2'}} // Generic member args correct, but return type doesn't match. struct A : P2 { func wonka() {} } let a = A() for j in i.wibble(a, a) { // expected-error {{type 'A' does not conform to protocol 'Sequence'}} } // Generic as part of function/tuple types func f6<T:P2>(_ g: Void -> T) -> (c: Int, i: T) { return (c: 0, i: g()) } func f7() -> (c: Int, v: A) { let g: Void -> A = { return A() } return f6(g) // expected-error {{cannot convert return expression of type '(c: Int, i: A)' to return type '(c: Int, v: A)'}} } func f8<T:P2>(_ n: T, _ f: (T) -> T) {} f8(3, f4) // expected-error {{in argument type '(Int) -> Int', 'Int' does not conform to expected type 'P2'}} typealias Tup = (Int, Double) func f9(_ x: Tup) -> Tup { return x } f8((1,2.0), f9) // expected-error {{in argument type '(Tup) -> Tup', 'Tup' (aka '(Int, Double)') does not conform to expected type 'P2'}} // <rdar://problem/19658691> QoI: Incorrect diagnostic for calling nonexistent members on literals 1.doesntExist(0) // expected-error {{value of type 'Int' has no member 'doesntExist'}} [1, 2, 3].doesntExist(0) // expected-error {{value of type '[Int]' has no member 'doesntExist'}} "awfawf".doesntExist(0) // expected-error {{value of type 'String' has no member 'doesntExist'}} // Does not conform to protocol. f5(i) // expected-error {{argument type 'Int' does not conform to expected type 'P2'}} // Make sure we don't leave open existentials when diagnosing. // <rdar://problem/20598568> func pancakes(_ p: P2) { f4(p.wonka) // expected-error{{cannot convert value of type '() -> ()' to expected argument type 'Int'}} f4(p.wonka()) // expected-error{{cannot convert value of type '()' to expected argument type 'Int'}} } protocol Shoes { static func select(_ subject: Shoes) -> Self } // Here the opaque value has type (metatype_type (archetype_type ... )) func f(_ x: Shoes, asType t: Shoes.Type) { return t.select(x) // expected-error{{unexpected non-void return value in void function}} } infix operator **** { associativity left precedence 200 } func ****(_: Int, _: String) { } i **** i // expected-error{{cannot convert value of type 'Int' to expected argument type 'String'}} infix operator ***~ { associativity left precedence 200 } func ***~(_: Int, _: String) { } i ***~ i // expected-error{{cannot convert value of type 'Int' to expected argument type 'String'}} @available(*, unavailable, message: "call the 'map()' method on the sequence") public func myMap<C : Collection, T>( _ source: C, _ transform: (C.Iterator.Element) -> T ) -> [T] { fatalError("unavailable function can't be called") } @available(*, unavailable, message: "call the 'map()' method on the optional value") public func myMap<T, U>(_ x: T?, _ f: @noescape (T) -> U) -> U? { fatalError("unavailable function can't be called") } // <rdar://problem/20142523> // FIXME: poor diagnostic, to be fixed in 20142462. For now, we just want to // make sure that it doesn't crash. func rdar20142523() { myMap(0..<10, { x in // expected-error{{ambiguous reference to member '..<'}} () return x }) } // <rdar://problem/21080030> Bad diagnostic for invalid method call in boolean expression: (_, IntegerLiteralConvertible)' is not convertible to 'IntegerLiteralConvertible func rdar21080030() { var s = "Hello" if s.characters.count() == 0 {} // expected-error{{cannot call value of non-function type 'Distance'}} } // <rdar://problem/21248136> QoI: problem with return type inference mis-diagnosed as invalid arguments func r21248136<T>() -> T { preconditionFailure() } // expected-note 2 {{in call to function 'r21248136'}} r21248136() // expected-error {{generic parameter 'T' could not be inferred}} let _ = r21248136() // expected-error {{generic parameter 'T' could not be inferred}} // <rdar://problem/16375647> QoI: Uncallable funcs should be compile time errors func perform<T>() {} // expected-error {{generic parameter 'T' is not used in function signature}} // <rdar://problem/17080659> Error Message QOI - wrong return type in an overload func recArea(_ h: Int, w : Int) { return h * w // expected-error {{no '*' candidates produce the expected contextual result type '()'}} // expected-note @-1 {{overloads for '*' exist with these result types: UInt8, Int8, UInt16, Int16, UInt32, Int32, UInt64, Int64, UInt, Int, Float, Double}} } // <rdar://problem/17224804> QoI: Error In Ternary Condition is Wrong func r17224804(_ monthNumber : Int) { // expected-error @+2 {{binary operator '+' cannot be applied to operands of type 'String' and 'Int'}} // expected-note @+1 {{overloads for '+' exist with these partially matching parameter lists: (Int, Int), (String, String), (UnsafeMutablePointer<Pointee>, Int), (UnsafePointer<Pointee>, Int)}} let monthString = (monthNumber <= 9) ? ("0" + monthNumber) : String(monthNumber) } // <rdar://problem/17020197> QoI: Operand of postfix '!' should have optional type; type is 'Int?' func r17020197(_ x : Int?, y : Int) { if x! { } // expected-error {{type 'Int' does not conform to protocol 'Boolean'}} // <rdar://problem/12939553> QoI: diagnostic for using an integer in a condition is utterly terrible if y {} // expected-error {{type 'Int' does not conform to protocol 'Boolean'}} } // <rdar://problem/20714480> QoI: Boolean expr not treated as Bool type when function return type is different func validateSaveButton(_ text: String) { return (text.characters.count > 0) ? true : false // expected-error {{unexpected non-void return value in void function}} } // <rdar://problem/20201968> QoI: poor diagnostic when calling a class method via a metatype class r20201968C { func blah() { r20201968C.blah() // expected-error {{use of instance member 'blah' on type 'r20201968C'; did you mean to use a value of type 'r20201968C' instead?}} } } // <rdar://problem/21459429> QoI: Poor compilation error calling assert func r21459429(_ a : Int) { assert(a != nil, "ASSERT COMPILATION ERROR") // expected-error {{value of type 'Int' can never be nil, comparison isn't allowed}} } // <rdar://problem/21362748> [WWDC Lab] QoI: cannot subscript a value of type '[Int]?' with an index of type 'Int' struct StructWithOptionalArray { var array: [Int]? } func testStructWithOptionalArray(_ foo: StructWithOptionalArray) -> Int { return foo.array[0] // expected-error {{value of optional type '[Int]?' not unwrapped; did you mean to use '!' or '?'?}} {{19-19=!}} } // <rdar://problem/19774755> Incorrect diagnostic for unwrapping non-optional bridged types var invalidForceUnwrap = Int()! // expected-error {{cannot force unwrap value of non-optional type 'Int'}} {{31-32=}} // <rdar://problem/20905802> Swift using incorrect diagnostic sometimes on String().asdf String().asdf // expected-error {{value of type 'String' has no member 'asdf'}} // <rdar://problem/21553065> Spurious diagnostic: '_' can only appear in a pattern or on the left side of an assignment protocol r21553065Protocol {} class r21553065Class<T : AnyObject> {} _ = r21553065Class<r21553065Protocol>() // expected-error {{type 'r21553065Protocol' does not conform to protocol 'AnyObject'}} // Type variables not getting erased with nested closures struct Toe { let toenail: Nail // expected-error {{use of undeclared type 'Nail'}} func clip() { toenail.inspect { x in toenail.inspect { y in } } } } // <rdar://problem/21447318> dot'ing through a partially applied member produces poor diagnostic class r21447318 { var x = 42 func doThing() -> r21447318 { return self } } func test21447318(_ a : r21447318, b : () -> r21447318) { a.doThing.doThing() // expected-error {{method 'doThing' was used as a property; add () to call it}} {{12-12=()}} b.doThing() // expected-error {{function 'b' was used as a property; add () to call it}} {{4-4=()}} } // <rdar://problem/20409366> Diagnostics for init calls should print the class name class r20409366C { init(a : Int) {} init?(a : r20409366C) { let req = r20409366C(a: 42)? // expected-error {{cannot use optional chaining on non-optional value of type 'r20409366C'}} {{32-33=}} } } // <rdar://problem/18800223> QoI: wrong compiler error when swift ternary operator branches don't match func r18800223(_ i : Int) { // 20099385 _ = i == 0 ? "" : i // expected-error {{result values in '? :' expression have mismatching types 'String' and 'Int'}} // 19648528 _ = true ? [i] : i // expected-error {{result values in '? :' expression have mismatching types '[Int]' and 'Int'}} var buttonTextColor: String? _ = (buttonTextColor != nil) ? 42 : {$0}; // expected-error {{result values in '? :' expression have mismatching types 'Int' and '(_) -> _'}} } // <rdar://problem/21883806> Bogus "'_' can only appear in a pattern or on the left side of an assignment" is back _ = { $0 } // expected-error {{unable to infer closure return type in current context}} _ = 4() // expected-error {{cannot call value of non-function type 'Int'}} _ = 4(1) // expected-error {{cannot call value of non-function type 'Int'}} // <rdar://problem/21784170> Incongruous `unexpected trailing closure` error in `init` function which is cast and called without trailing closure. func rdar21784170() { let initial = (1.0 as Double, 2.0 as Double) (Array.init as (Double...) -> Array<Double>)(initial as (Double, Double)) // expected-error {{cannot convert value of type '(Double, Double)' to expected argument type 'Double'}} } // <rdar://problem/21829141> BOGUS: unexpected trailing closure func expect<T, U>(_: T) -> (U.Type) -> Int { return { a in 0 } } func expect<T, U>(_: T, _: Int = 1) -> (U.Type) -> String { return { a in "String" } } let expectType1 = expect(Optional(3))(Optional<Int>.self) let expectType1Check: Int = expectType1 // <rdar://problem/19804707> Swift Enum Scoping Oddity func rdar19804707() { enum Op { case BinaryOperator((Double, Double) -> Double) } var knownOps : Op knownOps = Op.BinaryOperator({$1 - $0}) knownOps = Op.BinaryOperator(){$1 - $0} knownOps = Op.BinaryOperator{$1 - $0} knownOps = .BinaryOperator({$1 - $0}) // FIXME: rdar://19804707 - These two statements should be accepted by the type checker. knownOps = .BinaryOperator(){$1 - $0} // expected-error {{reference to member 'BinaryOperator' cannot be resolved without a contextual type}} knownOps = .BinaryOperator{$1 - $0} // expected-error {{reference to member 'BinaryOperator' cannot be resolved without a contextual type}} } // <rdar://problem/20789423> Unclear diagnostic for multi-statement closure with no return type func r20789423() { class C { func f(_ value: Int) { } } let p: C print(p.f(p)()) // expected-error {{cannot convert value of type 'C' to expected argument type 'Int'}} let _f = { (v: Int) in // expected-error {{unable to infer closure return type in current context}} print("a") return "hi" } } func f7(_ a: Int) -> (b: Int) -> Int { return { b in a+b } } f7(1)(b: 1) f7(1.0)(2) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}} f7(1)(1.0) // expected-error {{missing argument label 'b:' in call}} f7(1)(b: 1.0) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}} let f8 = f7(2) f8(b: 1) f8(10) // expected-error {{missing argument label 'b:' in call}} {{4-4=b: }} f8(1.0) // expected-error {{missing argument label 'b:' in call}} f8(b: 1.0) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}} class CurriedClass { func method1() {} func method2(_ a: Int) -> (b : Int) -> () { return { b in () } } func method3(_ a: Int, b : Int) {} } let c = CurriedClass() _ = c.method1 c.method1(1) // expected-error {{argument passed to call that takes no arguments}} _ = c.method2(1) _ = c.method2(1.0) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}} c.method2(1)(b: 2) c.method2(1)(c: 2) // expected-error {{incorrect argument label in call (have 'c:', expected 'b:')}} {{14-15=b}} c.method2(1)(c: 2.0) // expected-error {{incorrect argument label in call (have 'c:', expected 'b:')}} c.method2(1)(b: 2.0) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}} c.method2(1.0)(b: 2) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}} c.method2(1.0)(b: 2.0) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}} CurriedClass.method1(c)() _ = CurriedClass.method1(c) CurriedClass.method1(c)(1) // expected-error {{argument passed to call that takes no arguments}} CurriedClass.method1(2.0)(1) // expected-error {{use of instance member 'method1' on type 'CurriedClass'; did you mean to use a value of type 'CurriedClass' instead?}} CurriedClass.method2(c)(32)(b: 1) _ = CurriedClass.method2(c) _ = CurriedClass.method2(c)(32) _ = CurriedClass.method2(1,2) // expected-error {{use of instance member 'method2' on type 'CurriedClass'; did you mean to use a value of type 'CurriedClass' instead?}} CurriedClass.method2(c)(1.0)(b: 1) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}} CurriedClass.method2(c)(1)(b: 1.0) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}} CurriedClass.method2(c)(2)(c: 1.0) // expected-error {{incorrect argument label in call (have 'c:', expected 'b:')}} CurriedClass.method3(c)(32, b: 1) _ = CurriedClass.method3(c) _ = CurriedClass.method3(c)(1, 2) // expected-error {{missing argument label 'b:' in call}} {{32-32=b: }} _ = CurriedClass.method3(c)(1, b: 2)(32) // expected-error {{cannot call value of non-function type '()'}} _ = CurriedClass.method3(1, 2) // expected-error {{use of instance member 'method3' on type 'CurriedClass'; did you mean to use a value of type 'CurriedClass' instead?}} CurriedClass.method3(c)(1.0, b: 1) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}} CurriedClass.method3(c)(1) // expected-error {{missing argument for parameter 'b' in call}} CurriedClass.method3(c)(c: 1.0) // expected-error {{missing argument for parameter 'b' in call}} extension CurriedClass { func f() { method3(1, b: 2) method3() // expected-error {{missing argument for parameter #1 in call}} method3(42) // expected-error {{missing argument for parameter 'b' in call}} method3(self) // expected-error {{missing argument for parameter 'b' in call}} } } extension CurriedClass { func m1(_ a : Int, b : Int) {} func m2(_ a : Int) {} } // <rdar://problem/23718816> QoI: "Extra argument" error when accidentally currying a method CurriedClass.m1(2, b: 42) // expected-error {{use of instance member 'm1' on type 'CurriedClass'; did you mean to use a value of type 'CurriedClass' instead?}} // <rdar://problem/22108559> QoI: Confusing error message when calling an instance method as a class method CurriedClass.m2(12) // expected-error {{use of instance member 'm2' on type 'CurriedClass'; did you mean to use a value of type 'CurriedClass' instead?}} // <rdar://problem/19870975> Incorrect diagnostic for failed member lookups within closures passed as arguments ("(_) -> _") func ident<T>(_ t: T) -> T {} var c = ident({1.DOESNT_EXIST}) // error: expected-error {{value of type 'Int' has no member 'DOESNT_EXIST'}} // <rdar://problem/20712541> QoI: Int/UInt mismatch produces useless error inside a block var afterMessageCount : Int? = nil func uintFunc() -> UInt {} func takeVoidVoidFn(_ a : () -> ()) {} takeVoidVoidFn { () -> Void in afterMessageCount = uintFunc() // expected-error {{cannot assign value of type 'UInt' to type 'Int?'}} } // <rdar://problem/19997471> Swift: Incorrect compile error when calling a function inside a closure func f19997471(_ x: String) {} func f19997471(_ x: Int) {} func someGeneric19997471<T>(_ x: T) { takeVoidVoidFn { f19997471(x) // expected-error {{cannot invoke 'f19997471' with an argument list of type '(T)'}} // expected-note @-1 {{overloads for 'f19997471' exist with these partially matching parameter lists: (String), (Int)}} } } // <rdar://problem/20371273> Type errors inside anonymous functions don't provide enough information func f20371273() { let x: [Int] = [1, 2, 3, 4] let y: UInt = 4 x.filter { $0 == y } // expected-error {{binary operator '==' cannot be applied to operands of type 'Int' and 'UInt'}} // expected-note @-1 {{overloads for '==' exist with these partially matching parameter lists: (UInt, UInt), (Int, Int)}} } // <rdar://problem/20921068> Swift fails to compile: [0].map() { _ in let r = (1,2).0; return r } // FIXME: Should complain about not having a return type annotation in the closure. [0].map { _ in let r = (1,2).0; return r } // expected-error @-1 {{expression type '[_]' is ambiguous without more context}} // <rdar://problem/21078316> Less than useful error message when using map on optional dictionary type func rdar21078316() { var foo : [String : String]? var bar : [(String, String)]? bar = foo.map { ($0, $1) } // expected-error {{contextual closure type '([String : String]) -> [(String, String)]' expects 1 argument, but 2 were used in closure body}} } // <rdar://problem/20978044> QoI: Poor diagnostic when using an incorrect tuple element in a closure var numbers = [1, 2, 3] zip(numbers, numbers).filter { $0.2 > 1 } // expected-error {{value of tuple type '(Int, Int)' has no member '2'}} // <rdar://problem/20868864> QoI: Cannot invoke 'function' with an argument list of type 'type' func foo20868864(_ callback: ([String]) -> ()) { } func rdar20868864(_ s: String) { var s = s foo20868864 { (strings: [String]) in s = strings // expected-error {{cannot assign value of type '[String]' to type 'String'}} } } // <rdar://problem/20491794> Error message does not tell me what the problem is enum Color { case Red case Unknown(description: String) static func rainbow() -> Color {} static func overload(a : Int) -> Color {} static func overload(b : Int) -> Color {} static func frob(_ a : Int, b : inout Int) -> Color {} } let _: (Int, Color) = [1,2].map({ ($0, .Unknown("")) }) // expected-error {{'map' produces '[T]', not the expected contextual result type '(Int, Color)'}} let _: [(Int, Color)] = [1,2].map({ ($0, .Unknown("")) })// expected-error {{missing argument label 'description:' in call}} {{51-51=description: }} let _: [Color] = [1,2].map { _ in .Unknown("") }// expected-error {{missing argument label 'description:' in call}} {{44-44=description: }} let _: Int -> (Int, Color) = { ($0, .Unknown("")) } // expected-error {{missing argument label 'description:' in call}} {{46-46=description: }} let _: Color = .Unknown("") // expected-error {{missing argument label 'description:' in call}} {{25-25=description: }} let _: Color = .Unknown // expected-error {{contextual member 'Unknown' expects argument of type '(description: String)'}} let _: Color = .Unknown(42) // expected-error {{cannot convert value of type 'Int' to expected argument type 'String'}} let _ : Color = .rainbow(42) // expected-error {{argument passed to call that takes no arguments}} let _ : (Int, Float) = (42.0, 12) // expected-error {{cannot convert value of type 'Double' to specified type 'Int'}} let _ : Color = .rainbow // expected-error {{contextual member 'rainbow' expects argument of type '()'}} let _: Color = .overload(a : 1.0) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}} let _: Color = .overload(1.0) // expected-error {{ambiguous reference to member 'overload'}} // expected-note @-1 {{overloads for 'overload' exist with these partially matching parameter lists: (a: Int), (b: Int)}} let _: Color = .overload(1) // expected-error {{ambiguous reference to member 'overload'}} // expected-note @-1 {{overloads for 'overload' exist with these partially matching parameter lists: (a: Int), (b: Int)}} let _: Color = .frob(1.0, &i) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}} let _: Color = .frob(1, i) // expected-error {{passing value of type 'Int' to an inout parameter requires explicit '&'}} let _: Color = .frob(1, b: i) // expected-error {{passing value of type 'Int' to an inout parameter requires explicit '&'}} let _: Color = .frob(1, &d) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}} let _: Color = .frob(1, b: &d) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}} var someColor : Color = .red // expected-error {{type 'Color' has no member 'red'}} someColor = .red // expected-error {{type 'Color' has no member 'red'}} func testTypeSugar(_ a : Int) { typealias Stride = Int let x = Stride(a) x+"foo" // expected-error {{binary operator '+' cannot be applied to operands of type 'Stride' (aka 'Int') and 'String'}} // expected-note @-1 {{overloads for '+' exist with these partially matching parameter lists: (Int, Int), (String, String), (Int, UnsafeMutablePointer<Pointee>), (Int, UnsafePointer<Pointee>)}} } // <rdar://problem/21974772> SegFault in FailureDiagnosis::visitInOutExpr func r21974772(_ y : Int) { let x = &(1.0 + y) // expected-error {{binary operator '+' cannot be applied to operands of type 'Double' and 'Int'}} //expected-note @-1 {{overloads for '+' exist with these partially matching parameter lists: (Int, Int), (Double, Double), (UnsafeMutablePointer<Pointee>, Int), (UnsafePointer<Pointee>, Int)}} } // <rdar://problem/22020088> QoI: missing member diagnostic on optional gives worse error message than existential/bound generic/etc protocol r22020088P {} func r22020088Foo<T>(_ t: T) {} func r22020088bar(_ p: r22020088P?) { r22020088Foo(p.fdafs) // expected-error {{value of type 'r22020088P?' has no member 'fdafs'}} } // <rdar://problem/22288575> QoI: poor diagnostic involving closure, bad parameter label, and mismatch return type func f(_ arguments: [String]) -> [ArraySlice<String>] { return arguments.split(maxSplits: 1, omittingEmptySubsequences: false, isSeparator: { $0 == "--" }) } struct AOpts : OptionSet { let rawValue : Int } class B { func function(_ x : Int8, a : AOpts) {} func f2(_ a : AOpts) {} static func f1(_ a : AOpts) {} } func test(_ a : B) { B.f1(nil) // expected-error {{nil is not compatible with expected argument type 'AOpts'}} a.function(42, a: nil) //expected-error {{nil is not compatible with expected argument type 'AOpts'}} a.function(42, nil) //expected-error {{missing argument label 'a:' in call}} a.f2(nil) // expected-error {{nil is not compatible with expected argument type 'AOpts'}} } // <rdar://problem/21684487> QoI: invalid operator use inside a closure reported as a problem with the closure typealias MyClosure = ([Int]) -> Bool func r21684487() { var closures = Array<MyClosure>() let testClosure = {(list: [Int]) -> Bool in return true} let closureIndex = closures.index{$0 === testClosure} // expected-error {{cannot convert value of type 'MyClosure' (aka 'Array<Int> -> Bool') to expected argument type 'AnyObject?'}} } // <rdar://problem/18397777> QoI: special case comparisons with nil func r18397777(_ d : r21447318?) { let c = r21447318() if c != nil { // expected-error {{value of type 'r21447318' can never be nil, comparison isn't allowed}} } if d { // expected-error {{optional type 'r21447318?' cannot be used as a boolean; test for '!= nil' instead}} {{6-6=(}} {{7-7= != nil)}} } if !d { // expected-error {{optional type 'r21447318?' cannot be used as a boolean; test for '== nil' instead}} {{6-7=}} {{7-7=(}} {{8-8= == nil)}} } if !Optional(c) { // expected-error {{optional type 'Optional<_>' cannot be used as a boolean; test for '== nil' instead}} {{6-7=}} {{7-7=(}} {{18-18= == nil)}} } } // <rdar://problem/22255907> QoI: bad diagnostic if spurious & in argument list func r22255907_1<T>(_ a : T, b : Int) {} func r22255907_2<T>(_ x : Int, a : T, b: Int) {} func reachabilityForInternetConnection() { var variable: Int = 42 r22255907_1(&variable, b: 2.1) // expected-error {{'&' used with non-inout argument of type 'Int'}} {{15-16=}} r22255907_2(1, a: &variable, b: 2.1)// expected-error {{'&' used with non-inout argument of type 'Int'}} {{21-22=}} } // <rdar://problem/21601687> QoI: Using "=" instead of "==" in if statement leads to incorrect error message if i = 6 { } // expected-error {{use of '=' in a boolean context, did you mean '=='?}} {{6-7===}} _ = (i = 6) ? 42 : 57 // expected-error {{use of '=' in a boolean context, did you mean '=='?}} {{8-9===}} // <rdar://problem/22263468> QoI: Not producing specific argument conversion diagnostic for tuple init func r22263468(_ a : String?) { typealias MyTuple = (Int, String) _ = MyTuple(42, a) // expected-error {{value of optional type 'String?' not unwrapped; did you mean to use '!' or '?'?}} {{20-20=!}} } // rdar://22470302 - Crash with parenthesized call result. class r22470302Class { func f() {} } func r22470302(_ c: r22470302Class) { print((c.f)(c)) // expected-error {{argument passed to call that takes no arguments}} } // <rdar://problem/21928143> QoI: Pointfree reference to generic initializer in generic context does not compile extension String { @available(*, unavailable, message: "calling this is unwise") func unavail<T : Sequence where T.Iterator.Element == String> // expected-note 2 {{'unavail' has been explicitly marked unavailable here}} (_ a : T) -> String {} } extension Array { func g() -> String { return "foo".unavail([""]) // expected-error {{'unavail' is unavailable: calling this is unwise}} } func h() -> String { return "foo".unavail([0]) // expected-error {{'unavail' is unavailable: calling this is unwise}} } } // <rdar://problem/22519983> QoI: Weird error when failing to infer archetype func safeAssign<T: RawRepresentable>(_ lhs: inout T) -> Bool {} // expected-note @-1 {{in call to function 'safeAssign'}} let a = safeAssign // expected-error {{generic parameter 'T' could not be inferred}} // <rdar://problem/21692808> QoI: Incorrect 'add ()' fixit with trailing closure struct Radar21692808<Element> { init(count: Int, value: Element) {} } func radar21692808() -> Radar21692808<Int> { return Radar21692808<Int>(count: 1) { // expected-error {{cannot invoke initializer for type 'Radar21692808<Int>' with an argument list of type '(count: Int, () -> Int)'}} // expected-note @-1 {{expected an argument list of type '(count: Int, value: Element)'}} return 1 } } // <rdar://problem/17557899> - This shouldn't suggest calling with (). func someOtherFunction() {} func someFunction() -> () { // Producing an error suggesting that this return someOtherFunction // expected-error {{unexpected non-void return value in void function}} } // <rdar://problem/23560128> QoI: trying to mutate an optional dictionary result produces bogus diagnostic func r23560128() { var a : (Int,Int)? a.0 = 42 // expected-error {{value of optional type '(Int, Int)?' not unwrapped; did you mean to use '!' or '?'?}} {{4-4=?}} } // <rdar://problem/21890157> QoI: wrong error message when accessing properties on optional structs without unwrapping struct ExampleStruct21890157 { var property = "property" } var example21890157: ExampleStruct21890157? example21890157.property = "confusing" // expected-error {{value of optional type 'ExampleStruct21890157?' not unwrapped; did you mean to use '!' or '?'?}} {{16-16=?}} struct UnaryOp {} _ = -UnaryOp() // expected-error {{unary operator '-' cannot be applied to an operand of type 'UnaryOp'}} // expected-note @-1 {{overloads for '-' exist with these partially matching parameter lists: (Float), (Double)}} // <rdar://problem/23433271> Swift compiler segfault in failure diagnosis func f23433271(_ x : UnsafePointer<Int>) {} func segfault23433271(_ a : UnsafeMutablePointer<Void>) { f23433271(a[0]) // expected-error {{cannot convert value of type 'Void' (aka '()') to expected argument type 'UnsafePointer<Int>'}} } // <rdar://problem/22058555> crash in cs diags in withCString func r22058555() { var firstChar: UInt8 = 0 "abc".withCString { chars in firstChar = chars[0] // expected-error {{cannot assign value of type 'Int8' to type 'UInt8'}} } } // <rdar://problem/23272739> Poor diagnostic due to contextual constraint func r23272739(_ contentType: String) { let actualAcceptableContentTypes: Set<String> = [] return actualAcceptableContentTypes.contains(contentType) // expected-error {{unexpected non-void return value in void function}} } // <rdar://problem/23641896> QoI: Strings in Swift cannot be indexed directly with integer offsets func r23641896() { var g = "Hello World" g.replaceSubrange(0...2, with: "ce") // expected-error {{String may not be indexed with 'Int', it has variable size elements}} // expected-note @-1 {{consider using an existing high level algorithm, str.startIndex.advanced(by: n), or a projection like str.utf8}} _ = g[12] // expected-error {{'subscript' is unavailable: cannot subscript String with an Int, see the documentation comment for discussion}} } // <rdar://problem/23718859> QoI: Incorrectly flattening ((Int,Int)) argument list to (Int,Int) when printing note func test17875634() { var match: [(Int, Int)] = [] var row = 1 var col = 2 match.append(row, col) // expected-error {{extra argument in call}} } // <https://github.com/apple/swift/pull/1205> Improved diagnostics for enums with associated values enum AssocTest { case one(Int) } if AssocTest.one(1) == AssocTest.one(1) {} // expected-error{{binary operator '==' cannot be applied to two 'AssocTest' operands}} // expected-note @-1 {{binary operator '==' cannot be synthesized for enums with associated values}} // <rdar://problem/24251022> Swift 2: Bad Diagnostic Message When Adding Different Integer Types func r24251022() { var a = 1 var b: UInt32 = 2 a += a + b // expected-error {{cannot convert value of type 'UInt32' to expected argument type 'Int'}} } func overloadSetResultType(_ a : Int, b : Int) -> Int { // https://twitter.com/_jlfischer/status/712337382175952896 return a == b && 1 == 2 // expected-error {{'&&' produces 'Bool', not the expected contextual result type 'Int'}} } // <rdar://problem/21523291> compiler error message for mutating immutable field is incorrect func r21523291(_ bytes : UnsafeMutablePointer<UInt8>) { let i = 42 // expected-note {{change 'let' to 'var' to make it mutable}} let r = bytes[i++] // expected-error {{cannot pass immutable value as inout argument: 'i' is a 'let' constant}} }
apache-2.0
1ac1e07afae8a74c96fa0594fdf87fea
41.816406
195
0.668947
3.601643
false
false
false
false
el-hoshino/NotAutoLayout
Sources/NotAutoLayout/Types/Insets.swift
1
1811
// // Insets.swift // NotAutoLayout // // Created by 史 翔新 on 2018/03/16. // Copyright © 2018年 史翔新. All rights reserved. // import UIKit /// A struct that shows insets as margins from left, right, top and bottom. /// /// Basically it behaves like a `UIEdgeInsets` type that has the same properties `top`, `left`, `bottom` and `right`, but since it's declared as another type just in NotAutoLayout, you can add any extensions you want and that won't affect the system's `UIEdgeInsets` type. /// /// Conforms to: `CGTypeConvertible`. public struct Insets { /// The top inset. public var top: Float /// The left inset. public var left: Float /// The bottom inset. public var bottom: Float /// The right inset. public var right: Float /// Initializes a `Insets` with top inset (as `top`), left inset (as `left`), bottom inset (as `bottom`) and right inset (as `right`). public init(top: Float, left: Float, bottom: Float, right: Float) { self.top = top self.left = left self.bottom = bottom self.right = right } } extension Insets { /// Insets that all `top`, `left`, `bottom` and `right` insets are `0` public static let zero: Insets = .init(top: 0, left: 0, bottom: 0, right: 0) } extension Insets: CGTypeConvertible { public var cgValue: UIEdgeInsets { return UIEdgeInsets(top: self.top.cgValue, left: self.left.cgValue, bottom: self.bottom.cgValue, right: self.right.cgValue) } public init(_ insets: UIEdgeInsets) { self.top = Float(insets.top) self.left = Float(insets.left) self.bottom = Float(insets.bottom) self.right = Float(insets.right) } } extension Insets: CustomStringConvertible { public var description: String { return "(top: \(self.top), left: \(self.left), bottom: \(self.bottom), right: \(self.right))" } }
apache-2.0
0642ba5dae5768a0a17bb054371b6653
25.411765
272
0.682628
3.369606
false
false
false
false
eurofurence/ef-app_ios
Packages/EurofurenceModel/Tests/EurofurenceModelTests/Test Doubles/API/FakeAPI.swift
1
5272
import EurofurenceModel import Foundation class FakeAPI: API { private var feedbackRequests: [EventFeedbackRequest: (Bool) -> Void] = [:] func submitEventFeedback(_ request: EventFeedbackRequest, completionHandler: @escaping (Bool) -> Void) { feedbackRequests[request] = completionHandler } func simulateSuccessfulFeedbackResponse(for request: EventFeedbackRequest) { guard let handler = feedbackRequests[request] else { return } handler(true) feedbackRequests[request] = nil } func simulateUnsuccessfulFeedbackResponse(for request: EventFeedbackRequest) { guard let handler = feedbackRequests[request] else { return } handler(false) feedbackRequests[request] = nil } private(set) var capturedLoginRequest: LoginRequest? private var loginHandler: ((LoginResponse?) -> Void)? func performLogin(request: LoginRequest, completionHandler: @escaping (LoginResponse?) -> Void) { capturedLoginRequest = request loginHandler = completionHandler } private(set) var wasToldToLoadPrivateMessages = false private(set) var privateMessagesLoadCount = 0 private(set) var capturedAuthToken: String? private var messagesHandler: (([MessageCharacteristics]?) -> Void)? func loadPrivateMessages(authorizationToken: String, completionHandler: @escaping ([MessageCharacteristics]?) -> Void) { wasToldToLoadPrivateMessages = true privateMessagesLoadCount += 1 capturedAuthToken = authorizationToken self.messagesHandler = completionHandler } private(set) var messageIdentifierMarkedAsRead: String? private(set) var capturedAuthTokenForMarkingMessageAsRead: String? func markMessageWithIdentifierAsRead(_ identifier: String, authorizationToken: String) { messageIdentifierMarkedAsRead = identifier capturedAuthTokenForMarkingMessageAsRead = authorizationToken } var requestedFullStoreRefresh: Bool { return capturedLastSyncTime == nil } fileprivate var completionHandler: ((ModelCharacteristics?) -> Void)? private(set) var capturedLastSyncTime: Date? private(set) var didBeginSync = false func fetchLatestData(lastSyncTime: Date?, completionHandler: @escaping (ModelCharacteristics?) -> Void) { didBeginSync = true capturedLastSyncTime = lastSyncTime self.completionHandler = completionHandler } private struct DownloadRequest: Hashable { var identifier: String var contentHashSha1: String } private var stubbedResponses = [DownloadRequest: Data]() private(set) var downloadedImageIdentifiers = [String]() func fetchImage(identifier: String, contentHashSha1: String, completionHandler: @escaping (Data?) -> Void) { downloadedImageIdentifiers.append(identifier) let data = "\(identifier)_\(contentHashSha1)".data(using: .utf8) let request = DownloadRequest(identifier: identifier, contentHashSha1: contentHashSha1) stubbedResponses[request] = data completionHandler(data) } } extension FakeAPI { func stubbedImage(for identifier: String?, availableImages: [ImageCharacteristics]) -> Data? { return stubbedResponses.first(where: { $0.key.identifier == identifier })?.value } func simulateSuccessfulSync(_ response: ModelCharacteristics) { completionHandler?(response) } func simulateUnsuccessfulSync() { completionHandler?(nil) } func simulateLoginResponse(_ response: LoginResponse) { loginHandler?(response) } func simulateLoginFailure() { loginHandler?(nil) } func simulateMessagesResponse(response: [MessageCharacteristics] = []) { messagesHandler?(response) } func simulateMessagesFailure() { messagesHandler?(nil) } } class SlowFakeImageAPI: FakeAPI { fileprivate var pendingFetches = [() -> Void]() var numberOfPendingFetches: Int { return pendingFetches.count } override func fetchImage( identifier: String, contentHashSha1: String, completionHandler: @escaping (Data?) -> Void ) { pendingFetches.append { super.fetchImage( identifier: identifier, contentHashSha1: contentHashSha1, completionHandler: completionHandler ) } } } extension SlowFakeImageAPI { func resolvePendingFetches() { pendingFetches.forEach({ $0() }) pendingFetches.removeAll() } func resolveNextFetch() { guard pendingFetches.isEmpty == false else { return } let next = pendingFetches.remove(at: 0) next() } } class OnlyToldToRefreshOnceMockAPI: FakeAPI { private var refreshCount = 0 var toldToRefreshOnlyOnce: Bool { return refreshCount == 1 } override func fetchLatestData(lastSyncTime: Date?, completionHandler: @escaping (ModelCharacteristics?) -> Void) { refreshCount += 1 super.fetchLatestData(lastSyncTime: lastSyncTime, completionHandler: completionHandler) } }
mit
23dfbe4ff57fc5fd54704cdffadcc219
30.195266
118
0.676024
5.178782
false
false
false
false
PETERZer/SingularityIMClient-PeterZ
SingularityIMClient-PeterZ/Model/ChatListModel.swift
1
6412
// // ChatListModel.swift // SingularityIMClient // // Created by apple on 1/14/16. // Copyright © 2016 张勇. All rights reserved. // import UIKit public class ChatListModel: NSObject { public var _chat_session_id:String? public var _chat_session_type:String? public var _last_message:String? public var _last_message_id:String? public var _last_message_time:String! public var _last_message_type:String? public var _last_sender_id:String? public var _message_count:String? public var _target_id:String? public var _target_name:String? public var _target_online_status:String? public var _target_picture:String? public var chat_session_id:String?{ get{ if self._chat_session_id == nil { print("_chat_session_id没有值") return nil }else { return self._chat_session_id } } set(newChatSID){ self._chat_session_id = newChatSID } } public var chat_session_type:String?{ get{ if self._chat_session_type == nil { print("_chat_session_type没有值") return nil }else { return self._chat_session_type } } set(newChatSType){ self._chat_session_type = newChatSType } } public var last_message:String?{ get{ if self._last_message == nil { print("_last_message没有值") return nil }else { return self._last_message } } set(newLastMessage){ self._last_message = newLastMessage } } public var last_message_id:String?{ get{ if self._last_message_id == nil { print("_last_message_id没有值") return nil }else { return self._last_message_id } } set(newLastMessageId){ self._last_message_id = newLastMessageId } } public var last_message_time:String!{ get{ if self._last_message_time == nil { print("_last_message_time没有值") return nil }else { return self._last_message_time } } set(newLastMessageTime){ self._last_message_time = newLastMessageTime } } public var last_message_type:String?{ get{ if self._last_message_type == nil { print("_last_message_type没有值") return nil }else { return self._last_message_type } } set(newLastMessageType){ self._last_message_type = newLastMessageType } } public var last_sender_id:String?{ get{ if self._last_sender_id == nil { print("_last_sender_id没有值") return nil }else { return self._last_sender_id } } set(newLasterSenderId){ self._last_sender_id = newLasterSenderId } } public var message_count:String?{ get{ if self._message_count == nil { print("_message_count没有值") return nil }else { return self._message_count } } set(newMessageCount){ self._message_count = newMessageCount } } public var target_id:String?{ get{ if self._target_id == nil { print("_target_id没有值") return nil }else { return self._target_id } } set(newTargetId){ self._target_id = newTargetId } } public var target_name:String?{ get{ if self._target_name == nil { print("_target_name没有值") return nil }else { return self._target_name } } set(newTargetName){ self._target_name = newTargetName } } public var target_online_status:String?{ get{ if self._target_online_status == nil { print("_target_online_status没有值") return nil }else { return self._target_online_status } } set(newTargetOS){ self._target_online_status = newTargetOS } } public var target_picture:String?{ get{ if self._target_picture == nil { print("_target_picture没有值") return nil }else { return self._target_picture } } set(newTargetPicture){ self._target_picture = newTargetPicture } } //MARK: 设置数据 public func setChatListModel(dic:AnyObject?) -> ChatListModel{ self.chat_session_id = dic?.valueForKey("chat_session_id")as? String let chat_session_type = dic?.valueForKey("chat_session_type")! self.chat_session_type = String(chat_session_type!) self.last_message = dic?.valueForKey("last_message")as? String self.last_message_id = dic?.valueForKey("last_message_id")as? String let last_message_time = dic?.valueForKey("last_message_time")! self.last_message_time = String(last_message_time!) self.last_message_type = dic?.valueForKey("last_message_type")as? String self.last_sender_id = dic?.valueForKey("last_sender_id")as? String let message_count = dic?.valueForKey("message_count")! self.message_count = String(message_count!) self.target_id = dic?.valueForKey("target_id")as? String self.target_name = dic?.valueForKey("target_name")as? String self.target_online_status = dic?.valueForKey("target_online_status")as? String self.target_picture = dic?.valueForKey("target_picture")as? String return self } }
mit
602c91ac8b1ae138d153bc0c179c37af
27.376682
89
0.49676
4.480878
false
false
false
false
Elm-Tree-Island/Shower
Shower/Carthage/Checkouts/ReactiveSwift/Sources/UnidirectionalBinding.swift
6
5391
import Foundation import Dispatch import enum Result.NoError precedencegroup BindingPrecedence { associativity: right // Binds tighter than assignment but looser than everything else higherThan: AssignmentPrecedence } infix operator <~ : BindingPrecedence // FIXME: Swift 4.x - Conditional Conformance // public protocol BindingSource: SignalProducerConvertible where Error == NoError {} // extension Signal: BindingSource where Error == NoError {} // extension SignalProducer: BindingSource where Error == NoError {} /// Describes a source which can be bound. public protocol BindingSource: SignalProducerConvertible { // FIXME: Swift 4 compiler regression. // All requirements are replicated to workaround the type checker issue. // https://bugs.swift.org/browse/SR-5090 associatedtype Value associatedtype Error: Swift.Error var producer: SignalProducer<Value, Error> { get } } extension Signal: BindingSource {} extension SignalProducer: BindingSource {} /// Describes an entity which be bond towards. public protocol BindingTargetProvider { associatedtype Value var bindingTarget: BindingTarget<Value> { get } } extension BindingTargetProvider { /// Binds a source to a target, updating the target's value to the latest /// value sent by the source. /// /// - note: The binding will automatically terminate when the target is /// deinitialized, or when the source sends a `completed` event. /// /// ```` /// let property = MutableProperty(0) /// let signal = Signal({ /* do some work after some time */ }) /// property <~ signal /// ```` /// /// ```` /// let property = MutableProperty(0) /// let signal = Signal({ /* do some work after some time */ }) /// let disposable = property <~ signal /// ... /// // Terminates binding before property dealloc or signal's /// // `completed` event. /// disposable.dispose() /// ```` /// /// - parameters: /// - target: A target to be bond to. /// - source: A source to bind. /// /// - returns: A disposable that can be used to terminate binding before the /// deinitialization of the target or the source's `completed` /// event. @discardableResult public static func <~ <Source: BindingSource> (provider: Self, source: Source) -> Disposable? where Source.Value == Value, Source.Error == NoError { return source.producer .take(during: provider.bindingTarget.lifetime) .startWithValues(provider.bindingTarget.action) } /// Binds a source to a target, updating the target's value to the latest /// value sent by the source. /// /// - note: The binding will automatically terminate when the target is /// deinitialized, or when the source sends a `completed` event. /// /// ```` /// let property = MutableProperty(0) /// let signal = Signal({ /* do some work after some time */ }) /// property <~ signal /// ```` /// /// ```` /// let property = MutableProperty(0) /// let signal = Signal({ /* do some work after some time */ }) /// let disposable = property <~ signal /// ... /// // Terminates binding before property dealloc or signal's /// // `completed` event. /// disposable.dispose() /// ```` /// /// - parameters: /// - target: A target to be bond to. /// - source: A source to bind. /// /// - returns: A disposable that can be used to terminate binding before the /// deinitialization of the target or the source's `completed` /// event. @discardableResult public static func <~ <Source: BindingSource> (provider: Self, source: Source) -> Disposable? where Value == Source.Value?, Source.Error == NoError { return provider <~ source.producer.optionalize() } } /// A binding target that can be used with the `<~` operator. public struct BindingTarget<Value>: BindingTargetProvider { public let lifetime: Lifetime public let action: (Value) -> Void public var bindingTarget: BindingTarget<Value> { return self } /// Creates a binding target which consumes values on the specified scheduler. /// /// If no scheduler is specified, the binding target would consume the value /// immediately. /// /// - parameters: /// - scheduler: The scheduler on which the `action` consumes the values. /// - lifetime: The expected lifetime of any bindings towards `self`. /// - action: The action to consume values. public init(on scheduler: Scheduler = ImmediateScheduler(), lifetime: Lifetime, action: @escaping (Value) -> Void) { self.lifetime = lifetime if scheduler is ImmediateScheduler { self.action = action } else { self.action = { value in scheduler.schedule { action(value) } } } } /// Creates a binding target which consumes values on the specified scheduler. /// /// If no scheduler is specified, the binding target would consume the value /// immediately. /// /// - parameters: /// - scheduler: The scheduler on which the key path consumes the values. /// - lifetime: The expected lifetime of any bindings towards `self`. /// - object: The object to consume values. /// - keyPath: The key path of the object that consumes values. public init<Object: AnyObject>(on scheduler: Scheduler = ImmediateScheduler(), lifetime: Lifetime, object: Object, keyPath: WritableKeyPath<Object, Value>) { self.init(on: scheduler, lifetime: lifetime) { [weak object] in object?[keyPath: keyPath] = $0 } } }
gpl-3.0
f46cc1d98ebe6d840ac87f9b4b9582c9
31.672727
158
0.683547
4.011161
false
false
false
false
azac/swift-javascriptish-arrays
Javascriptish.swift
1
3411
import Foundation extension Array { //push() Adds new elements to the end of an array, and returns the new length mutating func push(elements: (T)...) -> T[] { for i in elements { self.append(i) } return self } //pop() Removes the last element of an array, and returns that element mutating func pop() -> Element? { if (self.isEmpty) { return nil } else { return self.removeLast() } } //shift() Removes the first element of an array, and returns that element mutating func shift () -> Element? { if (self.isEmpty) { return nil } else { return self.removeAtIndex(0) } } //unshift() Adds new elements to the beginning of an array, and returns the new length mutating func unshift (elements: (T)...) -> Int { self = elements + self return self.count } //concat() Joins two or more arrays, and returns a copy of the joined arrays func concat (arrays: T[]...) -> T[] { var sum = self for i in arrays { sum = sum + i } return sum } //indexOf() Search the array for an element and returns its position func indexOf<T : Equatable>(item :T, startIndex: Int = 0) -> Int { for i in 0..self.count { if self[i] as T == item && i>=startIndex { return i } } return -1 } //lastIndexOf() Search the array for an elemet, starting at the end, and returns its position func lastIndexOf<T : Equatable>(item :T, startIndex: Int = 0) -> Int { var found = -1; for i in 0..self.count { if self[i] as T == item && i>=startIndex { found=i } } return found } //join() Joins all elements of an array into a string func join(separator:String=",") -> String{ var str : String = "" for (idx, item) in enumerate(self) { str += "\(item)" if idx < self.count-1 { str += separator } } return str } // reverse() Reverses the order of the elements in an array // sort of works like JS //sort() Sorts the elements of an array // sort of works like JS //slice() Selects a part of an array, and returns the new array func slice (bounds:Int...) -> Slice<T> { var lowerIndex = bounds[0] if (bounds[0]<0) {lowerIndex = self.count+(bounds[0]);} var upperIndex = self.count-1 if bounds.count==2 { upperIndex=bounds[1]-1 if (upperIndex<0) {upperIndex = self.count-1+(bounds[1]);} } return self[lowerIndex...upperIndex] } //toString() Converts an array to a string, and returns the result func toString() -> String { return self.join(separator:",") } //splice() Adds/Removes elements from an array mutating func splice (#index:Int, howMany: Int, elements: (T)...) -> Slice<T> { let midIndex = index+howMany let arr_start = self[0...index-1] let cutout = self[index...midIndex-1] let arr_end = self[midIndex...(self.count-1)] self = arr_start + elements + arr_end return cutout } }
mit
a7ff7b9d1d548d606e0c3ddb3c1e82d2
17.240642
97
0.531516
4.226766
false
false
false
false
larcus94/Scholarship
Scholarship/AppDelegate.swift
1
966
// // AppDelegate.swift // Scholarship // // Created by Laurin Brandner on 06/02/15. // Copyright (c) 2015 Laurin Brandner. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { private lazy var window: UIWindow = { let window = UIWindow(frame: UIScreen.mainScreen().bounds) window.backgroundColor = UIColor.whiteColor() window.tintColor = UIColor.brandnerColor() return window }() func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { let controller = WelcomeViewController() let navigationController = UINavigationController(rootViewController: controller) navigationController.navigationBarHidden = true window.rootViewController = navigationController self.window.makeKeyAndVisible() return true } }
mit
f5081f67accf7f82f38c4baaf16ba497
26.6
127
0.694617
5.52
false
false
false
false
CD1212/Doughnut
Pods/FeedKit/Sources/FeedKit/Parser/XMLFeedParser.swift
2
6540
// // XMLFeedParser.swift // // Copyright (c) 2017 Nuno Manuel Dias // // 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 /// The actual engine behind the `FeedKit` framework. `XMLFeedParser` handles /// the parsing of RSS and Atom feeds. It is an `XMLParserDelegate` of /// itself. class XMLFeedParser: NSObject, XMLParserDelegate, FeedParserProtocol { /// The Feed Type currently being parsed. The Initial value of this variable /// is unknown until a recognizable element that matches a feed type is /// found. var feedType: XMLFeedType? /// The RSS feed model. var rssFeed: RSSFeed? /// The Atom feed model. var atomFeed: AtomFeed? /// The XML Parser. let xmlParser: XMLParser /// An XML Feed Parser, for rss and atom feeds. /// /// - Parameter data: A `Data` object containing an XML feed. required init(data: Data) { self.xmlParser = XMLParser(data: data) super.init() self.xmlParser.delegate = self } /// The current path along the XML's DOM elements. Path components are /// updated to reflect the current XML element being parsed. /// e.g. "/rss/channel/title" means it's currently parsing the channels /// `<title>` element. fileprivate var currentXMLDOMPath: URL = URL(string: "/")! /// A parsing error, if any. var parsingError: NSError? /// Starts parsing the feed. func parse() -> Result { let _ = self.xmlParser.parse() if let error = parsingError { return Result.failure(error) } guard let feedType = self.feedType else { return Result.failure(ParserError.feedNotFound.value) } switch feedType { case .atom: return Result.atom(self.atomFeed!) case .rdf, .rss: return Result.rss(self.rssFeed!) } } /// Redirects characters found between XML elements to their proper model /// mappers based on the `currentXMLDOMPath`. /// /// - Parameter string: The characters to map. fileprivate func map(_ string: String) { guard let feedType = self.feedType else { return } switch feedType { case .atom: if let path = AtomPath(rawValue: self.currentXMLDOMPath.absoluteString) { self.atomFeed?.map(string, for: path) } case .rdf: if let path = RDFPath(rawValue: self.currentXMLDOMPath.absoluteString) { self.rssFeed?.map(string, for: path) } case .rss: if let path = RSSPath(rawValue: self.currentXMLDOMPath.absoluteString) { self.rssFeed?.map(string, for: path) } } } } // MARK: - XMLParser delegate extension XMLFeedParser { func parser( _ parser: XMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String]) { // Update the current path along the XML's DOM elements by appending the new component with `elementName`. self.currentXMLDOMPath = self.currentXMLDOMPath.appendingPathComponent(elementName) // Get the feed type from the element, if it hasn't been done yet. guard let feedType = self.feedType else { self.feedType = XMLFeedType(rawValue: elementName) return } switch feedType { case .atom: if self.atomFeed == nil { self.atomFeed = AtomFeed() } if let path = AtomPath(rawValue: self.currentXMLDOMPath.absoluteString) { self.atomFeed?.map(attributeDict, for: path) } case .rdf: if self.rssFeed == nil { self.rssFeed = RSSFeed() } if let path = RDFPath(rawValue: self.currentXMLDOMPath.absoluteString) { self.rssFeed?.map(attributeDict, for: path) } case .rss: if self.rssFeed == nil { self.rssFeed = RSSFeed() } if let path = RSSPath(rawValue: self.currentXMLDOMPath.absoluteString) { self.rssFeed?.map(attributeDict, for: path) } } } func parser( _ parser: XMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?) { // Update the current path along the XML's DOM elements by deleting last component. self.currentXMLDOMPath = self.currentXMLDOMPath.deletingLastPathComponent() } func parser(_ parser: XMLParser, foundCDATA CDATABlock: Data) { guard let string = String(data: CDATABlock, encoding: .utf8) else { self.xmlParser.abortParsing() self.parsingError = ParserError.feedCDATABlockEncodingError(path: self.currentXMLDOMPath.absoluteString).value return } self.map(string) } func parser(_ parser: XMLParser, foundCharacters string: String) { self.map(string) } func parser(_ parser: XMLParser, parseErrorOccurred parseError: Error) { self.parsingError = NSError(domain: parseError.localizedDescription, code: -1) } }
gpl-3.0
027b14a2796ec45d0c7cccb6155a6577
33.421053
122
0.614679
4.651494
false
false
false
false
ccrama/Slide-iOS
Slide for Reddit/TableDisplayView.swift
1
11346
// // TableDisplayView.swift // Slide for Reddit // // Created by Carlos Crane on 05/29/18. // Copyright © 2018 Haptic Apps. All rights reserved. // import Anchorage import DTCoreText import reddift import SDWebImage import Then import UIKit import YYText class TableDisplayView: UIScrollView { var baseStackView = UIStackView() var baseData = [[NSAttributedString]]() var scrollView: UIScrollView! var baseColor: UIColor var tColor: UIColor var action: YYTextAction? var longAction: YYTextAction? var linksCallback: ((URL) -> Void)? var indexCallback: (() -> Int)? init(baseHtml: String, color: UIColor, accentColor: UIColor, action: YYTextAction?, longAction: YYTextAction?, linksCallback: ((URL) -> Void)?, indexCallback: (() -> Int)?) { self.linksCallback = linksCallback self.indexCallback = indexCallback let newData = baseHtml.replacingOccurrences(of: "http://view.table/", with: "") self.baseColor = color self.tColor = accentColor self.action = action self.longAction = longAction super.init(frame: CGRect.zero) parseHtml(newData.removingPercentEncoding ?? newData) self.bounces = true self.isUserInteractionEnabled = true baseStackView = UIStackView().then({ $0.axis = .vertical }) self.isScrollEnabled = true makeViews() } //Algorighm from https://github.com/ccrama/Slide/blob/master/app/src/main/java/me/ccrama/redditslide/Views/CommentOverflow.java func parseHtml(_ text: String) { let tableStart = "<table>" let tableEnd = "</table>" let tableHeadStart = "<thead>" let tableHeadEnd = "</thead>" let tableRowStart = "<tr>" let tableRowEnd = "</tr>" let tableColumnStart = "<td>" let tableColumnEnd = "</td>" let tableColumnStartLeft = "<td align=\"left\">" let tableColumnStartRight = "<td align=\"right\">" let tableColumnStartCenter = "<td align=\"center\">" let tableHeaderStart = "<th>" let tableHeaderStartLeft = "<th align=\"left\">" let tableHeaderStartRight = "<th align=\"right\">" let tableHeaderStartCenter = "<th align=\"center\">" let tableHeaderEnd = "</th>" var columnStarted = false var isHeader = true var currentRow = [NSAttributedString]() var currentString = "" for string in text.trimmed().components(separatedBy: "<") { let current = "<\(string)".trimmed() if current == "<" { continue } //print(current) if current == tableStart { } else if current == tableHeadStart { } else if current == tableRowStart { currentRow = [] } else if current == tableRowEnd { isHeader = false baseData.append(currentRow) } else if current == tableEnd { } else if current == tableHeadEnd { } else if !columnStarted && (current == tableColumnStart || current == tableHeaderStart) { columnStarted = true // TODO: - maybe gravity = Gravity.START; } else if !columnStarted && (current == tableColumnStartRight || current == tableHeaderStartRight) { columnStarted = true // TODO: - maybe gravity = Gravity.END; } else if !columnStarted && (current == tableColumnStartCenter || current == tableHeaderStartCenter) { columnStarted = true // TODO: - maybe gravity = Gravity.CENTER; } else if !columnStarted && (current == tableColumnStartLeft || current == tableHeaderStartLeft) { columnStarted = true // TODO: - maybe gravity = Gravity.START; } else if current == tableColumnEnd || current == tableHeaderEnd { if currentString.startsWith("<td") { let index = currentString.indexOf(">") currentString = currentString.substring(index! + 1, length: currentString.length - index! - 1) } columnStarted = false currentRow.append(TextDisplayStackView.createAttributedChunk(baseHTML: currentString.trimmed(), fontSize: CGFloat((isHeader ? 3 : 0) + 16 ), submission: false, accentColor: tColor, fontColor: baseColor, linksCallback: linksCallback, indexCallback: indexCallback)) currentString = "" } else { currentString.append(current) } } /*var header = [NSAttributedString]() for row in baseData { if(header.isEmpty){ header = row } else { for index in 0 ..< row.count { flippedData.append([header[index], row[index]]) } } } backupData = baseData*/ } var maxCellWidth: CGFloat { if traitCollection.userInterfaceIdiom == .phone { return UIScreen.main.bounds.width - 50 } else { return 400 } } let verticalPadding: CGFloat = 4 let horizontalPadding: CGFloat = 4 var globalWidth: CGFloat = 0 var globalHeight: CGFloat = 0 func makeViews() { var columnWidths = [CGFloat](repeating: 0, count: baseData[safeIndex: 0]?.count ?? 0) // Determine width of each column for row in baseData { for (x, text) in row.enumerated() { let framesetter = CTFramesetterCreateWithAttributedString(text) let singleLineTextWidth = CTFramesetterSuggestFrameSizeWithConstraints(framesetter, CFRange(), nil, CGSize.init(width: CGFloat.greatestFiniteMagnitude, height: CGFloat.greatestFiniteMagnitude), nil).width let width = min(singleLineTextWidth, maxCellWidth) + (horizontalPadding * 2) columnWidths[x] = max(columnWidths[x], width) } } globalWidth = columnWidths.reduce(0, +) // Determine heights of rows now that we know column widths var rowHeights = [CGFloat](repeating: 0, count: baseData.count) for (y, row) in baseData.enumerated() { for (x, text) in row.enumerated() { let framesetter = CTFramesetterCreateWithAttributedString(text) let height = CTFramesetterSuggestFrameSizeWithConstraints(framesetter, CFRange(), nil, CGSize.init(width: columnWidths[x], height: CGFloat.greatestFiniteMagnitude), nil).height + (verticalPadding * 2) rowHeights[y] = max(rowHeights[y], height) } } globalHeight = rowHeights.reduce(0, +) // Create each row for (y, row) in baseData.enumerated() { let rowStack = UIStackView().then({ $0.axis = .horizontal $0.spacing = 0 $0.alignment = .top $0.distribution = .fill }) for (x, text) in row.enumerated() { let label = YYLabel() label.numberOfLines = 0 label.textVerticalAlignment = .top label.highlightLongPressAction = longAction label.highlightTapAction = action label.attributedText = text label.textContainerInset = UIEdgeInsets(top: verticalPadding, left: horizontalPadding, bottom: -verticalPadding, right: -horizontalPadding) label.lineBreakMode = .byTruncatingTail if y % 2 != 0 { label.backgroundColor = ColorUtil.theme.foregroundColor } label.widthAnchor == columnWidths[x]// + 100 label.heightAnchor == rowHeights[y] rowStack.addArrangedSubview(label) } baseStackView.addArrangedSubview(rowStack) } addSubview(baseStackView) contentInset = UIEdgeInsets.init(top: 0, left: 8, bottom: 0, right: 8) baseStackView.edgeAnchors == edgeAnchors contentSize = CGSize.init(width: globalWidth, height: globalHeight) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } public static func getEstimatedHeight(baseHtml: String) -> CGFloat { let tableStart = "<table>" let tableEnd = "</table>" let tableHeadStart = "<thead>" let tableHeadEnd = "</thead>" let tableRowStart = "<tr>" let tableRowEnd = "</tr>" let tableColumnStart = "<td>" let tableColumnEnd = "</td>" let tableColumnStartLeft = "<td align=\"left\">" let tableColumnStartRight = "<td align=\"right\">" let tableColumnStartCenter = "<td align=\"center\">" let tableHeaderStart = "<th>" let tableHeaderStartLeft = "<th align=\"left\">" let tableHeaderStartRight = "<th align=\"right\">" let tableHeaderStartCenter = "<th align=\"center\">" let tableHeaderEnd = "</th>" var columnStarted = false var currentString = "" var estHeight = CGFloat(0) for string in baseHtml.trimmed().components(separatedBy: "<") { let current = "<\(string)".trimmed() if current == "<" { continue } //print(current) if current == tableStart { } else if current == tableHeadStart { } else if current == tableRowStart { } else if current == tableRowEnd { estHeight += 30 } else if current == tableEnd { } else if current == tableHeadEnd { } else if !columnStarted && (current == tableColumnStart || current == tableHeaderStart) { columnStarted = true // TODO: - maybe gravity = Gravity.START; } else if !columnStarted && (current == tableColumnStartRight || current == tableHeaderStartRight) { columnStarted = true // TODO: - maybe gravity = Gravity.END; } else if !columnStarted && (current == tableColumnStartCenter || current == tableHeaderStartCenter) { columnStarted = true // TODO: - maybe gravity = Gravity.CENTER; } else if !columnStarted && (current == tableColumnStartLeft || current == tableHeaderStartLeft) { columnStarted = true // TODO: - maybe gravity = Gravity.START; } else if current == tableColumnEnd || current == tableHeaderEnd { if currentString.startsWith("<td") { let index = currentString.indexOf(">") currentString = currentString.substring(index! + 1, length: currentString.length - index! - 1) } columnStarted = false currentString = "" } else { currentString.append(current) } } return estHeight } } private extension Array { subscript(safeIndex index: Int) -> Element? { guard index >= 0, index < endIndex else { return nil } return self[index] } }
apache-2.0
6ee7515adf13c6ed7ebb8c1f2478f730
40.254545
279
0.572587
5.017691
false
false
false
false
magnetsystems/max-ios
Tests/Tests/MMReachabilityConditionSpec.swift
1
2652
/* * Copyright (c) 2015 Magnet Systems, Inc. * All rights reserved. * * 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 Foundation import Quick import Nimble import MagnetMax import AFNetworking class MMReachabilityConditionSpec : QuickSpec { override func spec() { describe("MMReachabilityCondition") { it("allows you to suspend operation until you are online!") { var isFinished = false let queue: OperationQueue = OperationQueue() let operation = BlockOperation { (continuation: Void -> Void) in isFinished = true continuation() } // Initialize the condition first! let reachabilityCondition = MMReachabilityCondition() // Pretend we are Disconnected let userInfo = [AFNetworkingReachabilityNotificationStatusItem: NSNumber(integer: AFNetworkReachabilityStatus.NotReachable.rawValue)] NSNotificationCenter.defaultCenter().postNotificationName(AFNetworkingReachabilityDidChangeNotification, object: nil, userInfo: userInfo) operation.addCondition(reachabilityCondition) queue.addOperation(operation) // Reconnect after 3 seconds! let interval: NSTimeInterval = 3 let when = dispatch_time(DISPATCH_TIME_NOW, Int64(interval * Double(NSEC_PER_SEC))) dispatch_after(when, dispatch_get_global_queue(QOS_CLASS_DEFAULT, 0)) { // Now, we are connected again! let userInfo = [AFNetworkingReachabilityNotificationStatusItem: NSNumber(integer: AFNetworkReachabilityStatus.ReachableViaWWAN.rawValue)] NSNotificationCenter.defaultCenter().postNotificationName(AFNetworkingReachabilityDidChangeNotification, object: nil, userInfo: userInfo) } expect{isFinished}.toEventually(beTruthy(), timeout: 10, pollInterval: 2, description: "Could not execute") } } } }
apache-2.0
3e280a18ce9dd73338471ce7729f88c9
45.526316
157
0.649698
5.642553
false
false
false
false
wangxin20111/WXWeiBo
WXWeibo/WXWeibo/Classes/Main/WXQRCodeController.swift
1
1953
// // WXQRCodeController.swift // WXWeibo // // Created by 王鑫 on 16/6/27. // Copyright © 2016年 王鑫. All rights reserved. // import UIKit class WXQRCodeController: UIViewController ,UITabBarDelegate{ @IBAction func cancelBtnClick(sender: UIBarButtonItem) { dismissViewControllerAnimated(true, completion: nil) } @IBAction func photoAlbumBtnClick(sender: AnyObject) { } @IBOutlet weak var tabbar: UITabBar! //MARK: - 从storyboard中获取一些属性,用来更新,做动画 //容器的高度 @IBOutlet weak var containerHeightCons: NSLayoutConstraint! //冲击波top和容器的距离 @IBOutlet weak var scanLineTopCons: NSLayoutConstraint! //冲击波的view的高度 @IBOutlet weak var scanView: UIImageView! override func viewDidLoad() { super.viewDidLoad() tabbar.selectedItem = tabbar.items![0] tabbar.delegate = self } //开始执行动画 private func startAnimation(time:NSTimeInterval){ scanLineTopCons.constant = -containerHeightCons.constant view.layoutIfNeeded() UIView.animateWithDuration(time, animations: { self.scanLineTopCons.constant = self.containerHeightCons.constant UIView.setAnimationRepeatCount(MAXFLOAT) self.view.layoutIfNeeded() }) } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) startAnimation(2.0) } //MARK: - tabbar代理方法 func tabBar(tabBar: UITabBar, didSelectItem item: UITabBarItem) { //1.改变尺寸 if item.tag == 1 { //二维码 containerHeightCons.constant = 300 }else{ //条形码 containerHeightCons.constant = 150 } //2.停止所有的动画 scanView.layer.removeAllAnimations() //3.重新开启动画 startAnimation(1.0) } }
mit
526001109765cda61a93aad611ee7e3a
28.508197
77
0.645
4.522613
false
false
false
false
blitzagency/events
Events/TypedEventManagerHost/TypedEventManagerHost+ParameterlessCallback.swift
1
1314
// // TypedEventManagerHost+ParameterlessCallback.swift // Events // // Created by Adam Venturella on 7/22/16. // Copyright © 2016 BLITZ. All rights reserved. // import Foundation extension TypedEventManagerHost { public func listenTo<Event: RawRepresentable, Publisher: TypedEventManager<Event>>(_ publisher: Publisher, event: Event, callback: @escaping () -> ()) where Event.RawValue == String { eventManager.listenTo(publisher, event: event.rawValue, callback: callback) } public func listenTo<Event: RawRepresentable, Publisher: TypedEventManagerHost>(_ publisher: Publisher, event: Publisher.EventType, callback: @escaping () -> ()) where Publisher.EventType == Event, Event.RawValue == String { listenTo(publisher, event: event.rawValue, callback: callback) } func listenTo<Publisher: TypedEventManagerHost>(_ publisher: Publisher, event: String, callback: @escaping () -> ()){ let wrappedCallback: (EventPublisher<Publisher>) -> () = wrapCallback(callback) internalOn(publisher, event: event, callback: wrappedCallback) } func wrapCallback<Publisher: TypedEventManagerHost>(_ callback: @escaping () -> ()) -> (EventPublisher<Publisher>) -> (){ return { event in callback() } } }
mit
db47078d787598a30340a2b8036b7791
33.552632
165
0.681645
4.574913
false
false
false
false
brentdax/swift
test/SILOptimizer/merge_exclusivity.swift
1
11297
// RUN: %target-swift-frontend -O -enforce-exclusivity=checked -emit-sil -primary-file %s | %FileCheck %s --check-prefix=TESTSIL // REQUIRES: optimized_stdlib,asserts // REQUIRES: PTRSIZE=64 public var check: UInt64 = 0 @inline(never) func sum(_ x: UInt64, _ y: UInt64) -> UInt64 { return x &+ y } // TESTSIL-LABEL: sil [noinline] @$s17merge_exclusivity10MergeTest1yySiF : $@convention(thin) // TESTSIL: bb0 // TESTSIL: [[GLOBALVAR:%.*]] = global_addr @$s17merge_exclusivity5checks6UInt64Vvp // TESTSIL: [[B1:%.*]] = begin_access [modify] [dynamic] [no_nested_conflict] [[GLOBALVAR]] // TESTSIL: end_access [[B1]] // TESTSIL: bb5 // TESTSIL: [[B2:%.*]] = begin_access [modify] [dynamic] [no_nested_conflict] [[GLOBALVAR]] // TESTSIL-NEXT: load [[B2]] // TESTSIL: store {{.*}} to [[B2]] // TESTSIL: end_access [[B2]] // TESTSIL: bb6 // TESTSIL: [[B3:%.*]] = begin_access [modify] [dynamic] [no_nested_conflict] [[GLOBALVAR]] // TESTSIL-NEXT: load [[B3]] // TESTSIL: store {{.*}} to [[B3]] // TESTSIL: end_access [[B3]] // TESTSIL: bb7 // TESTSIL: [[B4:%.*]] = begin_access [modify] [dynamic] [no_nested_conflict] [[GLOBALVAR]] // TESTSIL-NEXT: load [[B4]] // TESTSIL: store {{.*}} to [[B4]] // TESTSIL: end_access [[B4]] // TESTSIL-NOT: begin_access // TESTSIL-LABEL: } // end sil function '$s17merge_exclusivity10MergeTest1yySiF' @inline(never) public func MergeTest1(_ N: Int) { let range = 0..<10000 check = 0 for _ in 1...N { for e in range { check = sum(check, UInt64(e)) if (e == 0) { check = sum(check, UInt64(1)) } else { check = sum(check, UInt64(2)) } } } } // TESTSIL-LABEL: sil [noinline] @$s17merge_exclusivity10MergeTest2yySiF : $@convention(thin) // TESTSIL: bb0 // TESTSIL: [[GLOBALVAR:%.*]] = global_addr @$s17merge_exclusivity5checks6UInt64Vvp // TESTSIL: [[B1:%.*]] = begin_access [modify] [dynamic] [no_nested_conflict] [[GLOBALVAR]] // TESTSIL: end_access [[B1]] // TESTSIL: bb6 // TESTSIL: [[B2:%.*]] = begin_access [modify] [dynamic] [no_nested_conflict] [[GLOBALVAR]] // TESTSIL-NEXT: load [[B2]] // TESTSIL: store {{.*}} to [[B2]] // TESTSIL: end_access [[B2]] // TESTSIL: bb7 // TESTSIL: [[B3:%.*]] = begin_access [modify] [dynamic] [no_nested_conflict] [[GLOBALVAR]] // TESTSIL-NEXT: load [[B3]] // TESTSIL: store {{.*}} to [[B3]] // TESTSIL: end_access [[B3]] // TESTSIL-NOT: begin_access // TESTSIL-LABEL: } // end sil function '$s17merge_exclusivity10MergeTest2yySiF' @inline(never) public func MergeTest2(_ N: Int) { let range = 0..<10000 check = 0 for _ in 1...N { for e in range { if (e == 0) { check = sum(check, UInt64(1)) } else { check = sum(check, UInt64(2)) } } } } // TESTSIL-LABEL: sil [noinline] @$s17merge_exclusivity10MergeTest3yySiF : $@convention(thin) // TESTSIL: bb0 // TESTSIL: [[GLOBALVAR:%.*]] = global_addr @$s17merge_exclusivity5checks6UInt64Vvp // TESTSIL: [[B1:%.*]] = begin_access [modify] [dynamic] [no_nested_conflict] [[GLOBALVAR]] // TESTSIL: end_access [[B1]] // TESTSIL-NOT: begin_access // TESTSIL-LABEL: } // end sil function '$s17merge_exclusivity10MergeTest3yySiF' @inline(never) public func MergeTest3(_ N: Int) { let range = 0..<10000 check = 0 for _ in 1...N { for e in range { check = sum(check, UInt64(e)) } } } // TESTSIL-LABEL: sil [noinline] @$s17merge_exclusivity10MergeTest4yySiF : $@convention(thin) // TESTSIL: bb0 // TESTSIL: [[GLOBALVAR:%.*]] = global_addr @$s17merge_exclusivity5checks6UInt64Vvp // TESTSIL: [[B1:%.*]] = begin_access [modify] [dynamic] [no_nested_conflict] [[GLOBALVAR]] // TESTSIL: end_access [[B1]] // TESTSIL: bb7 // TESTSIL: [[B2:%.*]] = begin_access [modify] [dynamic] [no_nested_conflict] [[GLOBALVAR]] // TESTSIL-NEXT: load [[B2]] // TESTSIL: store {{.*}} to [[B2]] // TESTSIL: end_access [[B2]] // TESTSIL: bb8 // TESTSIL: [[B3:%.*]] = begin_access [modify] [dynamic] [no_nested_conflict] [[GLOBALVAR]] // TESTSIL-NEXT: load [[B3]] // TESTSIL: store {{.*}} to [[B3]] // TESTSIL: end_access [[B3]] // TESTSIL-NOT: begin_access // TESTSIL-LABEL: } // end sil function '$s17merge_exclusivity10MergeTest4yySiF' @inline(never) public func MergeTest4(_ N: Int) { let range = 0..<10000 check = 0 for _ in 1...N { for e in range { if (e == 0) { check = sum(check, UInt64(1)) } check = sum(check, UInt64(e)) } } } // TESTSIL-LABEL: sil [noinline] @$s17merge_exclusivity10MergeTest5yySiF : $@convention(thin) // TESTSIL: bb0 // TESTSIL: [[GLOBALVAR:%.*]] = global_addr @$s17merge_exclusivity5checks6UInt64Vvp // TESTSIL: [[B1:%.*]] = begin_access [modify] [dynamic] [no_nested_conflict] [[GLOBALVAR]] // TESTSIL: end_access [[B1]] // TESTSIL: bb6 // TESTSIL: [[B2:%.*]] = begin_access [modify] [dynamic] [no_nested_conflict] [[GLOBALVAR]] // TESTSIL-NEXT: load [[B2]] // TESTSIL: store {{.*}} to [[B2]] // TESTSIL: end_access [[B2]] // TESTSIL: bb7 // TESTSIL: [[B3:%.*]] = begin_access [modify] [dynamic] [no_nested_conflict] [[GLOBALVAR]] // TESTSIL-NEXT: load [[B3]] // TESTSIL: store {{.*}} to [[B3]] // TESTSIL: end_access [[B3]] // TESTSIL: bb8 // TESTSIL: [[B4:%.*]] = begin_access [modify] [dynamic] [no_nested_conflict] [[GLOBALVAR]] // TESTSIL-NEXT: load [[B4]] // TESTSIL: store {{.*}} to [[B4]] // TESTSIL: end_access [[B4]] // TESTSIL-NOT: begin_access // TESTSIL-LABEL: } // end sil function '$s17merge_exclusivity10MergeTest5yySiF' @inline(never) public func MergeTest5(_ N: Int) { let range = 0..<10000 check = 0 for _ in 1...N { for e in range { if (e == 0) { check = sum(check, UInt64(1)) } else { check = sum(check, UInt64(2)) } check = sum(check, UInt64(e)) } } } // TESTSIL-LABEL: sil [noinline] @$s17merge_exclusivity10MergeTest6yySiF : $@convention(thin) // TESTSIL: bb0 // TESTSIL: [[GLOBALVAR:%.*]] = global_addr @$s17merge_exclusivity5checks6UInt64Vvp // TESTSIL: [[B1:%.*]] = begin_access [modify] [dynamic] [no_nested_conflict] [[GLOBALVAR]] // TESTSIL: end_access [[B1]] // TESTSIL-NOT: begin_access // TESTSIL-LABEL: } // end sil function '$s17merge_exclusivity10MergeTest6yySiF' @inline(never) public func MergeTest6(_ N: Int) { let range = 0..<10000 check = 0 for _ in 1...N { for e in range { check = sum(check, UInt64(e)) for _ in range { check = sum(check, UInt64(e)) } check = sum(check, UInt64(e)) } } } @inline(never) public func foo() { } // TESTSIL-LABEL: sil [noinline] @$s17merge_exclusivity10MergeTest7yySiF : $@convention(thin) // TESTSIL: bb0 // TESTSIL: [[GLOBALVAR:%.*]] = global_addr @$s17merge_exclusivity5checks6UInt64Vvp // TESTSIL: [[B1:%.*]] = begin_access [modify] [dynamic] [no_nested_conflict] [[GLOBALVAR]] // TESTSIL: end_access [[B1]] // TESTSIL-NOT: begin_access // TESTSIL-LABEL: } // end sil function '$s17merge_exclusivity10MergeTest7yySiF' @inline(never) public func MergeTest7(_ N: Int) { let range = 0..<10000 check = 0 for _ in 1...N { for e in range { check = sum(check, UInt64(e)) for _ in range { foo() } check = sum(check, UInt64(e)) } } } // TESTSIL-LABEL: sil [noinline] @$s17merge_exclusivity10MergeTest8yySiF : $@convention(thin) // TESTSIL: bb0 // TESTSIL: [[GLOBALVAR:%.*]] = global_addr @$s17merge_exclusivity5checks6UInt64Vvp // TESTSIL: [[B1:%.*]] = begin_access [modify] [dynamic] [no_nested_conflict] [[GLOBALVAR]] // TESTSIL: end_access [[B1]] // TESTSIL-NOT: begin_access // TESTSIL-LABEL: } // end sil function '$s17merge_exclusivity10MergeTest8yySiF' @inline(never) public func MergeTest8(_ N: Int) { let range = 0..<10000 check = 0 for _ in 1...N { for e in range { check = sum(check, UInt64(e)) for _ in range { foo() } check = sum(check, UInt64(e)) } } for _ in 1...N { for e in range { check = sum(check, UInt64(e)) for _ in range { foo() } check = sum(check, UInt64(e)) } } } // Large, test that tests the interaction between access merging, // and the rest of the access optimizations. public protocol WriteProt { func writeTo(_ stream: StreamClass) } public final class StreamClass { private var buffer: [UInt8] public init() { self.buffer = [] } public func write(_ byte: UInt8) { buffer.append(byte) } public func write(_ value: WriteProt) { value.writeTo(self) } public func writeEscaped(_ string: String) { writeEscaped(string: string.utf8) } public func writeEscaped<T: Collection>( string sequence: T ) where T.Iterator.Element == UInt8 { for character in sequence { buffer.append(character) buffer.append(character) } } } public func toStream(_ stream: StreamClass, _ value: WriteProt) -> StreamClass { stream.write(value) return stream } extension UInt8: WriteProt { public func writeTo(_ stream: StreamClass) { stream.write(self) } } public func asWriteProt(_ string: String) -> WriteProt { return EscapedString(value: string) } private struct EscapedString: WriteProt { let value: String func writeTo(_ stream: StreamClass) { _ = toStream(stream, UInt8(ascii: "a")) stream.writeEscaped(value) _ = toStream(stream, UInt8(ascii: "a")) } } public func asWriteProt<T>(_ items: [T], transform: @escaping (T) -> String) -> WriteProt { return EscapedTransforme(items: items, transform: transform) } private struct EscapedTransforme<T>: WriteProt { let items: [T] let transform: (T) -> String func writeTo(_ stream: StreamClass) { for (i, item) in items.enumerated() { if i != 0 { _ = toStream(stream, asWriteProt(transform(item))) } _ = toStream(stream, asWriteProt(transform(item))) } } } // TESTSIL-LABEL: sil [noinline] @$s17merge_exclusivity14run_MergeTest9yySiF : $@convention(thin) // TESTSIL: [[REFADDR:%.*]] = ref_element_addr {{.*}} : $StreamClass, #StreamClass.buffer // TESTSIL-NEXT: [[B1:%.*]] = begin_access [modify] [dynamic] [no_nested_conflict] [[REFADDR]] // TESTSIL: end_access [[B1]] // TESTSIL: [[BCONF:%.*]] = begin_access [modify] [dynamic] [[REFADDR]] // TESTSIL: apply {{.*}} : $@convention(method) (Int, @inout Array<UInt8>) -> () // TESTSIL: end_access [[BCONF]] // TESTSIL: [[BCONF:%.*]] = begin_access [modify] [dynamic] [[REFADDR]] // TESTSIL: apply {{.*}} : $@convention(method) (Int, @inout Array<UInt8>) -> () // TESTSIL: end_access [[BCONF]] // TESTSIL: [[BCONF:%.*]] = begin_access [modify] [dynamic] [[REFADDR]] // TESTSIL: apply {{.*}} : $@convention(method) (Int, @inout Array<UInt8>) -> () // TESTSIL: end_access [[BCONF]] // TESTSIL-LABEL: } // end sil function '$s17merge_exclusivity14run_MergeTest9yySiF' @inline(never) public func run_MergeTest9(_ N: Int) { struct Thing { var value: String init(_ value: String) { self.value = value } } let listOfStrings: [String] = (0..<10).map { "This is the number: \($0)!\n" } let listOfThings: [Thing] = listOfStrings.map(Thing.init) for _ in 1...N { let stream = StreamClass() _ = toStream(stream, asWriteProt(listOfThings, transform: { $0.value })) } }
apache-2.0
2c0594ef0ba6b466434b51551d1bea7b
30.912429
129
0.618306
3.311932
false
true
false
false
kousun12/RxSwift
RxExample/RxExample/Examples/Calculator/CalculatorViewController.swift
4
8865
// // CalculatorViewController.swift // RxExample // // Created by Carlos García on 4/8/15. // Copyright (c) 2015 Krunoslav Zaher. All rights reserved. // import UIKit #if !RX_NO_MODULE import RxSwift import RxCocoa #endif class CalculatorViewController: ViewController { enum Operator { case Addition case Subtraction case Multiplication case Division } enum Action { case Clear case ChangeSign case Percent case Operation(Operator) case Equal case AddNumber(Character) case AddDot } struct CalState { let previousNumber: String! let action: Action let currentNumber: String! let inScreen: String let replace: Bool } @IBOutlet weak var lastSignLabel: UILabel! @IBOutlet weak var resultLabel: UILabel! @IBOutlet weak var allClearButton: UIButton! @IBOutlet weak var changeSignButton: UIButton! @IBOutlet weak var percentButton: UIButton! @IBOutlet weak var divideButton: UIButton! @IBOutlet weak var multiplyButton: UIButton! @IBOutlet weak var minusButton: UIButton! @IBOutlet weak var plusButton: UIButton! @IBOutlet weak var equalButton: UIButton! @IBOutlet weak var dotButton: UIButton! @IBOutlet weak var zeroButton: UIButton! @IBOutlet weak var oneButton: UIButton! @IBOutlet weak var twoButton: UIButton! @IBOutlet weak var threeButton: UIButton! @IBOutlet weak var fourButton: UIButton! @IBOutlet weak var fiveButton: UIButton! @IBOutlet weak var sixButton: UIButton! @IBOutlet weak var sevenButton: UIButton! @IBOutlet weak var eightButton: UIButton! @IBOutlet weak var nineButton: UIButton! let CLEAR_STATE = CalState(previousNumber: nil, action: .Clear, currentNumber: "0", inScreen: "0", replace: true) let disposeBag = DisposeBag() override func viewDidLoad() { let commands:[Observable<Action>] = [ allClearButton.rx_tap.map { _ in .Clear }, changeSignButton.rx_tap.map { _ in .ChangeSign }, percentButton.rx_tap.map { _ in .Percent }, divideButton.rx_tap.map { _ in .Operation(.Division) }, multiplyButton.rx_tap.map { _ in .Operation(.Multiplication) }, minusButton.rx_tap.map { _ in .Operation(.Subtraction) }, plusButton.rx_tap.map { _ in .Operation(.Addition) }, equalButton.rx_tap.map { _ in .Equal }, dotButton.rx_tap.map { _ in .AddDot }, zeroButton.rx_tap.map { _ in .AddNumber("0") }, oneButton.rx_tap.map { _ in .AddNumber("1") }, twoButton.rx_tap.map { _ in .AddNumber("2") }, threeButton.rx_tap.map { _ in .AddNumber("3") }, fourButton.rx_tap.map { _ in .AddNumber("4") }, fiveButton.rx_tap.map { _ in .AddNumber("5") }, sixButton.rx_tap.map { _ in .AddNumber("6") }, sevenButton.rx_tap.map { _ in .AddNumber("7") }, eightButton.rx_tap.map { _ in .AddNumber("8") }, nineButton.rx_tap.map { _ in .AddNumber("9") } ] commands .asObservable() .merge() .scan(CLEAR_STATE) { [unowned self] a, x in return self.tranformState(a, x) } .debug("debugging") .subscribeNext { [weak self] calState in self?.resultLabel.text = self?.prettyFormat(calState.inScreen) switch calState.action { case .Operation(let operation): switch operation { case .Addition: self?.lastSignLabel.text = "+" case .Subtraction: self?.lastSignLabel.text = "-" case .Multiplication: self?.lastSignLabel.text = "x" case .Division: self?.lastSignLabel.text = "/" } default: self?.lastSignLabel.text = "" } } .addDisposableTo(disposeBag) } func tranformState(a: CalState, _ x: Action) -> CalState { switch x { case .Clear: return CLEAR_STATE case .AddNumber(let c): return addNumber(a, c) case .AddDot: return addDot(a) case .ChangeSign: let d = "\(-Double(a.inScreen)!)" return CalState(previousNumber: a.previousNumber, action: a.action, currentNumber: d, inScreen: d, replace: true) case .Percent: let d = "\(Double(a.inScreen)!/100)" return CalState(previousNumber: a.previousNumber, action: a.action, currentNumber: d, inScreen: d, replace: true) case .Operation(let o): return performOperation(a, o) case .Equal: return performEqual(a) } } func addNumber(a: CalState, _ char: Character) -> CalState { let cn = a.currentNumber == nil || a.replace ? String(char) : a.inScreen + String(char) return CalState(previousNumber: a.previousNumber, action: a.action, currentNumber: cn, inScreen: cn, replace: false) } func addDot(a: CalState) -> CalState { let cn = a.inScreen.rangeOfString(".") == nil ? a.currentNumber + "." : a.currentNumber return CalState(previousNumber: a.previousNumber, action: a.action, currentNumber: cn, inScreen: cn, replace: false) } func performOperation(a: CalState, _ o: Operator) -> CalState { if a.previousNumber == nil { return CalState(previousNumber: a.currentNumber, action: .Operation(o), currentNumber: nil, inScreen: a.currentNumber, replace: true) } else { let previous = Double(a.previousNumber)! let current = Double(a.inScreen)! switch a.action { case .Operation(let op): switch op { case .Addition: let result = "\(previous + current)" return CalState(previousNumber: result, action: .Operation(o), currentNumber: nil, inScreen: result, replace: true) case .Subtraction: let result = "\(previous - current)" return CalState(previousNumber: result, action: .Operation(o), currentNumber: nil, inScreen: result, replace: true) case .Multiplication: let result = "\(previous * current)" return CalState(previousNumber: result, action: .Operation(o), currentNumber: nil, inScreen: result, replace: true) case .Division: let result = "\(previous / current)" return CalState(previousNumber: result, action: .Operation(o), currentNumber: nil, inScreen: result, replace: true) } default: return CalState(previousNumber: nil, action: .Operation(o), currentNumber: a.currentNumber, inScreen: a.inScreen, replace: true) } } } func performEqual(a: CalState) -> CalState { let previous = Double(a.previousNumber ?? "0") let current = Double(a.inScreen)! switch a.action { case .Operation(let op): switch op { case .Addition: let result = "\(previous! + current)" return CalState(previousNumber: nil, action: .Clear, currentNumber: result, inScreen: result, replace: true) case .Subtraction: let result = "\(previous! - current)" return CalState(previousNumber: nil, action: .Clear, currentNumber: result, inScreen: result, replace: true) case .Multiplication: let result = "\(previous! * current)" return CalState(previousNumber: nil, action: .Clear, currentNumber: result, inScreen: result, replace: true) case .Division: let result = previous! / current let resultText = result == Double.infinity ? "0" : "\(result)" return CalState(previousNumber: nil, action: .Clear, currentNumber: resultText, inScreen: resultText, replace: true) } default: return CalState(previousNumber: nil, action: .Clear, currentNumber: a.currentNumber, inScreen: a.inScreen, replace: true) } } func prettyFormat(str: String) -> String { if str.hasSuffix(".0") { return str.substringToIndex(str.endIndex.predecessor().predecessor()) } return str } }
mit
75b0fcce9c94bd50ff75491b56589636
37.53913
145
0.564869
4.49721
false
false
false
false
thanhtanh/T4TextFieldValidator
T4TextFieldValidator/T4TextFieldValidator.swift
1
13726
// // T4TextFieldValidator.swift // CustomTextField // // Created by SB 3 on 10/16/15. // Copyright © 2015 T4nhpt. All rights reserved. // import UIKit public class T4TextFieldValidator: UITextField { /* // Only override drawRect: if you perform custom drawing. // An empty implementation adversely affects performance during animation. override func drawRect(rect: CGRect) { // Drawing code } */ var strLengthValidationMsg = "" var supportObj:TextFieldValidatorSupport = TextFieldValidatorSupport() var strMsg = "" var arrRegx:NSMutableArray = [] var popUp :IQPopUp? @IBInspectable var isMandatory:Bool = true /**< Default is YES*/ @IBOutlet var presentInView:UIView? /**< Assign view on which you want to show popup and it would be good if you provide controller's view*/ @IBInspectable var popUpColor:UIColor? /**< Assign popup background color, you can also assign default popup color from macro "ColorPopUpBg" at the top*/ private var _validateOnCharacterChanged = false @IBInspectable var validateOnCharacterChanged:Bool { /**< Default is YES, Use it whether you want to validate text on character change or not.*/ get { return _validateOnCharacterChanged } set { supportObj.validateOnCharacterChanged = newValue _validateOnCharacterChanged = newValue } } private var _validateOnResign = false @IBInspectable var validateOnResign:Bool { get { return _validateOnResign } set { supportObj.validateOnResign = newValue _validateOnResign = newValue } } private var ColorPopUpBg = UIColor(red: 0.702, green: 0.000, blue: 0.000, alpha: 1.000) private var MsgValidateLength = NSLocalizedString("THIS_FIELD_CANNOT_BE_BLANK", comment: "This field can not be blank") override init(frame: CGRect) { super.init(frame: frame) self.setup() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.setup() } public override var delegate:UITextFieldDelegate? { didSet { supportObj.delegate = delegate super.delegate=supportObj } } func setup() { validateOnCharacterChanged = true isMandatory = true validateOnResign = true popUpColor = ColorPopUpBg strLengthValidationMsg = MsgValidateLength.copy() as! String supportObj.validateOnCharacterChanged = validateOnCharacterChanged supportObj.validateOnResign = validateOnResign let notify = NSNotificationCenter.defaultCenter() notify.addObserver(self, selector: "didHideKeyboard", name: UIKeyboardWillHideNotification, object: nil) } public func addRegx(strRegx:String, withMsg msg:String) { let dic:NSDictionary = ["regx":strRegx, "msg":msg] arrRegx.addObject(dic) } public func updateLengthValidationMsg(msg:String){ strLengthValidationMsg = msg } public func addConfirmValidationTo(txtConfirm:T4TextFieldValidator, withMsg msg:String) { let dic = [txtConfirm:"confirm", msg:"msg"] arrRegx.addObject(dic) } public func validate() -> Bool { if isMandatory { if self.text?.characters.count == 0 { self.showErrorIconForMsg(strLengthValidationMsg) return false } } for var i = 0; i < arrRegx.count; i++ { let dic = arrRegx.objectAtIndex(i) if dic.objectForKey("confirm") != nil { let txtConfirm = dic.objectForKey("confirm") as! T4TextFieldValidator if txtConfirm.text != self.text { self.showErrorIconForMsg(dic.objectForKey("msg") as! String) return false } } else if dic.objectForKey("regx") as! String != "" && self.text?.characters.count != 0 && !self.validateString(self.text!, withRegex:dic.objectForKey("regx") as! String) { self.showErrorIconForMsg(dic.objectForKey("msg") as! String) return false } } self.rightView=nil return true } public func dismissPopup() { popUp?.removeFromSuperview() } // MARK: Internal methods func didHideKeyboard() { popUp?.removeFromSuperview() } func tapOnError() { self.showErrorWithMsg(strMsg) } func validateString(stringToSearch:String, withRegex regexString:String) ->Bool { let regex = NSPredicate(format: "SELF MATCHES %@", regexString) return regex.evaluateWithObject(stringToSearch) } func showErrorIconForMsg(msg:String) { let btnError = UIButton(frame: CGRectMake(0, 0, 25, 25)) btnError.addTarget(self, action: "tapOnError", forControlEvents: UIControlEvents.TouchUpInside) btnError.setBackgroundImage(UIImage(named: "icon_error"), forState: .Normal) self.rightView = btnError self.rightViewMode = UITextFieldViewMode.Always strMsg = msg } func showErrorWithMsg(msg:String) { if (presentInView == nil) { // [TSMessage showNotificationWithTitle:msg type:TSMessageNotificationTypeError] print("Should set `Present in view` for the UITextField") return } popUp = IQPopUp(frame: CGRectZero) popUp!.strMsg = msg popUp!.popUpColor = popUpColor popUp!.showOnRect = self.convertRect(self.rightView!.frame, toView: presentInView) popUp!.fieldFrame = self.superview?.convertRect(self.frame, toView: presentInView) popUp!.backgroundColor = UIColor.clearColor() presentInView!.addSubview(popUp!) popUp!.translatesAutoresizingMaskIntoConstraints = false let dict = ["v1":popUp!] popUp?.superview?.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[v1]-0-|", options: NSLayoutFormatOptions.DirectionLeadingToTrailing, metrics: nil, views: dict)) popUp?.superview?.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[v1]-0-|", options: NSLayoutFormatOptions.DirectionLeadingToTrailing, metrics: nil, views: dict)) supportObj.popUp=popUp } } // ----------------------------------------------- class TextFieldValidatorSupport : NSObject, UITextFieldDelegate { var delegate:UITextFieldDelegate? var validateOnCharacterChanged: Bool = false var validateOnResign = false var popUp :IQPopUp? func textFieldShouldBeginEditing(textField: UITextField) -> Bool { if delegate!.respondsToSelector("textFieldShouldBeginEditing") { return delegate!.textFieldShouldBeginEditing!(textField) } return true } func textFieldDidBeginEditing(textField: UITextField) { if delegate!.respondsToSelector("textFieldDidBeginEditing") { delegate!.textFieldDidEndEditing!(textField) } } func textFieldShouldEndEditing(textField: UITextField) -> Bool { if delegate!.respondsToSelector("textFieldShouldEndEditing") { return delegate!.textFieldShouldEndEditing!(textField) } return true } func textFieldDidEndEditing(textField: UITextField) { if delegate!.respondsToSelector("textFieldDidEndEditing") { delegate?.textFieldDidEndEditing!(textField) } popUp?.removeFromSuperview() if validateOnResign { (textField as! T4TextFieldValidator).validate() } } func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool { (textField as! T4TextFieldValidator).dismissPopup() if validateOnCharacterChanged { (textField as! T4TextFieldValidator).performSelector("validate", withObject: nil, afterDelay:0.1) } else { (textField as! T4TextFieldValidator).rightView = nil } if delegate!.respondsToSelector("textField:shouldChangeCharactersInRange:replacementString:") { return delegate!.textField!(textField, shouldChangeCharactersInRange: range, replacementString: string) } return true } func textFieldShouldClear(textField: UITextField) -> Bool { if delegate!.respondsToSelector("textFieldShouldClear"){ delegate?.textFieldShouldClear!(textField) } return true } func textFieldShouldReturn(textField: UITextField) -> Bool { if delegate!.respondsToSelector("textFieldShouldReturn") { delegate?.textFieldShouldReturn!(textField) } return true } } // ----------------------------------------------- class IQPopUp : UIView { var showOnRect:CGRect? var popWidth:Int = 0 var fieldFrame:CGRect? var strMsg:NSString = "" var popUpColor:UIColor? var FontSize:CGFloat = 15 var PaddingInErrorPopUp:CGFloat = 5 var FontName = "Helvetica-Bold" override func drawRect(rect:CGRect) { let color = CGColorGetComponents(popUpColor!.CGColor) UIGraphicsBeginImageContext(CGSizeMake(30, 20)) let ctx = UIGraphicsGetCurrentContext() CGContextSetRGBFillColor(ctx, color[0], color[1], color[2], 1) CGContextSetShadowWithColor(ctx, CGSizeMake(0, 0), 7.0, UIColor.blackColor().CGColor) let points = [ CGPointMake(15, 5), CGPointMake(25, 25), CGPointMake(5,25)] CGContextAddLines(ctx, points, 3) CGContextClosePath(ctx) CGContextFillPath(ctx) let viewImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() let imgframe = CGRectMake((showOnRect!.origin.x + ((showOnRect!.size.width-30)/2)), ((showOnRect!.size.height/2) + showOnRect!.origin.y), 30, 13) let img = UIImageView(image: viewImage, highlightedImage: nil) self.addSubview(img) img.translatesAutoresizingMaskIntoConstraints = false var dict:Dictionary<String, AnyObject> = ["img":img] img.superview?.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat(String(format:"H:|-%f-[img(%f)]", imgframe.origin.x, imgframe.size.width), options:NSLayoutFormatOptions.DirectionLeadingToTrailing, metrics:nil, views:dict)) img.superview?.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat(String(format:"V:|-%f-[img(%f)]",imgframe.origin.y,imgframe.size.height), options:NSLayoutFormatOptions.DirectionLeadingToTrailing, metrics:nil, views:dict)) let font = UIFont(name: FontName, size: FontSize) var size:CGSize = self.strMsg.boundingRectWithSize(CGSize(width: fieldFrame!.size.width - (PaddingInErrorPopUp*2), height: 1000), options: NSStringDrawingOptions.UsesLineFragmentOrigin, attributes: [NSFontAttributeName:font!], context: nil).size size = CGSizeMake(ceil(size.width), ceil(size.height)) let view = UIView(frame: CGRectZero) self.insertSubview(view, belowSubview:img) view.backgroundColor=self.popUpColor view.layer.cornerRadius=5.0 view.layer.shadowColor = UIColor.blackColor().CGColor view.layer.shadowRadius=5.0 view.layer.shadowOpacity=1.0 view.layer.shadowOffset=CGSizeMake(0, 0) view.translatesAutoresizingMaskIntoConstraints = false dict = ["view":view] view.superview?.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat(String(format:"H:|-%f-[view(%f)]",fieldFrame!.origin.x+(fieldFrame!.size.width-(size.width + (PaddingInErrorPopUp*2))),size.width+(PaddingInErrorPopUp*2)), options:NSLayoutFormatOptions.DirectionLeadingToTrailing, metrics:nil, views:dict)) view.superview?.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat(String(format:"V:|-%f-[view(%f)]",imgframe.origin.y+imgframe.size.height,size.height+(PaddingInErrorPopUp*2)), options:NSLayoutFormatOptions.DirectionLeadingToTrailing, metrics:nil, views:dict)) let lbl = UILabel(frame: CGRectZero) lbl.font = font lbl.numberOfLines=0 lbl.backgroundColor = UIColor.clearColor() lbl.text=self.strMsg as String lbl.textColor = UIColor.whiteColor() view.addSubview(lbl) lbl.translatesAutoresizingMaskIntoConstraints = false dict = ["lbl":lbl] lbl.superview?.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat(String(format:"H:|-%f-[lbl(%f)]", PaddingInErrorPopUp, size.width), options:NSLayoutFormatOptions.DirectionLeadingToTrailing , metrics:nil, views:dict)) lbl.superview?.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat(String(format:"V:|-%f-[lbl(%f)]", PaddingInErrorPopUp,size.height), options:NSLayoutFormatOptions.DirectionLeadingToTrailing, metrics:nil, views:dict)) } override func pointInside(point: CGPoint, withEvent event: UIEvent?) -> Bool { self.removeFromSuperview() return false } }
mit
df0da78f8a8123abaa8f66cefc2cc247
36.094595
325
0.642404
5.081451
false
false
false
false
nanthi1990/Typhoon-Swift-Example
PocketForecast/Model/WeatherReport.swift
3
2567
//////////////////////////////////////////////////////////////////////////////// // // TYPHOON FRAMEWORK // Copyright 2013, Typhoon Framework Contributors // All Rights Reserved. // // NOTICE: The authors permit you to use, modify, and distribute this file // in accordance with the terms of the license agreement accompanying it. // //////////////////////////////////////////////////////////////////////////////// import Foundation public class WeatherReport : NSObject, NSCoding, Printable { public private(set) var city : String public private(set) var date : NSDate public private(set) var currentConditions : CurrentConditions public private(set) var forecast : Array<ForecastConditions> public var cityDisplayName : String { var displayName : String let components : Array<String> = self.city.componentsSeparatedByString(",") if (components.count > 1) { displayName = components[0] } else { displayName = self.city.capitalizedString } return displayName } public init(city : String, date : NSDate, currentConditions : CurrentConditions, forecast : Array<ForecastConditions>) { self.city = city self.date = date self.currentConditions = currentConditions self.forecast = forecast } public required init(coder : NSCoder) { self.city = coder.decodeObjectForKey("city") as! String self.date = coder.decodeObjectForKey("date") as! NSDate self.currentConditions = coder.decodeObjectForKey("currentConditions") as! CurrentConditions self.forecast = coder.decodeObjectForKey("forecast") as! Array<ForecastConditions> } public func reportDateAsString() -> String { let dateFormatter = NSDateFormatter() dateFormatter.dateFormat = "MMM dd',' yyyy 'at' hh:mm a" dateFormatter.locale = NSLocale.currentLocale() return dateFormatter.stringFromDate(self.date) } public override var description: String { return String(format: "Weather Report: city=%@, current conditions = %@, forecast=%@", self.city, self.currentConditions, self.forecast ) } public func encodeWithCoder(coder : NSCoder) { coder.encodeObject(self.city, forKey:"city") coder.encodeObject(self.date, forKey:"date") coder.encodeObject(self.currentConditions, forKey:"currentConditions") coder.encodeObject(self.forecast, forKey:"forecast") } }
apache-2.0
eac1b918f5bb13620739d6f01e483b8e
34.164384
145
0.620958
5.21748
false
false
false
false
EasonWQY/swiftweaher1
Swift Weather/ViewController.swift
2
8333
// // ViewController.swift // Swift Weather // // Created by Jake Lin on 4/06/2014. // Copyright (c) 2014 rushjet. All rights reserved. // import UIKit import CoreLocation import Alamofire import SwiftyJSON import SwiftWeatherService class ViewController: UIViewController, CLLocationManagerDelegate { let locationManager:CLLocationManager = CLLocationManager() @IBOutlet var loadingIndicator : UIActivityIndicatorView! = nil @IBOutlet var icon : UIImageView! @IBOutlet var temperature : UILabel! @IBOutlet var loading : UILabel! @IBOutlet var location : UILabel! @IBOutlet weak var time1: UILabel! @IBOutlet weak var time2: UILabel! @IBOutlet weak var time3: UILabel! @IBOutlet weak var time4: UILabel! @IBOutlet weak var image1: UIImageView! @IBOutlet weak var image2: UIImageView! @IBOutlet weak var image3: UIImageView! @IBOutlet weak var image4: UIImageView! @IBOutlet weak var temp1: UILabel! @IBOutlet weak var temp2: UILabel! @IBOutlet weak var temp3: UILabel! @IBOutlet weak var temp4: UILabel! override func viewDidLoad() { super.viewDidLoad() locationManager.delegate = self locationManager.desiredAccuracy = kCLLocationAccuracyBest self.loadingIndicator.startAnimating() let background = UIImage(named: "background.png") self.view.backgroundColor = UIColor(patternImage: background!) let singleFingerTap = UITapGestureRecognizer(target: self, action: "handleSingleTap:") self.view.addGestureRecognizer(singleFingerTap) locationManager.requestAlwaysAuthorization() locationManager.startUpdatingLocation() } func handleSingleTap(recognizer: UITapGestureRecognizer) { locationManager.startUpdatingLocation() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // It maybe a Xcode 6.2 beta Swift compiler's bug, it throws "command failed due to signal segmentation fault 11" error /* func updateWeatherInfo(latitude: CLLocationDegrees, longitude: CLLocationDegrees) { let service = SwiftWeatherService.WeatherService() service.retrieveForecast(latitude, longitude: longitude, success: { response in println(response) // self.updateUISuccess(response.object!) }, failure:{ response in println(response) println("Error: " + response.error!.localizedDescription) self.loading.text = "Internet appears down!" }) } */ func updateWeatherInfo(latitude: CLLocationDegrees, longitude: CLLocationDegrees) { let url = "http://api.openweathermap.org/data/2.5/forecast" let params = ["lat":latitude, "lon":longitude] println(params) Alamofire.request(.GET, url, parameters: params) .responseJSON { (request, response, json, error) in if(error != nil) { println("Error: \(error)") println(request) println(response) self.loading.text = "Internet appears down!" } else { println("Success: \(url)") println(request) var json = JSON(json!) self.updateUISuccess(json) } } } func updateUISuccess(json: JSON) { self.loading.text = nil self.loadingIndicator.hidden = true self.loadingIndicator.stopAnimating() let service = SwiftWeatherService.WeatherService() // If we can get the temperature from JSON correctly, we assume the rest of JSON is correct. if let tempResult = json["list"][0]["main"]["temp"].double { // Get country let country = json["city"]["country"].stringValue // Get and convert temperature var temperature = service.convertTemperature(country, temperature: tempResult) self.temperature.text = "\(temperature)°" // Get city name self.location.text = json["city"]["name"].stringValue // Get and set icon let weather = json["list"][0]["weather"][0] let condition = weather["id"].intValue var icon = weather["icon"].stringValue var nightTime = service.isNightTime(icon) service.updateWeatherIcon(condition, nightTime: nightTime, index: 0, callback: self.updatePictures) // Get forecast for index in 1...4 { println(json["list"][index]) if let tempResult = json["list"][index]["main"]["temp"].double { // Get and convert temperature var temperature = service.convertTemperature(country, temperature: tempResult) if (index==1) { self.temp1.text = "\(temperature)°" } else if (index==2) { self.temp2.text = "\(temperature)°" } else if (index==3) { self.temp3.text = "\(temperature)°" } else if (index==4) { self.temp4.text = "\(temperature)°" } // Get forecast time var dateFormatter = NSDateFormatter() dateFormatter.dateFormat = "HH:mm" let rawDate = json["list"][index]["dt"].doubleValue let date = NSDate(timeIntervalSince1970: rawDate) let forecastTime = dateFormatter.stringFromDate(date) if (index==1) { self.time1.text = forecastTime } else if (index==2) { self.time2.text = forecastTime } else if (index==3) { self.time3.text = forecastTime } else if (index==4) { self.time4.text = forecastTime } // Get and set icon let weather = json["list"][index]["weather"][0] let condition = weather["id"].intValue var icon = weather["icon"].stringValue var nightTime = service.isNightTime(icon) service.updateWeatherIcon(condition, nightTime: nightTime, index: index, callback: self.updatePictures) } else { continue } } } else { self.loading.text = "Weather info is not available!" } } func updatePictures(index: Int, name: String) { if (index==0) { self.icon.image = UIImage(named: name) } if (index==1) { self.image1.image = UIImage(named: name) } if (index==2) { self.image2.image = UIImage(named: name) } if (index==3) { self.image3.image = UIImage(named: name) } if (index==4) { self.image4.image = UIImage(named: name) } } //MARK: - CLLocationManagerDelegate func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) { var location:CLLocation = locations[locations.count-1] as! CLLocation if (location.horizontalAccuracy > 0) { self.locationManager.stopUpdatingLocation() println(location.coordinate) updateWeatherInfo(location.coordinate.latitude, longitude: location.coordinate.longitude) } } func locationManager(manager: CLLocationManager!, didFailWithError error: NSError!) { println(error) self.loading.text = "Can't get your location!" } override func preferredStatusBarStyle() -> UIStatusBarStyle { return .LightContent } }
mit
fef3cd742101ef6f829b8118bcc996af
37.027397
123
0.555716
5.428944
false
false
false
false
bvic23/VinceRP
VinceRP/Common/Core/Source.swift
1
1193
// // Created by Viktor Belenyesi on 15/09/15. // Copyright (c) 2015 Viktor Belenyesi. All rights reserved. // let noValueError = NSError(domain: "no value", code: -1, userInfo: nil) public class Source<T>: Hub<T> { let state: AtomicReference<Try<T>> public init(initValue: T) { state = AtomicReference(Try(initValue)) super.init() } public override init() { state = AtomicReference(Try(noValueError)) super.init() } public func update(newValue: T) { self.updateSilent(newValue) self.propagate() } public func error(error: NSError) { self.state.value = Try(error) self.propagate() } public func updateSilent(newValue: T) { self.state.value = Try(newValue) } override func isSuccess() -> Bool { return toTry().isSuccess() } override public func toTry() -> Try<T> { return state.value } public func hasValue() -> Bool { if !isSuccess() { if case .Failure(let e) = toTry() { return e !== noValueError } } return true } }
mit
ad3932ff35929131dda453f45e657728
21.509434
71
0.54736
4.099656
false
false
false
false
marinehero/LeetCode-Solutions-in-Swift
Solutions/Solutions/Medium/Medium_060_Permutation_Sequence.swift
4
1213
/* https://leetcode.com/problems/permutation-sequence/ #60 Permutation Sequence Level: medium The set [1,2,3,…,n] contains a total of n! unique permutations. By listing and labeling all of the permutations in order, We get the following sequence (ie, for n = 3): "123" "132" "213" "231" "312" "321" Given n and k, return the kth permutation sequence. Note: Given n will be between 1 and 9 inclusive. Inspired by @lucastan at https://leetcode.com/discuss/11023/most-concise-c-solution-minimal-memory-required */ import Foundation struct Medium_060_Permutation_Sequence { static func getPermutation(n n: Int, var k: Int) -> String { var i: Int, j: Int, f: Int = 1 var s = [Character](count: n, repeatedValue: "0") let map: [Int: Character] = [1: "1", 2: "2", 3: "3", 4: "4", 5: "5", 6: "6", 7: "7", 8: "8", 9: "9"] for i = 1; i <= n; i++ { f *= i s[i-1] = map[i]! } for i = 0, k--; i < n; i++ { f /= n - i j = i + k / f let c = s[j] for ; j > i; j-- { s[j] = s[j-1] } k %= f s[i] = c } return String(s) } }
mit
9077f6855f8c9410a3504250e9e63fe6
22.764706
108
0.519405
3.004963
false
false
false
false
hongchenxi/iOS-9-Sampler
iOS9Sampler/SampleViewControllers/StillImageFiltersViewController.swift
91
4574
// // StillImageFiltersViewController.swift // iOS9Sampler // // Created by Shuichi Tsutsumi on 2015/06/19. // Copyright © 2015 Shuichi Tsutsumi. All rights reserved. // import UIKit class StillImageFiltersViewController: UIViewController, UIPickerViewDataSource, UIPickerViewDelegate { @IBOutlet weak var imageView: UIImageView! @IBOutlet weak var picker: UIPickerView! @IBOutlet weak var indicator: UIActivityIndicatorView! var items: [String] = [] var orgImage: UIImage! override func viewDidLoad() { super.viewDidLoad() orgImage = imageView.image let exceptCategories = [ kCICategoryTransition, kCICategoryGenerator, kCICategoryReduction, ] items = FilterHelper.filterNamesFor_iOS9(kCICategoryBuiltIn, exceptCategories: exceptCategories) items.insert("Original", atIndex: 0) print("num:\(items.count)\n") } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // 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. } */ // ========================================================================= // MARK: - UIPickerViewDataSource func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int { return 1 } func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { return items.count } // ========================================================================= // MARK: - UIPickerViewDelegate func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { return items[row] } func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { if row == 0 { imageView.image = orgImage return } indicator.startAnimating() dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) { let inputImage = CIImage(image: self.orgImage)! // Create CIFilter object let params = [kCIInputImageKey: inputImage] let filter = CIFilter(name: self.items[row], withInputParameters: params)! filter.setDefaults() let attributes = filter.attributes // for CIShadedMaterial if attributes["inputShadingImage"] != nil { filter.setValue(inputImage, forKey: "inputShadingImage") } // Apply filter let context = CIContext(options: nil) let outputImage = filter.outputImage if outputImage == nil { dispatch_async(dispatch_get_main_queue()) { self.imageView.image = nil self.indicator.stopAnimating() } } else { var extent = outputImage!.extent // let scale = UIScreen.mainScreen().scale var scale: CGFloat! // some outputImage have infinite extents. e.g. CIDroste if extent.isInfinite == true { let size = self.imageView.frame.size scale = UIScreen.mainScreen().scale extent = CGRectMake(0, 0, size.width * scale, size.height * scale) } else { scale = extent.size.width / self.orgImage.size.width } let cgImage = context.createCGImage(outputImage!, fromRect: extent) let image = UIImage(CGImage: cgImage, scale: scale, orientation: UIImageOrientation.Up) print("extent:\(extent), image:\(image), org:\(self.orgImage), scale:\(scale)\n") dispatch_async(dispatch_get_main_queue()) { self.imageView.image = image self.indicator.stopAnimating() } } } } }
mit
21ae8c51b2739a347335c2bfc2a44cc2
32.625
109
0.552591
5.638718
false
false
false
false
ustwo/github-scanner
Sources/GitHubKit/Model/RepositoryLicenseInfo.swift
1
1603
// // RepositoryLicenseInfo.swift // GitHub Scanner // // Created by Aaron McTavish on 14/02/2017. // Copyright © 2017 ustwo Fampany Ltd. All rights reserved. // import Foundation /// Represents the open-source license info for a repository. public struct RepositoryLicenseInfo { // MARK: - Properties /// Key name for the license. Used for GitHub searches and uri creation. public let key: String? /// User friendly name for the license. public let name: String? /// URL to the canonical copy of the license (not neccessarily located in the repository). public let url: URL? } // MARK: - JSONInitializable extension RepositoryLicenseInfo: JSONInitializable { // MARK: - Types private struct JSONKeys { static let key = "key" static let name = "name" static let url = "url" } // MARK: - Initializers public init?(json: Any) { guard let jsonArray = json as? [String: Any] else { return nil } let key = jsonArray[JSONKeys.key] as? String let name = jsonArray[JSONKeys.name] as? String var url: URL? if let licenseURL = jsonArray[JSONKeys.url] as? String { url = URL(string: licenseURL) } self.init(key: key, name: name, url: url) } } // MARK: - Equatable extension RepositoryLicenseInfo: Equatable { public static func == (lhs: RepositoryLicenseInfo, rhs: RepositoryLicenseInfo) -> Bool { return lhs.key == rhs.key && lhs.name == rhs.name && lhs.url == rhs.url } }
mit
f10aab0c28b471b484bd967e45116da0
20.945205
94
0.619226
4.226913
false
false
false
false
SoCM/iOS-FastTrack-2014-2015
04-App Architecture/Swift 4/Breadcrumbs/Breadcrumbs-3/Breadcrumbs/ViewController.swift
2
6130
// // ViewController.swift // Breadcrumbs // // Created by Nicholas Outram on 20/01/2016. // Copyright © 2016 Plymouth University. All rights reserved. // import UIKit import MapKit import CoreLocation class ViewController: UIViewController, CLLocationManagerDelegate, MKMapViewDelegate { /// The application state - "where we are in a known sequence" enum AppState { case waitingForViewDidLoad case requestingAuth case liveMapNoLogging case liveMapLogging init() { self = .waitingForViewDidLoad } } /// The type of input (and its value) applied to the state machine enum AppStateInputSource { case none case start case authorisationStatus(Bool) case userWantsToStart(Bool) } // MARK: - Outlets @IBOutlet weak var mapView: MKMapView! @IBOutlet weak var startButton: UIBarButtonItem! @IBOutlet weak var stopButton: UIBarButtonItem! @IBOutlet weak var clearButton: UIBarButtonItem! @IBOutlet weak var optionsButton: UIBarButtonItem! // MARK: - Properties lazy var locationManager : CLLocationManager = { let loc = CLLocationManager() //Set up location manager with defaults loc.desiredAccuracy = kCLLocationAccuracyBest loc.distanceFilter = kCLDistanceFilterNone loc.delegate = self //Optimisation of battery loc.pausesLocationUpdatesAutomatically = true loc.activityType = CLActivityType.fitness loc.allowsBackgroundLocationUpdates = false return loc }() //Applicaion state fileprivate var state : AppState = AppState() { willSet { print("Changing from state \(state) to \(newValue)") } didSet { self.updateOutputWithState() } } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. self.updateStateWithInput(.start) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - CLLocationManagerDelegate func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) { if status == CLAuthorizationStatus.authorizedAlways { self.updateStateWithInput(.authorisationStatus(true)) } else { self.updateStateWithInput(.authorisationStatus(false)) } } // MARK: Action and Events @IBAction func doStart(_ sender: AnyObject) { self.updateStateWithInput(.userWantsToStart(true)) } @IBAction func doStop(_ sender: AnyObject) { self.updateStateWithInput(.userWantsToStart(false)) } @IBAction func doClear(_ sender: AnyObject) { } @IBAction func doOptions(_ sender: AnyObject) { } // MARK: State Machine //UPDATE STATE func updateStateWithInput(_ ip : AppStateInputSource) { var nextState = self.state switch (self.state) { case .waitingForViewDidLoad: if case .start = ip { nextState = .requestingAuth } case .requestingAuth: if case .authorisationStatus(let val) = ip, val == true { nextState = .liveMapNoLogging } case .liveMapNoLogging: //Check for user cancelling permission if case .authorisationStatus(let val) = ip, val == false { nextState = .requestingAuth } //Check for start button else if case .userWantsToStart(let val) = ip, val == true { nextState = .liveMapLogging } case .liveMapLogging: //Check for user cancelling permission if case .authorisationStatus(let val) = ip, val == false { nextState = .requestingAuth } //Check for stop button else if case .userWantsToStart(let val) = ip, val == false { nextState = .liveMapNoLogging } } self.state = nextState } //UPDATE (MOORE) OUTPUTS func updateOutputWithState() { switch (self.state) { case .waitingForViewDidLoad: break case .requestingAuth: locationManager.requestAlwaysAuthorization() //Set UI into default state until authorised //Buttons startButton.isEnabled = false stopButton.isEnabled = false clearButton.isEnabled = false optionsButton.isEnabled = false //Map defaults (pedantic) mapView.delegate = nil mapView.showsUserLocation = false //Location manger (pedantic) locationManager.stopUpdatingLocation() locationManager.allowsBackgroundLocationUpdates = false case .liveMapNoLogging: //Buttons for logging startButton.isEnabled = true stopButton.isEnabled = false optionsButton.isEnabled = false //Live Map mapView.showsUserLocation = true mapView.userTrackingMode = .follow mapView.showsTraffic = true mapView.delegate = self case .liveMapLogging: //Buttons startButton.isEnabled = false stopButton.isEnabled = true optionsButton.isEnabled = true //Map mapView.showsUserLocation = true mapView.userTrackingMode = .follow mapView.showsTraffic = true mapView.delegate = self } } }
mit
eebb5e67e9167c2ce6ddee99ec5197b1
28.325359
110
0.571708
5.876318
false
false
false
false
slavapestov/swift
test/Generics/slice_test.swift
3
2248
// RUN: %target-parse-verify-swift -parse-stdlib import Swift infix operator < { associativity none precedence 170 } infix operator == { associativity none precedence 160 } infix operator != { associativity none precedence 160 } func testslice(s: Array<Int>) { for i in 0..<s.count { print(s[i]+1) } for i in s { print(i+1) } _ = s[0..<2] _ = s[0...1] } @_silgen_name("malloc") func c_malloc(size: Int) -> UnsafeMutablePointer<Void> @_silgen_name("free") func c_free(p: UnsafeMutablePointer<Void>) class Vector<T> { var length : Int var capacity : Int var base : UnsafeMutablePointer<T> init() { length = 0 capacity = 0 base = nil } func push_back(elem: T) { if length == capacity { let newcapacity = capacity * 2 + 2 let size = Int(Builtin.sizeof(T.self)) let newbase = UnsafeMutablePointer<T>(c_malloc(newcapacity * size)) for i in 0..<length { (newbase + i).initialize((base+i).move()) } c_free(base) base = newbase capacity = newcapacity } (base+length).initialize(elem) length += 1 } func pop_back() -> T { length -= 1 return (base + length).move() } subscript (i : Int) -> T { get { if i >= length { Builtin.int_trap() } return (base + i).memory } set { if i >= length { Builtin.int_trap() } (base + i).memory = newValue } } deinit { for i in 0..<length { (base + i).destroy() } c_free(base) } } protocol Comparable { func <(lhs: Self, rhs: Self) -> Bool } func sort<T : Comparable>(inout array: [T]) { for i in 0..<array.count { for j in i+1..<array.count { if array[j] < array[i] { let temp = array[i] array[i] = array[j] array[j] = temp } } } } func find<T : Eq>(array: [T], value: T) -> Int { var idx = 0 for elt in array { if (elt == value) { return idx } idx += 1 } return -1 } func findIf<T>(array: [T], fn: (T) -> Bool) -> Int { var idx = 0 for elt in array { if (fn(elt)) { return idx } idx += 1 } return -1 } protocol Eq { func ==(lhs: Self, rhs: Self) -> Bool func !=(lhs: Self, rhs: Self) -> Bool }
apache-2.0
06be42262e2723479c331664f1828f43
17.42623
78
0.544929
3.184136
false
false
false
false
argent-os/argent-ios
app-ios/FormerInputAccessoryView.swift
1
5145
// // FormerInputAccessoryView.swift // argent-ios // // Created by Sinan Ulkuatam on 3/19/16. // Copyright © 2016 Sinan Ulkuatam. All rights reserved. // import UIKit import Former final class FormerInputAccessoryView: UIToolbar { private weak var former: Former? private weak var leftArrow: UIBarButtonItem! private weak var rightArrow: UIBarButtonItem! init(former: Former) { super.init(frame: CGRect(origin: CGPointZero, size: CGSize(width: 0, height: 44))) self.former = former configure() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func update() { leftArrow.enabled = former?.canBecomeEditingPrevious() ?? false rightArrow.enabled = former?.canBecomeEditingNext() ?? false } private func configure() { barTintColor = .whiteColor() tintColor = UIColor.mediumBlue() clipsToBounds = true userInteractionEnabled = true let flexible = UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: nil, action: nil) let leftArrow = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem(rawValue: 105)!, target: self, action: #selector(FormerInputAccessoryView.handleBackButton)) let space = UIBarButtonItem(barButtonSystemItem: .FixedSpace, target: nil, action: nil) space.width = 20 let rightArrow = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem(rawValue: 106)!, target: self, action: #selector(FormerInputAccessoryView.handleForwardButton)) let doneButton = UIBarButtonItem(barButtonSystemItem: .Done, target: self, action: #selector(FormerInputAccessoryView.handleDoneButton)) let rightSpace = UIBarButtonItem(barButtonSystemItem: .FixedSpace, target: nil, action: nil) setItems([leftArrow, space, rightArrow, flexible, doneButton, rightSpace], animated: false) self.leftArrow = leftArrow self.rightArrow = rightArrow let topLineView = UIView() topLineView.backgroundColor = UIColor(white: 0, alpha: 0.3) topLineView.translatesAutoresizingMaskIntoConstraints = false addSubview(topLineView) let bottomLineView = UIView() bottomLineView.backgroundColor = UIColor(white: 0, alpha: 0.3) bottomLineView.translatesAutoresizingMaskIntoConstraints = false addSubview(bottomLineView) let leftLineView = UIView() leftLineView.backgroundColor = UIColor(white: 0, alpha: 0.3) leftLineView.translatesAutoresizingMaskIntoConstraints = false addSubview(leftLineView) let rightLineView = UIView() rightLineView.backgroundColor = UIColor(white: 0, alpha: 0.3) rightLineView.translatesAutoresizingMaskIntoConstraints = false addSubview(rightLineView) let constraints = [ NSLayoutConstraint.constraintsWithVisualFormat( "V:|-0-[topLine(0.5)]", options: [], metrics: nil, views: ["topLine": topLineView] ), NSLayoutConstraint.constraintsWithVisualFormat( "V:[bottomLine(0.5)]-0-|", options: [], metrics: nil, views: ["bottomLine": bottomLineView] ), NSLayoutConstraint.constraintsWithVisualFormat( "V:|-10-[leftLine]-10-|", options: [], metrics: nil, views: ["leftLine": leftLineView] ), NSLayoutConstraint.constraintsWithVisualFormat( "V:|-10-[rightLine]-10-|", options: [], metrics: nil, views: ["rightLine": rightLineView] ), NSLayoutConstraint.constraintsWithVisualFormat( "H:|-0-[topLine]-0-|", options: [], metrics: nil, views: ["topLine": topLineView] ), NSLayoutConstraint.constraintsWithVisualFormat( "H:|-0-[bottomLine]-0-|", options: [], metrics: nil, views: ["bottomLine": bottomLineView] ), NSLayoutConstraint.constraintsWithVisualFormat( "H:|-84-[leftLine(0.5)]", options: [], metrics: nil, views: ["leftLine": leftLineView] ), NSLayoutConstraint.constraintsWithVisualFormat( "H:[rightLine(0.5)]-74-|", options: [], metrics: nil, views: ["rightLine": rightLineView] ) ] addConstraints(constraints.flatMap { $0 }) } private dynamic func handleBackButton() { update() former?.becomeEditingPrevious() } private dynamic func handleForwardButton() { update() former?.becomeEditingNext() } private dynamic func handleDoneButton() { former?.endEditing() } }
mit
d5e206ec9382b308cbc31e10f6633418
36.830882
179
0.595645
5.734671
false
false
false
false
convergeeducacao/Charts
Source/Charts/Highlight/HorizontalBarHighlighter.swift
4
1986
// // HorizontalBarHighlighter.swift // Charts // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/Charts // import Foundation import CoreGraphics @objc(HorizontalBarChartHighlighter) open class HorizontalBarHighlighter: BarHighlighter { open override func getHighlight(x: CGFloat, y: CGFloat) -> Highlight? { if let barData = self.chart?.data as? BarChartData { let pos = getValsForTouch(x: y, y: x) guard let high = getHighlight(xValue: Double(pos.y), x: y, y: x) else { return nil } if let set = barData.getDataSetByIndex(high.dataSetIndex) as? IBarChartDataSet, set.isStacked { return getStackedHighlight(high: high, set: set, xValue: Double(pos.y), yValue: Double(pos.x)) } return high } return nil } internal override func buildHighlight( dataSet set: IChartDataSet, dataSetIndex: Int, xValue: Double, rounding: ChartDataSetRounding) -> Highlight? { guard let chart = self.chart as? BarLineScatterCandleBubbleChartDataProvider else { return nil } if let e = set.entryForXValue(xValue, rounding: rounding) { let px = chart.getTransformer(forAxis: set.axisDependency).pixelForValues(x: e.y, y: e.x) return Highlight(x: e.x, y: e.y, xPx: px.x, yPx: px.y,dataSetIndex: dataSetIndex, axis: set.axisDependency) } return nil } internal override func getDistance(x1: CGFloat, y1: CGFloat, x2: CGFloat, y2: CGFloat) -> CGFloat { return abs(y1 - y2) } }
apache-2.0
45f7fcb296655b9ffcc9c4cb2b7007a3
30.03125
119
0.557402
4.728571
false
false
false
false
steelwheels/KiwiScript
KiwiLibrary/Source/File/KLReadline.swift
1
1319
/** * @file KLReadline.swift * @brief Define KLReadline class * @par Copyright * Copyright (C) 2021 Steel Wheels Project */ import CoconutData import KiwiEngine import JavaScriptCore import Foundation @objc public protocol KLReadlineProtocol: JSExport { func input() -> JSValue func history() -> JSValue } @objc public class KLReadline: NSObject, KLReadlineProtocol { private var mReadline: CNReadline private var mConsole: CNFileConsole private var mContext: KEContext private var mNullValue: JSValue public init(readline rline: CNReadline, console cons: CNFileConsole, context ctxt: KEContext) { mReadline = rline mConsole = cons mContext = ctxt mNullValue = JSValue(nullIn: ctxt) } public func input() -> JSValue { let result:String? switch mReadline.readLine(console: mConsole) { case .string(let str, _): result = str case .error(let err): mConsole.error(string: err.toString()) result = nil case .none: result = nil @unknown default: CNLog(logLevel: .error, message: "Can not happen", atFunction: #function, inFile: #file) result = nil } if let str = result { return JSValue(object: str, in: mContext) } else { return mNullValue } } public func history() -> JSValue { return JSValue(object: mReadline.history, in: mContext) } }
lgpl-2.1
b3aa628de036a845297e32748d8f1a43
22.140351
96
0.710387
3.248768
false
false
false
false
gaurav1981/Nuke
Sources/Processor.swift
3
5928
// The MIT License (MIT) // // Copyright (c) 2017 Alexander Grebenyuk (github.com/kean). import Foundation /// Performs image processing. public protocol Processing: Equatable { /// Returns processed image. func process(_ image: Image) -> Image? } /// Composes multiple processors. public struct ProcessorComposition: Processing { private let processors: [AnyProcessor] /// Composes multiple processors. public init(_ processors: [AnyProcessor]) { self.processors = processors } /// Processes the given image by applying each processor in an order in /// which they were added. If one of the processors fails to produce /// an image the processing stops and `nil` is returned. public func process(_ input: Image) -> Image? { return processors.reduce(input as Image!) { image, processor in return autoreleasepool { image != nil ? processor.process(image!) : nil } } } /// Returns true if the underlying processors are pairwise-equivalent. public static func ==(lhs: ProcessorComposition, rhs: ProcessorComposition) -> Bool { return lhs.processors.elementsEqual(rhs.processors) } } /// Type-erased image processor. public struct AnyProcessor: Processing { private let _process: (Image) -> Image? private let _processor: Any private let _equals: (AnyProcessor) -> Bool public init<P: Processing>(_ processor: P) { self._process = { processor.process($0) } self._processor = processor self._equals = { ($0._processor as? P) == processor } } public func process(_ image: Image) -> Image? { return self._process(image) } public static func ==(lhs: AnyProcessor, rhs: AnyProcessor) -> Bool { return lhs._equals(rhs) } } #if !os(macOS) import UIKit /// Decompresses and (optionally) scales down input images. Maintains /// original aspect ratio. /// /// Decompressing compressed image formats (such as JPEG) can significantly /// improve drawing performance as it allows a bitmap representation to be /// created in the background rather than on the main thread. public struct Decompressor: Processing { /// An option for how to resize the image. public enum ContentMode { /// Scales the image so that it completely fills the target size. /// Doesn't clip images. case aspectFill /// Scales the image so that it fits the target size. case aspectFit } /// Size to pass to disable resizing. public static let MaximumSize = CGSize(width: CGFloat.greatestFiniteMagnitude, height: CGFloat.greatestFiniteMagnitude) private let targetSize: CGSize private let contentMode: ContentMode /// Initializes `Decompressor` with the given parameters. /// - parameter targetSize: Size in pixels. `MaximumSize` by default. /// - parameter contentMode: An option for how to resize the image /// to the target size. `.aspectFill` by default. public init(targetSize: CGSize = MaximumSize, contentMode: ContentMode = .aspectFill) { self.targetSize = targetSize self.contentMode = contentMode } /// Decompresses and scales the image. public func process(_ image: Image) -> Image? { return decompress(image, targetSize: targetSize, contentMode: contentMode) } /// Returns true if both have the same `targetSize` and `contentMode`. public static func ==(lhs: Decompressor, rhs: Decompressor) -> Bool { return lhs.targetSize == rhs.targetSize && lhs.contentMode == rhs.contentMode } #if !os(watchOS) /// Returns target size in pixels for the given view. Takes main screen /// scale into the account. public static func targetSize(for view: UIView) -> CGSize { // in pixels let scale = UIScreen.main.scale let size = view.bounds.size return CGSize(width: size.width * scale, height: size.height * scale) } #endif } private func decompress(_ image: UIImage, targetSize: CGSize, contentMode: Decompressor.ContentMode) -> UIImage { guard let cgImage = image.cgImage else { return image } let bitmapSize = CGSize(width: cgImage.width, height: cgImage.height) let scaleHor = targetSize.width / bitmapSize.width let scaleVert = targetSize.height / bitmapSize.height let scale = contentMode == .aspectFill ? max(scaleHor, scaleVert) : min(scaleHor, scaleVert) return decompress(image, scale: CGFloat(min(scale, 1))) } private func decompress(_ image: UIImage, scale: CGFloat) -> UIImage { guard let cgImage = image.cgImage else { return image } let size = CGSize(width: round(scale * CGFloat(cgImage.width)), height: round(scale * CGFloat(cgImage.height))) // For more info see: // - Quartz 2D Programming Guide // - https://github.com/kean/Nuke/issues/35 // - https://github.com/kean/Nuke/issues/57 let alphaInfo: CGImageAlphaInfo = isOpaque(cgImage) ? .noneSkipLast : .premultipliedLast guard let ctx = CGContext(data: nil, width: Int(size.width), height: Int(size.height), bitsPerComponent: 8, bytesPerRow: 0, space: CGColorSpaceCreateDeviceRGB(), bitmapInfo: alphaInfo.rawValue) else { return image } ctx.draw(cgImage, in: CGRect(origin: CGPoint.zero, size: size)) guard let decompressed = ctx.makeImage() else { return image } return UIImage(cgImage: decompressed, scale: image.scale, orientation: image.imageOrientation) } private func isOpaque(_ image: CGImage) -> Bool { let alpha = image.alphaInfo return alpha == .none || alpha == .noneSkipFirst || alpha == .noneSkipLast } #endif
mit
dd4edc0e1b38cb58623654a49318e718
39.054054
208
0.651484
4.731045
false
false
false
false
xinmyname/HandsomeURLSession
HandsomeURLSessionTests/WhenTextIsRequestedAsynchronously.swift
1
1874
// // WhenATextRequstIsMadeAsynchronously.swift // HandsomeURLSession // // Created by Andy Sherwood on 7/21/16. // // import XCTest import HandsomeURLSession class WhenTextIsRequestedAsynchronously: XCTestCase { let _request = URLRequest(url: URL(string:"http://marco.coffee")!) let _text = "Casey was right." func testThatTheTextMatches() { let session = MockURLSession(for: _request, text:_text) let exp = expectation(description: "") let task = session.textTask(with: _request) { (text:String?, response:HTTPURLResponse?, error:Error?) in XCTAssertEqual(text, self._text) exp.fulfill() } task.resume() waitForExpectations(timeout: 2) } func testThatFailedHTTPStatusCodesAreInResponseWithoutError() { let expectedStatusCode = 404 let session = MockURLSession(for: _request, statusCode:expectedStatusCode) let exp = expectation(description: "") let task = session.textTask(with: _request) { (text:String?, response:HTTPURLResponse?, error:Error?) in XCTAssertEqual(response?.statusCode, expectedStatusCode) XCTAssertNil(error) exp.fulfill() } task.resume() waitForExpectations(timeout: 2) } func testThatNoResponseYieldsAnError() { let session = MockURLSession(response: nil) let exp = expectation(description: "") let task = session.textTask(with: _request) { (text:String?, response:HTTPURLResponse?, error:Error?) in XCTAssertNil(response) XCTAssertNotNil(error) exp.fulfill() } task.resume() waitForExpectations(timeout: 2) } }
mit
71aed660dfd4aac8c9777a6894b65e0f
26.970149
112
0.59285
4.984043
false
true
false
false
optimizely/objective-c-sdk
Pods/Mixpanel-swift/Mixpanel/DeviceInfoMessage.swift
1
6054
// // DeviceInfoMessage.swift // Mixpanel // // Created by Yarden Eitan on 8/26/16. // Copyright © 2016 Mixpanel. All rights reserved. // import Foundation import UIKit class DeviceInfoRequest: BaseWebSocketMessage { init() { super.init(type: MessageType.deviceInfoRequest.rawValue) } override func responseCommand(connection: WebSocketWrapper) -> Operation? { let operation = BlockOperation { [weak connection] in guard let connection = connection else { return } var response: DeviceInfoResponse? = nil DispatchQueue.main.sync { let currentDevice = UIDevice.current let infoResponseInput = InfoResponseInput(systemName: currentDevice.systemName, systemVersion: currentDevice.systemVersion, appVersion: Bundle.main.infoDictionary?["CFBundleVersion"] as? String, appRelease: Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String, deviceName: currentDevice.name, deviceModel: currentDevice.model, libLanguage: "Swift", libVersion: "2.6", // workaround for a/b testing availableFontFamilies: self.availableFontFamilies(), mainBundleIdentifier: Bundle.main.bundleIdentifier, tweaks: self.getTweaks()) response = DeviceInfoResponse(infoResponseInput) } connection.send(message: response) } return operation } func availableFontFamilies() -> [[String: AnyObject]] { var fontFamilies = [[String: AnyObject]]() let systemFonts = [UIFont.systemFont(ofSize: 17), UIFont.boldSystemFont(ofSize: 17), UIFont.italicSystemFont(ofSize: 17)] var foundSystemFamily = false for familyName in UIFont.familyNames { var fontNames = UIFont.fontNames(forFamilyName: familyName) if familyName == systemFonts.first!.familyName { for systemFont in systemFonts { if !fontNames.contains(systemFont.fontName) { fontNames.append(systemFont.fontName) } } foundSystemFamily = true } fontFamilies.append(["family": familyName as AnyObject, "font_names": UIFont.fontNames(forFamilyName: familyName) as AnyObject]) } if !foundSystemFamily { fontFamilies.append(["family": systemFonts.first!.familyName as AnyObject, "font_names": systemFonts.map { $0.fontName } as AnyObject]) } return fontFamilies } func getTweaks() -> [[String: AnyObject]] { var tweaks = [[String: AnyObject]]() guard let allTweaks = MixpanelTweaks.defaultStore.tweakCollections["Mixpanel"]?.allTweaks else { return tweaks } for tweak in allTweaks { let (value, defaultValue, min, max) = MixpanelTweaks.defaultStore.currentViewDataForTweak(tweak).getValueDefaultMinMax() let tweakDict = ["name": tweak.tweakName as AnyObject, "encoding": getEncoding(value) as AnyObject, "value": value as AnyObject, "default": defaultValue as AnyObject, "minimum": min as AnyObject? ?? defaultValue as AnyObject, "maximum": max as AnyObject? ?? defaultValue as AnyObject] as [String : AnyObject] tweaks.append(tweakDict) } return tweaks } func getEncoding(_ value: TweakableType) -> String { if value is Double || value is CGFloat { return "d" } else if value is String { return "@" } else if value is Int { return "i" } return "" } } struct InfoResponseInput { let systemName: String let systemVersion: String let appVersion: String? let appRelease: String? let deviceName: String let deviceModel: String let libLanguage: String let libVersion: String? let availableFontFamilies: [[String: Any]] let mainBundleIdentifier: String? let tweaks: [[String: Any]] } class DeviceInfoResponse: BaseWebSocketMessage { init(_ infoResponse: InfoResponseInput) { var payload = [String: AnyObject]() payload["system_name"] = infoResponse.systemName as AnyObject payload["system_version"] = infoResponse.systemVersion as AnyObject payload["device_name"] = infoResponse.deviceName as AnyObject payload["device_model"] = infoResponse.deviceModel as AnyObject payload["available_font_families"] = infoResponse.availableFontFamilies as AnyObject payload["tweaks"] = infoResponse.tweaks as AnyObject payload["lib_language"] = infoResponse.libLanguage as AnyObject if let appVersion = infoResponse.appVersion { payload["app_version"] = appVersion as AnyObject } if let appRelease = infoResponse.appRelease { payload["app_release"] = appRelease as AnyObject } if let libVersion = infoResponse.libVersion { payload["lib_version"] = libVersion as AnyObject } if let mainBundleIdentifier = infoResponse.mainBundleIdentifier { payload["main_bundle_identifier"] = mainBundleIdentifier as AnyObject } super.init(type: MessageType.deviceInfoResponse.rawValue, payload: payload) } }
apache-2.0
fc54b157edb31d52c24b4a60076af418
41.034722
139
0.569965
5.770257
false
false
false
false
breadwallet/breadwallet-ios
breadwallet/src/Platform/BRGeoLocationPlugin.swift
1
10905
// // BRGeoLocationPlugin.swift // BreadWallet // // Created by Samuel Sutch on 2/8/16. // Copyright (c) 2016-2019 Breadwinner AG. All rights reserved. // import Foundation import CoreLocation class BRGeoLocationDelegate: NSObject, CLLocationManagerDelegate { var manager: CLLocationManager? var response: BRHTTPResponse var remove: (() -> Void)? init(response: BRHTTPResponse) { self.response = response super.init() DispatchQueue.main.async { self.manager = CLLocationManager() self.manager?.delegate = self } } func getOne() { DispatchQueue.main.async { self.manager?.desiredAccuracy = kCLLocationAccuracyHundredMeters self.manager?.requestLocation() } } func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { var j = [String: Any]() guard let l = locations.last else { j["error"] = "unknown error" self.response.provide(500, json: j) self.remove?() return } j["timestamp"] = l.timestamp.description as AnyObject? j["coordinate"] = ["latitude": l.coordinate.latitude, "longitude": l.coordinate.longitude] j["altitude"] = l.altitude as AnyObject? j["horizontal_accuracy"] = l.horizontalAccuracy as AnyObject? j["description"] = l.description as AnyObject? response.request.queue.async { self.response.provide(200, json: j) self.remove?() } } func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) { var j = [String: AnyObject]() j["error"] = error.localizedDescription as AnyObject? response.request.queue.async { self.response.provide(500, json: j) self.remove?() } } } open class BRGeoLocationPlugin: NSObject, BRHTTPRouterPlugin, CLLocationManagerDelegate, BRWebSocketClient { lazy var manager = CLLocationManager() var outstanding = [BRGeoLocationDelegate]() var sockets = [String: BRWebSocket]() override init() { super.init() self.manager.delegate = self } open func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) { print("new authorization status: \(status)") } open func hook(_ router: BRHTTPRouter) { // GET /_permissions/geo // // Call this method to retrieve the current permission status for geolocation. // The returned JSON dictionary contains the following keys: // // "status" = "denied" | "restricted | "undetermined" | "inuse" | "always" // "user_queried" = true | false // "location_enabled" = true | false // // The status correspond to those found in the apple CLLocation documentation: http://apple.co/1O0lHFv // // "user_queried" indicates whether or not the user has already been asked for geolocation // "location_enabled" indicates whether or not the user has geo location enabled on their phone router.get("/_permissions/geo") { (request, _) -> BRHTTPResponse in let userDefaults = UserDefaults.standard let authStatus = CLLocationManager.authorizationStatus() var retJson = [String: Any]() switch authStatus { case .denied: retJson["status"] = "denied" case .restricted: retJson["status"] = "restricted" case .notDetermined: retJson["status"] = "undetermined" case .authorizedWhenInUse: retJson["status"] = "inuse" case .authorizedAlways: retJson["status"] = "always" @unknown default: assertionFailure("unknown location auth status") retJson["status"] = "undetermined" } retJson["user_queried"] = userDefaults.bool(forKey: "geo_permission_was_queried") retJson["location_enabled"] = CLLocationManager.locationServicesEnabled() return try BRHTTPResponse(request: request, code: 200, json: retJson as AnyObject) } // POST /_permissions/geo // // Call this method to request the geo permission from the user. // The request body should be a JSON dictionary containing a single key, "style" // the value of which should be either "inuse" or "always" - these correspond to the // two ways the user can authorize geo access to the app. "inuse" will request // geo availability to the app when the app is foregrounded, and "always" will request // full time geo availability to the app router.post("/_permissions/geo") { (request, _) -> BRHTTPResponse in if let j = request.json(), let dict = j as? NSDictionary, dict["style"] is String { return BRHTTPResponse(request: request, code: 500) // deprecated } return BRHTTPResponse(request: request, code: 400) } // GET /_geo // // Calling this method will query CoreLocation for a location object. The returned value may not be returned // very quick (sometimes getting a geo lock takes some time) so be sure to display to the user some status // while waiting for a response. // // Response Object: // // "coordinate" = { "latitude": double, "longitude": double } // "altitude" = double // "description" = "a string representation of this object" // "timestamp" = "ISO-8601 timestamp of when this location was generated" // "horizontal_accuracy" = double router.get("/_geo") { (request, _) -> BRHTTPResponse in if let authzErr = self.getAuthorizationError() { return try BRHTTPResponse(request: request, code: 400, json: authzErr) } let resp = BRHTTPResponse(async: request) let del = BRGeoLocationDelegate(response: resp) del.remove = { objc_sync_enter(self) if let idx = self.outstanding.firstIndex(where: { (d) -> Bool in return d == del }) { self.outstanding.remove(at: idx) } objc_sync_exit(self) } objc_sync_enter(self) self.outstanding.append(del) objc_sync_exit(self) print("outstanding delegates: \(self.outstanding)") // get location only once del.getOne() return resp } // GET /_geosocket // // This opens up a websocket to the location manager. It will return a new location every so often (but with no // predetermined interval) with the same exact structure that is sent via the GET /_geo call. // // It will start the location manager when there is at least one client connected and stop the location manager // when the last client disconnects. router.websocket("/_geosocket", client: self) } func getAuthorizationError() -> [String: Any]? { var retJson = [String: Any]() if !CLLocationManager.locationServicesEnabled() { retJson["error"] = S.LocationPlugin.disabled return retJson } let authzStatus = CLLocationManager.authorizationStatus() if authzStatus != .authorizedWhenInUse && authzStatus != .authorizedAlways { retJson["error"] = S.LocationPlugin.notAuthorized return retJson } return nil } var lastLocation: [String: Any]? var isUpdatingSockets = false // location manager for continuous websocket clients public func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { var j = [String: Any]() guard let l = locations.last else { j["error"] = "unknown error" sendToAllSockets(data: j) return } j["timestamp"] = l.timestamp.description as AnyObject? j["coordinate"] = ["latitude": l.coordinate.latitude, "longitude": l.coordinate.longitude] j["altitude"] = l.altitude as AnyObject? j["horizontal_accuracy"] = l.horizontalAccuracy as AnyObject? j["description"] = l.description as AnyObject? lastLocation = j sendToAllSockets(data: j) } public func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) { var j = [String: Any]() j["error"] = error.localizedDescription as AnyObject? sendToAllSockets(data: j) } func sendTo(socket: BRWebSocket, data: [String: Any]) { do { let j = try JSONSerialization.data(withJSONObject: data, options: []) if let s = String(data: j, encoding: .utf8) { socket.request.queue.async { socket.send(s) } } } catch let e { print("LOCATION SOCKET FAILED ENCODE JSON: \(e)") } } func sendToAllSockets(data: [String: Any]) { for (_, s) in sockets { sendTo(socket: s, data: data) } } public func socketDidConnect(_ socket: BRWebSocket) { print("LOCATION SOCKET CONNECT \(socket.id)") sockets[socket.id] = socket // on first socket connect to the manager if !isUpdatingSockets { // if not authorized yet send an error if let authzErr = getAuthorizationError() { sendTo(socket: socket, data: authzErr) return } // begin updating location isUpdatingSockets = true DispatchQueue.main.async { self.manager.delegate = self self.manager.startUpdatingLocation() } } if let loc = lastLocation { sendTo(socket: socket, data: loc) } } public func socketDidDisconnect(_ socket: BRWebSocket) { print("LOCATION SOCKET DISCONNECT \(socket.id)") sockets.removeValue(forKey: socket.id) // on last socket disconnect stop updating location if sockets.isEmpty { isUpdatingSockets = false lastLocation = nil self.manager.stopUpdatingLocation() } } public func socket(_ socket: BRWebSocket, didReceiveText text: String) { print("LOCATION SOCKET RECV TEXT \(text)") } public func socket(_ socket: BRWebSocket, didReceiveData data: Data) { print("LOCATION SOCKET RECV DATA \(data.hexString)") } }
mit
1e3f98eba9f85c780730bc75884234cc
38.51087
119
0.59028
5.057978
false
false
false
false
wireapp/wire-ios-sync-engine
Source/SessionManager/JailbreakDetector.swift
1
4722
// // Wire // Copyright (C) 2019 Wire Swiss GmbH // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see http://www.gnu.org/licenses/. // import UIKit import Darwin public protocol JailbreakDetectorProtocol { func isJailbroken() -> Bool } public final class JailbreakDetector: NSObject, JailbreakDetectorProtocol { private let fm = FileManager.default public func isJailbroken() -> Bool { #if targetEnvironment(simulator) return false #else return hasJailbrokenFiles || hasWriteablePaths || hasSymlinks || callsFork || canOpenJailbrokenStores #endif } private var hasJailbrokenFiles: Bool { let paths: [String] = [ "/private/var/stash", "/private/var/lib/apt", "/private/var/tmp/cydia.log", "/private/var/lib/cydia", "/private/var/mobile/Library/SBSettings/Themes", "/Library/MobileSubstrate/MobileSubstrate.dylib", "/Library/MobileSubstrate/DynamicLibraries/Veency.plist", "/Library/MobileSubstrate/DynamicLibraries/LiveClock.plist", "/System/Library/LaunchDaemons/com.ikey.bbot.plist", "/System/Library/LaunchDaemons/com.saurik.Cydia.Startup.plist", "/var/cache/apt", "/var/lib/apt", "/var/lib/cydia", "/var/log/syslog", "/var/tmp/cydia.log", "/bin/bash", "/bin/sh", "/usr/sbin/sshd", "/usr/libexec/ssh-keysign", "/usr/sbin/sshd", "/usr/bin/sshd", "/usr/libexec/sftp-server", "/etc/ssh/sshd_config", "/etc/apt", "/Applications/Cydia.app", "/Applications/RockApp.app", "/Applications/Icy.app", "/Applications/WinterBoard.app", "/Applications/SBSettings.app", "/Applications/MxTube.app", "/Applications/IntelliScreen.app", "/Applications/FakeCarrier.app", "/Applications/blackra1n.app" ] for path in paths { if fm.fileExists(atPath: path) { return true } } return false } private var hasWriteablePaths: Bool { if fm.isWritableFile(atPath: "/") { return true } if fm.isWritableFile(atPath: "/private") { return true } return false } private var hasSymlinks: Bool { let symlinks: [String] = [ "/Library/Ringtones", "/Library/Wallpaper", "/usr/arm-apple-darwin9", "/usr/include", "/usr/libexec", "/usr/share", "/Applications" ] for link in symlinks { if fm.fileExists(atPath: link), let attributes = try? fm.attributesOfItem(atPath: link), attributes[.type] as? String == "NSFileTypeSymbolicLink" { return true } } return false } private var callsFork: Bool { let RTLD_DEFAULT = UnsafeMutableRawPointer(bitPattern: -2) let forkPtr = dlsym(RTLD_DEFAULT, "fork") typealias ForkType = @convention(c) () -> Int32 let fork = unsafeBitCast(forkPtr, to: ForkType.self) return fork() != -1 } private var canOpenJailbrokenStores: Bool { let jailbrokenStoresURLs: [String] = ["cydia://app", "sileo://package", "sileo://source"] for url in jailbrokenStoresURLs { if UIApplication.shared.canOpenURL(URL(string: url)!) { return true } } return false } } @objcMembers public class MockJailbreakDetector: NSObject, JailbreakDetectorProtocol { public var jailbroken: Bool = false @objc(initAsJailbroken:) public init(jailbroken: Bool = false) { self.jailbroken = jailbroken } public func isJailbroken() -> Bool { return jailbroken } }
gpl-3.0
0d60b341ae4615dbd14bdaa5cc9008de
28.886076
86
0.565438
4.360111
false
false
false
false
sagarduwal/programming
searching/linear_search/swift/linear_search.swift
2
489
func linearSearch(arr: [Int], key: Int) -> Int { for(idx, element) in arr.enumerated() { if (element == key) { return idx } } return -1 } // Could you use this way for readability //func linearSearch(arr: [Int], key: Int) -> Int { // return arr.enumerated().filter { $1 == key }.first?.offset ?? -1 //} let arr1 = [23,45,21,55,234,1,34,90] let searchKey = 21 print("Key \(searchKey) found at index: \(linearSearch(arr: arr1, key: searchKey))")
gpl-3.0
0b6b192a09f2bf2cdb6b5afca25c13b8
26.222222
84
0.588957
3.175325
false
false
false
false
itsaboutcode/WordPress-iOS
WordPress/Classes/ViewRelated/Blog/Blog List/BlogListDataSource.swift
1
11146
import CoreData import Foundation import UIKit import WordPressShared private protocol BlogListDataSourceMapper { func map(_ data: [Blog]) -> [[Blog]] } private struct BrowsingWithRecentDataSourceMapper: BlogListDataSourceMapper { func map(_ data: [Blog]) -> [[Blog]] { let service = RecentSitesService() let recentSiteUrls = service.allRecentSites let visible = data.filter({ $0.visible }) let allRecent = recentSiteUrls.compactMap({ url in return visible.first(where: { $0.url == url }) }) let recent = Array(allRecent.prefix(service.maxSiteCount)) let other = visible.filter({ blog in return !recent.contains(blog) }) return [recent, other] } } private struct BrowsingDataSourceMapper: BlogListDataSourceMapper { func map(_ data: [Blog]) -> [[Blog]] { return [data.filter({ $0.visible })] } } private struct EditingDataSourceMapper: BlogListDataSourceMapper { func map(_ data: [Blog]) -> [[Blog]] { return [data.filter({ blog in blog.supports(.visibility) })] } } private struct SearchingDataSourceMapper: BlogListDataSourceMapper { let query: String func map(_ data: [Blog]) -> [[Blog]] { guard let query = query.nonEmptyString() else { return [data] } return [data.filter({ blog in let nameContainsQuery = blog.settings?.name.map({ $0.localizedCaseInsensitiveContains(query) }) ?? false let urlContainsQuery = blog.url.map({ $0.localizedCaseInsensitiveContains(query) }) ?? false return nameContainsQuery || urlContainsQuery })] } } /// Filters the list to show only a matching blog, or only blogs with an account. /// Used by the login epilogue screen. /// private struct LoggedInDataSourceMapper: BlogListDataSourceMapper { let matchingBlog: Blog? func map(_ data: [Blog]) -> [[Blog]] { return [data.filter({ blog in if let matchingBlog = matchingBlog { return blog == matchingBlog } else { return blog.account != nil } })] } } class BlogListDataSource: NSObject { override init() { super.init() // We can't decide if we're using recent sites until the results controller // is configured and we have a list of blogs, so we have to update this right // after initializing the data source. updateMode() resultsController.delegate = self } // MARK: - Configuration @objc let recentSitesMinCount = 11 /// If this is set to `false`, the rows will never show the disclosure indicator. /// @objc var shouldShowDisclosureIndicator = true // MARK: - Inputs // Pass to the LoggedInDataSource to match a specifc blog. @objc var blog: Blog? @objc var editing: Bool = false { didSet { updateMode() } } @objc var searching: Bool = false { didSet { updateMode() } } @objc var searchQuery: String = "" { didSet { updateMode() } } @objc var loggedIn: Bool = false { didSet { updateMode() } } @objc var selecting: Bool = false { didSet { if selecting != oldValue { dataChanged?() } } } @objc var selectedBlogId: NSManagedObjectID? = nil { didSet { if selectedBlogId != oldValue { dataChanged?() } } } @objc var account: WPAccount? = nil { didSet { if account != oldValue { cachedSections = nil dataChanged?() } } } // MARK: - Outputs @objc var dataChanged: (() -> Void)? @objc var visibilityChanged: ((Blog, Bool) -> Void)? @objc(blogAtIndexPath:) func blog(at indexPath: IndexPath) -> Blog { return sections[indexPath.section][indexPath.row] } @objc(indexPathForBlog:) func indexPath(for blog: Blog) -> IndexPath? { for (sectionIndex, section) in sections.enumerated() { for (rowIndex, row) in section.enumerated() { if row == blog { return IndexPath(row: rowIndex, section: sectionIndex) } } } return nil } @objc var allBlogsCount: Int { return allBlogs.count } @objc var displayedBlogsCount: Int { return sections.reduce(0, { result, section in result + section.count }) } @objc var visibleBlogsCount: Int { return allBlogs.filter({ $0.visible }).count } // MARK: - Internal properties fileprivate let resultsController: NSFetchedResultsController<Blog> = { let context = ContextManager.sharedInstance().mainContext let request = NSFetchRequest<Blog>(entityName: NSStringFromClass(Blog.self)) request.sortDescriptors = [ NSSortDescriptor(key: "accountForDefaultBlog.userID", ascending: false), NSSortDescriptor(key: "settings.name", ascending: true, selector: #selector(NSString.localizedCaseInsensitiveCompare(_:))) ] let controller = NSFetchedResultsController(fetchRequest: request, managedObjectContext: context, sectionNameKeyPath: nil, cacheName: nil) do { try controller.performFetch() } catch { fatalError("Error fetching blogs list: \(error)") } return controller }() fileprivate var mode: Mode = .browsing { didSet { if mode != oldValue { cachedSections = nil dataChanged?() } } } fileprivate var cachedSections: [[Blog]]? } // MARK: - Mode private extension BlogListDataSource { enum Mode: Equatable { case browsing case browsingWithRecent case editing case searching(String) case loggedIn(Blog?) var mapper: BlogListDataSourceMapper { switch self { case .browsing: return BrowsingDataSourceMapper() case .browsingWithRecent: return BrowsingWithRecentDataSourceMapper() case .editing: return EditingDataSourceMapper() case .searching(let query): return SearchingDataSourceMapper(query: query) case .loggedIn(let blog): return LoggedInDataSourceMapper(matchingBlog: blog) } } static func == (lhs: Mode, rhs: Mode) -> Bool { switch (lhs, rhs) { case (.browsing, .browsing), (.browsingWithRecent, .browsingWithRecent), (.editing, .editing): return true case let (.searching(lquery), .searching(rquery)): return lquery == rquery case let (.loggedIn(lblog), .loggedIn(rblog)): return lblog == rblog default: return false } } } func updateMode() { // Extracted this into its own function so the compiler can enforce that // a mode must be returned mode = modeForCurrentState() } func modeForCurrentState() -> Mode { if loggedIn { return .loggedIn(blog) } if editing { return .editing } if searching { return .searching(searchQuery) } if visibleBlogsCount > recentSitesMinCount { return .browsingWithRecent } return .browsing } } // MARK: - Data private extension BlogListDataSource { var sections: [[Blog]] { if let sections = cachedSections { return sections } let mappedSections = mode.mapper.map(allBlogs) cachedSections = mappedSections return mappedSections } var allBlogs: [Blog] { guard let blogs = resultsController.fetchedObjects else { return [] } guard let account = account else { return blogs } return blogs.filter({ $0.account == account }) } } // MARK: - Results Controller Delegate extension BlogListDataSource: NSFetchedResultsControllerDelegate { func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) { cachedSections = nil // TODO: only propagate if the filtered data changed dataChanged?() } } // MARK: - UITableView Data Source extension BlogListDataSource: UITableViewDataSource { func numberOfSections(in tableView: UITableView) -> Int { return sections.count } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return sections[section].count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let blog = self.blog(at: indexPath) guard let cell = tableView.dequeueReusableCell(withIdentifier: WPBlogTableViewCell.reuseIdentifier()) as? WPBlogTableViewCell else { fatalError("Failed to get a blog cell") } let displayURL = blog.displayURL as String? ?? "" if let name = blog.settings?.name?.nonEmptyString() { cell.textLabel?.text = name cell.detailTextLabel?.text = displayURL } else { cell.textLabel?.text = displayURL cell.detailTextLabel?.text = nil } cell.accessibilityIdentifier = blog.displayURL as String? if selecting { if selectedBlogId == blog.objectID { cell.accessoryType = .checkmark } else { cell.accessoryType = .none } } else { switch mode { case .loggedIn: cell.accessoryType = .none default: cell.accessoryType = shouldShowDisclosureIndicator ? .disclosureIndicator : .none } } cell.selectionStyle = tableView.isEditing ? .none : .blue cell.visibilitySwitch?.accessibilityIdentifier = String(format: "Switch-Visibility-%@", blog.settings?.name ?? "") cell.visibilitySwitch?.isOn = blog.visible cell.visibilitySwitchToggled = { [visibilityChanged] cell in guard let isOn = cell.visibilitySwitch?.isOn else { return } visibilityChanged?(blog, isOn) } switch mode { case .loggedIn: WPStyleGuide.configureCellForLogin(cell) default: WPStyleGuide.configureTableViewBlogCell(cell) } // Here we initiate the site icon download _after_ setting the border used in conjunction with the placeholder cell.imageView?.downloadSiteIcon(for: blog) return cell } func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { return true } }
gpl-2.0
71efa4df43513ca15029a5a7872d7bae
28.643617
146
0.584694
5.048007
false
false
false
false
mark-randall/Forms
Pod/Classes/InputViews/FormCheckboxInputView.swift
1
6558
// // FormCheckboxInputView.swift // // The MIT License (MIT) // // Created by mrandall on 11/30/15. // Copyright © 2015 mrandall. All rights reserved. // // 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 private enum InputSelector: Selector { case buttonWastTapped = "buttonWastTapped:" } //@IBDesignable public class FormCheckboxInputView: UIView, ButtonFormIputView { override public class func requiresConstraintBasedLayout() -> Bool { return true } //MARK: - FormInputView public var identifier: String //MARK: - FormInputViewModelView public var viewModel: FormInputViewModel<Bool>? { didSet { bindViewModel() } } //MARK: - Layout Configuration public var inputSpacing = 0.1 //MARK: - FormBaseTextInputView lazy var stackView: UIStackView = { [unowned self] in let stackView = UIStackView() stackView.axis = .Vertical stackView.spacing = CGFloat(self.inputSpacing) stackView.distribution = .Fill self.addSubview(stackView) return stackView }() lazy var checkBoxCaptionStackView: UIStackView = { [unowned self] in let stackView = UIStackView() stackView.axis = .Horizontal stackView.spacing = CGFloat(self.inputSpacing) stackView.distribution = .Fill return stackView }() //MARK: - Subviews lazy public var button: UIButton = { [unowned self] in let button = UIButton() button.addTarget(self, action: InputSelector.buttonWastTapped.rawValue, forControlEvents: .TouchUpInside) return button }() lazy public var captionLabel: UILabel = { [unowned self] in let captionLabel = UILabel() captionLabel.lineBreakMode = .ByWordWrapping return captionLabel }() lazy public var errorLabel: UILabel = { [unowned self] in let errorLabel = UILabel() errorLabel.lineBreakMode = .ByWordWrapping return errorLabel }() //MARK: - Init public convenience init(withViewModel viewModel: FormInputViewModel<Bool>) { self.init(frame: CGRect(x: 0, y: 0, width: 100, height: 100)) identifier = viewModel.identifier self.viewModel = viewModel commonInit() } override public init(frame: CGRect) { self.identifier = NSUUID().UUIDString super.init(frame: frame) commonInit() } public required init?(coder aDecoder: NSCoder) { self.identifier = NSUUID().UUIDString super.init(coder: aDecoder) commonInit() } override public func prepareForInterfaceBuilder() { commonInit() addSubviewConstraints() addSubviews() } func commonInit() { bindViewModel() } //MARK: - Layout override public func updateConstraints() { addSubviewConstraints() addSubviews() super.updateConstraints() } override public func intrinsicContentSize() -> CGSize { return stackView.intrinsicContentSize() } //MARK: - Add Subviews private var didAddSubviewConstriants = false private func addSubviewConstraints() { guard didAddSubviewConstriants == false else { return } didAddSubviewConstriants = true //layout subviews UIView.createConstraints(visualFormatting: [ "H:|-(0)-[stackView]-(0)-|", "V:|-(0)-[stackView]-(0)-|", ], views: [ "stackView": stackView, ]) button.widthAnchor.constraintEqualToAnchor(button.heightAnchor, multiplier: 1.0).active = true invalidateIntrinsicContentSize() } private var didAddSubviews = false private func addSubviews() { guard didAddSubviews == false else { return } didAddSubviews = true checkBoxCaptionStackView.addArrangedSubview(self.button) checkBoxCaptionStackView.addArrangedSubview(self.captionLabel) stackView.addArrangedSubview(checkBoxCaptionStackView) stackView.addArrangedSubview(errorLabel) invalidateIntrinsicContentSize() } //MARK: - Actions func buttonWastTapped(sender: AnyObject) { guard let viewModel = self.viewModel else { return } viewModel.value = !viewModel.value! } //MARK: - FormInputViewModelView public func bindViewModel() { guard let viewModel = self.viewModel else { return } viewModel.valueObservable.observe { self.button.selected = $0 ?? false } viewModel.captionObservable.observe { self.captionLabel.attributedText = $0 } viewModel.hiddenObservable.observe { self.hidden = $0 } viewModel.errorTextObservable.observe { self.errorLabel.hidden = $0.string.isEmpty self.errorLabel.attributedText = $0 } viewModel.inputViewLayoutObservable.observe { self.stackView.spacing = CGFloat($0.subviewSpacing) self.checkBoxCaptionStackView.spacing = CGFloat($0.subviewSpacing) } } } //MARK: - Equatable func ==(lhs: FormCheckboxInputView, rhs: FormCheckboxInputView) -> Bool { return lhs.identifier == rhs.identifier }
mit
08e364d5cadaa7286eff4fa3036395a4
29.21659
113
0.636877
5.118657
false
false
false
false
wilfreddekok/Antidote
Antidote/UserDefaultsManager.swift
1
2896
// 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/. class UserDefaultsManager { var lastActiveProfile: String? { get { return stringForKey(Keys.LastActiveProfile) } set { setObject(newValue, forKey: Keys.LastActiveProfile) } } var UDPEnabled: Bool { get { return boolForKey(Keys.UDPEnabled, defaultValue: false) } set { setBool(newValue, forKey: Keys.UDPEnabled) } } var showNotificationPreview: Bool { get { return boolForKey(Keys.ShowNotificationsPreview, defaultValue: true) } set { setBool(newValue, forKey: Keys.ShowNotificationsPreview) } } enum AutodownloadImages: String { case Never case UsingWiFi case Always } var autodownloadImages: AutodownloadImages { get { let defaultValue = AutodownloadImages.Never guard let string = stringForKey(Keys.AutodownloadImages) else { return defaultValue } return AutodownloadImages(rawValue: string) ?? defaultValue } set { setObject(newValue.rawValue, forKey: Keys.AutodownloadImages) } } func resetUDPEnabled() { removeObjectForKey(Keys.UDPEnabled) } } private extension UserDefaultsManager { struct Keys { static let LastActiveProfile = "user-info/last-active-profile" static let UDPEnabled = "user-info/udp-enabled" static let ShowNotificationsPreview = "user-info/snow-notification-preview" static let AutodownloadImages = "user-info/autodownload-images" } func setObject(object: AnyObject?, forKey key: String) { let defaults = NSUserDefaults.standardUserDefaults() defaults.setObject(object, forKey:key) defaults.synchronize() } func stringForKey(key: String) -> String? { let defaults = NSUserDefaults.standardUserDefaults() return defaults.stringForKey(key) } func setBool(value: Bool, forKey key: String) { let defaults = NSUserDefaults.standardUserDefaults() defaults.setBool(value, forKey: key) defaults.synchronize() } func boolForKey(key: String, defaultValue: Bool) -> Bool { let defaults = NSUserDefaults.standardUserDefaults() if let result = defaults.objectForKey(key) { return result.boolValue } else { return defaultValue } } func removeObjectForKey(key: String) { let defaults = NSUserDefaults.standardUserDefaults() defaults.removeObjectForKey(key) defaults.synchronize() } }
mpl-2.0
e70d442bba2f6f2eb8fcfacb14f04246
28.252525
83
0.625691
5.054101
false
false
false
false
gerryisaac/iPhone-CTA-Bus-Tracker-App
Bus Tracker/predictionDisplayViewController.swift
1
14449
// // predictionDisplayViewController.swift // Bus Tracker // // Created by Gerard Isaac on 11/3/14. // Copyright (c) 2014 Gerard Isaac. All rights reserved. // import UIKit import Foundation class predictionDisplayViewController: UIViewController, UIScrollViewDelegate { var routeNumber:NSString? = NSString() var stopNumber:NSString? = NSString() var tagValue:Int? //Variable to Hold Scroll Data var stops: NSArray = [] var stopData: NSMutableArray = [] var stopCount: Int = 0 //Scroll View var mainScroll:UIScrollView = UIScrollView() var pageControl:UIPageControl = UIPageControl() var rxml:RXMLElement = RXMLElement() override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. self.view.backgroundColor = UIColor.blackColor() //Run Data Function populatePredictions(routeNumber!,stopNum: stopNumber!) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } //Retrieve Data for Selected Stop in this Route func populatePredictions(routeNum: NSString, stopNum: NSString) { //Create Spinner var spinner:UIActivityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.White) spinner.frame = CGRectMake(self.view.frame.size.width/2 - 25, self.view.frame.size.height/2, 50, 50); spinner.transform = CGAffineTransformMakeScale(1.5, 1.5); //spinner.backgroundColor = [UIColor blackColor]; self.view.addSubview(spinner); spinner.startAnimating() //Load Bus Tracker Data let feedURL:NSString = "http://www.ctabustracker.com/bustime/api/v1/getpredictions?key=\(yourCTAkey.keyValue)&rt=\(routeNum)&stpid=\(stopNum)" //println("Feed URL is \(feedURL)") let manager = AFHTTPRequestOperationManager() manager.responseSerializer = AFHTTPResponseSerializer() let contentType:NSSet = NSSet(object: "text/xml") manager.responseSerializer.acceptableContentTypes = contentType manager.GET(feedURL, parameters: nil, success: { (operation: AFHTTPRequestOperation!, responseObject: AnyObject!) in //println("Success") var responseData:NSData = responseObject as NSData //var responseString = NSString(data: responseData, encoding:NSASCIIStringEncoding) //println(responseString) self.rxml = RXMLElement.elementFromXMLData(responseData) as RXMLElement //println(rxml) var mainXML:RXMLElement = self.rxml.child("*") var checker:NSString = mainXML.tag //println(checker) /*Pattern Checker*/ if checker.isEqualToString("prd") { //println("Build Scrollview") //println("EQUAL Response:\(responseString)") self.stops = self.rxml.children("prd") self.stopData.addObjectsFromArray(self.stops) self.stopCount = self.stopData.count //println(self.stops) //println(self.stopCount) self.createScrollDataScreen(self.stopCount) } else { let searchString:NSString = "//msg" self.rxml.iterateWithRootXPath(searchString, usingBlock: { appElement -> Void in //println(appElement.text) //println("ELSE Response:\(responseString)") //Create Background Image let bgImage = UIImage(named:"patternsCellNoticeBgI5.png")! var bgImageView = UIImageView(frame: CGRectMake(0, 0, screenDimensions.screenWidth, screenDimensions.screenHeight)) bgImageView.image = bgImage self.view.addSubview(bgImageView) var txtField: UILabel = UILabel(frame:CGRectMake(screenDimensions.screenWidth/2 - 100, screenDimensions.screenHeight/2 - 110, 220, 100)) txtField.backgroundColor = UIColor.clearColor() txtField.font = UIFont(name:"Gotham-Light", size:40.0) txtField.textAlignment = NSTextAlignment.Center txtField.numberOfLines = 0 txtField.lineBreakMode = NSLineBreakMode.ByWordWrapping txtField.textColor = UIColor.whiteColor() var message:NSString = appElement.text txtField.text = message.capitalizedString self.view.addSubview(txtField) }) } spinner.stopAnimating() }, failure: { (operation: AFHTTPRequestOperation!, error: NSError!) in var alertView = UIAlertView(title: "Error Retrieving Data", message: error.localizedDescription, delegate: nil, cancelButtonTitle: "OK") alertView.show() println(error) }) } func createScrollDataScreen(pageCount:Int){ //Create Scrollview var currentWidth:CGFloat = 0.0 let fixedHeight:CGFloat = 504 var scrollViewFrame:CGRect = CGRectMake(0, 64, screenDimensions.screenWidth, fixedHeight) var bgImage:UIImage = UIImage(named:"predictionsScrollBg.png")! var bgPlaceholder:UIImageView = UIImageView(frame: scrollViewFrame) bgPlaceholder.image = bgImage self.view.addSubview(bgPlaceholder) self.mainScroll = UIScrollView(frame: scrollViewFrame) self.mainScroll.backgroundColor = UIColor.clearColor() //Set delegate self.mainScroll.delegate = self self.mainScroll.pagingEnabled = true self.mainScroll.showsHorizontalScrollIndicator = true var scrollContent:UIView = UIView(frame: CGRectMake(0, 0, screenDimensions.screenWidth, fixedHeight)) scrollContent.frame = CGRectMake(0, 0, screenDimensions.screenWidth * CGFloat(pageCount), fixedHeight) //Time Stamp var timeStamp:NSString = "0" //Type var stopType :NSString? //Stop Name var stopName :NSString? //Stop ID Number var stopID :NSString? //Vehicle ID Number var vehicleID :NSString? //Distance to Stop var distanceStop :NSString? //Route Number var routeNum :NSString? //Route Direction var routeDir :NSString? //Destination var destination :NSString? //Predicted Time var predictedTime :NSString = "0" //Block ID var blockID :NSString? //Trip ID var tripID :NSString? var rootXML:RXMLElement = self.rxml.child("prd") rootXML.iterateElements(self.stops, usingBlock: { appElement -> Void in //Time Stamp timeStamp = appElement.child("tmstmp").text //Type stopType = appElement.child("typ").text //Stop Name stopName = appElement.child("stpnm").text //Stop ID Number stopID = appElement.child("stpid").text //Vehicle ID Number vehicleID = appElement.child("vid").text //Distance to Stop distanceStop = appElement.child("dstp").text //Route Number routeNum = appElement.child("rt").text //Route Direction var routeDir = appElement.child("rtdir").text //self.switchRouteDir(routeDir!) switch routeDir { case "Northbound": routeDir = "NB" case "Southbound": routeDir = "SB" case "Westbound": routeDir = "WB" case "Eastbound": routeDir = "EB" default: routeDir = appElement.child("rtdir").text } //Destination destination = appElement.child("des").text //Predicted Time predictedTime = appElement.child("prdtm").text //Block ID blockID = appElement.child("tablockid").text //Trip ID tripID = appElement.child("tatripid").text //Format the Date var dateFormatter = NSDateFormatter() dateFormatter.timeZone = NSTimeZone(name:"GMT") dateFormatter.locale = NSLocale(localeIdentifier:"en_US_POSIX") dateFormatter.dateFormat = "yyyyMMdd HH:mm" var currentDate:NSDate = dateFormatter.dateFromString(timeStamp)! var predictedDate:NSDate = dateFormatter.dateFromString(predictedTime)! //println("Current Date: \(currentDate) and Predicted Time: \(predictedDate)") //let calendar = NSCalendar.currentCalendar() //let components = calendar.components(.CalendarUnitHour | .CalendarUnitMinute, fromDate: currentDate) //let hour = components.hour //let minutes = components.minute //println("Current Date Minutes: \(minutes)") //date2 = dateFormatter.dateFromString(predictedTime!) //dateFormatter.dateFormat = "mm" //Time difference in seconds var timeDifference:NSTimeInterval = NSTimeInterval() timeDifference = predictedDate.timeIntervalSinceDate(currentDate) //println("Time Difference: \(timeDifference)") //println("Timestamp:\(timeStamp) Type:\(type) Stop Name:\(stopName) Stop ID:\(stopID) Vehicle ID:\(vehicleID) Distance to Stop:\(distanceStop) Route Number: \(routeNum) Route Direction:\(routeDir) Destination:\(destination) Predicted Time:\(predictedTime) Block ID:\(blockID) Trip ID:\(tripID) Estimated Arrival: \(timeDifference/60) minutes") //Create ScrollView Content and add Pages for Holding the Data var xLocation:CGFloat = 0.0 //var pageEntry: UIView = UIView(frame:CGRectMake(xLocation + currentWidth, 0, 320, 416)) var pageEntry: predictionPageEntry = predictionPageEntry(frame:CGRectMake(xLocation + currentWidth, 0, screenDimensions.screenWidth, fixedHeight)) pageEntry.timeStampLabel.text = timeStamp pageEntry.stopTypeLabel.text = stopType pageEntry.stopNameLabel.text = stopName pageEntry.vehicleIDLabel.text = vehicleID pageEntry.distanceStopLabel.text = distanceStop pageEntry.routeNumLabel.text = routeNum pageEntry.routeDirLabel.text = routeDir pageEntry.destinationLabel.text = destination pageEntry.predictedTimeLabel.text = "\(timeDifference/60) minutes" pageEntry.blockIDLabel.text = blockID pageEntry.tripIDLabel.text = tripID //Add Time Button Tag //Extract Integer Value of Stop ID and Assign as Tags to Buttons self.tagValue = NSString(string: vehicleID!).integerValue //println(self.tagValue) pageEntry.busLocation.tag = self.tagValue! pageEntry.busLocation.addTarget(self, action: "locationButtonAction:", forControlEvents: UIControlEvents.TouchUpInside) currentWidth = currentWidth + pageEntry.frame.size.width scrollContent.addSubview(pageEntry) //println("Page Made") }) var scrollViewContentSize:CGSize = CGSizeMake(screenDimensions.screenWidth * CGFloat(pageCount), fixedHeight); self.mainScroll.contentSize = scrollViewContentSize self.mainScroll.addSubview(scrollContent) self.view.addSubview(self.mainScroll) if pageCount > 1 { //Create Page Control View var pageControlBg:UIView = UIView(frame: CGRectMake(0, screenDimensions.screenHeight - 30, screenDimensions.screenWidth, 30)) pageControlBg.backgroundColor = UIColor.blackColor() pageControlBg.alpha = 0.5 self.view.addSubview(pageControlBg) //x y width height pageControl.frame = CGRectMake(100, screenDimensions.screenHeight - 30, screenDimensions.screenWidth - 200, 30) pageControl.numberOfPages = pageCount pageControl.currentPage = 0 pageControl.userInteractionEnabled = false self.view.addSubview(pageControl) } } func scrollViewDidScroll(scrollView: UIScrollView) { //println("Scrolled") var pageWidth:CGFloat = self.mainScroll.frame.size.width; var page:Int = Int(floor((self.mainScroll.contentOffset.x - pageWidth / 2 ) / pageWidth)) + 1; //this provides the page number self.pageControl.currentPage = page;// this displays the white dot as current page } //Bus Location Button Action func locationButtonAction(sender:UIButton!) { //println("Bus Location Tapped") //Cast Self and Get Tag Number let button:UIButton = sender //println(button.tag) //Display Bus Location Using Vehicle ID var busLocMap:mapModalViewController = mapModalViewController() busLocMap.busID = String(button.tag) busLocMap.view.frame = CGRectMake(0, 20, screenDimensions.screenWidth, screenDimensions.screenHeight) busLocMap.view.backgroundColor = UIColor.blackColor() self.modalPresentationStyle = UIModalPresentationStyle.CurrentContext self.presentViewController(busLocMap, animated: true, completion: nil) } }
mit
74cb7b0c5c94cfff15d9fbe0c8c13338
41.497059
356
0.593121
5.512781
false
false
false
false
didierbrun/DBPathRecognizer
PathRecognizer/ViewController.swift
1
4489
// // ViewController.swift // PathRecognizer // // Created by Didier Brun on 15/03/2015. // Copyright (c) 2015 Didier Brun. All rights reserved. // import UIKit class ViewController: UIViewController { var rawPoints:[Int] = [] var recognizer:DBPathRecognizer? @IBOutlet var renderView: RenderView! @IBOutlet var letterLabel: UILabel! override func viewDidLoad() { //define the number of direction of PathModel let recognizer = DBPathRecognizer(sliceCount: 8, deltaMove: 16.0) //define specific formes to draw on PathModel recognizer.addModel(PathModel(directions: [7, 1], datas:"A" as AnyObject)) recognizer.addModel(PathModel(directions: [2,6,0,1,2,3,4,0,1,2,3,4], datas:"B" as AnyObject)) recognizer.addModel(PathModel(directions: [4,3,2,1,0], datas:"C" as AnyObject)) recognizer.addModel(PathModel(directions: [2,6,7,0,1,2,3,4], datas:"D" as AnyObject)) recognizer.addModel(PathModel(directions: [4,3,2,1,0,4,3,2,1,0], datas:"E" as AnyObject)) recognizer.addModel(PathModel(directions: [4,2], datas:"F" as AnyObject)) recognizer.addModel(PathModel(directions: [4,3,2,1,0,7,6,5,0], datas:"G" as AnyObject)) recognizer.addModel(PathModel(directions: [2,6,7,0,1,2], datas:"H" as AnyObject)) recognizer.addModel(PathModel(directions: [2], datas:"I" as AnyObject)) recognizer.addModel(PathModel(directions: [2,3,4], datas:"J" as AnyObject)) recognizer.addModel(PathModel(directions: [3,4,5,6,7,0,1], datas:"K" as AnyObject)) recognizer.addModel(PathModel(directions: [2,0], datas:"L" as AnyObject)) recognizer.addModel(PathModel(directions: [6,1,7,2], datas:"M" as AnyObject)) recognizer.addModel(PathModel(directions: [6,1,6], datas:"N" as AnyObject)) recognizer.addModel(PathModel(directions: [4,3,2,1,0,7,6,5,4], datas:"O" as AnyObject)) recognizer.addModel(PathModel(directions: [6,7,0,1,2,3,4], datas:"P" as AnyObject)) recognizer.addModel(PathModel(directions: [4,3,2,1,0,7,6,5,4,0], datas:"Q" as AnyObject)) recognizer.addModel(PathModel(directions: [2,6,7,0,1,2,3,4,1], datas:"R" as AnyObject)) recognizer.addModel(PathModel(directions: [4,3,2,1,0,1,2,3,4], datas:"S" as AnyObject)) recognizer.addModel(PathModel(directions: [0,2], datas:"T" as AnyObject)) recognizer.addModel(PathModel(directions: [2,1,0,7,6], datas:"U" as AnyObject)) recognizer.addModel(PathModel(directions: [1,7,0], datas:"V" as AnyObject)) recognizer.addModel(PathModel(directions: [2,7,1,6], datas:"W" as AnyObject)) recognizer.addModel(PathModel(directions: [1,0,7,6,5,4,3], datas:"X" as AnyObject)) recognizer.addModel(PathModel(directions: [2,1,0,7,6,2,3,4,5,6,7], datas:"Y" as AnyObject)) recognizer.addModel(PathModel(directions: [0,3,0], datas:"Z" as AnyObject)) self.recognizer = recognizer super.viewDidLoad() } //takes the coordinates of the first touch override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { rawPoints = [] let touch = touches.first let location = touch!.location(in: view) rawPoints.append(Int(location.x)) rawPoints.append(Int(location.y)) } //takes all coordinates if touch moves and override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) { let touch = touches.first let location = touch!.location(in: view) if(rawPoints[rawPoints.count-2] != Int(location.x) && rawPoints[rawPoints.count-1] != Int(location.y)) { rawPoints.append(Int(location.x)) rawPoints.append(Int(location.y)) } self.renderView.pointsToDraw = rawPoints } //create the final path and makes action is letter is S override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { var path:Path = Path() path.addPointFromRaw(rawPoints) let gesture:PathModel? = self.recognizer!.recognizePath(path) if gesture != nil { let letters = gesture!.datas as? String letterLabel.text = letters } else { letterLabel.text = "" } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } }
mit
9298a9bec90fb83afb402abfd9ca1436
43.009804
112
0.633994
3.523548
false
false
false
false
skyfe79/SwiftImageProcessing
10_Convolution.playground/Contents.swift
1
863
//: Playground - noun: a place where people can play import UIKit let monet1 = RGBAImage(image: UIImage(named: "monet1")!)! let monet2 = RGBAImage(image: UIImage(named: "monet2")!)! let tiger = RGBAImage(image: UIImage(named: "tiger")!)! // Brightness ImageProcess.brightness(monet1, contrast: 0.8, brightness: 0.5).toUIImage() // Split let (R,G,B) = ImageProcess.splitRGB(monet1) R.toUIImage() // Sharpening let m1 = Array2D(cols:3, rows:3, elements: [ 0.0/5.0, -1.0/5.0, 0.0/5.0, -1.0/5.0, 9.0/5.0,-1.0/5.0, 0.0/5.0, -1.0/5.0, 0.0/5.0]) ImageProcess.convolution(R.clone(), mask: m1).toUIImage() // Blur3x3 let m2 = Array2D(cols: 3, rows: 3, elements: [ 1.0/9.0, 1.0/9.0, 1.0/9.0, 1.0/9.0, 1.0/9.0, 1.0/9.0, 1.0/9.0, 1.0/9.0, 1.0/9.0, ] ) ImageProcess.convolution(R.clone(), mask: m2).toUIImage()
mit
d3f43769f6bca87a899290fd3fd12553
21.710526
75
0.606025
2.253264
false
false
false
false
mlibai/XZKit
XZKit/Code/TimeKeeper/XZTimekeeper.swift
1
9682
// // XZTimekeeper.swift // XZKit // // Created by Xezun on 2017/8/9. // Copyright © 2017年 XEZUN INC. All rights reserved. // import UIKit /// 遵循 Timekeepable 协议可获得计时器 timekeeper 属性,该计时器以自身作为代理。 public protocol Timekeepable: Timekeeping, TimekeeperDelegate { } /// Timekeeper 代理协议。 public protocol TimekeeperDelegate: AnyObject { /// 计时器每执行一次嘀嗒计时,都会触发此方法。 /// - Parameters: /// - timekeeper: 调用此方法的 Timekeeper 计时器。 /// - timeInterval: 计时器从启动或上一次调用本方法时,到现在的时长。 func timekeeper(_ timekeeper: Timekeeper, didTime timeInterval: TimeInterval) } public protocol Timekeeping: AnyObject { /// 计时器最大计时时长,默认 0 ,超过该时长,计时器自动暂停。 var duration: TimeInterval { get set } /// 当前时间:计时器当前已计时时长。 var currentTime: TimeInterval { get set } /// 计时器是否暂停,默认 true 。 /// 请通过 resume() 和 pause 方法来启动或暂停计时器。 var isPaused: Bool { get } /// 计时频率(周期)。通过设置此属性,可以控制计时器向 delegate 汇报计时进度的频率。 /// 默认值 .never 表示计时完成前,不发送代理事件。 /// - Note: 计时器执行过程中,设置此属性无效。 var timeInterval: DispatchTimeInterval { get set } /// 误差允许值。计时器尽量保证满足此误差,并不绝对。 /// - Note: 计时器执行过程中,设置此属性无效。 var timeLeeway: DispatchTimeInterval { get set } /// 暂停计时器。 /// - Note: 暂停中的计时器调用此方法不执行任何操作。 /// - Note: 暂停时,当前的计时状态会保存 func pause() /// 未开始或暂停中的计时器开始或恢复执行。 /// - Note: 执行中的计时器,调用此方法不执行任何操作。 func resume() } /// 基于 DispatchSourceTimer 实现的计时器。 /// - Note: 与定时器不同,计时器主要提供计时(累计时长)的能力。 open class Timekeeper: Timekeeping { /// 代理。 open weak var delegate: TimekeeperDelegate? open var duration: TimeInterval = 0 open var currentTime: TimeInterval = 0 open private(set) var isPaused: Bool = true open var timeInterval: DispatchTimeInterval = .never open var timeLeeway: DispatchTimeInterval = .seconds(0) /// 记录了上次的计时的绝对时间点,或者暂停前已执行的周期时长。 private var timestamp: TimeInterval = 0 open func pause() { if isPaused { return } isPaused = true // 暂停时,记录时长。 timestamp = (CACurrentMediaTime() - timestamp) currentTime += timestamp dispatchTimer.suspend() } open func resume() { guard isPaused else { return } isPaused = false // 重置已完成的计时器 if currentTime >= duration { currentTime = 0 } // 计算到下个重复周期 let next = min(duration, TimeInterval(timeInterval)) - timestamp timestamp = CACurrentMediaTime() dispatchTimer.schedule(wallDeadline: .now() + next, repeating: timeInterval, leeway: timeLeeway) dispatchTimer.resume() } /// 创建一个计时器。 /// - Note: 计时器默认处于暂停状态,需调用 resume() 方法启动。 /// - Parameter queue: 计时器使用的队列(如发送代理事件)。 public init(queue: DispatchQueue = .main) { dispatchTimer = DispatchSource.makeTimerSource(queue: queue) dispatchTimer.setEventHandler(handler: { [weak self] in self?.dispatchTimerAction() }) } deinit { // DispatchSourceTimer 在初始化、暂停的情况下,不能执行 cancel 方法。 if isPaused { dispatchTimer.setEventHandler(handler: nil) dispatchTimer.resume() } dispatchTimer.cancel() } /// 定时器。 private let dispatchTimer: DispatchSourceTimer private func dispatchTimerAction() { // 计算时长。 let now = CACurrentMediaTime() // 当前时间 let delta = (now - timestamp) // 与上次的时间差 let newTime = currentTime + delta // 新的时间点 let remain = duration - newTime // 剩余时长 // 如果没有剩余时长,那么定时器暂停;如果不够一个间隔,则重新设置倒计时。 if remain < 1.0e-9 { currentTime = duration timestamp = 0 isPaused = true dispatchTimer.suspend() } else { if remain < TimeInterval(timeInterval) { dispatchTimer.schedule(deadline: .now() + remain, repeating: timeInterval, leeway: timeLeeway) } timestamp = now currentTime = newTime } delegate?.timekeeper(self, didTime: delta) } } extension Timekeepable { public var duration: TimeInterval { get { return timekeeper.duration } set { timekeeper.duration = newValue } } public var timeInterval: DispatchTimeInterval { get { return timekeeper.timeInterval } set { timekeeper.timeInterval = newValue } } public var timeLeeway: DispatchTimeInterval { get { return timekeeper.timeLeeway } set { timekeeper.timeLeeway = newValue} } public var currentTime: TimeInterval { get { return timekeeper.currentTime } set { timekeeper.currentTime = currentTime } } public var isPaused: Bool { return timekeeper.isPaused } public func pause() { timekeeper.pause() } public func resume() { timekeeper.resume() } /// 用于处理计时的 DisplayTimer 对象,默认主线程。 /// - Note: 该属性可写,可自定义(比如使用其它队列)所使用的 Timekeeper 对象。 public var timekeeper: Timekeeper { get { if let timekeeper = objc_getAssociatedObject(self, &AssociationKey.timekeeper) as? Timekeeper { return timekeeper } let timekeeper = Timekeeper.init(queue: .main) timekeeper.delegate = self self.timekeeper = timekeeper return timekeeper } set { objc_setAssociatedObject(self, &AssociationKey.timekeeper, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } } extension DispatchTimeInterval: ExpressibleByFloatLiteral { public typealias FloatLiteralType = TimeInterval public init(_ timeInterval: TimeInterval) { self.init(floatLiteral: timeInterval) } /// 根据当前 timeInterval (秒)小数点后面的位数选择合适的精度。 /// - Note: Double占8个字节(64位)内存空间,最多可提供16位有效数字,小数点后默认保留6位。如全是整数,zd最多提供15位有效数字。 /// - Note: 负数和大于 999_999_999_999_999 的值将构造为 .never 。 /// - Parameter timeInterval: 以秒为单位的时间值。 public init(floatLiteral timeInterval: TimeInterval) { if timeInterval < 0 || timeInterval > 999_999_999_999_999 { self = .never return } var t0 = timeInterval + 5.0e-10 // 四舍五入 var t1 = floor(t0) var t2 = t0 - t1 var tn = 0 var tx = 1.0e-9 // 最小精度 1 纳秒。 while t2 >= tx { t0 = t0 * 1000 t1 = floor(t0) t2 = t0 - t1 tn = tn + 1 tx = tx * 1000 // 保持最小精度不变 } let value = Int(floor(t0)) switch tn { case 0: self = .seconds(value) case 1: self = .milliseconds(value) case 2: self = .microseconds(value) default: self = .nanoseconds(value) } } public static func - (lhs: DispatchTimeInterval, rhs: TimeInterval) -> TimeInterval { switch lhs { case .never: return TimeInterval(Int.max) - rhs case .seconds(let value): return TimeInterval(value) - rhs case .milliseconds(let value): return TimeInterval(value) * 1.0e-3 - rhs case .microseconds(let value): return TimeInterval(value) * 1.0e-6 - rhs case .nanoseconds(let value): return TimeInterval(value) * 1.0e-6 - rhs @unknown default: return 0 } } } extension TimeInterval { public init(_ timeInterval: DispatchTimeInterval) { switch timeInterval { case .never: self = TimeInterval(UInt.max) case .seconds(let value): self = TimeInterval(value) case .milliseconds(let value): self = TimeInterval(value) * 1.0e-3 case .microseconds(let value): self = TimeInterval(value) * 1.0e-6 case .nanoseconds(let value): self = TimeInterval(value) * 1.0e-9 default: self = 0 } } } private struct AssociationKey { static var timekeeper = 0 }
mit
e4d9a8e4de1154071b5aaadcd96b579c
26.51505
116
0.576638
4.011214
false
false
false
false
getsentry/sentry-swift
Tests/SentryTests/Protocol/SentryThreadEquality.swift
1
1722
import Foundation extension Sentry.Thread { open override func isEqual(_ object: Any?) -> Bool { if let other = object as? Sentry.Thread { return threadId == other.threadId && name == other.name && stacktrace == other.stacktrace && crashed == other.crashed && current == other.current } else { return false } } override open var description: String { "\(self.serialize())" } } extension Sentry.Stacktrace { open override func isEqual(_ object: Any?) -> Bool { if let other = object as? Sentry.Stacktrace { return frames == other.frames && registers == other.registers } else { return false } } override open var description: String { "\(self.serialize())" } } extension Sentry.Frame { open override func isEqual(_ object: Any?) -> Bool { if let other = object as? Sentry.Frame { return symbolAddress == other.symbolAddress && fileName == other.fileName && function == other.function && module == other.module && package == other.package && imageAddress == other.imageAddress && platform == other.platform && instructionAddress == other.instructionAddress && lineNumber == other.lineNumber && columnNumber == other.columnNumber && inApp == other.inApp } else { return false } } override open var description: String { "\(self.serialize())" } }
mit
7cc8d13a5063ad1cc37cbdd82a65b97a
28.689655
65
0.515099
5.298462
false
false
false
false
a1exb1/ABToolKit-pod
Pod/Classes/FormView/FormViewConfiguration.swift
1
2928
// // FormViewConfiguration.swift // Pods // // Created by Alex Bechmann on 09/06/2015. // // import UIKit public enum FormCellType { case None case DatePicker case TextField case TextFieldCurrency case Button } public class FormViewConfiguration { public var labelText: String = "" public var formCellType = FormCellType.TextField public var value: AnyObject? public var identifier: String = "" //currency public var currencyLocale = NSLocale(localeIdentifier: "en_GB") //button public var buttonTextColor = UIColor.blueColor() //datepicker public var format: String = DateFormat.DateTime.rawValue private convenience init(labelText: String, formCellType: FormCellType, value: AnyObject?, identifier: String) { self.init() self.labelText = labelText self.formCellType = formCellType self.value = value self.identifier = identifier } public class func datePicker(labelText: String, date: NSDate?, identifier: String, format: String?) -> FormViewConfiguration { let config = FormViewConfiguration(labelText: labelText, formCellType: FormCellType.DatePicker, value: date, identifier: identifier) if let f = format { config.format = f } return config } public class func textField(labelText: String, value: String?, identifier: String) -> FormViewConfiguration { return FormViewConfiguration(labelText: labelText, formCellType: FormCellType.TextField, value: value, identifier: identifier) } public class func textFieldCurrency(labelText: String, value: String?, identifier: String) -> FormViewConfiguration { return textFieldCurrency(labelText, value: value, identifier: identifier, locale: nil) } public class func textFieldCurrency(labelText: String, value: String?, identifier: String, locale: NSLocale?) -> FormViewConfiguration { let config = FormViewConfiguration(labelText: labelText, formCellType: FormCellType.TextFieldCurrency, value: value, identifier: identifier) if let l = locale { config.currencyLocale = l } return config } public class func button(buttonText: String, buttonTextColor: UIColor, identifier: String) -> FormViewConfiguration { let config = FormViewConfiguration(labelText: buttonText, formCellType: FormCellType.Button, value: nil, identifier: identifier) config.buttonTextColor = buttonTextColor return config } public class func normalCell(identifier: String) -> FormViewConfiguration { return FormViewConfiguration(labelText: "", formCellType: FormCellType.None, value: nil, identifier: identifier) } }
mit
bc8ad192c9912cbcea1f5236179017ff
30.826087
148
0.66291
5.323636
false
true
false
false
slightair/syu
Syu/Model/Content.swift
1
3891
import Foundation import Himotoki import Mustache struct Content { enum SyntaxType: String, CustomStringConvertible, MustacheBoxable { case globalVariable = "data" case typeAlias = "tdef" case function = "func" case enumeration = "enum" case enumerationCase = "enumelt" case structure = "struct" case `class` = "cl" case `protocol` = "intf" case instanceMethod = "instm" case instanceProperty = "instp" case typeMethod = "clm" case typeProperty = "structdata" case unknown var description: String { switch self { case .globalVariable: return "Global Variable" case .typeAlias: return "Type Alias" case .function: return "Function" case .enumeration: return "Enumeration" case .enumerationCase: return "Enumeration Case" case .structure: return "Structure" case .class: return "Class" case .protocol: return "Protocol" case .instanceMethod: return "Instance Method" case .instanceProperty: return "Instance Property" case .typeMethod: return "Type Method" case .typeProperty: return "Type Property" case .unknown: return "Unknown" } } var mustacheBox: MustacheBox { return Box(self.description) } } struct Section: Decodable, MustacheBoxable { struct Symbol: Decodable, MustacheBoxable { let title: String let name: String? let abstract: String? static func decode(_ e: Extractor) throws -> Symbol { return try Symbol( title: e <| ["t", "x"], name: e <|? "n", abstract: e <|? ["a", "x"] ) } var mustacheBox: MustacheBox { return Box([ "name": name ?? title, "abstract": abstract ?? "" ]) } } let title: String let symbols: [Symbol]? static func decode(_ e: Extractor) throws -> Section { return try Section( title: e <| ["t", "x"], symbols: e <||? ["s"] ) } var mustacheBox: MustacheBox { return Box([ "title": title, "symbols": symbols ?? [] ]) } } let syntaxType: SyntaxType let name: String let abstract: String? let overview: String? let sections: [Section]? } extension Content: Decodable { static let SyntaxTypeTransformer = Transformer<String?, SyntaxType> { string throws -> SyntaxType in guard let string = string else { return .unknown } if let type = SyntaxType(rawValue: string) { return type } else { print("unknown syntax type: \(string)") return .unknown } } static func decode(_ e: Extractor) throws -> Content { return try Content( syntaxType: SyntaxTypeTransformer.apply(e <|? "k"), name: e <| ["t", "x"], abstract: e <|? ["a", "x"], overview: e <|? ["o", "x"], sections: e <||? "c" ) } } extension Content: MustacheBoxable { var mustacheBox: MustacheBox { return Box([ "syntaxType": syntaxType, "name": name, "abstract": abstract ?? "", "overview": overview ?? "", "sections": sections ?? [] ]) } }
mit
0f1dce4f677689d3091dfacda4d2b320
26.992806
104
0.477512
5.188
false
false
false
false
shopgun/shopgun-ios-sdk
Sources/TjekAPI/Utils/ImageURL.swift
1
1737
/// /// Copyright (c) 2020 Tjek. All rights reserved. /// import Foundation public struct ImageURL: Equatable, Codable, Hashable { public var url: URL public var width: Int public init(url: URL, width: Int) { self.url = url self.width = width } } extension Collection where Element == ImageURL { public var smallestToLargest: [ImageURL] { self.sorted(by: { $0.width <= $1.width }) } public var largestImage: ImageURL? { smallestToLargest.last } public var smallestImage: ImageURL? { smallestToLargest.first } // TODO: Add ability to 'round up' to nearest image: LH - 25 May 2020 /** Returns the smallest image that is at least as wide as the specified `minWidth`. If no imageURLs match the criteria (they are all smaller than the specified minWidth), and `fallbackToNearest` is true, this will return the largest possible image. */ public func imageURL(widthAtLeast minWidth: Int, fallbackToNearest: Bool) -> ImageURL? { let urls = smallestToLargest return urls.first(where: { $0.width >= minWidth }) ?? (fallbackToNearest ? urls.last : nil) } /** Returns the largest imageURL whose width is no more than the specified `maxWidth`. If no imageURLs match the criteria (they are all bigger than the specified maxWidth), and `fallbackToNearest` is true, this will return the smallest possible image. */ public func imageURL(widthNoMoreThan maxWidth: Int, fallbackToNearest: Bool) -> ImageURL? { let urls = smallestToLargest return urls.last(where: { $0.width <= maxWidth }) ?? (fallbackToNearest ? urls.first : nil) } }
mit
b597186da8b6e6cf7b44b91e9a0d2398
32.403846
169
0.65285
4.397468
false
false
false
false
MChainZhou/DesignPatterns
Mediator/Mediator/Simple_2_生活案例/Mainborad.swift
1
1257
// // Mainborad.swift // Mediator // // Created by apple on 2017/8/30. // Copyright © 2017年 apple. All rights reserved. // import UIKit class Mainborad: ComputerMediator { private var cpu:CPU? private var displaycard:Displaycard? private var soundcard:Soundcard? private var cddevice:CDDevice? func setCPU(cpu:CPU) { self.cpu = cpu } func setdisplaycard(displaycard:Displaycard) { self.displaycard = displaycard } func setSoundcard(soundcard:Soundcard) { self.soundcard = soundcard } func setCDDevice(cddivece:CDDevice) { self.cddevice = cddivece } override func change(colleague: ComputerColleague) { if colleague == cddevice { self.handleCD(cddevice: colleague as! CDDevice) } else if colleague == cpu { self.handleCPU(cpu: colleague as! CPU) } } //CPU解析光盘数据 private func handleCD(cddevice:CDDevice){ self.cpu?.decodeData(data: cddevice.read()) } //声卡和显卡播放 private func handleCPU(cpu:CPU){ self.soundcard?.soundPlay(data: cpu.getSoundData()) self.displaycard?.videoPlay(data: cpu.getVideoData()) } }
mit
41cd065d22efe98205f18f080277fb43
22.615385
61
0.624593
3.698795
false
false
false
false
sbennett912/SwiftGL
SwiftGL-Demo/Source/OSX/GLView.swift
1
6231
// // GLView.swift // SwiftGL-Demo // // Created by Scott Bennett on 2014-07-12. // Copyright (c) 2014 Scott Bennett. All rights reserved. // import Foundation extension GLView { // deinit { // // Stop the display link BEFORE releasing anything in the view // // otherwise the display link thread may call into the view and crash // // when it encounters something that has been release // CVDisplayLinkStop(displayLink) // CVDisplayLinkRelease(displayLink) // // // Release the renderer AFTER display link has been released // Engine.finalize() // } override open func awakeFromNib() { let attributes: [NSOpenGLPixelFormatAttribute] = [ // Must specify the 3.2 Core Profile to use OpenGL 3.2 NSOpenGLPixelFormatAttribute(NSOpenGLPFAOpenGLProfile), NSOpenGLPixelFormatAttribute(NSOpenGLProfileVersion3_2Core), NSOpenGLPixelFormatAttribute(NSOpenGLPFADoubleBuffer), NSOpenGLPixelFormatAttribute(NSOpenGLPFAColorSize), NSOpenGLPixelFormatAttribute(32), NSOpenGLPixelFormatAttribute(NSOpenGLPFADepthSize), NSOpenGLPixelFormatAttribute(24), NSOpenGLPixelFormatAttribute(NSOpenGLPFAStencilSize), NSOpenGLPixelFormatAttribute(8), NSOpenGLPixelFormatAttribute(NSOpenGLPFAMultisample), NSOpenGLPixelFormatAttribute(NSOpenGLPFASampleBuffers), NSOpenGLPixelFormatAttribute(1), NSOpenGLPixelFormatAttribute(NSOpenGLPFASamples), NSOpenGLPixelFormatAttribute(4), NSOpenGLPixelFormatAttribute(0) ] let pf = NSOpenGLPixelFormat(attributes: attributes) if let context = NSOpenGLContext(format: pf!, share: nil) { // When we're using a CoreProfile context, crash if we call a legacy OpenGL function // This will make it much more obvious where and when such a function call is made so // that we can remove such calls. // Without this we'd simply get GL_INVALID_OPERATION error for calling legacy functions // but it would be more difficult to see where that function was called. CGLEnable(context.cglContextObj!, kCGLCECrashOnRemovedFunctions) pixelFormat = pf openGLContext = context // Opt-In to Retina resolution wantsBestResolutionOpenGLSurface = true } } // func initGL() { // // The reshape function may have changed the thread to which our OpenGL // // context is attached before prepareOpenGL and initGL are called. So call // // makeCurrentContext to ensure that our OpenGL context current to this // // thread (i.e. makeCurrentContext directs all OpenGL calls on this thread // // to [self openGLContext]) // openGLContext.makeCurrentContext() // // // Synchronize buffer swaps with vertical refresh rate // var swapInt = GLint(1) // openGLContext.setValues(&swapInt, forParameter: .GLCPSwapInterval) // } // override func reshape() { // super.reshape() // // // We draw on a secondary thread through the display link. However, when // // resizing the view, -drawRect is called on the main thread. // // Add a mutex around to avoid the threads accessing the context // // simultaneously when resizing. // CGLLockContext(openGLContext.CGLContextObj) // // // Get the view size in Points // let viewRectPoints = self.bounds // // // Rendering at retina resolutions will reduce aliasing, but at the potential // // cost of framerate and battery life due to the GPU needing to render more // // pixels. // // // Any calculations the renderer does which use pixel dimentions, must be // // in "retina" space. [NSView convertRectToBacking] converts point sizes // // to pixel sizes. Thus the renderer gets the size in pixels, not points, // // so that it can set it's viewport and perform and other pixel based // // calculations appropriately. // // viewRectPixels will be larger (2x) than viewRectPoints for retina displays. // // viewRectPixels will be the same as viewRectPoints for non-retina displays // let viewRectPixels = convertRectToBacking(viewRectPoints) // // // Set the new dimensions in our renderer // Engine.resize(width: Float(viewRectPixels.size.width), height: Float(viewRectPixels.size.height)) // // CGLUnlockContext(openGLContext.CGLContextObj) // } override open func draw(_ dirtyRect: NSRect) { // Called during resize operations // Avoid flickering during resize by drawiing drawView() } func drawView() { openGLContext!.makeCurrentContext() // We draw on a secondary thread through the display link // When resizing the view, -reshape is called automatically on the main // thread. Add a mutex around to avoid the threads accessing the context // simultaneously when resizing CGLLockContext(openGLContext!.cglContextObj!) Engine.update() Engine.render() CGLFlushDrawable(openGLContext!.cglContextObj!) CGLUnlockContext(openGLContext!.cglContextObj!) } // override func renewGState() { // // Called whenever graphics state updated (such as window resize) // // // OpenGL rendering is not synchronous with other rendering on the OSX. // // Therefore, call disableScreenUpdatesUntilFlush so the window server // // doesn't render non-OpenGL content in the window asynchronously from // // OpenGL content, which could cause flickering. (non-OpenGL content // // includes the title bar and drawing done by the app with other APIs) // window.disableScreenUpdatesUntilFlush() // // super.renewGState() // } func windowWillClose(_ notification: Notification) { // Stop the display link when the window is closing because default // OpenGL render buffers will be destroyed. If display link continues to // fire without renderbuffers, OpenGL draw calls will set errors. CVDisplayLinkStop(displayLink) } }
mit
ff378c45b3485f5a0ee814b82f0e3ca5
43.191489
128
0.675333
4.699095
false
false
false
false
steveholt55/metro
iOS/MetroTransit/Model/Route/Route+Methods.swift
1
2029
// // Copyright © 2016 Brandon Jenniges. All rights reserved. // import UIKit import CoreData import Alamofire extension Route { // MARK: - Core Data convenience init?(json: [String : AnyObject]) { let entity = Route.getEntity(String(Route)) self.init(entity: entity, insertIntoManagedObjectContext: Route.getManagedObjectContext()) guard let routeNumberString = json["Route"] as? String, let routeNumberInt = Int(routeNumberString), let providerIdString = json["ProviderID"] as? String, let providerIdInt = Int(providerIdString), let routeName = json["Description"] as? String else { return nil } self.routeNumber = NSNumber(integer: routeNumberInt) self.providerId = NSNumber(integer: providerIdInt) self.name = routeName } // MARK: - Metro API static func getRoutes(complete complete:(routes:[Route]) -> Void) { let URL = NSURL(string: "http://svc.metrotransit.org/NexTrip/Routes") HTTPClient().get(URL!, parameters: ["format":"json"]) { (json:AnyObject?, response:NSHTTPURLResponse?, error:NSError?) -> Void in var routes = [Route]() if let json = json as? [[String : AnyObject]] { for item in json { if let route = Route(json: item) { routes.append(route) } } } complete(routes: routes) } } static func getRoutesContainingName(string: String, routes:[Route]) -> [Route] { let whitespaceSet = NSCharacterSet.whitespaceCharacterSet() if string.stringByTrimmingCharactersInSet(whitespaceSet) == "" { return routes } let lowercaseString = string.lowercaseString return routes.filter { (route : Route) -> Bool in return route.name!.lowercaseString.rangeOfString(lowercaseString) != nil } } }
mit
6d0cfe018f5663fc0c082e2df91244e2
33.965517
137
0.590237
4.851675
false
false
false
false
curoo/OAuthSwift
OAuthSwiftDemo/AppDelegate.swift
7
3733
// // AppDelegate.swift // OAuthSwift // // Created by Dongri Jin on 6/21/14. // Copyright (c) 2014 Dongri Jin. All rights reserved. // import UIKit import OAuthSwift @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate, UIWebViewDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject : AnyObject]?) -> Bool { // Override point for customization after application launch. let viewController: ViewController = ViewController() let naviController: UINavigationController = UINavigationController(rootViewController: viewController) self.window = UIWindow(frame: UIScreen.mainScreen().bounds) self.window!.rootViewController = naviController self.window!.makeKeyAndVisible() return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } func application(application: UIApplication, openURL url: NSURL, sourceApplication: String?, annotation: AnyObject) -> Bool { if (url.host == "oauth-callback") { if (url.path!.hasPrefix("/twitter") || url.path!.hasPrefix("/flickr") || url.path!.hasPrefix("/fitbit") || url.path!.hasPrefix("/withings") || url.path!.hasPrefix("/linkedin") || url.path!.hasPrefix("/bitbucket") || url.path!.hasPrefix("/smugmug") || url.path!.hasPrefix("/intuit") || url.path!.hasPrefix("/zaim") || url.path!.hasPrefix("/tumblr")) { OAuth1Swift.handleOpenURL(url) } if ( url.path!.hasPrefix("/github" ) || url.path!.hasPrefix("/instagram" ) || url.path!.hasPrefix("/foursquare") || url.path!.hasPrefix("/dropbox") || url.path!.hasPrefix("/dribbble") || url.path!.hasPrefix("/salesforce") || url.path!.hasPrefix("/google") || url.path!.hasPrefix("/linkedin2") || url.path!.hasPrefix("/slack") || url.path!.hasPrefix("/uber")) { OAuth2Swift.handleOpenURL(url) } } else { // Google provider is the only one wuth your.bundle.id url schema. OAuth2Swift.handleOpenURL(url) } return true } }
mit
1711deff64ccea669313e4bc58878665
63.362069
372
0.705867
5.058266
false
false
false
false