repo_name
stringlengths
6
91
ref
stringlengths
12
59
path
stringlengths
7
936
license
stringclasses
15 values
copies
stringlengths
1
3
content
stringlengths
61
714k
hash
stringlengths
32
32
line_mean
float64
4.88
60.8
line_max
int64
12
421
alpha_frac
float64
0.1
0.92
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
CaseyApps/HackingWithSwift
refs/heads/master
project30-files/Project30/ImageViewController.swift
unlicense
24
// // ImageViewController.swift // Project30 // // Created by Hudzilla on 26/11/2014. // Copyright (c) 2014 Hudzilla. All rights reserved. // import UIKit class ImageViewController: UIViewController { var owner: SelectionViewController! var image: String! var animTimer: NSTimer! var imageView: UIImageView! override func loadView() { super.loadView() view.backgroundColor = UIColor.blackColor() // create an image view that fills the screen imageView = UIImageView() imageView.contentMode = .ScaleAspectFit imageView.translatesAutoresizingMaskIntoConstraints = false imageView.alpha = 0 view.addSubview(imageView) // make the image view fill the screen let viewsDictionary = ["imageView": imageView] view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[imageView]|", options: [], metrics:nil, views: viewsDictionary)) view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[imageView]|", options: [], metrics:nil, views: viewsDictionary)) // schedule an animation that does something vaguely interesting self.animTimer = NSTimer.scheduledTimerWithTimeInterval(5, target: self, selector: "animateImage", userInfo: nil, repeats: true) } override func viewDidLoad() { super.viewDidLoad() title = image.stringByReplacingOccurrencesOfString(".jpg", withString: "") imageView.image = UIImage(named: image) // force the image to rasterize so we don't have to keep loading it at the original, large size imageView.layer.shouldRasterize = true imageView.layer.rasterizationScale = UIScreen.mainScreen().scale // NOTE: See if you can use the "Color hits green and misses red" option in the // Core Animation instrument to see what effect the above has in this project! } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) imageView.alpha = 0 UIView.animateWithDuration(3) { [unowned self] in self.imageView.alpha = 1 } } override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { let defaults = NSUserDefaults.standardUserDefaults() var currentVal = defaults.integerForKey(image) ?? 0 ++currentVal defaults.setInteger(currentVal, forKey:image) // tell the parent view controller that it should refresh its table counters when we go back owner.dirty = true } func animateImage() { // do something exciting with our image imageView.transform = CGAffineTransformIdentity UIView.animateWithDuration(3) { [unowned self] in self.imageView.transform = CGAffineTransformMakeScale(0.8, 0.8) } } 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. } */ }
bd68f3ebc7265a253822ec437bd9b36f
30.27
138
0.737128
false
false
false
false
gssdromen/CedFilterView
refs/heads/master
FilterTest/Cells/ESFCountDownCell1.swift
gpl-3.0
1
// // ESFCountDownCell1.swift // JingJiRen_ESF_iOS // // Created by cedricwu on 12/30/16. // Copyright © 2016 Cedric Wu. All rights reserved. // import UIKit class ESFCountDownCell1: ESFBaseTableViewCell { let mainLabel: UILabel = { let v = UILabel() v.font = UIFont.systemFont(ofSize: 14) return v }() let extraLabel: UILabel = { let v = UILabel() v.font = UIFont.systemFont(ofSize: 10) v.textColor = UIColor(hex6: 0x888888) return v }() let gou: UIImageView = { let v = UIImageView() v.image = UIImage(named: "ic_ESFHouseList_Gou") return v }() // MARK: - Public Methods func fillWith(mainTitle: String, extraTitle: String) { mainLabel.text = mainTitle extraLabel.text = extraTitle } func setSelect(flag: Bool) { mainLabel.textColor = flag ? UIColor(hex6: 0xF24500) : UIColor(hex6: 0x212121) gou.visible = flag } // MARK: - Views About override func initMyViews() { super.initMyViews() gou.visible = false } override func addMyViews() { super.addMyViews() contentView.addSubview(mainLabel) contentView.addSubview(extraLabel) contentView.addSubview(gou) } override func layoutMyViews() { super.layoutMyViews() mainLabel.snp.makeConstraints { (make) in make.top.equalTo(contentView).offset(7) make.left.equalTo(contentView).offset(12) } extraLabel.snp.makeConstraints { (make) in make.top.equalTo(contentView).offset(26) make.left.equalTo(contentView).offset(12) } gou.snp.makeConstraints { (make) in make.width.equalTo(18) make.height.equalTo(13) make.right.equalTo(contentView).offset(-24) make.centerY.equalTo(contentView) } } // MARK: - Life Cycle override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } }
d753a7dd941c359c7027cce3afe0c56c
25.069767
86
0.599911
false
false
false
false
uxmstudio/UXMBatchDownloader
refs/heads/master
Example/Tests/Tests.swift
mit
1
// https://github.com/Quick/Quick import Quick import Nimble import UXMBatchDownloader class TableOfContentsSpec: QuickSpec { override func spec() { describe("these will fail") { it("can do maths") { expect(1) == 2 } it("can read") { expect("number") == "string" } it("will eventually fail") { expect("time").toEventually( equal("done") ) } context("these will pass") { it("can do maths") { expect(23) == 23 } it("can read") { expect("🐮") == "🐮" } it("will eventually pass") { var time = "passing" DispatchQueue.main.async { time = "done" } waitUntil { done in Thread.sleep(forTimeInterval: 0.5) expect(time) == "done" done() } } } } } }
65d6217cca9f946552e8f06f88a3027c
22.24
60
0.362306
false
false
false
false
Mclarenyang/medicine_aid
refs/heads/master
medicine aid/AppDelegate.swift
apache-2.0
1
// // AppDelegate.swift // medicine aid // // Created by nexuslink mac 2 on 2017/5/7. // Copyright © 2017年 NMID. All rights reserved. // import UIKit import CoreData import RealmSwift @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. /// 加载纯代码视图 // 确定根视图 //进入动画启动并登录 self.window = UIWindow(frame:UIScreen.main.bounds) let navigationview = UINavigationController(rootViewController: RootViewController()) self.window?.rootViewController = navigationview self.window?.makeKeyAndVisible() //UserDefaults.standard.set(true, forKey: "firstLaunch") // //直接进入主页 等待优化 // self.window = UIWindow(frame:UIScreen.main.bounds) // let tabBarController = mainTabbarController() // self.window?.rootViewController = tabBarController // self.window?.backgroundColor = UIColor.white // self.window?.makeKeyAndVisible() // /* //录入测试数据 let textUser = UserText() textUser.UserID = "text" textUser.UserName = "黄力宏" textUser.UserNickname = "点我设置" textUser.UserSex = "男" textUser.UserAge = "35" textUser.UserPhoneNum = "18883992485" textUser.UserType = "P" textUser.UserHeadImage = UIImagePNGRepresentation(UIImage(named:"SettingHeardImage")!) as NSData! let realm = try! Realm() try! realm.write { realm.add(textUser, update: true) } let defaults = UserDefaults.standard defaults.set(textUser.UserID, forKey: "UserID") //数据库地址 print(realm.configuration.fileURL!) */ 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 invalidate graphics rendering callbacks. 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 active 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:. // Saves changes in the application's managed object context before the application terminates. self.saveContext() } // MARK: - Core Data stack lazy var persistentContainer: NSPersistentContainer = { /* The persistent container for the application. This implementation creates and returns a container, having loaded the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. */ let container = NSPersistentContainer(name: "medicine_aid") container.loadPersistentStores(completionHandler: { (storeDescription, error) in if let error = error as NSError? { // Replace this implementation with code to handle the error appropriately. // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. /* Typical reasons for an error here include: * The parent directory does not exist, cannot be created, or disallows writing. * The persistent store is not accessible, due to permissions or data protection when the device is locked. * The device is out of space. * The store could not be migrated to the current model version. Check the error message to determine what the actual problem was. */ fatalError("Unresolved error \(error), \(error.userInfo)") } }) return container }() // MARK: - Core Data Saving support func saveContext () { let context = persistentContainer.viewContext if context.hasChanges { do { try context.save() } catch { // Replace this implementation with code to handle the error appropriately. // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. let nserror = error as NSError fatalError("Unresolved error \(nserror), \(nserror.userInfo)") } } } }
02cd2237bd1fb16a518c4a20e44fdf63
43.129496
285
0.655853
false
false
false
false
bannzai/xcp
refs/heads/master
xcp/XCP/XCPHelperer.swift
mit
1
// // XCPHelperer.swift // xcp // // Created by kingkong999yhirose on 2016/12/23. // Copyright © 2016年 kingkong999yhirose. All rights reserved. // import Foundation func assertionMessage( with function: String = #function, file: String = #file, line: Int = #line, description: String ... ) -> String { return [ "function: \(function)", "file: \(file)", "line: \(line)", "description: \(description)", ].joined(separator: "\n") } extension Array { func ofType<T>(_ type: T.Type) -> [T] { return self.flatMap { $0 as? T } } } extension Array { func groupBy<GroupKey: Hashable>(for keyExtractor: (Element) -> GroupKey) -> [GroupKey: [Element]] { return reduce([GroupKey: [Element]]()) { result, value in let key = keyExtractor(value) let groupedValues = result[key] var dictionary = result dictionary[key] = (groupedValues ?? []) + [value] return dictionary } } } extension Dictionary { typealias Group = [Key: [Value]] func groupBy() -> [Group] { return reduce([Group]()) { result, pair in let groupedValues = result.flatMap { $0[pair.key] }.first let appendGroup: Group switch groupedValues { case .none: appendGroup = [pair.key: [pair.value]] case .some(let groupedValues): appendGroup = [pair.key: groupedValues + [pair.value]] } return result + [appendGroup] } } } extension LazyMapCollection { func toArray() -> Array<Element> { return Array(self) } }
5c380c5fb9c6b6a16daf45e59c36430b
24.895522
104
0.54121
false
false
false
false
AlesTsurko/DNMKit
refs/heads/master
DNMModel/OrderedDictionary.swift
gpl-2.0
1
// From: // https://github.com/lithium3141/SwiftDataStructures/blob/master/SwiftDataStructures/OrderedDictionary.swift // and // http://nshipster.com/swift-collection-protocols/ // // OrderedDictionary.swift // DNMUtility // // Created by James Bean on 11/9/15. // Copyright © 2015 James Bean. All rights reserved. // import Foundation public struct OrderedDictionary<Tk: Hashable, Tv: Equatable where Tk: Comparable>: Equatable, CustomStringConvertible { public var description: String { return getDescription() } public var keys: [Tk] = [] public var values: [Tk : Tv] = [:] public var count: Int { return keys.count } public init() { } public mutating func appendContentsOfOrderedDictionary( orderedDictionary: OrderedDictionary<Tk, Tv> ) { keys.appendContentsOf(orderedDictionary.keys) for key in orderedDictionary.keys { values.updateValue(orderedDictionary[key]!, forKey: key) } } public mutating func insertValue(value: Tv, forKey key: Tk, atIndex index: Int) { keys.insert(key, atIndex: index) values[key] = value } public subscript(key: Tk) -> Tv? { get { return values[key] } set(newValue) { if newValue == nil { values.removeValueForKey(key) keys = keys.filter { $0 != key } return } let oldValue = values.updateValue(newValue!, forKey: key) if oldValue == nil { keys.append(key) } } } private func getDescription() -> String { var description: String = "Ordered Dictionary: [\n" for i in 0..<keys.count { let key = keys[i] description += "\t(\(i), \(key)): \(self[key]!)\n" } description += "]" return description } } extension OrderedDictionary: SequenceType { public typealias Generator = AnyGenerator<(Tk, Tv)> public func generate() -> Generator { var zipped: [(Tk, Tv)] = [] for key in keys { zipped.append((key, values[key]!)) } var index = 0 return anyGenerator { if index < self.keys.count { return zipped[index++] } return nil } } } public func ==<Tk: Hashable, Tv: Equatable where Tk: Comparable>( lhs: OrderedDictionary<Tk, Tv>, rhs: OrderedDictionary<Tk, Tv> ) -> Bool { if lhs.keys != rhs.keys { return false } // for each lhs key, check if rhs has value for key, and if that value is the same for key in lhs.keys { if rhs.values[key] == nil || rhs.values[key]! != lhs.values[key]! { return false } } // do the same for rhs keys to lhs values for key in rhs.keys { if lhs.values[key] == nil || lhs.values[key]! != rhs.values[key]! { return false } } return true }
4050ec9f555cbf584ada22b0648078e4
27.150943
117
0.570567
false
false
false
false
Desgard/Calendouer-iOS
refs/heads/master
Calendouer/Calendouer/AnimatedSwitch.swift
mit
1
// AnimatedSwitch // The MIT License (MIT) // // Created by Alex Sergeev on 4/14/16. // Copyright © 2016 ALSEDI Group. 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 import QuartzCore typealias VoidClosure = () -> () enum AnimatedSwitchShapeType { case round case diamond case star case custom(UIBezierPath) } extension AnimatedSwitchShapeType { fileprivate func polygon(inCircleOfRadius radius: Double, vertices: Int, offset: Double = 0) -> [CGPoint] { let step = .pi * 2 / Double(vertices) let x: Double = 0 let y: Double = 0 var points = [CGPoint]() for i in 0...vertices { let xv = x - radius * cos(step * Double(i) + (step * offset)) let yv = y - radius * sin(step * Double(i) + (step * offset)) points.append(CGPoint(x: xv, y: yv)) } return points } fileprivate func starShape(_ radius: Double, vertices: Int) -> UIBezierPath { let path = UIBezierPath() let externalVertices = polygon(inCircleOfRadius: radius, vertices: vertices) let internalVertices = polygon(inCircleOfRadius: radius/2, vertices: vertices, offset: 0.5) if (externalVertices.count >= 3){ path.move(to: externalVertices[0]) for i in 0..<externalVertices.count-1 { path.addLine(to: internalVertices[i]) path.addLine(to: externalVertices[i + 1]) } path.close() } return path } func scaleFactor(_ from: Double, to: CGRect) -> CGFloat { var endRadius: CGFloat = sqrt(to.width * to.width + to.height * to.height) / 2 print("From \(from)") print("Initial \(endRadius)") switch (self) { case .star: endRadius = endRadius / 2 default: break } print("Adjusted \(endRadius)") print("Mult \(endRadius / CGFloat(from))") return endRadius / CGFloat(from) } func bezierPathInRect(_ rect: CGRect) -> UIBezierPath { let centerX = rect.origin.x + rect.width / 2 let centerY = rect.origin.y + rect.height / 2 let size = sqrt(rect.width * rect.width / 4 + rect.height * rect.height / 4) switch self { case .diamond: let path = UIBezierPath(rect: CGRect(x: 0, y: 0, width: size, height: size)); path.apply(CGAffineTransform(rotationAngle: CGFloat(Double.pi / 4)).concatenating(CGAffineTransform(translationX: centerX, y: rect.origin.y))) return path case .star: let path = starShape(Double(50), vertices: 5) path.apply(CGAffineTransform(translationX: centerX, y: centerY)) return path case .custom(let path): path.apply(CGAffineTransform(translationX: centerX, y: centerY)) return path default: return UIBezierPath(ovalIn: rect) } } } @IBDesignable class AnimatedSwitch: UISwitch, CAAnimationDelegate { fileprivate var originalParentBackground: UIColor? fileprivate var toColor: UIColor? fileprivate let animationIdentificator = "animatedSwitch" fileprivate let containerLayer = CAShapeLayer() @IBInspectable var color: UIColor = UIColor.clear @IBInspectable var startRadius: Double = 15 @IBInspectable var animationDuration: Double = 0.25 @IBInspectable var showBorder: Bool = true @IBInspectable var borderColor: UIColor = UIColor.white var shape: AnimatedSwitchShapeType = .diamond var isAnimating: Bool = false var animationDidStart: VoidClosure? var animationDidStop: VoidClosure? fileprivate func setupView(_ parent: UIView) { removeTarget(self, action: #selector(AnimatedSwitch.valueChanged), for: .valueChanged) addTarget(self, action: #selector(AnimatedSwitch.valueChanged), for: .valueChanged) containerLayer.anchorPoint = CGPoint(x: 0, y: 0) containerLayer.masksToBounds = true parent.layer.insertSublayer(containerLayer, at: 0) } override func willMove(toSuperview newSuperview: UIView?) { if let parent = newSuperview { setupView(parent) originalParentBackground = parent.backgroundColor } } override func layoutSubviews() { guard let parent = superview else { return } containerLayer.frame = CGRect(x: 0, y: 0, width: parent.frame.width, height: parent.frame.height) if isOn { containerLayer.backgroundColor = color.cgColor } else { containerLayer.backgroundColor = originalParentBackground?.cgColor } drawBorder() } func valueChanged() { guard let parent = superview else { return } if isOn { toColor = color } else { toColor = parent.backgroundColor } guard let _ = toColor else { return } let correctedFrame = CGRect(x: center.x - CGFloat(startRadius), y: center.y - CGFloat(startRadius), width: CGFloat(startRadius) * 2, height: CGFloat(startRadius) * 2) let layer = CAShapeLayer() layer.removeAllAnimations() layer.bounds = correctedFrame layer.path = shape.bezierPathInRect(correctedFrame).cgPath layer.position = self.center layer.lineWidth = 0 layer.fillColor = toColor!.cgColor containerLayer.addSublayer(layer) let animation = CABasicAnimation(keyPath: "transform") animation.duration = TimeInterval(animationDuration) animation.fromValue = NSValue(caTransform3D: CATransform3DIdentity) let multiplicator = shape.scaleFactor(startRadius / 2, to: parent.frame) animation.toValue = NSValue(caTransform3D: CATransform3DMakeScale(multiplicator, multiplicator, 1)) animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseIn) animation.delegate = self animation.setValue(layer, forKey: "animationLayer") animation.fillMode = kCAFillModeForwards; animation.isRemovedOnCompletion = false layer.add(animation, forKey: animationIdentificator) isAnimating = true if let callback = animationDidStart { callback() } drawBorder() } func animationDidStop(_ anim: CAAnimation, finished flag: Bool) { CATransaction.begin() CATransaction.setDisableActions(true) containerLayer.backgroundColor = toColor?.cgColor CATransaction.commit() if let layer = anim.value(forKey: "animationLayer") { (layer as AnyObject).removeFromSuperlayer() isAnimating = false } if let callback = animationDidStop { callback() } } func drawBorder() { if showBorder && isOn { self.layer.borderWidth = 0.5 self.layer.borderColor = self.borderColor.cgColor; self.layer.cornerRadius = frame.size.height / 2; } else { self.layer.borderWidth = 0 } } }
a64ffcaf8facd9447270b1d114a95b92
35.977876
174
0.631806
false
false
false
false
blitzagency/amigo-swift
refs/heads/master
Amigo/ForeignKey.swift
mit
1
// // ForeignKey.swift // Amigo // // Created by Adam Venturella on 7/3/15. // Copyright © 2015 BLITZ. All rights reserved. // import Foundation public struct ForeignKey{ public let relatedColumn: Column public var column: Column! public init(_ relatedColumn: Column, column: Column){ self.relatedColumn = relatedColumn self.column = column } public init(_ relatedColumn: Column){ self.relatedColumn = relatedColumn } public init(_ table: Table){ self.relatedColumn = table.primaryKey! } public init(_ model: ORMModel){ self.relatedColumn = model.table.primaryKey! } public var relatedTable: Table{ return relatedColumn.table! } }
941dfda3d3b0c6f62688364deac066d8
20.085714
57
0.649932
false
false
false
false
amomchilov/ZipNsequence
refs/heads/master
Zip4Sequence.swift
apache-2.0
1
/// Creates a sequence of tuples built out of 4 underlying sequences. /// /// In the `Zip4Sequence` instance returned by this function, the elements of /// the *i*th tuple are the *i*th elements of each underlying sequence. The /// following example uses the `zip(_:_:)` function to iterate over an array /// of strings and a countable range at the same time: /// /// let words = ["one", "two", "three", "four"] /// let numbers = 1...4 /// /// for (word, number) in zip(words, numbers) { /// print("\(word): \(number)") /// } /// // Prints "one: 1" /// // Prints "two: 2 /// // Prints "three: 3" /// // Prints "four: 4" /// /// If the 4 sequences passed to `zip(_:_:_:_:)` are different lengths, the /// resulting sequence is the same length as the shortest sequence. In this /// example, the resulting array is the same length as `words`: /// /// let naturalNumbers = 1...Int.max /// let zipped = Array(zip(words, naturalNumbers)) /// // zipped == [("one", 1), ("two", 2), ("three", 3), ("four", 4)] /// /// - Parameters: /// - sequence1: The sequence or collection in position 1 of each tuple. /// - sequence2: The sequence or collection in position 2 of each tuple. /// - sequence3: The sequence or collection in position 3 of each tuple. /// - sequence4: The sequence or collection in position 4 of each tuple. /// - Returns: A sequence of tuple pairs, where the elements of each pair are /// corresponding elements of `sequence1` and `sequence2`. public func zip< Sequence1 : Sequence, Sequence2 : Sequence, Sequence3 : Sequence, Sequence4 : Sequence >( _ sequence1: Sequence1, _ sequence2: Sequence2, _ sequence3: Sequence3, _ sequence4: Sequence4 ) -> Zip4Sequence< Sequence1, Sequence2, Sequence3, Sequence4 > { return Zip4Sequence( _sequence1: sequence1, _sequence2: sequence2, _sequence3: sequence3, _sequence4: sequence4 ) } /// An iterator for `Zip4Sequence`. public struct Zip4Iterator< Iterator1 : IteratorProtocol, Iterator2 : IteratorProtocol, Iterator3 : IteratorProtocol, Iterator4 : IteratorProtocol > : IteratorProtocol { /// The type of element returned by `next()`. public typealias Element = ( Iterator1.Element, Iterator2.Element, Iterator3.Element, Iterator4.Element ) /// Creates an instance around the underlying iterators. internal init( _ iterator1: Iterator1, _ iterator2: Iterator2, _ iterator3: Iterator3, _ iterator4: Iterator4 ) { _baseStream1 = iterator1 _baseStream2 = iterator2 _baseStream3 = iterator3 _baseStream4 = iterator4 } /// 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`. public mutating func next() -> Element? { // The next() function needs to track if it has reached the end. If we // didn't, and the first sequence is longer than the second, then when we // have already exhausted the second sequence, on every subsequent call to // next() we would consume and discard one additional element from the // first sequence, even though next() had already returned nil. if _reachedEnd { return nil } guard let element1 = _baseStream1.next(), let element2 = _baseStream2.next(), let element3 = _baseStream3.next(), let element4 = _baseStream4.next() else { _reachedEnd = true return nil } return ( element1, element2, element3, element4 ) } internal var _baseStream1: Iterator1 internal var _baseStream2: Iterator2 internal var _baseStream3: Iterator3 internal var _baseStream4: Iterator4 internal var _reachedEnd: Bool = false } /// A sequence of pairs built out of two underlying sequences. /// /// In a `Zip4Sequence` instance, the elements of the *i*th pair are the *i*th /// elements of each underlying sequence. To create a `Zip4Sequence` instance, /// use the `zip(_:_:_:_:)` function. /// /// The following example uses the `zip(_:_:)` function to iterate over an /// array of strings and a countable range at the same time: /// /// let words = ["one", "two", "three", "four"] /// let numbers = 1...4 /// /// for (word, number) in zip(words, numbers) { /// print("\(word): \(number)") /// } /// // Prints "one: 1" /// // Prints "two: 2 /// // Prints "three: 3" /// // Prints "four: 4" /// /// - SeeAlso: `zip(_:_:_:_:)` public struct Zip4Sequence< Sequence1 : Sequence, Sequence2 : Sequence, Sequence3 : Sequence, Sequence4 : Sequence > : Sequence { public typealias Stream1 = Sequence1.Iterator public typealias Stream2 = Sequence2.Iterator public typealias Stream3 = Sequence3.Iterator public typealias Stream4 = Sequence4.Iterator /// A type whose instances can produce the elements of this /// sequence, in order. public typealias Iterator = Zip4Iterator< Stream1, Stream2, Stream3, Stream4 > @available(*, unavailable, renamed: "Iterator") public typealias Generator = Iterator /// Creates an instance that makes pairs of elements from `sequence1` and /// `sequence2`. public // @testable init( _sequence1 sequence1: Sequence1, _sequence2 sequence2: Sequence2, _sequence3 sequence3: Sequence3, _sequence4 sequence4: Sequence4 ) { _sequence1 = sequence1 _sequence2 = sequence2 _sequence3 = sequence3 _sequence4 = sequence4 } /// Returns an iterator over the elements of this sequence. public func makeIterator() -> Iterator { return Iterator( _sequence1.makeIterator(), _sequence2.makeIterator(), _sequence3.makeIterator(), _sequence4.makeIterator() ) } internal let _sequence1: Sequence1 internal let _sequence2: Sequence2 internal let _sequence3: Sequence3 internal let _sequence4: Sequence4 }
245a6b900c7d3439adef6a2c8eb779bb
28.428571
78
0.653273
false
false
false
false
yl-github/YLDYZB
refs/heads/master
YLDouYuZB/YLDouYuZB/Classes/Main/Model/YLAnchorModel.swift
mit
1
// // YLAnchorModel.swift // YLDouYuZB // // Created by yl on 16/10/10. // Copyright © 2016年 yl. All rights reserved. // import UIKit class YLAnchorModel: NSObject { /** 房间号 */ var room_id : Int = 0 /** 房间图片对应的URLString */ var vertical_src : String = "" /** isVertical判断是手机直播还是电脑直播 0代表是电脑直播,1代表是手机直播*/ var isVertical : Int = 0 /** room_name 房间名称 */ var room_name : String = "" /** nickname 主播昵称 */ var nickname : String = "" /** online 观看人数 */ var online : Int = 0 /** 主播所在城市 */ var anchor_city : String = ""; // 构造函数 init(dict : [String : Any]) { super.init(); setValuesForKeys(dict); } override func setValue(_ value: Any?, forUndefinedKey key: String) {} }
6e7622143b38d2c2a9f9fe85bddb0e51
17.906977
73
0.531365
false
false
false
false
MikotoZero/SwiftyJSON
refs/heads/master
Source/SwiftyJSON/SwiftyJSON.swift
mit
1
// SwiftyJSON.swift // // Copyright (c) 2014 - 2017 Ruoyu Fu, Pinglin Tang // // 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 // MARK: - Error // swiftlint:disable line_length public enum SwiftyJSONError: Int, Swift.Error { case unsupportedType = 999 case indexOutOfBounds = 900 case elementTooDeep = 902 case wrongType = 901 case notExist = 500 case invalidJSON = 490 } extension SwiftyJSONError: CustomNSError { /// return the error domain of SwiftyJSONError public static var errorDomain: String { return "com.swiftyjson.SwiftyJSON" } /// return the error code of SwiftyJSONError public var errorCode: Int { return self.rawValue } /// return the userInfo of SwiftyJSONError public var errorUserInfo: [String: Any] { switch self { case .unsupportedType: return [NSLocalizedDescriptionKey: "It is an unsupported type."] case .indexOutOfBounds: return [NSLocalizedDescriptionKey: "Array Index is out of bounds."] case .wrongType: return [NSLocalizedDescriptionKey: "Couldn't merge, because the JSONs differ in type on top level."] case .notExist: return [NSLocalizedDescriptionKey: "Dictionary key does not exist."] case .invalidJSON: return [NSLocalizedDescriptionKey: "JSON is invalid."] case .elementTooDeep: return [NSLocalizedDescriptionKey: "Element too deep. Increase maxObjectDepth and make sure there is no reference loop."] } } } // MARK: - JSON Content /// Store raw value of JSON object private indirect enum Content { case bool(Bool) case number(NSNumber) case string(String) case array([Any]) case dictionary([String: Any]) case null case unknown } extension Content { var type: Type { switch self { case .bool: return .bool case .number: return .number case .string: return .string case .array: return .array case .dictionary: return .dictionary case .null: return .null case .unknown: return .unknown } } var rawValue: Any { switch self { case .bool(let bool): return bool case .number(let number): return number case .string(let string): return string case .array(let array): return array case .dictionary(let dictionary): return dictionary case .null, .unknown: return NSNull() } } } extension Content { init(_ rawValue: Any) { switch unwrap(rawValue) { case let value as NSNumber: if value.isBool { self = .bool(value.boolValue) } else { self = .number(value) } case let value as String: self = .string(value) case let value as [Any]: self = .array(value) case let value as [String: Any]: self = .dictionary(value) case _ as NSNull: self = .null case nil: self = .null default: self = .unknown } } } /// Private method to unwarp an object recursively private func unwrap(_ object: Any) -> Any { switch object { case let json as JSON: return unwrap(json.object) case let array as [Any]: return array.map(unwrap) case let dictionary as [String: Any]: return dictionary.mapValues(unwrap) default: return object } } // MARK: - JSON Type /** JSON's type definitions. See http://www.json.org */ public enum Type: Int { case number case string case bool case array case dictionary case null case unknown } // MARK: - JSON Base public struct JSON { /// Private content private var content: Content = .null /// Error in JSON, fileprivate setter public private(set) var error: SwiftyJSONError? /// JSON type, fileprivate setter public var type: Type { content.type } /// Object in JSON public var object: Any { get { content.rawValue } set { content = Content(newValue) error = content.type == .unknown ? SwiftyJSONError.unsupportedType : nil } } public static var null: JSON = .init(content: .null, error: nil) } // MARK: - Constructor extension JSON { /** Creates a JSON using the data. - parameter data: The NSData used to convert to json.Top level object in data is an NSArray or NSDictionary - parameter opt: The JSON serialization reading options. `[]` by default. - returns: The created JSON */ public init(data: Data, options opt: JSONSerialization.ReadingOptions = []) throws { let object: Any = try JSONSerialization.jsonObject(with: data, options: opt) self.init(jsonObject: object) } /** Creates a JSON object - note: this does not parse a `String` into JSON, instead use `init(parseJSON: String)` - parameter object: the object - returns: the created JSON object */ public init(_ object: Any) { switch object { case let object as Data: do { try self.init(data: object) } catch { self.init(jsonObject: NSNull()) } case let json as JSON: self = json self.error = nil default: self.init(jsonObject: object) } } /** Parses the JSON string into a JSON object - parameter jsonString: the JSON string - returns: the created JSON object */ public init(parseJSON jsonString: String) { if let data = jsonString.data(using: .utf8) { self.init(data) } else { self = .null } } /** Creates a JSON using the object. - parameter jsonObject: The object must have the following properties: All objects are NSString/String, NSNumber/Int/Float/Double/Bool, NSArray/Array, NSDictionary/Dictionary, or NSNull; All dictionary keys are NSStrings/String; NSNumbers are not NaN or infinity. - returns: The created JSON */ private init(jsonObject: Any) { self.object = jsonObject } } // MARK: - Merge extension JSON { /** Merges another JSON into this JSON, whereas primitive values which are not present in this JSON are getting added, present values getting overwritten, array values getting appended and nested JSONs getting merged the same way. - parameter other: The JSON which gets merged into this JSON - throws `ErrorWrongType` if the other JSONs differs in type on the top level. */ public mutating func merge(with other: JSON) throws { try self.merge(with: other, typecheck: true) } /** Merges another JSON into this JSON and returns a new JSON, whereas primitive values which are not present in this JSON are getting added, present values getting overwritten, array values getting appended and nested JSONS getting merged the same way. - parameter other: The JSON which gets merged into this JSON - throws `ErrorWrongType` if the other JSONs differs in type on the top level. - returns: New merged JSON */ public func merged(with other: JSON) throws -> JSON { var merged = self try merged.merge(with: other, typecheck: true) return merged } /** Private woker function which does the actual merging Typecheck is set to true for the first recursion level to prevent total override of the source JSON */ private mutating func merge(with other: JSON, typecheck: Bool) throws { if type == other.type { switch type { case .dictionary: for (key, _) in other { try self[key].merge(with: other[key], typecheck: false) } case .array: self = JSON((arrayObject ?? []) + (other.arrayObject ?? [])) default: self = other } } else { if typecheck { throw SwiftyJSONError.wrongType } else { self = other } } } } // MARK: - Index public enum Index<T: Any>: Comparable { case array(Int) case dictionary(DictionaryIndex<String, T>) case null static public func == (lhs: Index, rhs: Index) -> Bool { switch (lhs, rhs) { case (.array(let left), .array(let right)): return left == right case (.dictionary(let left), .dictionary(let right)): return left == right case (.null, .null): return true default: return false } } static public func < (lhs: Index, rhs: Index) -> Bool { switch (lhs, rhs) { case (.array(let left), .array(let right)): return left < right case (.dictionary(let left), .dictionary(let right)): return left < right default: return false } } static public func <= (lhs: Index, rhs: Index) -> Bool { switch (lhs, rhs) { case (.array(let left), .array(let right)): return left <= right case (.dictionary(let left), .dictionary(let right)): return left <= right case (.null, .null): return true default: return false } } static public func >= (lhs: Index, rhs: Index) -> Bool { switch (lhs, rhs) { case (.array(let left), .array(let right)): return left >= right case (.dictionary(let left), .dictionary(let right)): return left >= right case (.null, .null): return true default: return false } } } public typealias JSONIndex = Index<JSON> public typealias JSONRawIndex = Index<Any> extension JSON: Swift.Collection { public typealias Index = JSONRawIndex public var startIndex: Index { switch content { case .array(let arr): return .array(arr.startIndex) case .dictionary(let dic): return .dictionary(dic.startIndex) default: return .null } } public var endIndex: Index { switch content { case .array(let arr): return .array(arr.endIndex) case .dictionary(let dic): return .dictionary(dic.endIndex) default: return .null } } public func index(after i: Index) -> Index { switch (content, i) { case (.array(let value), .array(let idx)): return .array(value.index(after: idx)) case (.dictionary(let value), .dictionary(let idx)): return .dictionary(value.index(after: idx)) default: return .null } } public subscript (position: Index) -> (String, JSON) { switch (content, position) { case (.array(let value), .array(let idx)): return ("\(idx)", JSON(value[idx])) case (.dictionary(let value), .dictionary(let idx)): return (value[idx].key, JSON(value[idx].value)) default: return ("", JSON.null) } } } // MARK: - Subscript /** * To mark both String and Int can be used in subscript. */ public enum JSONKey { case index(Int) case key(String) } public protocol JSONSubscriptType { var jsonKey: JSONKey { get } } extension Int: JSONSubscriptType { public var jsonKey: JSONKey { return JSONKey.index(self) } } extension String: JSONSubscriptType { public var jsonKey: JSONKey { return JSONKey.key(self) } } extension JSON { /// If `type` is `.array`, return json whose object is `array[index]`, otherwise return null json with error. private subscript(index index: Int) -> JSON { get { switch content { case .array(let value) where value.indices.contains(index): return JSON(value[index]) case .array: return .init(content: .null, error: .indexOutOfBounds) default: return .init(content: .null, error: self.error ?? .wrongType) } } set { guard case .array(let rawArray) = content, rawArray.indices.contains(index), newValue.error == nil else { return } var copy = rawArray copy[index] = newValue.object content = .array(copy) } } /// If `type` is `.dictionary`, return json whose object is `dictionary[key]` , otherwise return null json with error. private subscript(key key: String) -> JSON { get { switch content { case .dictionary(let value): if let o = value[key] { return JSON(o) } else { return .init(content: .null, error: .notExist) } default: return .init(content: .null, error: self.error ?? SwiftyJSONError.wrongType) } } set { guard newValue.error == nil, case .dictionary(let rawDictionary) = content else { return } var copy = rawDictionary copy[key] = newValue.object content = .dictionary(copy) } } /// If `sub` is `Int`, return `subscript(index:)`; If `sub` is `String`, return `subscript(key:)`. private subscript(sub sub: JSONSubscriptType) -> JSON { get { switch sub.jsonKey { case .index(let index): return self[index: index] case .key(let key): return self[key: key] } } set { switch sub.jsonKey { case .index(let index): self[index: index] = newValue case .key(let key): self[key: key] = newValue } } } /** Find a json in the complex data structures by using array of Int and/or String as path. Example: ``` let json = JSON[data] let path = [9,"list","person","name"] let name = json[path] ``` The same as: let name = json[9]["list"]["person"]["name"] - parameter path: The target json's path. - returns: Return a json found by the path or a null json with error */ public subscript(path: [JSONSubscriptType]) -> JSON { get { return path.reduce(self) { $0[sub: $1] } } set { switch path.count { case 0: return case 1: self[sub: path[0]].object = newValue.object default: var aPath = path aPath.remove(at: 0) var nextJSON = self[sub: path[0]] nextJSON[aPath] = newValue self[sub: path[0]] = nextJSON } } } /** Find a json in the complex data structures by using array of Int and/or String as path. - parameter path: The target json's path. Example: let name = json[9,"list","person","name"] The same as: let name = json[9]["list"]["person"]["name"] - returns: Return a json found by the path or a null json with error */ public subscript(path: JSONSubscriptType...) -> JSON { get { return self[path] } set { self[path] = newValue } } } // MARK: - LiteralConvertible extension JSON: Swift.ExpressibleByStringLiteral { public init(stringLiteral value: StringLiteralType) { self.init(value) } public init(extendedGraphemeClusterLiteral value: StringLiteralType) { self.init(value) } public init(unicodeScalarLiteral value: StringLiteralType) { self.init(value) } } extension JSON: Swift.ExpressibleByIntegerLiteral { public init(integerLiteral value: IntegerLiteralType) { self.init(value) } } extension JSON: Swift.ExpressibleByBooleanLiteral { public init(booleanLiteral value: BooleanLiteralType) { self.init(value) } } extension JSON: Swift.ExpressibleByFloatLiteral { public init(floatLiteral value: FloatLiteralType) { self.init(value) } } extension JSON: Swift.ExpressibleByDictionaryLiteral { public init(dictionaryLiteral elements: (String, Any)...) { let dictionary = elements.reduce(into: [String: Any](), { $0[$1.0] = $1.1}) self.init(dictionary) } } extension JSON: Swift.ExpressibleByArrayLiteral { public init(arrayLiteral elements: Any...) { self.init(elements) } } // MARK: - Raw extension JSON: Swift.RawRepresentable { public init?(rawValue: Any) { let json = JSON(rawValue) guard json.type != .unknown else { return nil } self = json } public var rawValue: Any { return object } public func rawData(options opt: JSONSerialization.WritingOptions = JSONSerialization.WritingOptions(rawValue: 0)) throws -> Data { guard JSONSerialization.isValidJSONObject(object) else { throw SwiftyJSONError.invalidJSON } return try JSONSerialization.data(withJSONObject: object, options: opt) } public func rawString(_ encoding: String.Encoding = .utf8, options opt: JSONSerialization.WritingOptions = .prettyPrinted) -> String? { do { return try _rawString(encoding, options: [.jsonSerialization: opt]) } catch { print("Could not serialize object to JSON because:", error.localizedDescription) return nil } } public func rawString(_ options: [writingOptionsKeys: Any]) -> String? { let encoding = options[.encoding] as? String.Encoding ?? String.Encoding.utf8 let maxObjectDepth = options[.maxObjextDepth] as? Int ?? 10 do { return try _rawString(encoding, options: options, maxObjectDepth: maxObjectDepth) } catch { print("Could not serialize object to JSON because:", error.localizedDescription) return nil } } private func _rawString(_ encoding: String.Encoding = .utf8, options: [writingOptionsKeys: Any], maxObjectDepth: Int = 10) throws -> String? { guard maxObjectDepth > 0 else { throw SwiftyJSONError.invalidJSON } switch content { case .dictionary: do { if !(options[.castNilToNSNull] as? Bool ?? false) { let jsonOption = options[.jsonSerialization] as? JSONSerialization.WritingOptions ?? JSONSerialization.WritingOptions.prettyPrinted let data = try rawData(options: jsonOption) return String(data: data, encoding: encoding) } guard let dict = object as? [String: Any?] else { return nil } let body = try dict.keys.map { key throws -> String in guard let value = dict[key] else { return "\"\(key)\": null" } guard let unwrappedValue = value else { return "\"\(key)\": null" } let nestedValue = JSON(unwrappedValue) guard let nestedString = try nestedValue._rawString(encoding, options: options, maxObjectDepth: maxObjectDepth - 1) else { throw SwiftyJSONError.elementTooDeep } if nestedValue.type == .string { return "\"\(key)\": \"\(nestedString.replacingOccurrences(of: "\\", with: "\\\\").replacingOccurrences(of: "\"", with: "\\\""))\"" } else { return "\"\(key)\": \(nestedString)" } } return "{\(body.joined(separator: ","))}" } catch _ { return nil } case .array: do { if !(options[.castNilToNSNull] as? Bool ?? false) { let jsonOption = options[.jsonSerialization] as? JSONSerialization.WritingOptions ?? JSONSerialization.WritingOptions.prettyPrinted let data = try rawData(options: jsonOption) return String(data: data, encoding: encoding) } guard let array = object as? [Any?] else { return nil } let body = try array.map { value throws -> String in guard let unwrappedValue = value else { return "null" } let nestedValue = JSON(unwrappedValue) guard let nestedString = try nestedValue._rawString(encoding, options: options, maxObjectDepth: maxObjectDepth - 1) else { throw SwiftyJSONError.invalidJSON } if nestedValue.type == .string { return "\"\(nestedString.replacingOccurrences(of: "\\", with: "\\\\").replacingOccurrences(of: "\"", with: "\\\""))\"" } else { return nestedString } } return "[\(body.joined(separator: ","))]" } catch _ { return nil } case .string(let value): return value case .number(let value): return value.stringValue case .bool(let value): return value.description case .null: return "null" default: return nil } } } // MARK: - Printable, DebugPrintable extension JSON: Swift.CustomStringConvertible, Swift.CustomDebugStringConvertible { public var description: String { return rawString(options: .prettyPrinted) ?? "unknown" } public var debugDescription: String { return description } } // MARK: - Array extension JSON { //Optional [JSON] public var array: [JSON]? { guard case .array(let value) = content else { return nil } return value.map(JSON.init(_:)) } //Non-optional [JSON] public var arrayValue: [JSON] { return self.array ?? [] } //Optional [Any] public var arrayObject: [Any]? { get { guard case .array(let value) = content else { return nil } return value } set { self = .init(content: newValue != nil ? .array(newValue!) : .null, error: nil) } } } // MARK: - Dictionary extension JSON { //Optional [String : JSON] public var dictionary: [String: JSON]? { guard case .dictionary(let value) = content else { return nil } return value.mapValues(JSON.init(_:)) } //Non-optional [String : JSON] public var dictionaryValue: [String: JSON] { return dictionary ?? [:] } //Optional [String : Any] public var dictionaryObject: [String: Any]? { get { guard case .dictionary(let value) = content else { return nil } return value } set { self = .init(content: newValue != nil ? .dictionary(newValue!) : .null, error: nil) } } } // MARK: - Bool extension JSON { // : Swift.Bool //Optional bool public var bool: Bool? { get { guard case .bool(let value) = content else { return nil } return value } set { self = .init(content: newValue != nil ? .bool(newValue!) : .null, error: nil) } } //Non-optional bool public var boolValue: Bool { get { switch content { case .bool(let value): return value case .number(let value): return value.boolValue case .string(let value): return ["true", "y", "t", "yes", "1"].contains { value.caseInsensitiveCompare($0) == .orderedSame } default: return false } } set { self = .init(content: .bool(newValue), error: nil) } } } // MARK: - String extension JSON { //Optional string public var string: String? { get { guard case .string(let value) = content else { return nil } return value } set { self = .init(content: newValue != nil ? .string(newValue!) : .null, error: nil) } } //Non-optional string public var stringValue: String { get { switch content { case .string(let value): return value case .number(let value): return value.stringValue case .bool(let value): return String(value) default: return "" } } set { self = .init(content: .string(newValue), error: nil) } } } // MARK: - Number extension JSON { //Optional number public var number: NSNumber? { get { switch content { case .number(let value): return value case .bool(let value): return NSNumber(value: value ? 1 : 0) default: return nil } } set { self = .init(content: newValue != nil ? .number(newValue!) : .null, error: nil) } } //Non-optional number public var numberValue: NSNumber { get { switch content { case .string(let value): let decimal = NSDecimalNumber(string: value) return decimal == .notANumber ? .zero : decimal case .number(let value): return value case .bool(let value): return NSNumber(value: value ? 1 : 0) default: return NSNumber(value: 0.0) } } set { self = .init(content: .number(newValue), error: nil) } } } // MARK: - Null extension JSON { public var null: NSNull? { set { self = .null } get { switch content { case .null: return NSNull() default: return nil } } } public func exists() -> Bool { if let errorValue = error, (400...1000).contains(errorValue.errorCode) { return false } return true } } // MARK: - URL extension JSON { //Optional URL public var url: URL? { get { switch content { case .string(let value): // Check for existing percent escapes first to prevent double-escaping of % character if value.range(of: "%[0-9A-Fa-f]{2}", options: .regularExpression, range: nil, locale: nil) != nil { return Foundation.URL(string: value) } else if let encodedString_ = value.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed) { // We have to use `Foundation.URL` otherwise it conflicts with the variable name. return Foundation.URL(string: encodedString_) } else { return nil } default: return nil } } set { self = .init(content: newValue != nil ? .string(newValue!.absoluteString) : .null, error: nil) } } } // MARK: - Int, Double, Float, Int8, Int16, Int32, Int64 extension JSON { public var double: Double? { get { number?.doubleValue } set { number = newValue.map(NSNumber.init(value:)) } } public var doubleValue: Double { get { numberValue.doubleValue } set { numberValue = NSNumber(value: newValue) } } public var float: Float? { get { number?.floatValue } set { number = newValue.map(NSNumber.init(value:)) } } public var floatValue: Float { get { numberValue.floatValue } set { numberValue = NSNumber(value: newValue) } } public var int: Int? { get { number?.intValue } set { number = newValue.map(NSNumber.init(value:)) } } public var intValue: Int { get { numberValue.intValue } set { numberValue = NSNumber(value: newValue) } } public var uInt: UInt? { get { number?.uintValue } set { number = newValue.map(NSNumber.init(value:)) } } public var uIntValue: UInt { get { numberValue.uintValue } set { numberValue = NSNumber(value: newValue) } } public var int8: Int8? { get { number?.int8Value } set { number = newValue.map(NSNumber.init(value:)) } } public var int8Value: Int8 { get { numberValue.int8Value } set { numberValue = NSNumber(value: newValue) } } public var uInt8: UInt8? { get { number?.uint8Value } set { number = newValue.map(NSNumber.init(value:)) } } public var uInt8Value: UInt8 { get { numberValue.uint8Value } set { numberValue = NSNumber(value: newValue) } } public var int16: Int16? { get { number?.int16Value } set { number = newValue.map(NSNumber.init(value:)) } } public var int16Value: Int16 { get { numberValue.int16Value } set { numberValue = NSNumber(value: newValue) } } public var uInt16: UInt16? { get { number?.uint16Value } set { number = newValue.map(NSNumber.init(value:)) } } public var uInt16Value: UInt16 { get { numberValue.uint16Value } set { numberValue = NSNumber(value: newValue) } } public var int32: Int32? { get { number?.int32Value } set { number = newValue.map(NSNumber.init(value:)) } } public var int32Value: Int32 { get { numberValue.int32Value } set { numberValue = NSNumber(value: newValue) } } public var uInt32: UInt32? { get { number?.uint32Value } set { number = newValue.map(NSNumber.init(value:)) } } public var uInt32Value: UInt32 { get { numberValue.uint32Value } set { numberValue = NSNumber(value: newValue) } } public var int64: Int64? { get { number?.int64Value } set { number = newValue.map(NSNumber.init(value:)) } } public var int64Value: Int64 { get { numberValue.int64Value } set { numberValue = NSNumber(value: newValue) } } public var uInt64: UInt64? { get { number?.uint64Value } set { number = newValue.map(NSNumber.init(value:)) } } public var uInt64Value: UInt64 { get { numberValue.uint64Value } set { numberValue = NSNumber(value: newValue) } } } // MARK: - Comparable extension Content: Comparable { static func == (lhs: Content, rhs: Content) -> Bool { switch (lhs, rhs) { case let (.number(l), .number(r)): return l == r case let (.string(l), .string(r)): return l == r case let (.bool(l), .bool(r)): return l == r case let (.array(l), .array(r)): return l as NSArray == r as NSArray case let (.dictionary(l), .dictionary(r)): return l as NSDictionary == r as NSDictionary case (.null, .null): return true default: return false } } static func <= (lhs: Content, rhs: Content) -> Bool { switch (lhs, rhs) { case let (.number(l), .number(r)): return l <= r case let (.string(l), .string(r)): return l <= r case let (.bool(l), .bool(r)): return l == r case let (.array(l), .array(r)): return l as NSArray == r as NSArray case let (.dictionary(l), .dictionary(r)): return l as NSDictionary == r as NSDictionary case (.null, .null): return true default: return false } } static func >= (lhs: Content, rhs: Content) -> Bool { switch (lhs, rhs) { case let (.number(l), .number(r)): return l >= r case let (.string(l), .string(r)): return l >= r case let (.bool(l), .bool(r)): return l == r case let (.array(l), .array(r)): return l as NSArray == r as NSArray case let (.dictionary(l), .dictionary(r)): return l as NSDictionary == r as NSDictionary case (.null, .null): return true default: return false } } static func > (lhs: Content, rhs: Content) -> Bool { switch (lhs, rhs) { case let (.number(l), .number(r)): return l > r case let (.string(l), .string(r)): return l > r default: return false } } static func < (lhs: Content, rhs: Content) -> Bool { switch (lhs, rhs) { case let (.number(l), .number(r)): return l < r case let (.string(l), .string(r)): return l < r default: return false } } } extension JSON: Swift.Comparable { public static func == (lhs: JSON, rhs: JSON) -> Bool { return lhs.content == rhs.content } public static func <= (lhs: JSON, rhs: JSON) -> Bool { return lhs.content <= rhs.content } public static func >= (lhs: JSON, rhs: JSON) -> Bool { return lhs.content >= rhs.content } public static func < (lhs: JSON, rhs: JSON) -> Bool { return lhs.content < rhs.content } public static func > (lhs: JSON, rhs: JSON) -> Bool { return lhs.content > rhs.content } } private let trueNumber = NSNumber(value: true) private let falseNumber = NSNumber(value: false) private let trueObjCType = String(cString: trueNumber.objCType) private let falseObjCType = String(cString: falseNumber.objCType) // MARK: - NSNumber: Comparable private extension NSNumber { var isBool: Bool { let objCType = String(cString: self.objCType) if (self.compare(trueNumber) == .orderedSame && objCType == trueObjCType) || (self.compare(falseNumber) == .orderedSame && objCType == falseObjCType) { return true } else { return false } } } private func == (lhs: NSNumber, rhs: NSNumber) -> Bool { switch (lhs.isBool, rhs.isBool) { case (false, true): return false case (true, false): return false default: return lhs.compare(rhs) == .orderedSame } } private func != (lhs: NSNumber, rhs: NSNumber) -> Bool { return !(lhs == rhs) } private func < (lhs: NSNumber, rhs: NSNumber) -> Bool { switch (lhs.isBool, rhs.isBool) { case (false, true): return false case (true, false): return false default: return lhs.compare(rhs) == .orderedAscending } } private func > (lhs: NSNumber, rhs: NSNumber) -> Bool { switch (lhs.isBool, rhs.isBool) { case (false, true): return false case (true, false): return false default: return lhs.compare(rhs) == ComparisonResult.orderedDescending } } private func <= (lhs: NSNumber, rhs: NSNumber) -> Bool { switch (lhs.isBool, rhs.isBool) { case (false, true): return false case (true, false): return false default: return lhs.compare(rhs) != .orderedDescending } } private func >= (lhs: NSNumber, rhs: NSNumber) -> Bool { switch (lhs.isBool, rhs.isBool) { case (false, true): return false case (true, false): return false default: return lhs.compare(rhs) != .orderedAscending } } public enum writingOptionsKeys { case jsonSerialization case castNilToNSNull case maxObjextDepth case encoding } // MARK: - JSON: Codable extension JSON: Codable { public init(from decoder: Decoder) throws { guard let container = try? decoder.singleValueContainer(), !container.decodeNil() else { self = .null return } if let value = try? container.decode(Bool.self) { self = .init(content: .bool(value), error: nil) } else if let value = try? container.decode(Int.self) { self = .init(content: .number(value as NSNumber), error: nil) } else if let value = try? container.decode(Int8.self) { self = .init(content: .number(value as NSNumber), error: nil) } else if let value = try? container.decode(Int16.self) { self = .init(content: .number(value as NSNumber), error: nil) } else if let value = try? container.decode(Int32.self) { self = .init(content: .number(value as NSNumber), error: nil) } else if let value = try? container.decode(Int64.self) { self = .init(content: .number(value as NSNumber), error: nil) } else if let value = try? container.decode(UInt.self) { self = .init(content: .number(value as NSNumber), error: nil) } else if let value = try? container.decode(UInt8.self) { self = .init(content: .number(value as NSNumber), error: nil) } else if let value = try? container.decode(UInt16.self) { self = .init(content: .number(value as NSNumber), error: nil) } else if let value = try? container.decode(UInt32.self) { self = .init(content: .number(value as NSNumber), error: nil) } else if let value = try? container.decode(UInt64.self) { self = .init(content: .number(value as NSNumber), error: nil) } else if let value = try? container.decode(Double.self) { self = .init(content: .number(value as NSNumber), error: nil) } else if let value = try? container.decode(String.self) { self = .init(content: .string(value), error: nil) } else if let value = try? container.decode([JSON].self) { self = .init(value) } else if let value = try? container.decode([String: JSON].self) { self = .init(value) } else { self = .null } } public func encode(to encoder: Encoder) throws { var container = encoder.singleValueContainer() if object is NSNull { try container.encodeNil() return } switch object { case let intValue as Int: try container.encode(intValue) case let int8Value as Int8: try container.encode(int8Value) case let int32Value as Int32: try container.encode(int32Value) case let int64Value as Int64: try container.encode(int64Value) case let uintValue as UInt: try container.encode(uintValue) case let uint8Value as UInt8: try container.encode(uint8Value) case let uint16Value as UInt16: try container.encode(uint16Value) case let uint32Value as UInt32: try container.encode(uint32Value) case let uint64Value as UInt64: try container.encode(uint64Value) case let doubleValue as Double: try container.encode(doubleValue) case let boolValue as Bool: try container.encode(boolValue) case let stringValue as String: try container.encode(stringValue) case is [Any]: let jsonValueArray = array ?? [] try container.encode(jsonValueArray) case is [String: Any]: let jsonValueDictValue = dictionary ?? [:] try container.encode(jsonValueDictValue) default: break } } }
9ac910b52874b861ae9715f2678c2854
30.159566
266
0.573595
false
false
false
false
ruter/Strap-in-Swift
refs/heads/master
WordScramble/WordScramble/MasterViewController.swift
apache-2.0
1
// // MasterViewController.swift // WordScramble // // Created by Ruter on 16/4/15. // Copyright © 2016年 Ruter. All rights reserved. // import UIKit import GameplayKit class MasterViewController: UITableViewController { var allWords = [String]() var objects = [String]() override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .Add, target: self, action: #selector(promptForAnswer)) if let startWordsPath = NSBundle.mainBundle().pathForResource("start", ofType: "txt") { // I can't find this method /*String(contentsOfFile:, usedEncoding:)*/, but it works!?? if let startWords = try? String(contentsOfFile: startWordsPath, usedEncoding: nil) { allWords = startWords.componentsSeparatedByString("\n") } } else { allWords = ["silkworm"] } startGame() } func wordIsPossible(word: String) -> Bool { var tempWord = title!.lowercaseString for letter in word.characters { if let pos = tempWord.rangeOfString(String(letter)) { tempWord.removeAtIndex(pos.startIndex) } else { return false } } return true } func wordIsOriginal(word: String) -> Bool { return !objects.contains(word) } func wordIsReal(word: String) -> Bool { let checker = UITextChecker() let range = NSMakeRange(0, word.characters.count) let misspelledRange = checker.rangeOfMisspelledWordInString(word, range: range, startingAt: 0, wrap: false, language: "en") return misspelledRange.location == NSNotFound } func submitAnswer(answer: String) { let lowerAnswer = answer.lowercaseString let errorTitle: String let errorMessage: String if wordIsPossible(lowerAnswer) { if wordIsOriginal(lowerAnswer) { if wordIsReal(lowerAnswer) { objects.insert(answer, atIndex: 0) let indexPath = NSIndexPath(forRow: 0, inSection: 0) tableView.insertRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic) return } else { errorTitle = "Word not recognized" errorMessage = "You can't just make them up, you know!" } } else { errorTitle = "Word used already" errorMessage = "Be more original!" } } else { errorTitle = "Word not possible" errorMessage = "You can't spell that word from '\(title!.lowercaseString)'!" } let ac = UIAlertController(title: errorTitle, message: errorMessage, preferredStyle: .Alert) ac.addAction(UIAlertAction(title: "OK", style: .Default, handler: nil)) presentViewController(ac, animated: true, completion: nil) } func promptForAnswer() { let ac = UIAlertController(title: "Enter answer", message: nil, preferredStyle: .Alert) ac.addTextFieldWithConfigurationHandler(nil) let submitAction = UIAlertAction(title: "Submit", style: .Default) { [unowned self, ac] _ in let answer = ac.textFields![0] self.submitAnswer(answer.text!) } ac.addAction(submitAction) presentViewController(ac, animated: true, completion: nil) } func startGame() { allWords = GKRandomSource.sharedRandom().arrayByShufflingObjectsInArray(allWords) as! [String] title = allWords[0] objects.removeAll(keepCapacity: true) tableView.reloadData() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table View override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return objects.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) let object = objects[indexPath.row] cell.textLabel!.text = object return cell } }
a6da257f8bcdd3b2ae83060eab6602b9
29.434783
132
0.673571
false
false
false
false
romankisil/eqMac2
refs/heads/master
native/app/Source/Audio/Effects/Equalizers/Basic/BasicEqualizerState.swift
mit
1
// // BasicEqualizerState.swift // eqMac // // Created by Roman Kisil on 30/06/2018. // Copyright © 2018 Roman Kisil. All rights reserved. // import Foundation import ReSwift import SwiftyUserDefaults struct BasicEqualizerState: State { var selectedPresetId: String = "flat" var transition: Bool = false } enum BasicEqualizerAction: Action { case selectPreset(String, Bool) } func BasicEqualizerStateReducer(action: Action, state: BasicEqualizerState?) -> BasicEqualizerState { var state = state ?? BasicEqualizerState() switch action as? BasicEqualizerAction { case .selectPreset(let presetId, let transition)?: state.selectedPresetId = presetId state.transition = transition case .none: break } return state }
bc809afc490e2e709a76fdca29208262
20.628571
101
0.735799
false
false
false
false
WeefJim/JYJDrawerContainerController
refs/heads/master
JYJDrawerContainerController/JYJDrawerContainerController/CenterViewController.swift
apache-2.0
2
// // CenterViewController.swift // JYJDrawerContainerController // // Created by Mr.Jim on 6/8/15. // Copyright (c) 2015 Jim. All rights reserved. // import UIKit class CenterViewController: UIViewController { var maximunOffsetRatioLabel: UILabel! var minimumScaleRatioLabel: UILabel! var animationDurationLabel: UILabel! override func viewDidLoad() { super.viewDidLoad() self.navigationItem.title = "Home" self.navigationItem.leftBarButtonItem = UIBarButtonItem(image: UIImage(named: "baritem_menu"), style: .Plain, target: self, action: "leftBarButtonDidTap") maximunOffsetRatioLabel = UILabel() maximunOffsetRatioLabel.text = "MaximunOffsetRatio = 0.78" maximunOffsetRatioLabel.translatesAutoresizingMaskIntoConstraints = false self.view.addSubview(maximunOffsetRatioLabel) let maximunOffsetRatioSlider = UISlider() maximunOffsetRatioSlider.maximumValue = 1 maximunOffsetRatioSlider.value = 0.78 maximunOffsetRatioSlider.addTarget(self, action: "maximunOffsetRatioSliderDidChangeValue:", forControlEvents: .ValueChanged) maximunOffsetRatioSlider.translatesAutoresizingMaskIntoConstraints = false self.view.addSubview(maximunOffsetRatioSlider) minimumScaleRatioLabel = UILabel() minimumScaleRatioLabel.text = "MinimumScaleRatio = 0.80" minimumScaleRatioLabel.translatesAutoresizingMaskIntoConstraints = false self.view.addSubview(minimumScaleRatioLabel) let minimumScaleRatioSlider = UISlider() minimumScaleRatioSlider.maximumValue = 1 minimumScaleRatioSlider.value = 0.8 minimumScaleRatioSlider.addTarget(self, action: "minimumScaleRatioSliderDidChangeValue:", forControlEvents: .ValueChanged) minimumScaleRatioSlider.translatesAutoresizingMaskIntoConstraints = false self.view.addSubview(minimumScaleRatioSlider) animationDurationLabel = UILabel() animationDurationLabel.text = "AnimationDuration = 0.20" animationDurationLabel.translatesAutoresizingMaskIntoConstraints = false self.view.addSubview(animationDurationLabel) let animationDurationSlider = UISlider() animationDurationSlider.maximumValue = 1 animationDurationSlider.value = 0.2 animationDurationSlider.addTarget(self, action: "animationDurationSliderDidChangeValue:", forControlEvents: .ValueChanged) animationDurationSlider.translatesAutoresizingMaskIntoConstraints = false self.view.addSubview(animationDurationSlider) // AutoLayout UI let dic = ["maximunOffsetRatioLabel":maximunOffsetRatioLabel, "maximunOffsetRatioSlider":maximunOffsetRatioSlider, "minimumScaleRatioLabel": minimumScaleRatioLabel,"animationDurationLabel":animationDurationLabel, "animationDurationSlider":animationDurationSlider, "minimumScaleRatioSlider":minimumScaleRatioSlider] self.view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-[maximunOffsetRatioLabel]-|", options: [], metrics: nil, views: dic)) self.view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-[maximunOffsetRatioSlider]-|", options: [], metrics: nil, views: dic)) self.view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-[minimumScaleRatioLabel]-|", options: [], metrics: nil, views: dic)) self.view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-[minimumScaleRatioSlider]-|", options: [], metrics: nil, views: dic)) self.view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-[animationDurationLabel]-|", options: [], metrics: nil, views: dic)) self.view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-[animationDurationSlider]-|", options: [], metrics: nil, views: dic)) self.view.addConstraint(NSLayoutConstraint(item: minimumScaleRatioSlider, attribute: .CenterY, relatedBy: .Equal, toItem: self.view, attribute: .CenterY, multiplier: 1, constant: 0)) self.view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:[maximunOffsetRatioLabel]-[maximunOffsetRatioSlider]-[minimumScaleRatioLabel]-[minimumScaleRatioSlider]-[animationDurationLabel]-[animationDurationSlider]", options: [], metrics: nil, views: dic)) } func leftBarButtonDidTap(){ self.drawerContainerViewController?.toggleLeftViewController() } func maximunOffsetRatioSliderDidChangeValue(maximunOffsetRatioSlider: UISlider){ maximunOffsetRatioLabel.text = NSString(format: "MaximunOffsetRatio = %.2f", maximunOffsetRatioSlider.value) as String self.drawerContainerViewController?.maximunOffsetRatio = CGFloat(maximunOffsetRatioSlider.value) } func minimumScaleRatioSliderDidChangeValue(minimumScaleRatioSlider: UISlider){ minimumScaleRatioLabel.text = NSString(format: "MinimumScaleRatio = %.2f", minimumScaleRatioSlider.value) as String self.drawerContainerViewController?.minimumScaleRatio = CGFloat(minimumScaleRatioSlider.value) } func animationDurationSliderDidChangeValue(animationDurationSlider: UISlider){ animationDurationLabel.text = NSString(format: "AnimationDuration = %.2f", animationDurationSlider.value) as String self.drawerContainerViewController?.animationDuration = Double(animationDurationSlider.value) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
92a07b59b1729e7703b5102bdf5743dc
46.016
322
0.72571
false
false
false
false
alirsamar/BiOS
refs/heads/master
beginning-ios-alien-adventure-alien-adventure-2/Alien Adventure/RarityOfItems.swift
mit
1
// // RarityOfItems.swift // Alien Adventure // // Created by Jarrod Parkes on 10/4/15. // Copyright © 2015 Udacity. All rights reserved. // extension Hero { func rarityOfItems(inventory: [UDItem]) -> [UDItemRarity:Int] { var rarityCount = [UDItemRarity.Common: 0, .Uncommon: 0, .Rare: 0, .Legendary: 0] for item in inventory { switch item.rarity { case .Common: rarityCount[.Common] = rarityCount[.Common]! + 1 case.Uncommon: rarityCount[.Uncommon] = rarityCount[.Uncommon]! + 1 case .Rare: rarityCount[.Rare] = rarityCount[.Rare]! + 1 case .Legendary: rarityCount[.Legendary] = rarityCount[.Legendary]! + 1 } } return rarityCount } } // If you have completed this function and it is working correctly, feel free to skip this part of the adventure by opening the "Under the Hood" folder, and making the following change in Settings.swift: "static var RequestsToSkip = 4"
f019918552e62cb9054b1578f6a147bb
35.517241
235
0.60397
false
false
false
false
yujinjcho/movie_recommendations
refs/heads/develop
ios_ui/MovieRec/Classes/Modules/Rate/View/RateViewController.swift
mit
1
// // RateViewController.swift // MovieRec // // Created by Yujin Cho on 5/27/17. // Copyright © 2017 Yujin Cho. All rights reserved. // import os.log import UIKit import CloudKit class RateViewController: UIViewController, RateViewInterface { var eventHandler : RateModuleInterface? var currentTitle : String? @IBOutlet weak var titleNameLabel: UILabel! @IBOutlet weak var titleImage: UIImageView! @IBAction func rateLikeButton(_ sender: UIButton) { eventHandler?.processRating(ratingType: "1") } @IBAction func rateSkipButton(_ sender: UIButton) { eventHandler?.processRating(ratingType: "0") } @IBAction func rateDislikeButton(_ sender: UIButton) { eventHandler?.processRating(ratingType: "-1") } override func viewDidLoad() { titleImage.clipsToBounds = true super.viewDidLoad() configureView() eventHandler?.loadedView() } func showCurrentMovie(title:String, photoUrl: String, completion: (() -> Void)? = nil) { let url = URL(string: photoUrl) titleImage.kf.setImage(with: url, completionHandler: { (_, _, _, _) in self.titleNameLabel.text = title if let completion = completion { completion() } }) } func didTapNavigateToRecommendItem(){ eventHandler?.presentRecommendView(navigationController: self.navigationController!) } private func configureView() { navigationItem.title = "Rate" let navigateToRecommendItem = UIBarButtonItem(title: "Movie List", style: UIBarButtonItemStyle.plain, target: self, action: #selector(RateViewController.didTapNavigateToRecommendItem)) navigationItem.rightBarButtonItem = navigateToRecommendItem } }
b7807c27fab826ca604dd3565db99254
29.516667
192
0.657564
false
false
false
false
AdaptiveMe/adaptive-arp-api-lib-darwin
refs/heads/master
Pod/Classes/Sources.Api/BaseSocialBridge.swift
apache-2.0
1
/** --| ADAPTIVE RUNTIME PLATFORM |---------------------------------------------------------------------------------------- (C) Copyright 2013-2015 Carlos Lozano Diez t/a Adaptive.me <http://adaptive.me>. 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 appli- -cable 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. Original author: * Carlos Lozano Diez <http://github.com/carloslozano> <http://twitter.com/adaptivecoder> <mailto:[email protected]> Contributors: * Ferran Vila Conesa <http://github.com/fnva> <http://twitter.com/ferran_vila> <mailto:[email protected]> * See source code files for contributors. Release: * @version v2.2.15 -------------------------------------------| aut inveniam viam aut faciam |-------------------------------------------- */ import Foundation /** Base application for Social purposes Auto-generated implementation of IBaseSocial specification. */ public class BaseSocialBridge : IBaseSocial { /** Group of API. */ private var apiGroup : IAdaptiveRPGroup? = nil /** Default constructor. */ public init() { self.apiGroup = IAdaptiveRPGroup.Social } /** Return the API group for the given interface. */ public final func getAPIGroup() -> IAdaptiveRPGroup? { return self.apiGroup! } /** Return the API version for the given interface. */ public final func getAPIVersion() -> String? { return "v2.2.15" } /** Invokes the given method specified in the API request object. @param request APIRequest object containing method name and parameters. @return APIResponse with status code, message and JSON response or a JSON null string for void functions. Status code 200 is OK, all others are HTTP standard error conditions. */ public func invoke(request : APIRequest) -> APIResponse? { let response : APIResponse = APIResponse() var responseCode : Int32 = 200 var responseMessage : String = "OK" let responseJSON : String? = "null" switch request.getMethodName()! { default: // 404 - response null. responseCode = 404 responseMessage = "BaseSocialBridge does not provide the function '\(request.getMethodName()!)' Please check your client-side API version; should be API version >= v2.2.15." } response.setResponse(responseJSON!) response.setStatusCode(responseCode) response.setStatusMessage(responseMessage) return response } } /** ------------------------------------| Engineered with ♥ in Barcelona, Catalonia |-------------------------------------- */
246ae42729d155f5486d453383c70767
33.212766
189
0.609453
false
false
false
false
neoreeps/rest-tester
refs/heads/master
REST Tester/AppDelegate.swift
apache-2.0
1
// // AppDelegate.swift // REST Tester // // Created by Kenny Speer on 10/3/16. // Copyright © 2016 Kenny Speer. All rights reserved. // import UIKit import CoreData @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. 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 invalidate graphics rendering callbacks. 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 active 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:. // Saves changes in the application's managed object context before the application terminates. self.saveContext() } // MARK: - Core Data stack lazy var persistentContainer: NSPersistentContainer = { /* The persistent container for the application. This implementation creates and returns a container, having loaded the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. */ let container = NSPersistentContainer(name: "Model") container.loadPersistentStores(completionHandler: { (storeDescription, error) in if let error = error as NSError? { // Replace this implementation with code to handle the error appropriately. // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. /* Typical reasons for an error here include: * The parent directory does not exist, cannot be created, or disallows writing. * The persistent store is not accessible, due to permissions or data protection when the device is locked. * The device is out of space. * The store could not be migrated to the current model version. Check the error message to determine what the actual problem was. */ fatalError("Unresolved error \(error), \(error.userInfo)") } }) return container }() // MARK: - Core Data Saving support func saveContext () { let context = persistentContainer.viewContext if context.hasChanges { do { try context.save() } catch { // Replace this implementation with code to handle the error appropriately. // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. let nserror = error as NSError fatalError("Unresolved error \(nserror), \(nserror.userInfo)") } } } }
a37ccb98e5d1266b39459523a72223ce
48.612903
285
0.681838
false
false
false
false
kevin-zqw/play-swift
refs/heads/master
swift-lang/17. Optional Chaining.playground/section-1.swift
apache-2.0
1
// ------------------------------------------------------------------------------------------------ // Things to know: // // * Optional Chaining is the process of safely referencing a series of optionals (which contain // optionals, which contain optionals, etc.) without having to perform the optional unwrapping // checks at each step along the way. // ------------------------------------------------------------------------------------------------ // Consider a case of forced unwrapping like "someOptional!.someProperty". We already know that // this is only safe if we know that the optional will never be nil. For times that we don't know // this, we must check the optional before we can reference it. This can become cumbersome for // situations where many optionals are chained together as properties of properties. Let's create // a series of optionals to show this: class Artist { let name: String init(name: String) { self.name = name } } class Song { let name: String var artist: Artist? init(name: String, artist: Artist?) { self.name = name self.artist = artist } } class MusicPreferences { var favoriteSong: Song? init(favoriteSong: Song?) { self.favoriteSong = favoriteSong } } class Person { let name: String var musicPreferences: MusicPreferences? init (name: String, musicPreferences: MusicPreferences?) { self.name = name self.musicPreferences = musicPreferences } } // Here, we'll create a working chain: var someArtist: Artist? = Artist(name: "Somebody with talent") var favSong: Song? = Song(name: "Something with a beat", artist: someArtist) var musicPrefs: MusicPreferences? = MusicPreferences(favoriteSong: favSong) var person: Person? = Person(name: "Bill", musicPreferences: musicPrefs) // We can access this chain with forced unwrapping. In this controlled environment, this will work // but it's probably not advisable in a real world situation unless you're sure that each member // of the chain is sure to never be nil. person!.musicPreferences!.favoriteSong!.artist! // Let's break the chain, removing the user's music preferences: if var p = person { p.musicPreferences = nil } // With a broken chain, if we try to reference the arist like before, we will get a runtime error. // // The following line will compile, but will crash: // // person!.musicPreferences!.favoriteSong!.artist! // // The solusion here is to use optional chaining, which replaces the forced unwrapping "!" with // a "?" character. If at any point along this chain, any optional is nil, evaluation is aborted // and the entire result becomes nil. // // Let's see this entire chain, one step at a time working backwards. This let's us see exactly // where the optional chain becomes a valid value: person?.musicPreferences?.favoriteSong?.artist person?.musicPreferences?.favoriteSong person?.musicPreferences person // Optional chaining can be mixed with non-optionals as well as forced unwrapping and other // contexts (subcripts, function calls, return values, etc.) We won't bother to create the // series of classes and instances for the following example, but it should serve as a valid // example of how to use optional chaining syntax in various situations. Given the proper context // this line of code would compile and run as expected. // // person?.musicPreferences?[2].getFavoriteSong()?.artist?.name // // This line could be read as: optional person's second optional music preference's favorite song's // optional artist's name. // Optional chaining is handy and safe, we'll use it a lot.
954bd724ba5646b937191d2eadf1f951
36.765957
99
0.710423
false
false
false
false
CodaFi/swift
refs/heads/main
Sources/Foundation/NSData+DataProtocol.swift
apache-2.0
18
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2018 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 NSData : DataProtocol { @nonobjc public var startIndex: Int { return 0 } @nonobjc public var endIndex: Int { return length } @nonobjc public func lastRange<D, R>(of data: D, in r: R) -> Range<Int>? where D : DataProtocol, R : RangeExpression, NSData.Index == R.Bound { return Range<Int>(range(of: Data(data), options: .backwards, in: NSRange(r))) } @nonobjc public func firstRange<D, R>(of data: D, in r: R) -> Range<Int>? where D : DataProtocol, R : RangeExpression, NSData.Index == R.Bound { return Range<Int>(range(of: Data(data), in: NSRange(r))) } @nonobjc public var regions: [Data] { var datas = [Data]() enumerateBytes { (ptr, range, stop) in datas.append(Data(bytesNoCopy: UnsafeMutableRawPointer(mutating: ptr), count: range.length, deallocator: .custom({ (ptr: UnsafeMutableRawPointer, count: Int) -> Void in withExtendedLifetime(self) { } }))) } return datas } @nonobjc public subscript(position: Int) -> UInt8 { var byte = UInt8(0) var offset = position enumerateBytes { (ptr, range, stop) in offset -= range.lowerBound if range.contains(position) { byte = ptr.load(fromByteOffset: offset, as: UInt8.self) stop.pointee = true } } return byte } }
21872f81e3409b3ae07346e7afd6c16d
33.803571
180
0.562853
false
false
false
false
digoreis/swift-proposal-analyzer
refs/heads/master
swift-proposal-analyzer.playground/Pages/SE-0020.xcplaygroundpage/Contents.swift
mit
1
/*: # Swift Language Version Build Configuration * Proposal: [SE-0020](0020-if-swift-version.md) * Author: [David Farler](https://github.com/bitjammer) * Review Manager: [Doug Gregor](https://github.com/DougGregor) * Status: **Implemented (Swift 2.2)** * Commit: [apple/swift@c32fb8e](https://github.com/apple/swift/commit/c32fb8e7b9a67907e8b6580a46717c6a345ec7c6) ## Introduction This proposal aims to add a new build configuration option to Swift 2.2: `#if swift`. Swift-evolution threads: - [Swift 2.2: #if swift language version](https://lists.swift.org/pipermail/swift-evolution/Week-of-Mon-20151214/003385.html) - [Review](https://lists.swift.org/pipermail/swift-evolution/Week-of-Mon-20160111/006398.html) ## Motivation Over time, Swift syntax may change but library and package authors will want their code to work with multiple versions of the language. Up until now, the only recourse developers have is to maintain separate release branches that follow the language. This gives developers another tool to track syntax changes without having to maintain separate source trees. We also want to ease the transition between language revisions for package authors that distribute their source code, so clients can build their package with older or newer Swift. ## Proposed solution The solution is best illustrated with a simple example: ```swift #if swift(>=2.2) print("Active!") #else this! code! will! not! parse! or! produce! diagnostics! #endif ``` ## Detailed design This will use existing version mechanics already present in the compiler. The version of the language is baked into the compiler when it's built, so we know how to determine whether a block of code is active. If the version is at least as recent as specified in the condition, the active branch is parsed and compiled into your code. Like other build configurations, `#if swift` isn't line-based - it encloses whole statements or declarations. However, unlike the others, the compiler won't parse inactive branches guarded by `#if swift` or emit lex diagnostics, so syntactic differences for other Swift versions can be in the same file. For now, we'll only expect up to two version components, since it will be unlikely that a syntax change will make it in a +0.0.1 revision. The argument to the configuration function is a unary prefix expression, with one expected operator, `>=`, for simplicity. If the need arises, this can be expanded to include other comparison operators. ## Impact on existing code This mechanism is opt-in, so existing code won't be affected by this change. ## Alternatives considered We considered two other formats for the version argument: - String literals (`#if swift("2.2")`): this allows us to embed an arbitrary number of version components, but syntax changes are unlikely in micro-revisions. If we need another version component, the parser change won't be severe. - Just plain `#if swift(2.2)`: Although `>=` is a sensible default, it isn't clear what the comparison is here, and might be assumed to be `==`. - Argument lists (`#if swift(2, 2)`: This parses flexibly but can indicate that the second `2` might be an argument with a different meaning, instead of a component of the whole version. ---------- [Previous](@previous) | [Next](@next) */
c4d3939a7e9196aec7bade1ba0fd3ea3
36.556818
125
0.763691
false
false
false
false
Ming-Lau/DouyuTV
refs/heads/master
DouyuTV/DouyuTV/Classes/Home/View/HomeCycleView.swift
mit
1
// // HomeCycleView.swift // DouyuTV // // Created by 刘明 on 16/11/10. // Copyright © 2016年 刘明. All rights reserved. // import UIKit private let kCycleCell = "kCycleCell" class HomeCycleView: UIView { @IBOutlet weak var collectionView: UICollectionView! @IBOutlet weak var pageControl: UIPageControl! override func awakeFromNib() { super.awakeFromNib() autoresizingMask = UIViewAutoresizing() //注册cell collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: kCycleCell) } override func layoutSubviews() { super.layoutSubviews() let layout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout layout.itemSize = collectionView.bounds.size } } extension HomeCycleView{ class func homeCycleView() ->HomeCycleView{ return Bundle.main.loadNibNamed("HomeCycleView", owner: nil, options: nil)?.first as! HomeCycleView } } extension HomeCycleView : UICollectionViewDataSource{ func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return 6 } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: kCycleCell, for: indexPath) cell.backgroundColor = indexPath.item % 2 == 0 ? UIColor.blue : UIColor.red return cell } }
1ed775342da22060b17a47f2db335427
32.466667
121
0.705179
false
false
false
false
bakkenbaeck/Teapot
refs/heads/master
TeapotTests/MockTests.swift
mit
1
@testable import TeapotMac import XCTest class MockTests: XCTestCase { func testMock() { let mockedTeapot = MockTeapot(bundle: Bundle(for: MockTests.self), mockFilename: "get") mockedTeapot.get("/get") { result in switch result { case .success(let json, _): XCTAssertEqual(json?.dictionary?["key"] as? String, "value") case .failure(_, _, let error): XCTFail("Unexpected error getting mock: \(error)") } } } func testMissingMock() { let mockedTeapot = MockTeapot(bundle: Bundle(for: MockTests.self), mockFilename: "missing") mockedTeapot.get("/missing") { result in switch result { case .success: XCTFail() case .failure(_, _, let error): switch error.type { case .missingMockFile: XCTAssertEqual(error.description, "An error occurred: expected mockfile with name: missing.json") default: XCTFail("Incorrect error for missing mock: \(error)") } } } } func testInvalidMock() { let mockedTeapot = MockTeapot(bundle: Bundle(for: MockTests.self), mockFilename: "invalid") mockedTeapot.get("/invalid") { result in switch result { case .success: XCTFail() case .failure(_, _, let error): switch error.type { case .invalidMockFile: XCTAssertEqual(error.description, "An error occurred: invalid mockfile with name: invalid.json") default: XCTFail("Incorrect error for invalid file: \(error)") } } } } func testNoContent() { let mockedTeapot = MockTeapot(bundle: Bundle(for: MockTests.self), mockFilename: "get", statusCode: .noContent) mockedTeapot.get("/get") { result in switch result { case .success(_, let response): XCTAssertEqual(response.statusCode, 204) case .failure: XCTFail("Incorrect status code returned for no content") } } } func testUnauthorizedError() { let mockedTeapot = MockTeapot(bundle: Bundle(for: MockTests.self), mockFilename: "get", statusCode: .unauthorized) mockedTeapot.get("/get") { result in switch result { case .success: XCTFail() case .failure(_, let response, _): XCTAssertEqual(response.statusCode, 401) } } } func testEndPointOverriding() { let mockedTeapot = MockTeapot(bundle: Bundle(for: MockTests.self), mockFilename: "get") mockedTeapot.overrideEndPoint("overridden", withFilename: "overridden") mockedTeapot.get("/overridden") { result in switch result { case .success(let json, _): XCTAssertEqual(json?.dictionary?["overridden"] as? String, "value") case .failure(let error): XCTFail("Unexpected error overriding endpoint: \(error)") } } } func testEndpointOverriddingThenHittingOtherEndpointWithError() { let mockedTeapot = MockTeapot(bundle: Bundle(for: MockTests.self), mockFilename: "", statusCode: .internalServerError) mockedTeapot.overrideEndPoint("overridden", withFilename: "overridden") mockedTeapot.get("/overridden") { initialResult in switch initialResult { case .success(let json, _): XCTAssertEqual(json?.dictionary?["overridden"] as? String, "value") mockedTeapot.get("/get") { secondaryResult in switch secondaryResult { case .success: XCTFail("That should not have worked") case .failure(_, _, let error): print(error) XCTAssertEqual(error.responseStatus, 500) } } case .failure: XCTFail("The overridden endpoint should have worked") } } } func testCheckingForHeadersWhichAreThereSucceeds() { let mockedTeapot = MockTeapot(bundle: Bundle(for: MockTests.self), mockFilename: "get") let expectedHeaders = [ "foo": "bar", "baz": "foo2" ] mockedTeapot.setExpectedHeaders(expectedHeaders) mockedTeapot.get("/get", headerFields: expectedHeaders) { result in switch result { case .success(let json, _): XCTAssertEqual(json?.dictionary?["key"] as? String, "value") case .failure(_, _, let error): XCTFail("Unexpected error: \(error)") } } } func testCheckingForHeadersWhichAreNotThereReturnsError() { let mockedTeapot = MockTeapot(bundle: Bundle(for: MockTests.self), mockFilename: "get") let expectedHeaders = [ "foo": "bar", "baz": "foo2" ] mockedTeapot.setExpectedHeaders(expectedHeaders) mockedTeapot.get("/get") { result in switch result { case .success: XCTFail("Request succeeded which should not have!") case .failure(_, let response, let error): XCTAssertEqual(response.statusCode, 400) XCTAssertEqual(error, TeapotError.incorrectHeaders(expected: expectedHeaders, received: nil)) } } } func testCheckingForPartialHeadersReturnsError() { let mockedTeapot = MockTeapot(bundle: Bundle(for: MockTests.self), mockFilename: "get") let expectedHeaders = [ "foo": "bar", "baz": "foo2" ] mockedTeapot.setExpectedHeaders(expectedHeaders) let wrongHeaders = ["foo": "bar"] mockedTeapot.get("/get", headerFields: wrongHeaders) { result in switch result { case .success: XCTFail("Request succeeded which should not have!") case .failure(_, let response, let error): XCTAssertEqual(response.statusCode, 400) XCTAssertEqual(error, TeapotError.incorrectHeaders(expected: expectedHeaders, received: wrongHeaders)) } } } func testPassingExtraHeadersSucceeds() { let mockedTeapot = MockTeapot(bundle: Bundle(for: MockTests.self), mockFilename: "get") let expectedHeaders = [ "foo": "bar", "baz": "foo2" ] var headersToPass = expectedHeaders headersToPass["extra"] = "lol" mockedTeapot.setExpectedHeaders(expectedHeaders) mockedTeapot.get("/get", headerFields: headersToPass) { result in switch result { case .success(let json, _): XCTAssertEqual(json?.dictionary?["key"] as? String, "value") case .failure(_, _, let error): XCTFail("Unexpected error: \(error)") } } } func testClearingHeadersWorks() { let mockedTeapot = MockTeapot(bundle: Bundle(for: MockTests.self), mockFilename: "get") let expectedHeaders = [ "foo": "bar", "baz": "foo2" ] mockedTeapot.setExpectedHeaders(expectedHeaders) let wrongHeaders = ["foo": "bar"] mockedTeapot.get("/get", headerFields: wrongHeaders) { wrongHeaderResult in switch wrongHeaderResult { case .success: XCTFail("Request succeeded which should not have!") case .failure(_, let response, let error): XCTAssertEqual(response.statusCode, 400) XCTAssertEqual(error, TeapotError.incorrectHeaders(expected: expectedHeaders, received: wrongHeaders)) } } mockedTeapot.clearExpectedHeaders() mockedTeapot.get("/get") { clearedHeaderResult in switch clearedHeaderResult { case .success(let json, _): XCTAssertEqual(json?.dictionary?["key"] as? String, "value") case .failure(_, _, let error): XCTFail("Unexpected error: \(error)") } } } func testExpectedHeadersAreNotCheckedForEndpointOverrideButAreForMainRequest() { let mockedTeapot = MockTeapot(bundle: Bundle(for: MockTests.self), mockFilename: "get") let expectedHeaders = [ "foo": "bar", "baz": "foo2" ] mockedTeapot.setExpectedHeaders(expectedHeaders) // If you don't pass the expected headers to the overridden endpoint but do // pass them to the final endpoint, this should succeed. mockedTeapot.overrideEndPoint("overridden", withFilename: "overridden") mockedTeapot.get("/overridden") { firstOverriddenResult in switch firstOverriddenResult { case .success(let json, _): XCTAssertEqual(json?.dictionary?["overridden"] as? String, "value") mockedTeapot.get("/get", headerFields: expectedHeaders) { firstGetResult in switch firstGetResult { case .success(let json, _): XCTAssertEqual(json?.dictionary?["key"] as? String, "value") case .failure(_, _, let error): XCTFail("Unexpected error hitting primary endpoint: \(error)") } } case .failure(_, _, let error): XCTFail("Unexpected error hitting overridden endpoint: \(error)") } } // If you don't pass the expected headers to the overridden getter OR to the main get method, then this should fail. mockedTeapot.get("/overridden") { secondOverriddenResult in switch secondOverriddenResult { case .success(let json, _): XCTAssertEqual(json?.dictionary?["overridden"] as? String, "value") mockedTeapot.get("/get") { secondGetResult in switch secondGetResult { case .success: XCTFail("Unexpected success when not passing correct headers!") case .failure(_, _, let error): XCTAssertEqual(error, TeapotError.incorrectHeaders(expected: expectedHeaders, received: nil)) } } case .failure(_, _, let error): XCTFail("Unexpected error hitting overridden endpoint: \(error)") } } } }
49bc47a4af6b9160f8ae2b1dd5015f81
36.827465
126
0.56111
false
true
false
false
apple/swift-experimental-string-processing
refs/heads/main
Sources/_StringProcessing/Algorithms/Matching/MatchResult.swift
apache-2.0
1
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2021-2022 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 // //===----------------------------------------------------------------------===// struct _MatchResult<S: MatchingCollectionSearcher> { let match: S.Searched.SubSequence let result: S.Match var range: Range<S.Searched.Index> { match.startIndex..<match.endIndex } } struct _BackwardMatchResult<S: BackwardMatchingCollectionSearcher> { let match: S.BackwardSearched.SubSequence let result: S.Match var range: Range<S.BackwardSearched.Index> { match.startIndex..<match.endIndex } }
54d006d64111daddf3e84cf6ba3ede6c
29.892857
80
0.601156
false
false
false
false
russbishop/Swift-Flow
refs/heads/master
SwiftFlow/CoreTypes/MainStore.swift
mit
1
// // MainStore.swift // SwiftFlow // // Created by Benjamin Encz on 11/11/15. // Copyright © 2015 DigiTales. All rights reserved. // import Foundation /** This class is the default implementation of the `Store` protocol. You will use this store in most of your applications. You shouldn't need to implement your own store. You initialize the store with a reducer and an initial application state. If your app has multiple reducers you can combine them by initializng a `MainReducer` with all of your reducers as an argument. */ public class MainStore: Store { // TODO: Setter should not be public; need way for store enhancers to modify appState anyway /*private (set)*/ public var appState: StateType { didSet { subscribers.forEach { $0._newState(appState) } } } public var dispatchFunction: DispatchFunction! private var reducer: AnyReducer private var subscribers: [AnyStoreSubscriber] = [] private var isDispatching = false public required init(reducer: AnyReducer, appState: StateType) { self.reducer = reducer self.appState = appState self.dispatchFunction = self._defaultDispatch } public required init(reducer: AnyReducer, appState: StateType, middleware: [Middleware]) { self.reducer = reducer self.appState = appState self.dispatchFunction = self._defaultDispatch // Wrap the dispatch function with all middlewares self.dispatchFunction = middleware.reverse().reduce(self.dispatchFunction) { dispatchFunction, middleware in return middleware(self.dispatch, { self.appState })(dispatchFunction) } } public func subscribe(subscriber: AnyStoreSubscriber) { subscribers.append(subscriber) subscriber._newState(appState) } public func unsubscribe(subscriber: AnyStoreSubscriber) { let index = subscribers.indexOf { return $0 === subscriber } if let index = index { subscribers.removeAtIndex(index) } } public func _defaultDispatch(action: Action) -> Any { if isDispatching { // Use Obj-C exception since throwing of exceptions can be verified through tests NSException.raise("SwiftFlow:IllegalDispatchFromReducer", format: "Reducers may not " + "dispatch actions.", arguments: getVaList(["nil"])) } isDispatching = true self.appState = self.reducer._handleAction(self.appState, action: action) isDispatching = false return action } public func dispatch(action: Action) -> Any { return dispatch(action, callback: nil) } public func dispatch(actionCreatorProvider: ActionCreator) -> Any { return dispatch(actionCreatorProvider, callback: nil) } public func dispatch(asyncActionCreatorProvider: AsyncActionCreator) { dispatch(asyncActionCreatorProvider, callback: nil) } public func dispatch(action: Action, callback: DispatchCallback?) -> Any { let returnValue = self.dispatchFunction(action) callback?(self.appState) return returnValue } public func dispatch(actionCreatorProvider: ActionCreator, callback: DispatchCallback?) -> Any { let action = actionCreatorProvider(state: self.appState, store: self) if let action = action { dispatch(action, callback: callback) } return action } public func dispatch(actionCreatorProvider: AsyncActionCreator, callback: DispatchCallback?) { actionCreatorProvider(state: self.appState, store: self) { actionProvider in let action = actionProvider(state: self.appState, store: self) if let action = action { self.dispatch(action, callback: callback) } } } }
3588895a5f143bb9a3add64c12335d93
32.431034
100
0.669159
false
false
false
false
tyleryouk11/space-hero
refs/heads/master
Stick-Hero/StickHeroGameScene.swift
mit
1
// // StickHeroGameScene.swift // Stick-Hero // // Created by 顾枫 on 15/6/19. // Copyright © 2015年 koofrank. All rights reserved. // import SpriteKit import GoogleMobileAds import UIKit class StickHeroGameScene: SKScene, SKPhysicsContactDelegate { var gameOver = false { willSet { if (newValue) { checkHighScoreAndStore() let gameOverLayer = childNodeWithName(StickHeroGameSceneChildName.GameOverLayerName.rawValue) as SKNode? gameOverLayer?.runAction(SKAction.moveDistance(CGVectorMake(0, 100), fadeInWithDuration: 0.2)) } } } var interstitial: GADInterstitial? let StackHeight:CGFloat = 650.0 let StackMaxWidth:CGFloat = 300.0 let StackMinWidth:CGFloat = 100.0 let gravity:CGFloat = -100.0 let StackGapMinWidth:Int = 80 let HeroSpeed:CGFloat = 760 let StoreScoreName = "com.stickHero.score" var isBegin = false var isEnd = false var leftStack:SKShapeNode? var rightStack:SKShapeNode? var nextLeftStartX:CGFloat = 0 var stickHeight:CGFloat = 0 var score:Int = 0 { willSet { let scoreBand = childNodeWithName(StickHeroGameSceneChildName.ScoreName.rawValue) as? SKLabelNode scoreBand?.text = "\(newValue)" scoreBand?.runAction(SKAction.sequence([SKAction.scaleTo(1.5, duration: 0.1), SKAction.scaleTo(1, duration: 0.1)])) if (newValue == 1) { let tip = childNodeWithName(StickHeroGameSceneChildName.TipName.rawValue) as? SKLabelNode tip?.runAction(SKAction.fadeAlphaTo(0, duration: 0.4)) } } } lazy var playAbleRect:CGRect = { let maxAspectRatio:CGFloat = 16.0/9.0 // iPhone 5" let maxAspectRatioWidth = self.size.height / maxAspectRatio let playableMargin = (self.size.width - maxAspectRatioWidth) / 2.0 return CGRectMake(playableMargin, 0, maxAspectRatioWidth, self.size.height) }() lazy var walkAction:SKAction = { var textures:[SKTexture] = [] for i in 0...1 { let texture = SKTexture(imageNamed: "human\(i + 1).png") textures.append(texture) } let action = SKAction.animateWithTextures(textures, timePerFrame: 0.15, resize: true, restore: true) return SKAction.repeatActionForever(action) }() //MARK: - override override init(size: CGSize) { super.init(size: size) anchorPoint = CGPointMake(0.5, 0.5) physicsWorld.contactDelegate = self } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func didMoveToView(view: SKView) { start() } override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { guard !gameOver else { let gameOverLayer = childNodeWithName(StickHeroGameSceneChildName.GameOverLayerName.rawValue) as SKNode? let location = touches.first?.locationInNode(gameOverLayer!) let retry = gameOverLayer!.nodeAtPoint(location!) if (retry.name == StickHeroGameSceneChildName.RetryButtonName.rawValue) { retry.runAction(SKAction.sequence([SKAction.setTexture(SKTexture(imageNamed: "button_retry_down"), resize: false), SKAction.waitForDuration(0.3)]), completion: {[unowned self] () -> Void in self.restart() }) } return } if !isBegin && !isEnd { isBegin = true let stick = loadStick() let hero = childNodeWithName(StickHeroGameSceneChildName.HeroName.rawValue) as! SKSpriteNode let action = SKAction.resizeToHeight(CGFloat(DefinedScreenHeight - StackHeight), duration: 1.5) stick.runAction(action, withKey:StickHeroGameSceneActionKey.StickGrowAction.rawValue) let scaleAction = SKAction.sequence([SKAction.scaleYTo(0.9, duration: 0.05), SKAction.scaleYTo(1, duration: 0.05)]) let loopAction = SKAction.group([SKAction.playSoundFileNamed(StickHeroGameSceneEffectAudioName.StickGrowAudioName.rawValue, waitForCompletion: true)]) stick.runAction(SKAction.repeatActionForever(loopAction), withKey: StickHeroGameSceneActionKey.StickGrowAudioAction.rawValue) hero.runAction(SKAction.repeatActionForever(scaleAction), withKey: StickHeroGameSceneActionKey.HeroScaleAction.rawValue) return } } override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) { if isBegin && !isEnd { isEnd = true let hero = childNodeWithName(StickHeroGameSceneChildName.HeroName.rawValue) as! SKSpriteNode hero.removeActionForKey(StickHeroGameSceneActionKey.HeroScaleAction.rawValue) hero.runAction(SKAction.scaleYTo(1, duration: 0.04)) let stick = childNodeWithName(StickHeroGameSceneChildName.StickName.rawValue) as! SKSpriteNode stick.removeActionForKey(StickHeroGameSceneActionKey.StickGrowAction.rawValue) stick.removeActionForKey(StickHeroGameSceneActionKey.StickGrowAudioAction.rawValue) stick.runAction(SKAction.playSoundFileNamed(StickHeroGameSceneEffectAudioName.StickGrowOverAudioName.rawValue, waitForCompletion: false)) stickHeight = stick.size.height; let action = SKAction.rotateToAngle(CGFloat(-M_PI / 2), duration: 0.4, shortestUnitArc: true) let playFall = SKAction.playSoundFileNamed(StickHeroGameSceneEffectAudioName.StickFallAudioName.rawValue, waitForCompletion: false) stick.runAction(SKAction.sequence([SKAction.waitForDuration(0.2), action, playFall]), completion: {[unowned self] () -> Void in self.heroGo(self.checkPass()) }) } } func start() { loadBackground() loadScoreBackground() loadScore() //loadTip() /* if (interstitial!.isReady) { interstitial!.presentFromRootViewController(GameViewController) }*/ loadGameOverLayer() leftStack = loadStacks(false, startLeftPoint: playAbleRect.origin.x) self.removeMidTouch(false, left:true) loadHero() let maxGap = Int(playAbleRect.width - StackMaxWidth - (leftStack?.frame.size.width)!) let gap = CGFloat(randomInRange(StackGapMinWidth...maxGap)) rightStack = loadStacks(false, startLeftPoint: nextLeftStartX + gap) gameOver = false } func restart() { isBegin = false isEnd = false score = 0 nextLeftStartX = 0 removeAllChildren() start() } private func checkPass() -> Bool { let stick = childNodeWithName(StickHeroGameSceneChildName.StickName.rawValue) as! SKSpriteNode let rightPoint = DefinedScreenWidth / 2 + stick.position.x + self.stickHeight guard rightPoint < self.nextLeftStartX else { return false } guard (CGRectIntersectsRect((leftStack?.frame)!, stick.frame) && CGRectIntersectsRect((rightStack?.frame)!, stick.frame)) else { return false } self.checkTouchMidStack() return true } private func checkTouchMidStack() { let stick = childNodeWithName(StickHeroGameSceneChildName.StickName.rawValue) as! SKSpriteNode let stackMid = rightStack!.childNodeWithName(StickHeroGameSceneChildName.StackMidName.rawValue) as! SKShapeNode let newPoint = stackMid.convertPoint(CGPointMake(-10, 10), toNode: self) if ((stick.position.x + self.stickHeight) >= newPoint.x && (stick.position.x + self.stickHeight) <= newPoint.x + 20) { loadPerfect() self.runAction(SKAction.playSoundFileNamed(StickHeroGameSceneEffectAudioName.StickTouchMidAudioName.rawValue, waitForCompletion: false)) score++ } } private func removeMidTouch(animate:Bool, left:Bool) { let stack = left ? leftStack : rightStack let mid = stack!.childNodeWithName(StickHeroGameSceneChildName.StackMidName.rawValue) as! SKShapeNode if (animate) { mid.runAction(SKAction.fadeAlphaTo(0, duration: 0.3)) } else { mid.removeFromParent() } } private func heroGo(pass:Bool) { let hero = childNodeWithName(StickHeroGameSceneChildName.HeroName.rawValue) as! SKSpriteNode guard pass else { let stick = childNodeWithName(StickHeroGameSceneChildName.StickName.rawValue) as! SKSpriteNode let dis:CGFloat = stick.position.x + self.stickHeight let disGap = nextLeftStartX - (DefinedScreenWidth / 2 - abs(hero.position.x)) - (rightStack?.frame.size.width)! / 2 let move = SKAction.moveToX(dis, duration: NSTimeInterval(abs(disGap / HeroSpeed))) hero.runAction(walkAction, withKey: StickHeroGameSceneActionKey.WalkAction.rawValue) hero.runAction(move, completion: {[unowned self] () -> Void in stick.runAction(SKAction.rotateToAngle(CGFloat(-M_PI), duration: 0.4)) hero.physicsBody!.affectedByGravity = true hero.runAction(SKAction.playSoundFileNamed(StickHeroGameSceneEffectAudioName.DeadAudioName.rawValue, waitForCompletion: false)) hero.removeActionForKey(StickHeroGameSceneActionKey.WalkAction.rawValue) self.runAction(SKAction.waitForDuration(0.5), completion: {[unowned self] () -> Void in self.gameOver = true }) }) return } let dis:CGFloat = -DefinedScreenWidth / 2 + nextLeftStartX - hero.size.width / 2 - 20 let disGap = nextLeftStartX - (DefinedScreenWidth / 2 - abs(hero.position.x)) - (rightStack?.frame.size.width)! / 2 let move = SKAction.moveToX(dis, duration: NSTimeInterval(abs(disGap / HeroSpeed))) hero.runAction(walkAction, withKey: StickHeroGameSceneActionKey.WalkAction.rawValue) hero.runAction(move) { [unowned self]() -> Void in self.score++ hero.runAction(SKAction.playSoundFileNamed(StickHeroGameSceneEffectAudioName.VictoryAudioName.rawValue, waitForCompletion: false)) hero.removeActionForKey(StickHeroGameSceneActionKey.WalkAction.rawValue) self.moveStackAndCreateNew() } } private func checkHighScoreAndStore() { let highScore = NSUserDefaults.standardUserDefaults().integerForKey(StoreScoreName) if (score > Int(highScore)) { showHighScore() NSUserDefaults.standardUserDefaults().setInteger(score, forKey: StoreScoreName) NSUserDefaults.standardUserDefaults().synchronize() } } private func showHighScore() { self.runAction(SKAction.playSoundFileNamed(StickHeroGameSceneEffectAudioName.HighScoreAudioName.rawValue, waitForCompletion: false)) let wait = SKAction.waitForDuration(0.4) let grow = SKAction.scaleTo(1.5, duration: 0.4) grow.timingMode = .EaseInEaseOut let explosion = starEmitterActionAtPosition(CGPointMake(0, 300)) let shrink = SKAction.scaleTo(1, duration: 0.2) let idleGrow = SKAction.scaleTo(1.2, duration: 0.4) idleGrow.timingMode = .EaseInEaseOut let idleShrink = SKAction.scaleTo(1, duration: 0.4) let pulsate = SKAction.repeatActionForever(SKAction.sequence([idleGrow, idleShrink])) let gameOverLayer = childNodeWithName(StickHeroGameSceneChildName.GameOverLayerName.rawValue) as SKNode? let highScoreLabel = gameOverLayer?.childNodeWithName(StickHeroGameSceneChildName.HighScoreName.rawValue) as SKNode? highScoreLabel?.runAction(SKAction.sequence([wait, explosion, grow, shrink]), completion: { () -> Void in highScoreLabel?.runAction(pulsate) }) } private func moveStackAndCreateNew() { let action = SKAction.moveBy(CGVectorMake(-nextLeftStartX + (rightStack?.frame.size.width)! + playAbleRect.origin.x - 2, 0), duration: 0.3) rightStack?.runAction(action) self.removeMidTouch(true, left:false) let hero = childNodeWithName(StickHeroGameSceneChildName.HeroName.rawValue) as! SKSpriteNode let stick = childNodeWithName(StickHeroGameSceneChildName.StickName.rawValue) as! SKSpriteNode hero.runAction(action) stick.runAction(SKAction.group([SKAction.moveBy(CGVectorMake(-DefinedScreenWidth, 0), duration: 0.5), SKAction.fadeAlphaTo(0, duration: 0.3)])) { () -> Void in stick.removeFromParent() } leftStack?.runAction(SKAction.moveBy(CGVectorMake(-DefinedScreenWidth, 0), duration: 0.5), completion: {[unowned self] () -> Void in self.leftStack?.removeFromParent() let maxGap = Int(self.playAbleRect.width - (self.rightStack?.frame.size.width)! - self.StackMaxWidth) let gap = CGFloat(randomInRange(self.StackGapMinWidth...maxGap)) self.leftStack = self.rightStack self.rightStack = self.loadStacks(true, startLeftPoint:self.playAbleRect.origin.x + (self.rightStack?.frame.size.width)! + gap) }) } } //MARK: - load node private extension StickHeroGameScene { func loadBackground() { guard let _ = childNodeWithName("background") as! SKSpriteNode? else { let texture = SKTexture(image: UIImage(named: "stick_background.jpg")!) let node = SKSpriteNode(texture: texture) node.size = texture.size() node.zPosition = StickHeroGameSceneZposition.BackgroundZposition.rawValue self.physicsWorld.gravity = CGVectorMake(0, gravity) addChild(node) return } } func loadScore() { let scoreBand = SKLabelNode(fontNamed: "Arial") scoreBand.name = StickHeroGameSceneChildName.ScoreName.rawValue scoreBand.text = "0" scoreBand.position = CGPointMake(0, DefinedScreenHeight / 2 - 200) scoreBand.fontColor = SKColor.whiteColor() scoreBand.fontSize = 100 scoreBand.zPosition = StickHeroGameSceneZposition.ScoreZposition.rawValue scoreBand.horizontalAlignmentMode = .Center addChild(scoreBand) } func loadScoreBackground() { let back = SKShapeNode(rect: CGRectMake(0-120, 1024-200-30, 240, 140), cornerRadius: 20) back.zPosition = StickHeroGameSceneZposition.ScoreBackgroundZposition.rawValue back.fillColor = SKColor.blackColor().colorWithAlphaComponent(0.3) back.strokeColor = SKColor.blackColor().colorWithAlphaComponent(0.3) addChild(back) } func loadHero() { let hero = SKSpriteNode(imageNamed: "human1") hero.name = StickHeroGameSceneChildName.HeroName.rawValue hero.position = CGPointMake(-DefinedScreenWidth / 2 + nextLeftStartX - hero.size.width / 2 - 20, -DefinedScreenHeight / 2 + StackHeight + hero.size.height / 2 - 4) hero.zPosition = StickHeroGameSceneZposition.HeroZposition.rawValue hero.physicsBody = SKPhysicsBody(rectangleOfSize: CGSizeMake(16, 18)) hero.physicsBody?.affectedByGravity = false hero.physicsBody?.allowsRotation = false addChild(hero) } /*func loadTip() { let tip = SKLabelNode(fontNamed: "HelveticaNeue-Bold") tip.name = StickHeroGameSceneChildName.TipName.rawValue tip.text = "将手放在屏幕使竿变长" tip.position = CGPointMake(0, DefinedScreenHeight / 2 - 350) tip.fontColor = SKColor.blackColor() tip.fontSize = 52 tip.zPosition = StickHeroGameSceneZposition.TipZposition.rawValue tip.horizontalAlignmentMode = .Center addChild(tip) }*/ func loadPerfect() { defer { let perfect = childNodeWithName(StickHeroGameSceneChildName.PerfectName.rawValue) as! SKLabelNode? let sequence = SKAction.sequence([SKAction.fadeAlphaTo(1, duration: 0.3), SKAction.fadeAlphaTo(0, duration: 0.3)]) let scale = SKAction.sequence([SKAction.scaleTo(1.4, duration: 0.3), SKAction.scaleTo(1, duration: 0.3)]) perfect!.runAction(SKAction.group([sequence, scale])) } guard let _ = childNodeWithName(StickHeroGameSceneChildName.PerfectName.rawValue) as! SKLabelNode? else { let perfect = SKLabelNode(fontNamed: "Arial") perfect.text = "Perfect +1" perfect.name = StickHeroGameSceneChildName.PerfectName.rawValue perfect.position = CGPointMake(0, -100) perfect.fontColor = SKColor.whiteColor() perfect.fontSize = 75 perfect.zPosition = StickHeroGameSceneZposition.PerfectZposition.rawValue perfect.horizontalAlignmentMode = .Center perfect.alpha = 0 addChild(perfect) return } } func loadStick() -> SKSpriteNode { let hero = childNodeWithName(StickHeroGameSceneChildName.HeroName.rawValue) as! SKSpriteNode let stick = SKSpriteNode(color: SKColor.whiteColor(), size: CGSizeMake(12, 1)) stick.zPosition = StickHeroGameSceneZposition.StickZposition.rawValue stick.name = StickHeroGameSceneChildName.StickName.rawValue stick.anchorPoint = CGPointMake(0.5, 0); stick.position = CGPointMake(hero.position.x + hero.size.width / 2 + 18, hero.position.y - hero.size.height / 2) addChild(stick) return stick } func loadStacks(animate: Bool, startLeftPoint: CGFloat) -> SKShapeNode { let max:Int = Int(StackMaxWidth / 10) let min:Int = Int(StackMinWidth / 10) let width:CGFloat = CGFloat(randomInRange(min...max) * 10) let height:CGFloat = StackHeight let stack = SKShapeNode(rectOfSize: CGSizeMake(width, height)) stack.fillColor = SKColor.whiteColor() stack.strokeColor = SKColor.whiteColor() stack.zPosition = StickHeroGameSceneZposition.StackZposition.rawValue stack.name = StickHeroGameSceneChildName.StackName.rawValue if (animate) { stack.position = CGPointMake(DefinedScreenWidth / 2, -DefinedScreenHeight / 2 + height / 2) stack.runAction(SKAction.moveToX(-DefinedScreenWidth / 2 + width / 2 + startLeftPoint, duration: 0.3), completion: {[unowned self] () -> Void in self.isBegin = false self.isEnd = false }) } else { stack.position = CGPointMake(-DefinedScreenWidth / 2 + width / 2 + startLeftPoint, -DefinedScreenHeight / 2 + height / 2) } addChild(stack) let mid = SKShapeNode(rectOfSize: CGSizeMake(20, 20)) mid.fillColor = SKColor.redColor() mid.strokeColor = SKColor.redColor() mid.zPosition = StickHeroGameSceneZposition.StackMidZposition.rawValue mid.name = StickHeroGameSceneChildName.StackMidName.rawValue mid.position = CGPointMake(0, height / 2 - 20 / 2) stack.addChild(mid) nextLeftStartX = width + startLeftPoint return stack } func loadGameOverLayer() { let node = SKNode() node.alpha = 0 node.name = StickHeroGameSceneChildName.GameOverLayerName.rawValue node.zPosition = StickHeroGameSceneZposition.GameOverZposition.rawValue addChild(node) let label = SKLabelNode(fontNamed: "HelveticaNeue-Bold") label.text = "Game Over" label.fontColor = SKColor.redColor() label.fontSize = 150 label.position = CGPointMake(0, 100) label.horizontalAlignmentMode = .Center node.addChild(label) let retry = SKSpriteNode(imageNamed: "button_retry_up") retry.name = StickHeroGameSceneChildName.RetryButtonName.rawValue retry.position = CGPointMake(0, -200) node.addChild(retry) let highScore = SKLabelNode(fontNamed: "AmericanTypewriter") highScore.text = "Highscore!" highScore.fontColor = UIColor.whiteColor() highScore.fontSize = 50 highScore.name = StickHeroGameSceneChildName.HighScoreName.rawValue highScore.position = CGPointMake(0, 300) highScore.horizontalAlignmentMode = .Center highScore.setScale(0) node.addChild(highScore) } //MARK: - Action func starEmitterActionAtPosition(position: CGPoint) -> SKAction { let emitter = SKEmitterNode(fileNamed: "StarExplosion") emitter?.position = position emitter?.zPosition = StickHeroGameSceneZposition.EmitterZposition.rawValue emitter?.alpha = 0.6 addChild((emitter)!) let wait = SKAction.waitForDuration(0.15) return SKAction.runBlock({ () -> Void in emitter?.runAction(wait) }) } }
b70fc21fda01c7cd66303ac2315cfcb0
41.140625
205
0.645393
false
false
false
false
Knoxantropicen/Focus-iOS
refs/heads/master
Focus/SettingsViewController.swift
mit
1
// // SettingsViewController.swift // Focus // // Created by TianKnox on 2017/5/29. // Copyright © 2017年 TianKnox. All rights reserved. // import UIKit class SettingsViewController: UIViewController { @IBOutlet weak var viewFrame: UIView! @IBOutlet weak var settingsLabel: UILabel! @IBOutlet weak var notificationLabel: UILabel! @IBOutlet weak var intervalLabel: UILabel! @IBOutlet weak var themeLabel: UILabel! @IBOutlet weak var languageLabel: UILabel! @IBOutlet weak var saveButton: UIButton! @IBOutlet weak var notificationSetting: UISwitch! @IBOutlet weak var timeIntervalSetting: UIDatePicker! @IBOutlet weak var themeSetting: UISegmentedControl! @IBOutlet weak var languageSetting: UISegmentedControl! let defaults = UserDefaults.standard override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = UIColor.black.withAlphaComponent(0.5) settingsLabel.text = Language.settings notificationLabel.text = Language.notification intervalLabel.text = Language.timeInterval themeLabel.text = Language.theme themeSetting.setTitle(Language.light, forSegmentAt: 0) themeSetting.setTitle(Language.dark, forSegmentAt: 1) languageLabel.text = Language.language languageSetting.setTitle(Language.english, forSegmentAt: 0) languageSetting.setTitle(Language.chinese, forSegmentAt: 1) saveButton.setTitle(Language.save, for: .normal) timeIntervalSetting.datePickerMode = .countDownTimer timeIntervalSetting.countDownDuration = TimeInterval(60) showAnimate() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func notificationEnabled(_ sender: UISwitch) { if sender.isOn { timeIntervalSetting.isEnabled = true } else { timeIntervalSetting.isEnabled = false } } func setThemeColor() { viewFrame.backgroundColor = Style.popBackgroundColor let textColor = Style.mainTextColor settingsLabel.textColor = textColor intervalLabel.textColor = textColor notificationLabel.textColor = textColor themeLabel.textColor = textColor languageLabel.textColor = textColor saveButton.setTitleColor(textColor, for: .normal) } func setOptions() { if let widgetNotificationStatus = UserDefaults(suiteName: "group.knox.Focuson.extension")?.bool(forKey: "notificationEnabled") { if widgetNotificationStatus { UserDefaults.standard.set(true, forKey: "notificationEnabled") } else { UserDefaults.standard.set(false, forKey: "notificationEnabled") } defaults.set(true, forKey: "veryFirstLaunch") } notificationSetting.isOn = UserDefaults.standard.bool(forKey: "notificationEnabled") if notificationSetting.isOn { timeIntervalSetting.isEnabled = true } else { timeIntervalSetting.isEnabled = false } if let timeInterval = UserDefaults.standard.object(forKey: "timeInterval") { timeIntervalSetting.countDownDuration = timeInterval as! TimeInterval } if Style.lightMode { themeSetting.selectedSegmentIndex = 0 } else { themeSetting.selectedSegmentIndex = 1 } if Language.EnglishLanguage { languageSetting.selectedSegmentIndex = 0 } else { languageSetting.selectedSegmentIndex = 1 } if !defaults.bool(forKey: "veryFirstLaunch") { notificationSetting.isOn = false timeIntervalSetting.isEnabled = false timeIntervalSetting.countDownDuration = 60 defaults.set(true, forKey: "veryFirstLaunch") } } func showAnimate() { setThemeColor() setOptions() self.view.transform = CGAffineTransform(scaleX: 1.3, y: 1.3) self.view.alpha = 0.0 UIView.animate(withDuration: 0.25, animations: { self.view.alpha = 1.0 self.view.transform = CGAffineTransform(scaleX: 1.0, y: 1.0) }) NotificationCenter.default.post(name: NSNotification.Name(rawValue: "disableSwipe"), object: nil) } func removeAnimate() { UIView.animate(withDuration: 0.25, animations: { self.view.transform = CGAffineTransform(scaleX: 1.3, y: 1.3) self.view.alpha = 0.0 }, completion:{(finished : Bool) in if (finished) { self.view.removeFromSuperview() } }) NotificationCenter.default.post(name: NSNotification.Name(rawValue: "enableSwipe"), object: nil) } @IBAction func saveSettings(_ sender: UIButton) { removeAnimate() // Notification if notificationSetting.isOn { UserDefaults.standard.set(true, forKey: "notificationEnabled") UserDefaults(suiteName: "group.knox.Focuson.extension")?.set(true, forKey: "notificationEnabled") } else { UserDefaults.standard.set(false, forKey: "notificationEnabled") UserDefaults(suiteName: "group.knox.Focuson.extension")?.set(false, forKey: "notificationEnabled") } PushNotification.isNotificationEnabled = notificationSetting.isOn // Time Interval UserDefaults.standard.set(timeIntervalSetting.countDownDuration, forKey: "timeInterval") PushNotification.timeInterval = timeIntervalSetting.countDownDuration // Theme if self.themeSetting.selectedSegmentIndex == 0 { Style.themeLight() } else { Style.themeDark() } // Language if languageSetting.selectedSegmentIndex == 0 { Language.setEnglish() } else { Language.setChinese() } // Activate self.view.superview?.backgroundColor = Style.mainBackgroundColor for subView in (self.view.superview?.subviews)! { if let textView = subView as? UITextView { textView.backgroundColor = Style.mainBackgroundColor textView.textColor = Style.mainTextColor if textView.text == Language.englishMainModel && !Language.EnglishLanguage { textView.text = Language.chineseMainModel } else if textView.text == Language.chineseMainModel && Language.EnglishLanguage { textView.text = Language.englishMainModel } } if let stackView = subView as? UIStackView { for subsubView in stackView.subviews { if let button = subsubView as? UIButton { switch button.restorationIdentifier! { case "checkButton": button.setImage(Style.checkIcon, for: .normal) case "plusButton": button.setImage(Style.plusIcon, for: .normal) default: break } } } } if let button = subView as? UIButton { switch button.restorationIdentifier! { case "symbolButton": button.setTitleColor(Style.symbolColor, for: .normal) case "settingsButton": button.setImage(Style.settingsIcon, for: .normal) default: break } } } } }
e32b2364b843259322cf1ca6257da65f
36.369668
136
0.604946
false
false
false
false
rain2540/Swift_100_Examples
refs/heads/master
A Set of Data/SD-of-Data-Set.playground/Contents.swift
mit
1
import Foundation // 和 func sum(of nums: [Double]) -> Double { return nums.reduce(0, { $0 + $1 }) } func sum(of input: Double...) -> Double { return input.reduce(0.0, +) } // 平均值 func average(of nums: [Double]) -> Double { return sum(of: a) / Double(nums.count) } // 极差 //: 极差 = (一组数据中的) 最大值 - 最小值 func range(of nums: [Double]) -> Double { guard let max = nums.max(), let min = nums.min() else { return 0.0 } return max - min } // 方差 //: 每个数据的值与全体数据的值的平均数之差的平方值的平均数。 func variance(of nums: [Double]) -> Double { let numAverage = average(of: nums) var sum = 0.0 for num in nums { let sub = num - numAverage let power = pow(sub, 2.0) sum += power } return sum / Double(nums.count) } // 标准差 //: 方差的平方根 func standardDeviation(of nums: [Double]) -> Double { return sqrt(variance(of: nums)) } // 样本方差 //: 每个样本值与全体样本值的平均数之差的平方值的平均数。 func sampleVariance(of nums: [Double]) -> Double { let numAverage = average(of: nums) var sum = 0.0 for num in nums { let sub = num - numAverage let power = pow(sub, 2.0) sum += power } return sum / Double(nums.count - 1) } // 样本标准差 func sampleStandardDeviation(of nums: [Double]) -> Double { return sqrt(sampleVariance(of: nums)) } // 一组数据中,每个数据的标准分 func standardScores(of scores: [Double]) -> [Double] { return scores.map{ ($0 - average(of: scores)) / standardDeviation(of: scores) } } func standardScore(of score: Double, by average: Double, _ standardDeviation: Double) -> Double { return (score - average) / standardDeviation } let a: [Double] = [70, 90, 60, 60]//[1, 2, 3, 4, 5] print("sum: ", sum(of: a)) print("average: ", average(of: a)) print("range: ", range(of: a)) print("variance: ", variance(of: a)) print("Standard Deviation: ", standardDeviation(of: a)) print("Sample Variance: ", sampleVariance(of: a)) print("Sample Standard Deviation: ", sampleStandardDeviation(of: a))
5d6a6bef8081628a77310f5d268df510
22.309524
97
0.620531
false
false
false
false
gsaslis/Rocket.Chat.iOS
refs/heads/develop
Rocket.Chat.iOS/ViewControllers/AccountBarViewController.swift
mit
1
// // AccountBar.swift // Rocket.Chat.iOS // // Created by giorgos on 8/26/15. // Copyright © 2015 Rocket.Chat. All rights reserved. // import UIKit class AccountBarViewController: UIViewController { // MARK: Properties @IBOutlet weak var detailsButton: UIButton! @IBOutlet weak var usernameLabel: UILabel! @IBOutlet weak var avatarIcon: UIImageView! @IBOutlet weak var statusIcon: UIImageView! /** this will tell you what the state was before the touch event */ var accountOptionsWereOpen = false var delegate:SwitchAccountViewDelegate! = nil override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Navigation //MARK: Navigation override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) { //rotate icon 180 let rotateAnimation = CABasicAnimation(keyPath: "transform.rotation") rotateAnimation.fromValue = 0.0 rotateAnimation.toValue = CGFloat(M_PI * 1.0) rotateAnimation.duration = 0.2 //handle the callback in the animationDidStop below rotateAnimation.delegate = self detailsButton.layer.addAnimation(rotateAnimation, forKey: nil) } override func animationDidStop(anim: CAAnimation, finished flag: Bool){ if (detailsButton.imageView?.image == UIImage(named: "Arrow-Up")) { detailsButton.imageView?.image = UIImage(named: "Arrow-Down") } else { detailsButton.imageView?.image = UIImage(named: "Arrow-Up") } if ((delegate) != nil){ // let delegate know about event delegate!.didClickOnAccountBar(accountOptionsWereOpen) accountOptionsWereOpen = !accountOptionsWereOpen } } /* // 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. } */ } /** This protocol is used for handling events from the AccountBar. */ protocol SwitchAccountViewDelegate { func didClickOnAccountBar(accountOptionsWereOpen: Bool) }
b24f5471de1436515b7e53a8d70105eb
27.571429
104
0.705
false
false
false
false
dymx101/Gamers
refs/heads/master
Gamers/ViewModels/HomeVideoCell.swift
apache-2.0
1
// // HomeVideoCell.swift // Gamers // // Created by 虚空之翼 on 15/8/9. // Copyright (c) 2015年 Freedom. All rights reserved. // import UIKit class HomeVideoCell: UITableViewCell { @IBOutlet weak var videoImage: UIImageView! @IBOutlet weak var videoTitle: UILabel! @IBOutlet weak var channelName: UILabel! @IBOutlet weak var videoViews: UILabel! var delegate: MyCellDelegate! // 点击触发自己的代理方法 @IBAction func clickShare(sender: AnyObject) { self.delegate.clickCellButton!(self) } override func awakeFromNib() { super.awakeFromNib() // 视频标题自动换行以及超出省略号 videoTitle.numberOfLines = 0 videoTitle.lineBreakMode = NSLineBreakMode.ByCharWrapping videoTitle.lineBreakMode = NSLineBreakMode.ByTruncatingTail } func setVideo(video: Video) { channelName.text = video.owner videoTitle.text = video.videoTitle videoViews.text = BasicFunction.formatViewsTotal(video.views) + " • " + BasicFunction.formatDateString(video.publishedAt) let imageUrl = video.imageSource.stringByReplacingOccurrencesOfString(" ", withString: "%20", options: NSStringCompareOptions.LiteralSearch, range: nil) videoImage.hnk_setImageFromURL(NSURL(string: imageUrl)!) } override func setSelected(selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } override func prepareForReuse() { super.prepareForReuse() videoImage.hnk_cancelSetImage() videoImage.image = nil } }
a3157cd905017a638a4df696aebf2757
26.783333
160
0.665267
false
false
false
false
edwardchao/MovingHelper
refs/heads/master
MovingHelper/ViewControllers/MasterViewController.swift
mit
3
// // MasterViewController.swift // MovingHelper // // Created by Ellen Shapiro on 6/7/15. // Copyright (c) 2015 Razeware. All rights reserved. // import UIKit //MARK: - Main view controller class public class MasterViewController: UITableViewController { //MARK: Properties private var movingDate: NSDate? private var sections = [[Task]]() private var allTasks = [Task]() { didSet { sections = SectionSplitter.sectionsFromTasks(allTasks) } } //MARK: View Lifecycle override public func viewDidLoad() { super.viewDidLoad() self.title = LocalizedStrings.taskListTitle movingDate = movingDateFromUserDefaults() if let storedTasks = TaskLoader.loadSavedTasksFromJSONFile(FileName.SavedTasks) { allTasks = storedTasks } //else case handled in view did appear } override public func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) if allTasks.count == 0 { showChooseMovingDateVC() } //else we're already good to go. } override public func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if let identifier = segue.identifier { let segueIdentifier: SegueIdentifier = SegueIdentifier(rawValue: identifier)! switch segueIdentifier { case .ShowDetailVCSegue: if let indexPath = self.tableView.indexPathForSelectedRow() { let task = taskForIndexPath(indexPath) (segue.destinationViewController as! DetailViewController).detailTask = task } case .ShowMovingDateVCSegue: (segue.destinationViewController as! MovingDateViewController).delegate = self default: NSLog("Unhandled identifier \(identifier)") //Do nothing. } } } //MARK: Task Handling func addOrUpdateTask(task: Task) { let index = task.dueDate.getIndex() let dueDateTasks = sections[index] var tasksWithDifferentID = filter(dueDateTasks) { $0.taskID != task.taskID } tasksWithDifferentID.append(task) tasksWithDifferentID.sort({ $0.taskID > $1.taskID }) sections[index] = tasksWithDifferentID tableView.reloadData() } //MARK: IBActions @IBAction func calendarIconTapped() { showChooseMovingDateVC() } private func showChooseMovingDateVC() { performSegueWithIdentifier(SegueIdentifier.ShowMovingDateVCSegue.rawValue, sender: nil) } //MARK: File Writing private func saveTasksToFile() { TaskSaver.writeTasksToFile(allTasks, fileName: FileName.SavedTasks) } //MARK: Moving Date Handling private func movingDateFromUserDefaults() -> NSDate? { return NSUserDefaults.standardUserDefaults() .valueForKey(UserDefaultKey.MovingDate.rawValue) as? NSDate } } //MARK: - Task Updated Delegate Extension extension MasterViewController: TaskUpdatedDelegate { public func taskUpdated(task: Task) { addOrUpdateTask(task) saveTasksToFile() } } //MARK: - Moving Date Delegate Extension extension MasterViewController: MovingDateDelegate { public func createdMovingTasks(tasks: [Task]) { allTasks = tasks saveTasksToFile() } public func updatedMovingDate() { movingDate = movingDateFromUserDefaults() tableView.reloadData() } } //MARK: - Table View Data Source Extension extension MasterViewController : UITableViewDataSource { private func taskForIndexPath(indexPath: NSIndexPath) -> Task { let tasks = tasksForSection(indexPath.section) return tasks[indexPath.row] } private func tasksForSection(section: Int) -> [Task] { let currentSection = sections[section] return currentSection } override public func numberOfSectionsInTableView(tableView: UITableView) -> Int { return sections.count } override public func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return 40 } override public func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let header = tableView.dequeueReusableCellWithIdentifier(TaskSectionHeaderView.cellIdentifierFromClassName()) as! TaskSectionHeaderView let dueDate = TaskDueDate.fromIndex(section) if let moveDate = movingDate { header.configureForDueDate(dueDate, moveDate: moveDate) } return header } override public func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { let tasks = tasksForSection(section) return tasks.count } override public func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier(TaskTableViewCell.cellIdentifierFromClassName(), forIndexPath: indexPath) as! TaskTableViewCell let task = taskForIndexPath(indexPath) cell.configureForTask(task) cell.delegate = self return cell } }
5115b76a07ba282ffe934b32262ac667
27.680233
154
0.7164
false
false
false
false
joerocca/GitHawk
refs/heads/master
Classes/Systems/GithubSessionManager.swift
mit
1
// // GitHubSession.swift // Freetime // // Created by Ryan Nystrom on 5/10/17. // Copyright © 2017 Ryan Nystrom. All rights reserved. // import Foundation import IGListKit protocol GithubSessionListener: class { func didReceiveRedirect(manager: GithubSessionManager, code: String) func didFocus(manager: GithubSessionManager, userSession: GithubUserSession, dismiss: Bool) func didLogout(manager: GithubSessionManager) } final class GithubSessionManager: NSObject, ListDiffable { private class ListenerWrapper: NSObject { weak var listener: GithubSessionListener? } private var listeners = [ListenerWrapper]() private enum Keys { enum v1 { static let session = "com.github.sessionmanager.session.1" } enum v2 { static let session = "com.github.sessionmanager.session.2" } } private let _userSessions = NSMutableOrderedSet() private let defaults = UserDefaults.standard override init() { // if a migration occurs, immediately save to disk var migrated = false if let v1data = defaults.object(forKey: Keys.v1.session) as? Data, let session = NSKeyedUnarchiver.unarchiveObject(with: v1data) as? GithubUserSession { _userSessions.add(session) // clear the outdated session format defaults.removeObject(forKey: Keys.v1.session) migrated = true } else if let v2data = defaults.object(forKey: Keys.v2.session) as? Data, let session = NSKeyedUnarchiver.unarchiveObject(with: v2data) as? NSOrderedSet { _userSessions.union(session) } super.init() if migrated { save() } } // MARK: Public API var focusedUserSession: GithubUserSession? { return _userSessions.firstObject as? GithubUserSession } var userSessions: [GithubUserSession] { return _userSessions.array as? [GithubUserSession] ?? [] } func addListener(listener: GithubSessionListener) { let wrapper = ListenerWrapper() wrapper.listener = listener listeners.append(wrapper) } public func focus( _ userSession: GithubUserSession, dismiss: Bool ) { _userSessions.remove(userSession) _userSessions.insert(userSession, at: 0) save() for wrapper in listeners { wrapper.listener?.didFocus(manager: self, userSession: userSession, dismiss: dismiss) } } public func logout() { _userSessions.removeAllObjects() save() for wrapper in listeners { wrapper.listener?.didLogout(manager: self) } } func save() { if _userSessions.count > 0 { defaults.set(NSKeyedArchiver.archivedData(withRootObject: _userSessions), forKey: Keys.v2.session) } else { defaults.removeObject(forKey: Keys.v2.session) } } func receivedCodeRedirect(url: URL) { guard let code = url.absoluteString.valueForQuery(key: "code") else { return } for wrapper in listeners { wrapper.listener?.didReceiveRedirect(manager: self, code: code) } } // MARK: ListDiffable func diffIdentifier() -> NSObjectProtocol { return self } func isEqual(toDiffableObject object: ListDiffable?) -> Bool { return self === object } }
023ac1778ef2fc7f83649f2945e043d1
27.553719
110
0.633864
false
false
false
false
ncalexan/firefox-ios
refs/heads/master
SyncTests/TestBookmarkTreeMerging.swift
mpl-2.0
1
/* 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 Deferred import Foundation import Shared @testable import Storage @testable import Sync import XCTest extension Dictionary { init<S: Sequence>(seq: S) where S.Iterator.Element == Element { self.init() for (k, v) in seq { self[k] = v } } } class MockLocalItemSource: LocalItemSource { var local: [GUID: BookmarkMirrorItem] = [:] func getLocalItemWithGUID(_ guid: GUID) -> Deferred<Maybe<BookmarkMirrorItem>> { guard let item = self.local[guid] else { return deferMaybe(DatabaseError(description: "Couldn't find item \(guid).")) } return deferMaybe(item) } func getLocalItemsWithGUIDs<T: Collection>(_ guids: T) -> Deferred<Maybe<[GUID: BookmarkMirrorItem]>> where T.Iterator.Element == GUID { var acc: [GUID: BookmarkMirrorItem] = [:] guids.forEach { guid in if let item = self.local[guid] { acc[guid] = item } } return deferMaybe(acc) } func prefetchLocalItemsWithGUIDs<T: Collection>(_ guids: T) -> Success where T.Iterator.Element == GUID { return succeed() } } class MockMirrorItemSource: MirrorItemSource { var mirror: [GUID: BookmarkMirrorItem] = [:] func getMirrorItemWithGUID(_ guid: GUID) -> Deferred<Maybe<BookmarkMirrorItem>> { guard let item = self.mirror[guid] else { return deferMaybe(DatabaseError(description: "Couldn't find item \(guid).")) } return deferMaybe(item) } func getMirrorItemsWithGUIDs<T: Collection>(_ guids: T) -> Deferred<Maybe<[GUID: BookmarkMirrorItem]>> where T.Iterator.Element == GUID { var acc: [GUID: BookmarkMirrorItem] = [:] guids.forEach { guid in if let item = self.mirror[guid] { acc[guid] = item } } return deferMaybe(acc) } func prefetchMirrorItemsWithGUIDs<T: Collection>(_ guids: T) -> Success where T.Iterator.Element == GUID { return succeed() } } class MockBufferItemSource: BufferItemSource { var buffer: [GUID: BookmarkMirrorItem] = [:] func getBufferItemsWithGUIDs<T: Collection>(_ guids: T) -> Deferred<Maybe<[GUID: BookmarkMirrorItem]>> where T.Iterator.Element == GUID { var acc: [GUID: BookmarkMirrorItem] = [:] guids.forEach { guid in if let item = self.buffer[guid] { acc[guid] = item } } return deferMaybe(acc) } func getBufferItemWithGUID(_ guid: GUID) -> Deferred<Maybe<BookmarkMirrorItem>> { guard let item = self.buffer[guid] else { return deferMaybe(DatabaseError(description: "Couldn't find item \(guid).")) } return deferMaybe(item) } func getBufferChildrenGUIDsForParent(_ guid: GUID) -> Deferred<Maybe<[GUID]>> { return deferMaybe(DatabaseError(description: "Not implemented")) } func prefetchBufferItemsWithGUIDs<T: Collection>(_ guids: T) -> Success where T.Iterator.Element == GUID { return succeed() } } class MockUploader { var deletions: Set<GUID> = Set<GUID>() var added: Set<GUID> = Set<GUID>() var records: [GUID: Record<BookmarkBasePayload>] = [:] func getStorer() -> TrivialBookmarkStorer { return TrivialBookmarkStorer(uploader: self.doUpload) } func doUpload(recs: [Record<BookmarkBasePayload>], lastTimestamp: Timestamp?, onUpload: (POSTResult, Timestamp) -> DeferredTimestamp) -> DeferredTimestamp { var success: [GUID] = [] recs.forEach { rec in success.append(rec.id) self.records[rec.id] = rec if rec.payload.deleted { self.deletions.insert(rec.id) } else { self.added.insert(rec.id) } } // Now pretend we did the upload. return onUpload(POSTResult(success: success, failed: [:]), Date.now()) } } // Thieved mercilessly from TestSQLiteBookmarks. private func getBrowserDBForFile(filename: String, files: FileAccessor) -> BrowserDB? { let db = BrowserDB(filename: filename, schema: BrowserSchema(), files: files) db.touch().succeeded() // Ensure the schema is created/updated in advance return db } class FailFastTestCase: XCTestCase { // This is how to make an assertion failure stop the current test function // but continue with other test functions in the same test case. // See http://stackoverflow.com/a/27016786/22003 override func invokeTest() { self.continueAfterFailure = false defer { self.continueAfterFailure = true } super.invokeTest() } } class TestBookmarkTreeMerging: FailFastTestCase { let files = MockFiles() override func tearDown() { do { try self.files.removeFilesInDirectory() } catch { } super.tearDown() } private func getBrowserDB(name: String) -> BrowserDB? { let file = "TBookmarkTreeMerging\(name).db" return getBrowserDBForFile(filename: file, files: self.files) } private func mockStatsSessionForBookmarks() -> SyncEngineStatsSession { let session = SyncEngineStatsSession(collection: "bookmarks") session.start() return session } func getSyncableBookmarks(name: String) -> MergedSQLiteBookmarks? { guard let db = self.getBrowserDB(name: name) else { XCTFail("Couldn't get prepared DB.") return nil } return MergedSQLiteBookmarks(db: db) } func getSQLiteBookmarks(name: String) -> SQLiteBookmarks? { guard let db = self.getBrowserDB(name: name) else { XCTFail("Couldn't get prepared DB.") return nil } return SQLiteBookmarks(db: db) } func dbLocalTree(name: String) -> BookmarkTree? { guard let bookmarks = self.getSQLiteBookmarks(name: name) else { XCTFail("Couldn't get bookmarks.") return nil } return bookmarks.treeForLocal().value.successValue } func localTree() -> BookmarkTree { let roots = BookmarkRoots.RootChildren.map { BookmarkTreeNode.folder(guid: $0, children: []) } let places = BookmarkTreeNode.folder(guid: BookmarkRoots.RootGUID, children: roots) var lookup: [GUID: BookmarkTreeNode] = [:] var parents: [GUID: GUID] = [:] for n in roots { lookup[n.recordGUID] = n parents[n.recordGUID] = BookmarkRoots.RootGUID } lookup[BookmarkRoots.RootGUID] = places return BookmarkTree(subtrees: [places], lookup: lookup, parents: parents, orphans: Set(), deleted: Set(), modified: Set(lookup.keys), virtual: Set()) } // Our synthesized tree is the same as the one we pull out of a brand new local DB. func testLocalTreeAssumption() { let constructed = self.localTree() let fromDB = self.dbLocalTree(name: "A") XCTAssertNotNil(fromDB) XCTAssertTrue(fromDB!.isFullyRootedIn(constructed)) XCTAssertTrue(constructed.isFullyRootedIn(fromDB!)) XCTAssertTrue(fromDB!.virtual.isEmpty) XCTAssertTrue(constructed.virtual.isEmpty) } // This should never occur in the wild: local will never be empty. func testMergingEmpty() { let r = BookmarkTree.emptyTree() let m = BookmarkTree.emptyMirrorTree() let l = BookmarkTree.emptyTree() let s = ItemSources(local: MockLocalItemSource(), mirror: MockMirrorItemSource(), buffer: MockBufferItemSource()) XCTAssertEqual(m.virtual, BookmarkRoots.Real) let merger = ThreeWayTreeMerger(local: l, mirror: m, remote: r, itemSources: s) guard let mergedTree = merger.produceMergedTree().value.successValue else { XCTFail("Couldn't merge.") return } mergedTree.dump() XCTAssertEqual(mergedTree.allGUIDs, BookmarkRoots.Real) guard let result = merger.produceMergeResultFromMergedTree(mergedTree).value.successValue else { XCTFail("Couldn't produce result.") return } // We don't test the local override completion, because of course we saw mirror items. XCTAssertTrue(result.uploadCompletion.isNoOp) XCTAssertTrue(result.bufferCompletion.isNoOp) } func getItemSourceIncludingEmptyRoots() -> ItemSources { let local = MockLocalItemSource() func makeRoot(guid: GUID, _ name: String) { local.local[guid] = BookmarkMirrorItem.folder(guid, modified: Date.now(), hasDupe: false, parentID: BookmarkRoots.RootGUID, parentName: "", title: name, description: nil, children: []) } makeRoot(guid: BookmarkRoots.MenuFolderGUID, "Bookmarks Menu") makeRoot(guid: BookmarkRoots.ToolbarFolderGUID, "Bookmarks Toolbar") makeRoot(guid: BookmarkRoots.MobileFolderGUID, "Mobile Bookmarks") makeRoot(guid: BookmarkRoots.UnfiledFolderGUID, "Unsorted Bookmarks") makeRoot(guid: BookmarkRoots.RootGUID, "") return ItemSources(local: local, mirror: MockMirrorItemSource(), buffer: MockBufferItemSource()) } func testMergingOnlyLocalRoots() { let r = BookmarkTree.emptyTree() let m = BookmarkTree.emptyMirrorTree() let l = self.localTree() let s = self.getItemSourceIncludingEmptyRoots() let merger = ThreeWayTreeMerger(local: l, mirror: m, remote: r, itemSources: s) guard let mergedTree = merger.produceMergedTree().value.successValue else { XCTFail("Couldn't merge.") return } mergedTree.dump() XCTAssertEqual(mergedTree.allGUIDs, BookmarkRoots.Real) guard let result = merger.produceMergeResultFromMergedTree(mergedTree).value.successValue else { XCTFail("Couldn't produce result.") return } XCTAssertFalse(result.isNoOp) XCTAssertTrue(result.overrideCompletion.processedLocalChanges.isSuperset(of: Set(BookmarkRoots.RootChildren))) // We should be dropping the roots from local, and uploading roots to the server. // The outgoing records should use Sync-style IDs. // We never upload the places root. let banned = Set<GUID>(["places", BookmarkRoots.RootGUID]) XCTAssertTrue(banned.isDisjoint(with: Set(result.uploadCompletion.records.map { $0.id }))) XCTAssertTrue(banned.isDisjoint(with: result.uploadCompletion.amendChildrenFromBuffer.keys)) XCTAssertTrue(banned.isDisjoint(with: result.uploadCompletion.amendChildrenFromMirror.keys)) XCTAssertTrue(banned.isDisjoint(with: result.uploadCompletion.amendChildrenFromLocal.keys)) XCTAssertEqual(Set(BookmarkRoots.RootChildren), Set(result.uploadCompletion.amendChildrenFromLocal.keys)) XCTAssertEqual(Set(BookmarkRoots.Real), result.overrideCompletion.processedLocalChanges) } func testMergingStorageLocalRootsEmptyServer() { guard let bookmarks = self.getSyncableBookmarks(name: "B") else { XCTFail("Couldn't get bookmarks.") return } // The mirror is never actually empty. let mirrorTree = bookmarks.treeForMirror().value.successValue! XCTAssertFalse(mirrorTree.isEmpty) XCTAssertEqual(mirrorTree.lookup.keys.count, 5) // Root and four children. XCTAssertEqual(1, mirrorTree.subtrees.count) let edgesBefore = bookmarks.treesForEdges().value.successValue! XCTAssertFalse(edgesBefore.local.isEmpty) XCTAssertTrue(edgesBefore.buffer.isEmpty) let uploader = MockUploader() let storer = uploader.getStorer() let applier = MergeApplier(buffer: bookmarks, storage: bookmarks, client: storer, statsSession: mockStatsSessionForBookmarks(), greenLight: { true }) applier.go().succeeded() // Now the local contents are replicated into the mirror, and both the buffer and local are empty. guard let mirror = bookmarks.treeForMirror().value.successValue else { XCTFail("Couldn't get mirror!") return } XCTAssertFalse(mirror.isEmpty) XCTAssertTrue(mirror.subtrees[0].recordGUID == BookmarkRoots.RootGUID) let edgesAfter = bookmarks.treesForEdges().value.successValue! XCTAssertTrue(edgesAfter.local.isEmpty) XCTAssertTrue(edgesAfter.buffer.isEmpty) XCTAssertEqual(uploader.added, Set(BookmarkRoots.RootChildren.map(BookmarkRoots.translateOutgoingRootGUID))) } func testComplexOrphaning() { // This test describes a scenario like this: // // [] [] [] // [M] [T] [M] [T] [M] [T] // | | | | | | // [C] [A] [C] [A] [C] [A] // | | | | // [D] [D] [B] [B] // | | // F E // // That is: we have locally added 'E' to folder B and deleted folder D, // and remotely added 'F' to folder D and deleted folder B. // // This is a fundamental conflict that would ordinarily produce orphans. // Our resolution for this is to put those orphans _somewhere_. // // That place is the lowest surviving parent: walk the tree until we find // a folder that still exists, and put the orphans there. This is a little // better than just dumping the records into Unsorted Bookmarks, and no // more complex than dumping them into the closest root. // // We expect: // // [] // [M] [T] // | | // [C] [A] // | | // F E // guard let bookmarks = self.getSyncableBookmarks(name: "G") else { XCTFail("Couldn't get bookmarks.") return } // Set up the mirror. let mirrorDate = Date.now() - 100000 let records = [ BookmarkMirrorItem.folder(BookmarkRoots.RootGUID, modified: mirrorDate, hasDupe: false, parentID: BookmarkRoots.RootGUID, parentName: "", title: "", description: "", children: BookmarkRoots.RootChildren), BookmarkMirrorItem.folder(BookmarkRoots.MenuFolderGUID, modified: mirrorDate, hasDupe: false, parentID: BookmarkRoots.RootGUID, parentName: "", title: "Bookmarks Menu", description: "", children: ["folderCCCCCC"]), BookmarkMirrorItem.folder(BookmarkRoots.UnfiledFolderGUID, modified: mirrorDate, hasDupe: false, parentID: BookmarkRoots.RootGUID, parentName: "", title: "Unsorted Bookmarks", description: "", children: []), BookmarkMirrorItem.folder(BookmarkRoots.ToolbarFolderGUID, modified: mirrorDate, hasDupe: false, parentID: BookmarkRoots.RootGUID, parentName: "", title: "Bookmarks Toolbar", description: "", children: ["folderAAAAAA"]), BookmarkMirrorItem.folder(BookmarkRoots.MobileFolderGUID, modified: mirrorDate, hasDupe: false, parentID: BookmarkRoots.RootGUID, parentName: "", title: "Mobile Bookmarks", description: "", children: []), BookmarkMirrorItem.folder("folderAAAAAA", modified: mirrorDate, hasDupe: false, parentID: BookmarkRoots.ToolbarFolderGUID, parentName: "Bookmarks Toolbar", title: "A", description: "", children: ["folderBBBBBB"]), BookmarkMirrorItem.folder("folderBBBBBB", modified: mirrorDate, hasDupe: false, parentID: "folderAAAAAA", parentName: "A", title: "B", description: "", children: []), BookmarkMirrorItem.folder("folderCCCCCC", modified: mirrorDate, hasDupe: false, parentID: BookmarkRoots.MenuFolderGUID, parentName: "Bookmarks Menu", title: "C", description: "", children: ["folderDDDDDD"]), BookmarkMirrorItem.folder("folderDDDDDD", modified: mirrorDate, hasDupe: false, parentID: "folderCCCCCC", parentName: "C", title: "D", description: "", children: []), ] bookmarks.populateMirrorViaBuffer(items: records, atDate: mirrorDate) bookmarks.wipeLocal() // Now the buffer is empty, and the mirror tree is what we expect. let mirrorTree = bookmarks.treeForMirror().value.successValue! XCTAssertFalse(mirrorTree.isEmpty) XCTAssertEqual(mirrorTree.lookup.keys.count, 9) XCTAssertEqual(1, mirrorTree.subtrees.count) XCTAssertEqual(mirrorTree.find("folderAAAAAA")!.children!.map { $0.recordGUID }, ["folderBBBBBB"]) XCTAssertEqual(mirrorTree.find("folderCCCCCC")!.children!.map { $0.recordGUID }, ["folderDDDDDD"]) let edgesBefore = bookmarks.treesForEdges().value.successValue! XCTAssertTrue(edgesBefore.local.isEmpty) // Because we're fully synced. XCTAssertTrue(edgesBefore.buffer.isEmpty) // Set up the buffer. let bufferDate = Date.now() let changedBufferRecords = [ BookmarkMirrorItem.deleted(BookmarkNodeType.folder, guid: "folderBBBBBB", modified: bufferDate), BookmarkMirrorItem.folder("folderAAAAAA", modified: bufferDate, hasDupe: false, parentID: BookmarkRoots.ToolbarFolderGUID, parentName: "Bookmarks Toolbar", title: "A", description: "", children: []), BookmarkMirrorItem.folder("folderDDDDDD", modified: bufferDate, hasDupe: false, parentID: "folderCCCCCC", parentName: "C", title: "D", description: "", children: ["bookmarkFFFF"]), BookmarkMirrorItem.bookmark("bookmarkFFFF", modified: bufferDate, hasDupe: false, parentID: "folderDDDDDD", parentName: "D", title: "F", description: nil, URI: "http://example.com/f", tags: "", keyword: nil), ] bookmarks.applyRecords(changedBufferRecords).succeeded() // Make local changes. bookmarks.local.modelFactory.value.successValue!.removeByGUID("folderDDDDDD").succeeded() bookmarks.local.insertBookmark("http://example.com/e".asURL!, title: "E", favicon: nil, intoFolder: "folderBBBBBB", withTitle: "B").succeeded() let insertedGUID = bookmarks.local.db.getGUIDs("SELECT guid FROM \(TableBookmarksLocal) WHERE title IS 'E'")[0] let edges = bookmarks.treesForEdges().value.successValue! XCTAssertFalse(edges.local.isEmpty) XCTAssertFalse(edges.buffer.isEmpty) XCTAssertTrue(edges.local.isFullyRootedIn(mirrorTree)) XCTAssertTrue(edges.buffer.isFullyRootedIn(mirrorTree)) XCTAssertTrue(edges.buffer.deleted.contains("folderBBBBBB")) XCTAssertFalse(edges.buffer.deleted.contains("folderDDDDDD")) XCTAssertFalse(edges.local.deleted.contains("folderBBBBBB")) XCTAssertTrue(edges.local.deleted.contains("folderDDDDDD")) // Now merge. let storageMerger = ThreeWayBookmarksStorageMerger(buffer: bookmarks, storage: bookmarks) let merger = storageMerger.getMerger().value.successValue! guard let mergedTree = merger.produceMergedTree().value.successValue else { XCTFail("Couldn't get merge result.") return } // Dump it so we can see it. mergedTree.dump() XCTAssertTrue(mergedTree.deleteLocally.contains("folderBBBBBB")) XCTAssertTrue(mergedTree.deleteFromMirror.contains("folderBBBBBB")) XCTAssertTrue(mergedTree.deleteRemotely.contains("folderDDDDDD")) XCTAssertTrue(mergedTree.deleteFromMirror.contains("folderDDDDDD")) XCTAssertTrue(mergedTree.acceptLocalDeletion.contains("folderDDDDDD")) XCTAssertTrue(mergedTree.acceptRemoteDeletion.contains("folderBBBBBB")) // E and F still exist, in Menu and Toolbar respectively. // Note that the merge itself includes asserts for this; we shouldn't even get here if // this part will fail. XCTAssertTrue(mergedTree.allGUIDs.contains(insertedGUID)) XCTAssertTrue(mergedTree.allGUIDs.contains("bookmarkFFFF")) let menu = mergedTree.root.mergedChildren![0] // menu, toolbar, unfiled, mobile, so 0. let toolbar = mergedTree.root.mergedChildren![1] // menu, toolbar, unfiled, mobile, so 1. XCTAssertEqual(BookmarkRoots.MenuFolderGUID, menu.guid) XCTAssertEqual(BookmarkRoots.ToolbarFolderGUID, toolbar.guid) let folderC = menu.mergedChildren![0] let folderA = toolbar.mergedChildren![0] XCTAssertEqual("folderCCCCCC", folderC.guid) XCTAssertEqual("folderAAAAAA", folderA.guid) XCTAssertEqual(insertedGUID, folderA.mergedChildren![0].guid) XCTAssertEqual("bookmarkFFFF", folderC.mergedChildren![0].guid) guard let result = merger.produceMergeResultFromMergedTree(mergedTree).value.successValue else { XCTFail("Couldn't get merge result.") return } XCTAssertFalse(result.isNoOp) // Everything in local is getting dropped. let formerLocalIDs = Set(edges.local.lookup.keys) XCTAssertTrue(result.overrideCompletion.processedLocalChanges.isSuperset(of: formerLocalIDs)) // Everything in the buffer is getting dropped. let formerBufferIDs = Set(edges.buffer.lookup.keys) XCTAssertTrue(result.bufferCompletion.processedBufferChanges.isSuperset(of: formerBufferIDs)) // The mirror will now contain everything added by each side, and not the deleted folders. XCTAssertEqual(result.overrideCompletion.mirrorItemsToDelete, Set(["folderBBBBBB", "folderDDDDDD"])) XCTAssertTrue(result.overrideCompletion.mirrorValuesToCopyFromLocal.isEmpty) XCTAssertTrue(result.overrideCompletion.mirrorValuesToCopyFromBuffer.isEmpty) XCTAssertTrue(result.overrideCompletion.mirrorItemsToInsert.keys.contains(insertedGUID)) // Because it was reparented. XCTAssertTrue(result.overrideCompletion.mirrorItemsToInsert.keys.contains("bookmarkFFFF")) // Because it was reparented. // The mirror now has the right structure. XCTAssertEqual(result.overrideCompletion.mirrorStructures["folderCCCCCC"]!, ["bookmarkFFFF"]) XCTAssertEqual(result.overrideCompletion.mirrorStructures["folderAAAAAA"]!, [insertedGUID]) // We're going to upload new records for C (lost a child), F (changed parent), // insertedGUID (new local record), A (new child), and D (deleted). // Anything that was in the mirror and only changed structure: let expected: [GUID: [GUID]] = ["folderCCCCCC": ["bookmarkFFFF"], "folderAAAAAA": [insertedGUID]] let actual: [GUID: [GUID]] = result.uploadCompletion.amendChildrenFromMirror XCTAssertEqual(actual as NSDictionary, expected as NSDictionary) // Anything deleted: XCTAssertTrue(result.uploadCompletion.records.contains(where: { (($0.id == "folderDDDDDD") && ($0.payload["deleted"].bool ?? false)) })) // Inserted: let uploadE = result.uploadCompletion.records.find { $0.id == insertedGUID } XCTAssertNotNil(uploadE) XCTAssertEqual(uploadE!.payload["title"].stringValue, "E") // We fixed the parent before uploading. XCTAssertEqual(uploadE!.payload["parentid"].stringValue, "folderAAAAAA") XCTAssertEqual(uploadE!.payload["parentName"].string ?? "", "A") // Reparented: let uploadF = result.uploadCompletion.records.find { $0.id == "bookmarkFFFF" } XCTAssertNotNil(uploadF) XCTAssertEqual(uploadF!.payload["title"].stringValue, "F") // We fixed the parent before uploading. XCTAssertEqual(uploadF!.payload["parentid"].stringValue, "folderCCCCCC") XCTAssertEqual(uploadF!.payload["parentName"].string ?? "", "C") } func testComplexMoveWithAdditions() { // This test describes a scenario like this: // // [] [] [] // [X] [Y] [X] [Y] [X] [Y] // | | | | // [A] C [A] [A] // / \ / \ / | \ // B E B C B D C // // That is: we have locally added 'D' to folder A, and remotely moved // A to a different root, added 'E', and moved 'C' back to the old root. // // Our expected result is: // // [] // [X] [Y] // | | // [A] C // / | \ // B D E // // … but we'll settle for any order of children for [A] that preserves B < E // and B < D -- in other words, (B E D) and (B D E) are both acceptable. // guard let bookmarks = self.getSyncableBookmarks(name: "F") else { XCTFail("Couldn't get bookmarks.") return } // Set up the mirror. let mirrorDate = Date.now() - 100000 let records = [ BookmarkMirrorItem.folder(BookmarkRoots.RootGUID, modified: mirrorDate, hasDupe: false, parentID: BookmarkRoots.RootGUID, parentName: "", title: "", description: "", children: BookmarkRoots.RootChildren), BookmarkMirrorItem.folder(BookmarkRoots.MenuFolderGUID, modified: mirrorDate, hasDupe: false, parentID: BookmarkRoots.RootGUID, parentName: "", title: "Bookmarks Menu", description: "", children: ["folderAAAAAA"]), BookmarkMirrorItem.folder(BookmarkRoots.UnfiledFolderGUID, modified: mirrorDate, hasDupe: false, parentID: BookmarkRoots.RootGUID, parentName: "", title: "Unsorted Bookmarks", description: "", children: []), BookmarkMirrorItem.folder(BookmarkRoots.ToolbarFolderGUID, modified: mirrorDate, hasDupe: false, parentID: BookmarkRoots.RootGUID, parentName: "", title: "Bookmarks Toolbar", description: "", children: []), BookmarkMirrorItem.folder(BookmarkRoots.MobileFolderGUID, modified: mirrorDate, hasDupe: false, parentID: BookmarkRoots.RootGUID, parentName: "", title: "Mobile Bookmarks", description: "", children: []), BookmarkMirrorItem.folder("folderAAAAAA", modified: mirrorDate, hasDupe: false, parentID: BookmarkRoots.MenuFolderGUID, parentName: "Bookmarks Menu", title: "A", description: "", children: ["bookmarkBBBB", "bookmarkCCCC"]), BookmarkMirrorItem.bookmark("bookmarkBBBB", modified: mirrorDate, hasDupe: false, parentID: "folderAAAAAA", parentName: "A", title: "B", description: nil, URI: "http://example.com/b", tags: "", keyword: nil), BookmarkMirrorItem.bookmark("bookmarkCCCC", modified: mirrorDate, hasDupe: false, parentID: "folderAAAAAA", parentName: "A", title: "C", description: nil, URI: "http://example.com/c", tags: "", keyword: nil), ] bookmarks.populateMirrorViaBuffer(items: records, atDate: mirrorDate) bookmarks.wipeLocal() // Now the buffer is empty, and the mirror tree is what we expect. let mirrorTree = bookmarks.treeForMirror().value.successValue! XCTAssertFalse(mirrorTree.isEmpty) XCTAssertEqual(mirrorTree.lookup.keys.count, 8) XCTAssertEqual(1, mirrorTree.subtrees.count) XCTAssertEqual(mirrorTree.find("folderAAAAAA")!.children!.map { $0.recordGUID }, ["bookmarkBBBB", "bookmarkCCCC"]) let edgesBefore = bookmarks.treesForEdges().value.successValue! XCTAssertTrue(edgesBefore.local.isEmpty) // Because we're fully synced. XCTAssertTrue(edgesBefore.buffer.isEmpty) // Set up the buffer. let bufferDate = Date.now() let changedBufferRecords = [ BookmarkMirrorItem.folder(BookmarkRoots.MenuFolderGUID, modified: bufferDate, hasDupe: false, parentID: BookmarkRoots.RootGUID, parentName: "", title: "Bookmarks Menu", description: "", children: ["bookmarkCCCC"]), BookmarkMirrorItem.folder(BookmarkRoots.ToolbarFolderGUID, modified: bufferDate, hasDupe: false, parentID: BookmarkRoots.RootGUID, parentName: "", title: "Bookmarks Toolbar", description: "", children: ["folderAAAAAA"]), BookmarkMirrorItem.folder("folderAAAAAA", modified: bufferDate, hasDupe: false, parentID: BookmarkRoots.ToolbarFolderGUID, parentName: "Bookmarks Toolbar", title: "A", description: "", children: ["bookmarkBBBB", "bookmarkEEEE"]), BookmarkMirrorItem.bookmark("bookmarkCCCC", modified: bufferDate, hasDupe: false, parentID: BookmarkRoots.MenuFolderGUID, parentName: "A", title: "C", description: nil, URI: "http://example.com/c", tags: "", keyword: nil), BookmarkMirrorItem.bookmark("bookmarkEEEE", modified: bufferDate, hasDupe: false, parentID: "folderAAAAAA", parentName: "A", title: "E", description: nil, URI: "http://example.com/e", tags: "", keyword: nil), ] bookmarks.applyRecords(changedBufferRecords).succeeded() let populatedBufferTree = bookmarks.treesForEdges().value.successValue!.buffer XCTAssertFalse(populatedBufferTree.isEmpty) XCTAssertTrue(populatedBufferTree.isFullyRootedIn(mirrorTree)) XCTAssertFalse(populatedBufferTree.find("bookmarkEEEE")!.isUnknown) XCTAssertFalse(populatedBufferTree.find("bookmarkCCCC")!.isUnknown) XCTAssertTrue(populatedBufferTree.find("bookmarkBBBB")!.isUnknown) // Now let's make local changes with the API. bookmarks.local.insertBookmark("http://example.com/d".asURL!, title: "D (local)", favicon: nil, intoFolder: "folderAAAAAA", withTitle: "A").succeeded() let populatedLocalTree = bookmarks.treesForEdges().value.successValue!.local let newMirrorTree = bookmarks.treeForMirror().value.successValue! XCTAssertEqual(1, newMirrorTree.subtrees.count) XCTAssertFalse(populatedLocalTree.isEmpty) XCTAssertTrue(populatedLocalTree.isFullyRootedIn(mirrorTree)) XCTAssertTrue(populatedLocalTree.isFullyRootedIn(newMirrorTree)) // It changed. XCTAssertNil(populatedLocalTree.find("bookmarkEEEE")) XCTAssertTrue(populatedLocalTree.find("bookmarkCCCC")!.isUnknown) XCTAssertTrue(populatedLocalTree.find("bookmarkBBBB")!.isUnknown) XCTAssertFalse(populatedLocalTree.find("folderAAAAAA")!.isUnknown) // Now merge. let storageMerger = ThreeWayBookmarksStorageMerger(buffer: bookmarks, storage: bookmarks) let merger = storageMerger.getMerger().value.successValue! guard let mergedTree = merger.produceMergedTree().value.successValue else { XCTFail("Couldn't get merge result.") return } // Dump it so we can see it. mergedTree.dump() guard let menu = mergedTree.root.mergedChildren?[0] else { XCTFail("Expected a child of the root.") return } XCTAssertEqual(menu.guid, BookmarkRoots.MenuFolderGUID) XCTAssertEqual(menu.mergedChildren?[0].guid, "bookmarkCCCC") guard let toolbar = mergedTree.root.mergedChildren?[1] else { XCTFail("Expected a second child of the root.") return } XCTAssertEqual(toolbar.guid, BookmarkRoots.ToolbarFolderGUID) let toolbarChildren = toolbar.mergedChildren! XCTAssertEqual(toolbarChildren.count, 1) // A. let aaa = toolbarChildren[0] XCTAssertEqual(aaa.guid, "folderAAAAAA") let aaaChildren = aaa.mergedChildren! XCTAssertEqual(aaaChildren.count, 3) // B, E, new local. XCTAssertFalse(aaaChildren.contains { $0.guid == "bookmarkCCCC" }) } func testApplyingTwoEmptyFoldersDoesntSmush() { guard let bookmarks = self.getSyncableBookmarks(name: "C") else { XCTFail("Couldn't get bookmarks.") return } // Insert two identical folders. We mark them with hasDupe because that's the Syncy // thing to do. let now = Date.now() let records = [ BookmarkMirrorItem.folder(BookmarkRoots.MobileFolderGUID, modified: now, hasDupe: false, parentID: BookmarkRoots.RootGUID, parentName: "", title: "Mobile Bookmarks", description: "", children: ["emptyempty01", "emptyempty02"]), BookmarkMirrorItem.folder("emptyempty01", modified: now, hasDupe: true, parentID: BookmarkRoots.MobileFolderGUID, parentName: "Mobile Bookmarks", title: "Empty", description: "", children: []), BookmarkMirrorItem.folder("emptyempty02", modified: now, hasDupe: true, parentID: BookmarkRoots.MobileFolderGUID, parentName: "Mobile Bookmarks", title: "Empty", description: "", children: []), ] bookmarks.buffer.applyRecords(records).succeeded() bookmarks.buffer.db.assertQueryReturns("SELECT COUNT(*) FROM \(TableBookmarksBuffer)", int: 3) bookmarks.buffer.db.assertQueryReturns("SELECT COUNT(*) FROM \(TableBookmarksBufferStructure)", int: 2) let storageMerger = ThreeWayBookmarksStorageMerger(buffer: bookmarks, storage: bookmarks) let merger = storageMerger.getMerger().value.successValue! guard let mergedTree = merger.produceMergedTree().value.successValue else { XCTFail("Couldn't get merge result.") return } // Dump it so we can see it. mergedTree.dump() // Now let's look at the tree. XCTAssertTrue(mergedTree.deleteFromMirror.isEmpty) XCTAssertEqual(BookmarkRoots.RootGUID, mergedTree.root.guid) XCTAssertEqual(BookmarkRoots.RootGUID, mergedTree.root.mirror?.recordGUID) XCTAssertNil(mergedTree.root.remote) XCTAssertTrue(MergeState<BookmarkMirrorItem>.unchanged == mergedTree.root.valueState) XCTAssertTrue(MergeState<BookmarkTreeNode>.unchanged == mergedTree.root.structureState) XCTAssertEqual(4, mergedTree.root.mergedChildren?.count) guard let mergedMobile = mergedTree.root.mergedChildren?[BookmarkRoots.RootChildren.index(of: BookmarkRoots.MobileFolderGUID) ?? -1] else { XCTFail("Didn't get a merged mobile folder.") return } XCTAssertEqual(BookmarkRoots.MobileFolderGUID, mergedMobile.guid) XCTAssertTrue(MergeState<BookmarkMirrorItem>.remote == mergedMobile.valueState) // This ends up as Remote because we didn't change any of its structure // when compared to the incoming record. guard case MergeState<BookmarkTreeNode>.remote = mergedMobile.structureState else { XCTFail("Didn't get expected Remote state.") return } XCTAssertEqual(["emptyempty01", "emptyempty02"], mergedMobile.remote!.children!.map { $0.recordGUID }) XCTAssertEqual(["emptyempty01", "emptyempty02"], mergedMobile.asMergedTreeNode().children!.map { $0.recordGUID }) XCTAssertEqual(["emptyempty01", "emptyempty02"], mergedMobile.mergedChildren!.map { $0.guid }) let empty01 = mergedMobile.mergedChildren![0] let empty02 = mergedMobile.mergedChildren![1] XCTAssertNil(empty01.local) XCTAssertNil(empty02.local) XCTAssertNil(empty01.mirror) XCTAssertNil(empty02.mirror) XCTAssertNotNil(empty01.remote) XCTAssertNotNil(empty02.remote) XCTAssertEqual("emptyempty01", empty01.remote!.recordGUID) XCTAssertEqual("emptyempty02", empty02.remote!.recordGUID) XCTAssertTrue(MergeState<BookmarkTreeNode>.remote == empty01.structureState) XCTAssertTrue(MergeState<BookmarkTreeNode>.remote == empty02.structureState) XCTAssertTrue(MergeState<BookmarkMirrorItem>.remote == empty01.valueState) XCTAssertTrue(MergeState<BookmarkMirrorItem>.remote == empty02.valueState) XCTAssertTrue(empty01.mergedChildren?.isEmpty ?? false) XCTAssertTrue(empty02.mergedChildren?.isEmpty ?? false) guard let result = merger.produceMergeResultFromMergedTree(mergedTree).value.successValue else { XCTFail("Couldn't get merge result.") return } let uploader = MockUploader() let storer = uploader.getStorer() let applier = MergeApplier(buffer: bookmarks, storage: bookmarks, client: storer, statsSession: mockStatsSessionForBookmarks(), greenLight: { true }) applier.applyResult(result).succeeded() guard let mirror = bookmarks.treeForMirror().value.successValue else { XCTFail("Couldn't get mirror!") return } // After merge, the buffer and local are empty. let edgesAfter = bookmarks.treesForEdges().value.successValue! XCTAssertTrue(edgesAfter.local.isEmpty) XCTAssertTrue(edgesAfter.buffer.isEmpty) // When merged in, we do not smush these two records together! XCTAssertFalse(mirror.isEmpty) XCTAssertTrue(mirror.subtrees[0].recordGUID == BookmarkRoots.RootGUID) XCTAssertNotNil(mirror.find("emptyempty01")) XCTAssertNotNil(mirror.find("emptyempty02")) XCTAssertTrue(mirror.deleted.isEmpty) guard let mobile = mirror.find(BookmarkRoots.MobileFolderGUID) else { XCTFail("No mobile folder in mirror.") return } if case let .folder(_, children) = mobile { XCTAssertEqual(children.map { $0.recordGUID }, ["emptyempty01", "emptyempty02"]) } else { XCTFail("Mobile isn't a folder.") } } /** * Input: * * [M] [] [M] * _______|_______ _____|_____ * / | \ / \ * [e01] [e02] [e03] [e02] [eL0] * * Expected output: * * Take remote, delete emptyemptyL0, upload the roots that * weren't remotely present. */ func testApplyingTwoEmptyFoldersMatchesOnlyOne() { guard let bookmarks = self.getSyncableBookmarks(name: "D") else { XCTFail("Couldn't get bookmarks.") return } // Insert three identical folders. We mark them with hasDupe because that's the Syncy // thing to do. let now = Date.now() let records = [ BookmarkMirrorItem.folder(BookmarkRoots.MobileFolderGUID, modified: now, hasDupe: false, parentID: BookmarkRoots.RootGUID, parentName: "", title: "Mobile Bookmarks", description: "", children: ["emptyempty01", "emptyempty02", "emptyempty03"]), BookmarkMirrorItem.folder("emptyempty01", modified: now, hasDupe: true, parentID: BookmarkRoots.MobileFolderGUID, parentName: "Mobile Bookmarks", title: "Empty", description: "", children: []), BookmarkMirrorItem.folder("emptyempty02", modified: now, hasDupe: true, parentID: BookmarkRoots.MobileFolderGUID, parentName: "Mobile Bookmarks", title: "Empty", description: "", children: []), BookmarkMirrorItem.folder("emptyempty03", modified: now, hasDupe: true, parentID: BookmarkRoots.MobileFolderGUID, parentName: "Mobile Bookmarks", title: "Empty", description: "", children: []), ] bookmarks.buffer.validate().succeeded() // It's valid! Empty. bookmarks.buffer.applyRecords(records).succeeded() bookmarks.buffer.validate().succeeded() // It's valid! Rooted in mobile_______. bookmarks.buffer.db.assertQueryReturns("SELECT COUNT(*) FROM \(TableBookmarksBuffer)", int: 4) bookmarks.buffer.db.assertQueryReturns("SELECT COUNT(*) FROM \(TableBookmarksBufferStructure)", int: 3) // Add one matching empty folder locally. // Add one by GUID, too. This is the most complex possible case. bookmarks.local.db.run("INSERT INTO \(TableBookmarksLocal) (guid, type, title, parentid, parentName, sync_status, local_modified) VALUES ('emptyempty02', \(BookmarkNodeType.folder.rawValue), 'Empty', '\(BookmarkRoots.MobileFolderGUID)', 'Mobile Bookmarks', \(SyncStatus.changed.rawValue), \(Date.now()))").succeeded() bookmarks.local.db.run("INSERT INTO \(TableBookmarksLocal) (guid, type, title, parentid, parentName, sync_status, local_modified) VALUES ('emptyemptyL0', \(BookmarkNodeType.folder.rawValue), 'Empty', '\(BookmarkRoots.MobileFolderGUID)', 'Mobile Bookmarks', \(SyncStatus.new.rawValue), \(Date.now()))").succeeded() bookmarks.local.db.run("INSERT INTO \(TableBookmarksLocalStructure) (parent, child, idx) VALUES ('\(BookmarkRoots.MobileFolderGUID)', 'emptyempty02', 0)").succeeded() bookmarks.local.db.run("INSERT INTO \(TableBookmarksLocalStructure) (parent, child, idx) VALUES ('\(BookmarkRoots.MobileFolderGUID)', 'emptyemptyL0', 1)").succeeded() let uploader = MockUploader() let storer = uploader.getStorer() let applier = MergeApplier(buffer: bookmarks, storage: bookmarks, client: storer, statsSession: mockStatsSessionForBookmarks(), greenLight: { true }) applier.go().succeeded() guard let mirror = bookmarks.treeForMirror().value.successValue else { XCTFail("Couldn't get mirror!") return } // After merge, the buffer and local are empty. let edgesAfter = bookmarks.treesForEdges().value.successValue! XCTAssertTrue(edgesAfter.local.isEmpty) XCTAssertTrue(edgesAfter.buffer.isEmpty) // All of the incoming records exist. XCTAssertFalse(mirror.isEmpty) XCTAssertEqual(mirror.subtrees[0].recordGUID, BookmarkRoots.RootGUID) XCTAssertNotNil(mirror.find("emptyempty01")) XCTAssertNotNil(mirror.find("emptyempty02")) XCTAssertNotNil(mirror.find("emptyempty03")) // The other roots are now in the mirror. XCTAssertTrue(BookmarkRoots.Real.every({ mirror.find($0) != nil })) // And are queued for upload. XCTAssertTrue(uploader.added.contains("toolbar")) XCTAssertTrue(uploader.added.contains("menu")) XCTAssertTrue(uploader.added.contains("unfiled")) XCTAssertFalse(uploader.added.contains("mobile")) // Structure and value didn't change. // The local record that was smushed is not present… XCTAssertNil(mirror.find("emptyemptyL0")) // … and because it was marked New, we don't bother trying to delete it. XCTAssertFalse(uploader.deletions.contains("emptyemptyL0")) guard let mobile = mirror.find(BookmarkRoots.MobileFolderGUID) else { XCTFail("No mobile folder in mirror.") return } if case let .folder(_, children) = mobile { // This order isn't strictly specified, but try to preserve the remote order if we can. XCTAssertEqual(children.map { $0.recordGUID }, ["emptyempty01", "emptyempty02", "emptyempty03"]) } else { XCTFail("Mobile isn't a folder.") } } // TODO: this test should be extended to also exercise the case of a conflict. func testLocalRecordsKeepTheirFavicon() { guard let bookmarks = self.getSyncableBookmarks(name: "E") else { XCTFail("Couldn't get bookmarks.") return } bookmarks.buffer.db.assertQueryReturns("SELECT COUNT(*) FROM \(TableBookmarksBuffer)", int: 0) bookmarks.buffer.db.assertQueryReturns("SELECT COUNT(*) FROM \(TableBookmarksBufferStructure)", int: 0) bookmarks.buffer.db.assertQueryReturns("SELECT COUNT(*) FROM \(TableBookmarksLocal)", int: 5) bookmarks.buffer.db.assertQueryReturns("SELECT COUNT(*) FROM \(TableBookmarksLocalStructure)", int: 4) bookmarks.local.db.run("INSERT INTO \(TableFavicons) (id, url, width, height, type, date) VALUES (11, 'http://example.org/favicon.ico', 16, 16, 0, \(Date.now()))").succeeded() bookmarks.local.db.run("INSERT INTO \(TableBookmarksLocal) (guid, type, title, parentid, parentName, sync_status, bmkUri, faviconID) VALUES ('somebookmark', \(BookmarkNodeType.bookmark.rawValue), 'Some Bookmark', '\(BookmarkRoots.MobileFolderGUID)', 'Mobile Bookmarks', \(SyncStatus.new.rawValue), 'http://example.org/', 11)").succeeded() bookmarks.local.db.run("INSERT INTO \(TableBookmarksLocalStructure) (parent, child, idx) VALUES ('\(BookmarkRoots.MobileFolderGUID)', 'somebookmark', 0)").succeeded() let uploader = MockUploader() let storer = uploader.getStorer() let applier = MergeApplier(buffer: bookmarks, storage: bookmarks, client: storer, statsSession: mockStatsSessionForBookmarks(), greenLight: { true }) applier.go().succeeded() // After merge, the buffer and local are empty. let edgesAfter = bookmarks.treesForEdges().value.successValue! XCTAssertTrue(edgesAfter.local.isEmpty) XCTAssertTrue(edgesAfter.buffer.isEmpty) // New record was uploaded. XCTAssertTrue(uploader.added.contains("somebookmark")) // So were all the roots, with the Sync-native names. XCTAssertTrue(uploader.added.contains("toolbar")) XCTAssertTrue(uploader.added.contains("menu")) XCTAssertTrue(uploader.added.contains("unfiled")) XCTAssertTrue(uploader.added.contains("mobile")) // … but not the Places root. XCTAssertFalse(uploader.added.contains("places")) XCTAssertFalse(uploader.added.contains(BookmarkRoots.RootGUID)) // Their parent IDs are translated. XCTAssertEqual(uploader.records["mobile"]?.payload["parentid"].string, "places") XCTAssertEqual(uploader.records["somebookmark"]?.payload["parentid"].string, "mobile") XCTAssertTrue(uploader.deletions.isEmpty) // The record looks sane. let bm = uploader.records["somebookmark"]! XCTAssertEqual("bookmark", bm.payload["type"].string) XCTAssertEqual("Some Bookmark", bm.payload["title"].string) // New record still has its icon ID in the local DB. bookmarks.local.db.assertQueryReturns("SELECT faviconID FROM \(TableBookmarksMirror) WHERE bmkUri = 'http://example.org/'", int: 11) } func testRemoteValueOnlyChange() { guard let bookmarks = self.getSyncableBookmarks(name: "F") else { XCTFail("Couldn't get bookmarks.") return } // Insert one folder and one child. let now = Date.now() let records = [ BookmarkMirrorItem.folder(BookmarkRoots.UnfiledFolderGUID, modified: now, hasDupe: false, parentID: BookmarkRoots.RootGUID, parentName: "", title: "Unsorted Bookmarks", description: "", children: ["folderAAAAAA"]), BookmarkMirrorItem.folder("folderAAAAAA", modified: now, hasDupe: false, parentID: BookmarkRoots.UnfiledFolderGUID, parentName: "Unsorted Bookmarks", title: "Folder A", description: "", children: ["bookmarkBBBB"]), BookmarkMirrorItem.bookmark("bookmarkBBBB", modified: now, hasDupe: false, parentID: "folderAAAAAA", parentName: "Folder A", title: "Initial Title", description: "No desc.", URI: "http://example.org/foo", tags: "", keyword: nil), ] bookmarks.buffer.validate().succeeded() // It's valid! Empty. bookmarks.buffer.applyRecords(records).succeeded() bookmarks.buffer.validate().succeeded() // It's valid! Rooted in mobile_______. bookmarks.buffer.db.assertQueryReturns("SELECT COUNT(*) FROM \(TableBookmarksBuffer)", int: 3) bookmarks.buffer.db.assertQueryReturns("SELECT COUNT(*) FROM \(TableBookmarksBufferStructure)", int: 2) let uploader = MockUploader() let storer = uploader.getStorer() let applier = MergeApplier(buffer: bookmarks, storage: bookmarks, client: storer, statsSession: mockStatsSessionForBookmarks(), greenLight: { true }) applier.go().succeeded() guard let _ = bookmarks.treeForMirror().value.successValue else { XCTFail("Couldn't get mirror!") return } // After merge, the buffer and local are empty. let edgesAfter = bookmarks.treesForEdges().value.successValue! XCTAssertTrue(edgesAfter.local.isEmpty) XCTAssertTrue(edgesAfter.buffer.isEmpty) // Check the title. let folder = bookmarks.modelFactory.value.successValue! .modelForFolder("folderAAAAAA").value.successValue!.current[0]! XCTAssertEqual(folder.title, "Initial Title") // Now process an incoming change. let changed = [ BookmarkMirrorItem.bookmark("bookmarkBBBB", modified: now, hasDupe: false, parentID: "folderAAAAAA", parentName: "Folder A", title: "New Title", description: "No desc.", URI: "http://example.org/foo", tags: "", keyword: nil), ] bookmarks.buffer.validate().succeeded() // It's valid! Empty. bookmarks.buffer.applyRecords(changed).succeeded() bookmarks.buffer.validate().succeeded() // It's valid! One record. bookmarks.buffer.db.assertQueryReturns("SELECT COUNT(*) FROM \(TableBookmarksBuffer)", int: 1) bookmarks.buffer.db.assertQueryReturns("SELECT COUNT(*) FROM \(TableBookmarksBufferStructure)", int: 0) let uu = MockUploader() let ss = uu.getStorer() let changeApplier = MergeApplier(buffer: bookmarks, storage: bookmarks, client: ss, statsSession: mockStatsSessionForBookmarks(), greenLight: { true }) changeApplier.go().succeeded() // The title changed. let updatedFolder = bookmarks.modelFactory.value.successValue! .modelForFolder("folderAAAAAA").value.successValue!.current[0]! XCTAssertEqual(updatedFolder.title, "New Title") // The buffer is empty. bookmarks.buffer.db.assertQueryReturns("SELECT COUNT(*) FROM \(TableBookmarksBuffer)", int: 0) bookmarks.buffer.db.assertQueryReturns("SELECT COUNT(*) FROM \(TableBookmarksBufferStructure)", int: 0) } } class TestMergedTree: FailFastTestCase { func testInitialState() { let children = BookmarkRoots.RootChildren.map { BookmarkTreeNode.unknown(guid: $0) } let root = BookmarkTreeNode.folder(guid: BookmarkRoots.RootGUID, children: children) let tree = MergedTree(mirrorRoot: root) XCTAssertTrue(tree.root.hasDecidedChildren) if case let .folder(guid, unmergedChildren) = tree.root.asUnmergedTreeNode() { XCTAssertEqual(guid, BookmarkRoots.RootGUID) XCTAssertEqual(unmergedChildren, children) } else { XCTFail("Root should start as Folder.") } // We haven't processed the children. XCTAssertNil(tree.root.mergedChildren) XCTAssertTrue(tree.root.asMergedTreeNode().isUnknown) // Simulate a merge. let mergedRoots = children.map { MergedTreeNode(guid: $0.recordGUID, mirror: $0, structureState: MergeState.unchanged) } tree.root.mergedChildren = mergedRoots // Now we have processed children. XCTAssertNotNil(tree.root.mergedChildren) XCTAssertFalse(tree.root.asMergedTreeNode().isUnknown) } } private extension MergedSQLiteBookmarks { func populateMirrorViaBuffer(items: [BookmarkMirrorItem], atDate mirrorDate: Timestamp) { self.applyRecords(items).succeeded() // … and add the root relationships that will be missing (we don't do those for the buffer, // so we need to manually add them and move them across). self.buffer.db.run([ "INSERT INTO \(TableBookmarksBufferStructure) (parent, child, idx) VALUES", "('\(BookmarkRoots.RootGUID)', '\(BookmarkRoots.MenuFolderGUID)', 0),", "('\(BookmarkRoots.RootGUID)', '\(BookmarkRoots.ToolbarFolderGUID)', 1),", "('\(BookmarkRoots.RootGUID)', '\(BookmarkRoots.UnfiledFolderGUID)', 2),", "('\(BookmarkRoots.RootGUID)', '\(BookmarkRoots.MobileFolderGUID)', 3)", ].joined(separator: " ")).succeeded() // Move it all to the mirror. self.local.db.moveBufferToMirrorForTesting() } func wipeLocal() { self.local.db.run(["DELETE FROM \(TableBookmarksLocalStructure)", "DELETE FROM \(TableBookmarksLocal)"]).succeeded() } }
d792afcaeff008c220889ea0ad02ec65
50.110029
346
0.658278
false
false
false
false
apple/swift-corelibs-foundation
refs/heads/main
Sources/FoundationNetworking/HTTPCookie.swift
apache-2.0
1
// This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // #if os(macOS) || os(iOS) || os(watchOS) || os(tvOS) import SwiftFoundation #else import Foundation #endif #if os(Windows) import WinSDK #endif public struct HTTPCookiePropertyKey : RawRepresentable, Equatable, Hashable { public private(set) var rawValue: String public init(_ rawValue: String) { self.rawValue = rawValue } public init(rawValue: String) { self.rawValue = rawValue } } extension HTTPCookiePropertyKey { /// Key for cookie name public static let name = HTTPCookiePropertyKey(rawValue: "Name") /// Key for cookie value public static let value = HTTPCookiePropertyKey(rawValue: "Value") /// Key for cookie origin URL public static let originURL = HTTPCookiePropertyKey(rawValue: "OriginURL") /// Key for cookie version public static let version = HTTPCookiePropertyKey(rawValue: "Version") /// Key for cookie domain public static let domain = HTTPCookiePropertyKey(rawValue: "Domain") /// Key for cookie path public static let path = HTTPCookiePropertyKey(rawValue: "Path") /// Key for cookie secure flag public static let secure = HTTPCookiePropertyKey(rawValue: "Secure") /// Key for cookie expiration date public static let expires = HTTPCookiePropertyKey(rawValue: "Expires") /// Key for cookie comment text public static let comment = HTTPCookiePropertyKey(rawValue: "Comment") /// Key for cookie comment URL public static let commentURL = HTTPCookiePropertyKey(rawValue: "CommentURL") /// Key for cookie discard (session-only) flag public static let discard = HTTPCookiePropertyKey(rawValue: "Discard") /// Key for cookie maximum age (an alternate way of specifying the expiration) public static let maximumAge = HTTPCookiePropertyKey(rawValue: "Max-Age") /// Key for cookie ports public static let port = HTTPCookiePropertyKey(rawValue: "Port") // For Cocoa compatibility internal static let created = HTTPCookiePropertyKey(rawValue: "Created") } internal extension HTTPCookiePropertyKey { static let httpOnly = HTTPCookiePropertyKey(rawValue: "HttpOnly") static private let _setCookieAttributes: [String: HTTPCookiePropertyKey] = { // Only some attributes are valid in the Set-Cookie header. let validProperties: [HTTPCookiePropertyKey] = [ .expires, .maximumAge, .domain, .path, .secure, .comment, .commentURL, .discard, .port, .version, .httpOnly ] let canonicalNames = validProperties.map { $0.rawValue.lowercased() } return Dictionary(uniqueKeysWithValues: zip(canonicalNames, validProperties)) }() init?(attributeName: String) { let canonical = attributeName.lowercased() switch HTTPCookiePropertyKey._setCookieAttributes[canonical] { case let property?: self = property case nil: return nil } } } /// `HTTPCookie` represents an http cookie. /// /// An `HTTPCookie` instance represents a single http cookie. It is /// an immutable object initialized from a dictionary that contains /// the various cookie attributes. It has accessors to get the various /// attributes of a cookie. open class HTTPCookie : NSObject { let _comment: String? let _commentURL: URL? let _domain: String let _expiresDate: Date? let _HTTPOnly: Bool let _secure: Bool let _sessionOnly: Bool let _name: String let _path: String let _portList: [NSNumber]? let _value: String let _version: Int var _properties: [HTTPCookiePropertyKey : Any] // See: https://tools.ietf.org/html/rfc2616#section-3.3.1 // Sun, 06 Nov 1994 08:49:37 GMT ; RFC 822, updated by RFC 1123 static let _formatter1: DateFormatter = { let formatter = DateFormatter() formatter.locale = Locale(identifier: "en_US_POSIX") formatter.dateFormat = "EEE, dd MMM yyyy HH:mm:ss O" formatter.timeZone = TimeZone(abbreviation: "GMT") return formatter }() // Sun Nov 6 08:49:37 1994 ; ANSI C's asctime() format static let _formatter2: DateFormatter = { let formatter = DateFormatter() formatter.locale = Locale(identifier: "en_US_POSIX") formatter.dateFormat = "EEE MMM d HH:mm:ss yyyy" formatter.timeZone = TimeZone(abbreviation: "GMT") return formatter }() // Sun, 06-Nov-1994 08:49:37 GMT ; Tomcat servers sometimes return cookies in this format static let _formatter3: DateFormatter = { let formatter = DateFormatter() formatter.locale = Locale(identifier: "en_US_POSIX") formatter.dateFormat = "EEE, dd-MMM-yyyy HH:mm:ss O" formatter.timeZone = TimeZone(abbreviation: "GMT") return formatter }() static let _allFormatters: [DateFormatter] = [_formatter1, _formatter2, _formatter3] /// Initialize a HTTPCookie object with a dictionary of parameters /// /// - Parameter properties: The dictionary of properties to be used to /// initialize this cookie. /// /// Supported dictionary keys and value types for the /// given dictionary are as follows. /// /// All properties can handle an NSString value, but some can also /// handle other types. /// /// <table border=1 cellspacing=2 cellpadding=4> /// <tr> /// <th>Property key constant</th> /// <th>Type of value</th> /// <th>Required</th> /// <th>Description</th> /// </tr> /// <tr> /// <td>HTTPCookiePropertyKey.comment</td> /// <td>NSString</td> /// <td>NO</td> /// <td>Comment for the cookie. Only valid for version 1 cookies and /// later. Default is nil.</td> /// </tr> /// <tr> /// <td>HTTPCookiePropertyKey.commentURL</td> /// <td>NSURL or NSString</td> /// <td>NO</td> /// <td>Comment URL for the cookie. Only valid for version 1 cookies /// and later. Default is nil.</td> /// </tr> /// <tr> /// <td>HTTPCookiePropertyKey.domain</td> /// <td>NSString</td> /// <td>Special, a value for either .originURL or /// HTTPCookiePropertyKey.domain must be specified.</td> /// <td>Domain for the cookie. Inferred from the value for /// HTTPCookiePropertyKey.originURL if not provided.</td> /// </tr> /// <tr> /// <td>HTTPCookiePropertyKey.discard</td> /// <td>NSString</td> /// <td>NO</td> /// <td>A string stating whether the cookie should be discarded at /// the end of the session. String value must be either "TRUE" or /// "FALSE". Default is "FALSE", unless this is cookie is version /// 1 or greater and a value for HTTPCookiePropertyKey.maximumAge is not /// specified, in which case it is assumed "TRUE".</td> /// </tr> /// <tr> /// <td>HTTPCookiePropertyKey.expires</td> /// <td>NSDate or NSString</td> /// <td>NO</td> /// <td>Expiration date for the cookie. Used only for version 0 /// cookies. Ignored for version 1 or greater.</td> /// </tr> /// <tr> /// <td>HTTPCookiePropertyKey.maximumAge</td> /// <td>NSString</td> /// <td>NO</td> /// <td>A string containing an integer value stating how long in /// seconds the cookie should be kept, at most. Only valid for /// version 1 cookies and later. Default is "0".</td> /// </tr> /// <tr> /// <td>HTTPCookiePropertyKey.name</td> /// <td>NSString</td> /// <td>YES</td> /// <td>Name of the cookie</td> /// </tr> /// <tr> /// <td>HTTPCookiePropertyKey.originURL</td> /// <td>NSURL or NSString</td> /// <td>Special, a value for either HTTPCookiePropertyKey.originURL or /// HTTPCookiePropertyKey.domain must be specified.</td> /// <td>URL that set this cookie. Used as default for other fields /// as noted.</td> /// </tr> /// <tr> /// <td>HTTPCookiePropertyKey.path</td> /// <td>NSString</td> /// <td>YES</td> /// <td>Path for the cookie</td> /// </tr> /// <tr> /// <td>HTTPCookiePropertyKey.port</td> /// <td>NSString</td> /// <td>NO</td> /// <td>comma-separated integer values specifying the ports for the /// cookie. Only valid for version 1 cookies and later. Default is /// empty string ("").</td> /// </tr> /// <tr> /// <td>HTTPCookiePropertyKey.secure</td> /// <td>NSString</td> /// <td>NO</td> /// <td>A string stating whether the cookie should be transmitted /// only over secure channels. String value must be either "TRUE" /// or "FALSE". Default is "FALSE".</td> /// </tr> /// <tr> /// <td>HTTPCookiePropertyKey.value</td> /// <td>NSString</td> /// <td>YES</td> /// <td>Value of the cookie</td> /// </tr> /// <tr> /// <td>HTTPCookiePropertyKey.version</td> /// <td>NSString</td> /// <td>NO</td> /// <td>Specifies the version of the cookie. Must be either "0" or /// "1". Default is "0".</td> /// </tr> /// </table> /// /// All other keys are ignored. /// /// - Returns: An initialized `HTTPCookie`, or nil if the set of /// dictionary keys is invalid, for example because a required key is /// missing, or a recognized key maps to an illegal value. /// /// - Experiment: This is a draft API currently under consideration for official import into Foundation as a suitable alternative /// - Note: Since this API is under consideration it may be either removed or revised in the near future public init?(properties: [HTTPCookiePropertyKey : Any]) { func stringValue(_ strVal: Any?) -> String? { if let subStr = strVal as? Substring { return String(subStr) } return strVal as? String } guard let path = stringValue(properties[.path]), let name = stringValue(properties[.name]), let value = stringValue(properties[.value]) else { return nil } let canonicalDomain: String if let domain = properties[.domain] as? String { canonicalDomain = domain } else if let originURL = properties[.originURL] as? URL, let host = originURL.host { canonicalDomain = host } else { return nil } _path = path _name = name _value = value _domain = canonicalDomain.lowercased() if let secureString = properties[.secure] as? String, !secureString.isEmpty { _secure = true } else { _secure = false } let version: Int if let versionString = properties[.version] as? String, versionString == "1" { version = 1 } else { version = 0 } _version = version if let portString = properties[.port] as? String { let portList = portString.split(separator: ",") .compactMap { Int(String($0)) } .map { NSNumber(value: $0) } if version == 1 { _portList = portList } else { // Version 0 only stores a single port number _portList = portList.count > 0 ? [portList[0]] : nil } } else { _portList = nil } var expDate: Date? = nil // Maximum-Age is preferred over expires-Date but only version 1 cookies use Maximum-Age if let maximumAge = properties[.maximumAge] as? String, let secondsFromNow = Int(maximumAge) { if version == 1 { expDate = Date(timeIntervalSinceNow: Double(secondsFromNow)) } } else { let expiresProperty = properties[.expires] if let date = expiresProperty as? Date { expDate = date } else if let dateString = expiresProperty as? String { let results = HTTPCookie._allFormatters.compactMap { $0.date(from: dateString) } expDate = results.first } } _expiresDate = expDate if let discardString = properties[.discard] as? String { _sessionOnly = discardString == "TRUE" } else { _sessionOnly = properties[.maximumAge] == nil && version >= 1 } _comment = properties[.comment] as? String if let commentURL = properties[.commentURL] as? URL { _commentURL = commentURL } else if let commentURL = properties[.commentURL] as? String { _commentURL = URL(string: commentURL) } else { _commentURL = nil } if let httpOnlyString = properties[.httpOnly] as? String { _HTTPOnly = httpOnlyString == "TRUE" } else { _HTTPOnly = false } _properties = [ .created : Date().timeIntervalSinceReferenceDate, // Cocoa Compatibility .discard : _sessionOnly, .domain : _domain, .name : _name, .path : _path, .secure : _secure, .value : _value, .version : _version ] if let comment = properties[.comment] { _properties[.comment] = comment } if let commentURL = properties[.commentURL] { _properties[.commentURL] = commentURL } if let expires = properties[.expires] { _properties[.expires] = expires } if let maximumAge = properties[.maximumAge] { _properties[.maximumAge] = maximumAge } if let originURL = properties[.originURL] { _properties[.originURL] = originURL } if let _portList = _portList { _properties[.port] = _portList } } /// Return a dictionary of header fields that can be used to add the /// specified cookies to the request. /// /// - Parameter cookies: The cookies to turn into request headers. /// - Returns: A dictionary where the keys are header field names, and the values /// are the corresponding header field values. open class func requestHeaderFields(with cookies: [HTTPCookie]) -> [String : String] { var cookieString = cookies.reduce("") { (sum, next) -> String in return sum + "\(next._name)=\(next._value); " } //Remove the final trailing semicolon and whitespace if ( cookieString.length > 0 ) { cookieString.removeLast() cookieString.removeLast() } if cookieString == "" { return [:] } else { return ["Cookie": cookieString] } } /// Return an array of cookies parsed from the specified response header fields and URL. /// /// This method will ignore irrelevant header fields so /// you can pass a dictionary containing data other than cookie data. /// - Parameter headerFields: The response header fields to check for cookies. /// - Parameter URL: The URL that the cookies came from - relevant to how the cookies are interpreted. /// - Returns: An array of HTTPCookie objects open class func cookies(withResponseHeaderFields headerFields: [String : String], for URL: URL) -> [HTTPCookie] { // HTTP Cookie parsing based on RFC 6265: https://tools.ietf.org/html/rfc6265 // Though RFC6265 suggests that multiple cookies cannot be folded into a single Set-Cookie field, this is // pretty common. It also suggests that commas and semicolons among other characters, cannot be a part of // names and values. This implementation takes care of multiple cookies in the same field, however it doesn't // support commas and semicolons in names and values(except for dates) guard let cookies: String = headerFields["Set-Cookie"] else { return [] } var httpCookies: [HTTPCookie] = [] // Let's do old school parsing, which should allow us to handle the // embedded commas correctly. var idx: String.Index = cookies.startIndex let end: String.Index = cookies.endIndex while idx < end { // Skip leading spaces. while idx < end && cookies[idx].isSpace { idx = cookies.index(after: idx) } let cookieStartIdx: String.Index = idx var cookieEndIdx: String.Index = idx while idx < end { // Scan to the next comma, but check that the comma is not a // legal comma in a value, by looking ahead for the token, // which indicates the comma was separating cookies. let cookiesRest = cookies[idx..<end] if let commaIdx = cookiesRest.firstIndex(of: ",") { // We are looking for WSP* TOKEN_CHAR+ WSP* '=' var lookaheadIdx = cookies.index(after: commaIdx) // Skip whitespace while lookaheadIdx < end && cookies[lookaheadIdx].isSpace { lookaheadIdx = cookies.index(after: lookaheadIdx) } // Skip over the token characters var tokenLength = 0 while lookaheadIdx < end && cookies[lookaheadIdx].isTokenCharacter { lookaheadIdx = cookies.index(after: lookaheadIdx) tokenLength += 1 } // Skip whitespace while lookaheadIdx < end && cookies[lookaheadIdx].isSpace { lookaheadIdx = cookies.index(after: lookaheadIdx) } // Check there was a token, and there's an equals. if lookaheadIdx < end && cookies[lookaheadIdx] == "=" && tokenLength > 0 { // We found a token after the comma, this is a cookie // separator, and not an embedded comma. idx = cookies.index(after: commaIdx) cookieEndIdx = commaIdx break } // Otherwise, keep scanning from the comma. idx = cookies.index(after: commaIdx) cookieEndIdx = idx } else { // No more commas, skip to the end. idx = end cookieEndIdx = end break } } if cookieEndIdx <= cookieStartIdx { continue } if let aCookie = createHttpCookie(url: URL, cookie: String(cookies[cookieStartIdx..<cookieEndIdx])) { httpCookies.append(aCookie) } } return httpCookies } //Bake a cookie private class func createHttpCookie(url: URL, cookie: String) -> HTTPCookie? { var properties: [HTTPCookiePropertyKey : Any] = [:] let scanner = Scanner(string: cookie) guard let nameValuePair = scanner.scanUpToString(";") else { // if the scanner does not read anything, there's no cookie return nil } guard case (let name?, let value?) = splitNameValue(nameValuePair) else { return nil } properties[.name] = name properties[.value] = value properties[.originURL] = url while scanner.scanString(";") != nil { if let attribute = scanner.scanUpToString(";") { switch splitNameValue(attribute) { case (nil, _): // ignore empty attribute names break case (let name?, nil): switch HTTPCookiePropertyKey(attributeName: name) { case .secure?: properties[.secure] = "TRUE" case .discard?: properties[.discard] = "TRUE" case .httpOnly?: properties[.httpOnly] = "TRUE" default: // ignore unknown attributes break } case (let name?, let value?): switch HTTPCookiePropertyKey(attributeName: name) { case .comment?: properties[.comment] = value case .commentURL?: properties[.commentURL] = value case .domain?: properties[.domain] = value case .maximumAge?: properties[.maximumAge] = value case .path?: properties[.path] = value case .port?: properties[.port] = value case .version?: properties[.version] = value case .expires?: properties[.expires] = value default: // ignore unknown attributes break } } } } if let domain = properties[.domain] as? String { // The provided domain string has to be prepended with a dot, // because the domain field indicates that it can be sent // subdomains of the domain (but only if it is not an IP address). if (!domain.hasPrefix(".") && !isIPv4Address(domain)) { properties[.domain] = ".\(domain)" } } else { // If domain wasn't provided, extract it from the URL. No dots in // this case, only exact matching. properties[.domain] = url.host } // Always lowercase the domain. if let domain = properties[.domain] as? String { properties[.domain] = domain.lowercased() } // the default Path is "/" if let path = properties[.path] as? String, path.first == "/" { // do nothing } else { properties[.path] = "/" } return HTTPCookie(properties: properties) } private class func splitNameValue(_ pair: String) -> (name: String?, value: String?) { let scanner = Scanner(string: pair) guard let name = scanner.scanUpToString("=")?.trim(), !name.isEmpty else { // if the scanner does not read anything, or the trimmed name is // empty, there's no name=value return (nil, nil) } guard scanner.scanString("=") != nil else { // if the scanner does not find =, there's no value return (name, nil) } let location = scanner.scanLocation let value = String(pair[pair.index(pair.startIndex, offsetBy: location)..<pair.endIndex]).trim() return (name, value) } private class func isIPv4Address(_ string: String) -> Bool { var x = in_addr() return inet_pton(AF_INET, string, &x) == 1 } /// Returns a dictionary representation of the receiver. /// /// This method returns a dictionary representation of the /// `HTTPCookie` which can be saved and passed to /// `init(properties:)` later to reconstitute an equivalent cookie. /// /// See the `HTTPCookie` `init(properties:)` method for /// more information on the constraints imposed on the dictionary, and /// for descriptions of the supported keys and values. /// /// - Experiment: This is a draft API currently under consideration for official import into Foundation as a suitable alternative /// - Note: Since this API is under consideration it may be either removed or revised in the near future open var properties: [HTTPCookiePropertyKey : Any]? { return _properties } /// The version of the receiver. /// /// Version 0 maps to "old-style" Netscape cookies. /// Version 1 maps to RFC2965 cookies. There may be future versions. open var version: Int { return _version } /// The name of the receiver. open var name: String { return _name } /// The value of the receiver. open var value: String { return _value } /// Returns The expires date of the receiver. /// /// The expires date is the date when the cookie should be /// deleted. The result will be nil if there is no specific expires /// date. This will be the case only for *session-only* cookies. /*@NSCopying*/ open var expiresDate: Date? { return _expiresDate } /// Whether the receiver is session-only. /// /// `true` if this receiver should be discarded at the end of the /// session (regardless of expiration date), `false` if receiver need not /// be discarded at the end of the session. open var isSessionOnly: Bool { return _sessionOnly } /// The domain of the receiver. /// /// This value specifies URL domain to which the cookie /// should be sent. A domain with a leading dot means the cookie /// should be sent to subdomains as well, assuming certain other /// restrictions are valid. See RFC 2965 for more detail. open var domain: String { return _domain } /// The path of the receiver. /// /// This value specifies the URL path under the cookie's /// domain for which this cookie should be sent. The cookie will also /// be sent for children of that path, so `"/"` is the most general. open var path: String { return _path } /// Whether the receiver should be sent only over secure channels /// /// Cookies may be marked secure by a server (or by a javascript). /// Cookies marked as such must only be sent via an encrypted connection to /// trusted servers (i.e. via SSL or TLS), and should not be delivered to any /// javascript applications to prevent cross-site scripting vulnerabilities. open var isSecure: Bool { return _secure } /// Whether the receiver should only be sent to HTTP servers per RFC 2965 /// /// Cookies may be marked as HTTPOnly by a server (or by a javascript). /// Cookies marked as such must only be sent via HTTP Headers in HTTP Requests /// for URL's that match both the path and domain of the respective Cookies. /// Specifically these cookies should not be delivered to any javascript /// applications to prevent cross-site scripting vulnerabilities. open var isHTTPOnly: Bool { return _HTTPOnly } /// The comment of the receiver. /// /// This value specifies a string which is suitable for /// presentation to the user explaining the contents and purpose of this /// cookie. It may be nil. open var comment: String? { return _comment } /// The comment URL of the receiver. /// /// This value specifies a URL which is suitable for /// presentation to the user as a link for further information about /// this cookie. It may be nil. /*@NSCopying*/ open var commentURL: URL? { return _commentURL } /// The list ports to which the receiver should be sent. /// /// This value specifies an NSArray of NSNumbers /// (containing integers) which specify the only ports to which this /// cookie should be sent. /// /// The array may be nil, in which case this cookie can be sent to any /// port. open var portList: [NSNumber]? { return _portList } open override var description: String { var str = "<\(type(of: self)) " str += "version:\(self._version) name:\"\(self._name)\" value:\"\(self._value)\" expiresDate:" if let expires = self._expiresDate { str += "\(expires)" } else { str += "nil" } str += " sessionOnly:\(self._sessionOnly) domain:\"\(self._domain)\" path:\"\(self._path)\" isSecure:\(self._secure) comment:" if let comments = self._comment { str += "\(comments)" } else { str += "nil" } str += " ports:{ " if let ports = self._portList { str += "\(NSArray(array: (ports)).componentsJoined(by: ","))" } else { str += "0" } str += " }>" return str } } //utils for cookie parsing fileprivate extension String { func trim() -> String { return self.trimmingCharacters(in: .whitespacesAndNewlines) } } fileprivate extension Character { var isSpace: Bool { return self == " " || self == "\t" || self == "\n" || self == "\r" } var isTokenCharacter: Bool { guard let asciiValue = self.asciiValue else { return false } // CTL, 0-31 and DEL (127) if asciiValue <= 31 || asciiValue >= 127 { return false } let nonTokenCharacters = "()<>@,;:\\\"/[]?={} \t" return !nonTokenCharacters.contains(self) } }
95df337c0791ec0d1da6e501d0236ed1
36.190773
134
0.571898
false
false
false
false
DoubleSha/BitcoinSwift
refs/heads/master
BitcoinSwift/Models/PingMessage.swift
apache-2.0
1
// // PingMessage.swift // BitcoinSwift // // Created by James MacWhyte on 9/27/14. // Copyright (c) 2014 DoubleSha. All rights reserved. // import Foundation public func ==(left: PingMessage, right: PingMessage) -> Bool { return left.nonce == right.nonce } /// The ping message is sent primarily to confirm that the TCP/IP connection is still valid. An /// error in transmission is presumed to be a closed connection and the address is removed as a /// current peer. /// https://en.bitcoin.it/wiki/Protocol_specification#ping public struct PingMessage: Equatable { public var nonce: UInt64 public init(nonce: UInt64? = nil) { if let nonce = nonce { self.nonce = nonce } else { self.nonce = UInt64(arc4random()) | (UInt64(arc4random()) << 32) } } } extension PingMessage: MessagePayload { public var command: Message.Command { return Message.Command.Ping } public var bitcoinData: NSData { let data = NSMutableData() data.appendUInt64(nonce) return data } public static func fromBitcoinStream(stream: NSInputStream) -> PingMessage? { let nonce = stream.readUInt64() if nonce == nil { Logger.warn("Failed to parse nonce from PingMessage") return nil } return PingMessage(nonce: nonce) } }
661a085cc961c2bbc93c6d6379d8df02
23.788462
95
0.683476
false
false
false
false
JQJoe/RxDemo
refs/heads/develop
Carthage/Checkouts/RxSwift/Preprocessor/Preprocessor/main.swift
apache-2.0
10
// // main.swift // Preprocessor // // Created by Krunoslav Zaher on 4/22/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // import Foundation if CommandLine.argc != 3 { print("./Preprocessor <source-files-root> <derived-data> ") exit(-1) } let sourceFilesRoot = CommandLine.arguments[1] let derivedData = CommandLine.arguments[2] let fileManager = FileManager() func escape(value: String) -> String { let escapedString = value.replacingOccurrences(of: "\n", with: "\\n") let escapedString1 = escapedString.replacingOccurrences(of: "\r", with: "\\r") let escapedString2 = escapedString1.replacingOccurrences(of: "\"", with: "\\\"") return "\"\(escapedString2)\"" } func processFile(path: String, outputPath: String) -> String { let url = URL(fileURLWithPath: path) let rawContent = try! Data(contentsOf: url) let content = String(data: rawContent, encoding: String.Encoding.utf8) guard let components = content?.components(separatedBy: "<%") else { return "" } var functionContentComponents: [String] = [] functionContentComponents.append("var components: [String] = [\"// This file is autogenerated. Take a look at `Preprocessor` target in RxSwift project \\n\"]\n") functionContentComponents.append("components.append(\(escape(value: components[0])))\n") for codePlusSuffix in (components[1 ..< components.count]) { let codePlusSuffixSeparated = codePlusSuffix.components(separatedBy: "%>") if codePlusSuffixSeparated.count != 2 { fatalError("Error in \(path) near \(codePlusSuffix)") } let code = codePlusSuffixSeparated[0] let suffix = codePlusSuffixSeparated[1] if code.hasPrefix("=") { functionContentComponents.append("components.append(String(\(code.substring(from: code.index(after: code.startIndex)))))\n") } else { functionContentComponents.append("\(code)\n") } functionContentComponents.append("components.append(\(escape(value: suffix)));\n") } functionContentComponents.append("try! components.joined(separator:\"\").write(toFile:\"\(outputPath)\", atomically: false, encoding: String.Encoding.utf8)") return functionContentComponents.joined(separator: "") } func runCommand(path: String) { _ = ProcessInfo().processIdentifier let process = Process() process.launchPath = "/bin/bash" process.arguments = ["-c", "xcrun swift \"\(path)\""] process.launch() process.waitUntilExit() if process.terminationReason != .exit { exit(-1) } } let files = try fileManager.subpathsOfDirectory(atPath: sourceFilesRoot) var generateAllFiles = ["// Generated code\n", "import Foundation\n"] for file in files { if ((file as NSString).pathExtension ?? "") != "tt" { continue } print(file) let path = (sourceFilesRoot as NSString).appendingPathComponent(file as String) let endIndex = path.index(before: path.index(before: path.index(before: path.endIndex))) let outputPath = path.substring(to: endIndex) + ".swift" generateAllFiles.append("_ = { () -> Void in\n\(processFile(path: path, outputPath: outputPath))\n}()\n") } let script = generateAllFiles.joined(separator: "") let scriptPath = (derivedData as NSString).appendingPathComponent("_preprocessor.sh") do { try script.write(toFile: scriptPath, atomically: true, encoding: String.Encoding.utf8) } catch _ { } runCommand(path: scriptPath)
f4a5a1a317a1c21fa8e5ee813cf812ac
33.095238
165
0.664525
false
false
false
false
apple/swift
refs/heads/main
test/IRGen/objc_extensions.swift
apache-2.0
1
// RUN: %empty-directory(%t) // RUN: %build-irgen-test-overlays // RUN: %target-swift-frontend(mock-sdk: -sdk %S/Inputs -I %t) -disable-objc-attr-requires-foundation-module -emit-module %S/Inputs/objc_extension_base.swift -o %t // RUN: %target-swift-frontend(mock-sdk: -sdk %S/Inputs -I %t) -primary-file %s -emit-ir -g | %FileCheck %s // REQUIRES: CPU=x86_64 || CPU=arm64 // REQUIRES: objc_interop import Foundation import gizmo import objc_extension_base // Check that metadata for nested enums added in extensions to imported classes // gets emitted concretely. // CHECK: [[CATEGORY_NAME:@.*]] = private constant [16 x i8] c"objc_extensions\00" // CHECK: [[METHOD_TYPE:@.*]] = private unnamed_addr constant [8 x i8] c"v16@0:8\00" // CHECK-LABEL: @"_CATEGORY_PROTOCOLS_Gizmo_$_objc_extensions" = internal constant // CHECK-SAME: i64 1, // CHECK-SAME: @_PROTOCOL__TtP15objc_extensions11NewProtocol_ // CHECK-LABEL: @"_CATEGORY_Gizmo_$_objc_extensions" = internal constant // CHECK-SAME: i8* getelementptr inbounds ([16 x i8], [16 x i8]* [[CATEGORY_NAME]], i64 0, i64 0), // CHECK-SAME: %objc_class* @"OBJC_CLASS_$_Gizmo", // CHECK-SAME: @"_CATEGORY_INSTANCE_METHODS_Gizmo_$_objc_extensions", // CHECK-SAME: @"_CATEGORY_CLASS_METHODS_Gizmo_$_objc_extensions", // CHECK-SAME: @"_CATEGORY_PROTOCOLS_Gizmo_$_objc_extensions", // CHECK-SAME: i8* null // CHECK-SAME: }, section "__DATA, {{.*}}", align 8 @objc protocol NewProtocol { func brandNewInstanceMethod() } extension NSObject { @objc func someMethod() -> String { return "Hello" } } extension Gizmo: NewProtocol { @objc func brandNewInstanceMethod() { } @objc class func brandNewClassMethod() { } // Overrides an instance method of NSObject override func someMethod() -> String { return super.someMethod() } // Overrides a class method of NSObject @objc override class func hasOverride() {} } /* * Make sure that two extensions of the same ObjC class in the same module can * coexist by having different category names. */ // CHECK: [[CATEGORY_NAME_1:@.*]] = private unnamed_addr constant [17 x i8] c"objc_extensions1\00" // CHECK: @"_CATEGORY_Gizmo_$_objc_extensions1" = internal constant // CHECK: i8* getelementptr inbounds ([17 x i8], [17 x i8]* [[CATEGORY_NAME_1]], i64 0, i64 0), // CHECK: %objc_class* @"OBJC_CLASS_$_Gizmo", // CHECK: {{.*}} @"_CATEGORY_INSTANCE_METHODS_Gizmo_$_objc_extensions1", // CHECK: {{.*}} @"_CATEGORY_CLASS_METHODS_Gizmo_$_objc_extensions1", // CHECK: i8* null, // CHECK: i8* null // CHECK: }, section "__DATA, {{.*}}", align 8 extension Gizmo { @objc func brandSpankingNewInstanceMethod() { } @objc class func brandSpankingNewClassMethod() { } } /* * Check that extensions of Swift subclasses of ObjC objects get categories. */ class Hoozit : NSObject { } // CHECK-LABEL: @"_CATEGORY_INSTANCE_METHODS__TtC15objc_extensions6Hoozit_$_objc_extensions" = internal constant // CHECK: i32 24, // CHECK: i32 1, // CHECK: [1 x { i8*, i8*, i8* }] [{ i8*, i8*, i8* } { // CHECK: i8* getelementptr inbounds ([8 x i8], [8 x i8]* @"\01L_selector_data(blibble)", i64 0, i64 0), // CHECK: i8* getelementptr inbounds ([8 x i8], [8 x i8]* [[STR:@.*]], i64 0, i64 0), // CHECK: i8* bitcast (void ([[OPAQUE:%.*]]*, i8*)* @"$s15objc_extensions6HoozitC7blibbleyyFTo" to i8*) // CHECK: }] // CHECK: }, section "__DATA, {{.*}}", align 8 // CHECK-LABEL: @"_CATEGORY_CLASS_METHODS__TtC15objc_extensions6Hoozit_$_objc_extensions" = internal constant // CHECK: i32 24, // CHECK: i32 1, // CHECK: [1 x { i8*, i8*, i8* }] [{ i8*, i8*, i8* } { // CHECK: i8* getelementptr inbounds ([8 x i8], [8 x i8]* @"\01L_selector_data(blobble)", i64 0, i64 0), // CHECK: i8* getelementptr inbounds ([8 x i8], [8 x i8]* [[STR]], i64 0, i64 0), // CHECK: i8* bitcast (void (i8*, i8*)* @"$s15objc_extensions6HoozitC7blobbleyyFZTo" to i8*) // CHECK: }] // CHECK: }, section "__DATA, {{.*}}", align 8 // CHECK-LABEL: @"_CATEGORY__TtC15objc_extensions6Hoozit_$_objc_extensions" = internal constant // CHECK: i8* getelementptr inbounds ([16 x i8], [16 x i8]* [[CATEGORY_NAME]], i64 0, i64 0), // CHECK: %swift.type* {{.*}} @"$s15objc_extensions6HoozitCMf", // CHECK: {{.*}} @"_CATEGORY_INSTANCE_METHODS__TtC15objc_extensions6Hoozit_$_objc_extensions", // CHECK: {{.*}} @"_CATEGORY_CLASS_METHODS__TtC15objc_extensions6Hoozit_$_objc_extensions", // CHECK: i8* null, // CHECK: i8* null // CHECK: }, section "__DATA, {{.*}}", align 8 extension Hoozit { @objc func blibble() { } @objc class func blobble() { } } class SwiftOnly { } // CHECK-LABEL: @"_CATEGORY_INSTANCE_METHODS__TtC15objc_extensions9SwiftOnly_$_objc_extensions" = internal constant // CHECK: i32 24, // CHECK: i32 1, // CHECK: [1 x { i8*, i8*, i8* }] [{ i8*, i8*, i8* } { // CHECK: i8* getelementptr inbounds ([7 x i8], [7 x i8]* @"\01L_selector_data(wibble)", i64 0, i64 0), // CHECK: i8* getelementptr inbounds ([8 x i8], [8 x i8]* [[STR]], i64 0, i64 0), // CHECK: i8* bitcast (void (i8*, i8*)* @"$s15objc_extensions9SwiftOnlyC6wibbleyyFTo" to i8*) // CHECK: }] }, section "__DATA, {{.*}}", align 8 extension SwiftOnly { @objc func wibble() { } } class Wotsit: Hoozit {} extension Hoozit { @objc func overriddenByExtensionInSubclass() {} } extension Wotsit { @objc override func overriddenByExtensionInSubclass() {} } extension NSObject { private enum SomeEnum { case X } @objc public func needMetadataOfSomeEnum() { print(NSObject.SomeEnum.X) } @objc class func hasOverride() {} } // CHECK-LABEL: @"_CATEGORY__TtCC15objc_extensions5Outer5Inner_$_objc_extensions" = internal constant // CHECK-SAME: i8* getelementptr inbounds ([16 x i8], [16 x i8]* [[CATEGORY_NAME]], i64 0, i64 0), // CHECK-SAME: @"_CATEGORY_INSTANCE_METHODS__TtCC15objc_extensions5Outer5Inner_$_objc_extensions", // CHECK-SAME: i8* null // CHECK-SAME: }, section "__DATA, {{.*}}", align 8 class Outer : NSObject { class Inner : NSObject {} } extension Outer.Inner { @objc func innerExtensionMethod() {} } /* * Make sure that @NSManaged causes a category to be generated. */ class NSDogcow : NSObject {} // CHECK: [[NAME:@.*]] = private unnamed_addr constant [5 x i8] c"woof\00" // CHECK: [[ATTR:@.*]] = private unnamed_addr constant [7 x i8] c"Tq,N,D\00" // CHECK: @"_CATEGORY_PROPERTIES__TtC15objc_extensions8NSDogcow_$_objc_extensions" = internal constant {{.*}} [[NAME]], {{.*}} [[ATTR]], {{.*}}, section "__DATA, {{.*}}", align 8 extension NSDogcow { @NSManaged var woof: Int } // CHECK: @"$sSo8NSObjectC15objc_extensionsE8SomeEnum33_1F05E59585E0BB585FCA206FBFF1A92DLLOSQACMc" = class SwiftSubGizmo : SwiftBaseGizmo { // Don't crash on this call. Emit an objC method call to super. // // CHECK-LABEL: define {{.*}} @"$s15objc_extensions13SwiftSubGizmoC4frobyyF" // CHECK: $s15objc_extensions13SwiftSubGizmoCMa // CHECK: objc_msgSendSuper2 // CHECK: ret public override func frob() { super.frob() } } @inline(never) func opaquePrint(_ value: Any) { print(value) } /* * Check that we can extend ObjC generics and use both the type and metatype of * the generic parameter. Specifically, we're checking that we emit debug info * if we look up the existential bound, and that we derive the argument to * `opaquePrint(_:)` from the actual parameter, not just the fixed metadata. */ extension FungingArray { // CHECK-LABEL: define {{.*}} @"$sSo12FungingArrayC15objc_extensionsEyAByxGxcfC" // CHECK-SAME: (%objc_object* %0, %swift.type* swiftself %1) // CHECK: @__swift_instantiateConcreteTypeFromMangledName{{.*}}@"$sSo9NSFunging_pMD"{{.*}}!dbg // CHECK-LABEL: define {{.*}} @"$sSo12FungingArrayC15objc_extensionsEyAByxGxcfc" // CHECK-SAME: (%objc_object* %0, %TSo12FungingArrayC* swiftself %1) // CHECK: [[ALLOCA:%[^, =]+]] = alloca %Any, align 8 // CHECK: @__swift_instantiateConcreteTypeFromMangledName{{.*}}@"$sSo9NSFunging_pMD"{{.*}}!dbg // CHECK: {{%[^, =]+}} = getelementptr inbounds %Any, %Any* [[ALLOCA]], i32 0, i32 0 // CHECK: [[ANYBUF:%[^, =]+]] = getelementptr inbounds %Any, %Any* [[ALLOCA]], i32 0, i32 0 // CHECK: [[BUFPTR:%[^, =]+]] = {{.*}} [[ANYBUF]] // CHECK: [[BUF_0:%[^, =]+]] = {{.*}} [[BUFPTR]] // CHECK: store {{.*}} %0, {{.*}} [[BUF_0]] // CHECK: call swiftcc void @"$s15objc_extensions11opaquePrintyyypF"(%Any* {{.*}} [[ALLOCA]]) @objc public convenience init(_ elem: Element) { opaquePrint(elem) self.init() } // CHECK-LABEL: define {{.*}} @"$sSo12FungingArrayC15objc_extensionsE7pinningAByxGxm_tcfC" // CHECK-SAME: (%swift.type* %0, %swift.type* swiftself %1) // CHECK: @__swift_instantiateConcreteTypeFromMangledName{{.*}}@"$sSo9NSFunging_pMD"{{.*}}!dbg // CHECK-LABEL: define {{.*}} @"$sSo12FungingArrayC15objc_extensionsE7pinningAByxGxm_tcfc" // CHECK-SAME: (%swift.type* %0, %TSo12FungingArrayC* swiftself %1) // CHECK: [[ALLOCA:%[^, =]+]] = alloca %Any, align 8 // CHECK: @__swift_instantiateConcreteTypeFromMangledName{{.*}}@"$sSo9NSFunging_pMD"{{.*}}!dbg // CHECK: [[OBJC_CLASS:%[^, =]+]] = call %objc_class* @swift_getObjCClassFromMetadata(%swift.type* %0) // CHECK: [[OBJC_CLASS_OBJ:%[^, =]+]] = bitcast %objc_class* [[OBJC_CLASS]] // CHECK: {{%[^, =]+}} = getelementptr inbounds %Any, %Any* [[ALLOCA]], i32 0, i32 0 // CHECK: [[ANYBUF:%[^, =]+]] = getelementptr inbounds %Any, %Any* [[ALLOCA]], i32 0, i32 0 // CHECK: [[BUFPTR:%[^, =]+]] = {{.*}} [[ANYBUF]] // CHECK: [[BUF_0:%[^, =]+]] = {{.*}} [[BUFPTR]] // CHECK: store {{.*}} [[OBJC_CLASS_OBJ]], {{.*}} [[BUF_0]] // CHECK: call swiftcc void @"$s15objc_extensions11opaquePrintyyypF"(%Any* {{.*}} [[ALLOCA]]) @objc public convenience init(pinning: Element.Type) { opaquePrint(pinning as AnyObject) self.init() } }
3e86609a7c09b83d3a5791dd97ffc53a
38.833333
178
0.645066
false
false
false
false
cclef615/crumbs
refs/heads/master
usernameSelect.swift
mit
1
// // usernameSelect.swift // crumbs // // Created by Colin Kohli on 8/3/15. // Copyright (c) 2015 Colin Kohli. All rights reserved. // import Foundation import UIKit func usernameSelect() -> UIAlertController?{ if (PFUser.currentUser() == nil){ var loginAlert: UIAlertController = UIAlertController(title: "Sign Up / Log In", message: "Please enter a username and password", preferredStyle: UIAlertControllerStyle.Alert) loginAlert.addTextFieldWithConfigurationHandler({ textfield in textfield.placeholder = "Your Handle" }) loginAlert.addTextFieldWithConfigurationHandler({ textfield in textfield.placeholder = "Your Password" textfield.secureTextEntry = true }) loginAlert.addAction(UIAlertAction(title: "Log in", style: UIAlertActionStyle.Default, handler:{ alertAction in let textFields: NSArray = loginAlert.textFields! as NSArray let usernameTextField: UITextField = textFields.objectAtIndex(0) as! UITextField let passwordTextField: UITextField = textFields.objectAtIndex(1) as! UITextField PFUser.logInWithUsernameInBackground(usernameTextField.text as String!, password: passwordTextField.text as String!){ (loggedInUser: PFUser?, signupError: NSError?) -> Void in if (loggedInUser != nil){ println("Login Success") } else{ println("Login Failure") } } })) loginAlert.addAction(UIAlertAction(title: "Sign Up", style: UIAlertActionStyle.Default, handler:{ alertAction in let textFields: NSArray = loginAlert.textFields! as NSArray let usernameTextField: UITextField = textFields.objectAtIndex(0) as! UITextField let passwordTextField: UITextField = textFields.objectAtIndex(1) as! UITextField var user: PFUser = PFUser() user.username = usernameTextField.text user.password = passwordTextField.text user.signUpInBackground() })) return loginAlert } return nil }
43fbbd80c2750a79bee2d31d2c7e8a08
34.235294
183
0.588727
false
false
false
false
yanil3500/acoustiCast
refs/heads/master
AcoustiCastr/AcoustiCastr/Episode.swift
mit
1
// // Episodes.swift // AcoustiCastr // // Created by Elyanil Liranzo Castro on 4/10/17. // Copyright © 2017 Elyanil Liranzo Castro. All rights reserved. // import UIKit class Episode { var title: String = "" var podDescription : String? var summary: String = "" var audiolink: String = "" var duration: String = "" var pubDate: String = "" init?(episode: [String : String]) { self.title = episode["title"]! if let summaryOfPod = episode["summary"]{ self.summary = summaryOfPod } if let link = episode["audiolink"] { self.audiolink = link } self.pubDate = episode["pubDate"]! // If duration is nil, then dont generate the episode, just return nil if let duration = episode["duration"] { self.duration = duration } else { return nil } if let podDescrip = episode["podDescription"] { self.podDescription = podDescrip } else { self.podDescription = nil } } }
152ad5fdc0d20870d6c550798937fa39
24.44186
78
0.554845
false
false
false
false
AndrewBennet/readinglist
refs/heads/master
ReadingList/Data/AmazonLinkBuilder.swift
gpl-3.0
1
import Foundation struct AmazonAffiliateLinkBuilder { let topLevelDomain: String let tag: String? init(locale: Locale) { topLevelDomain = Self.topLevelDomain(from: locale.regionCode) tag = Self.tag(from: locale.regionCode) } private static func topLevelDomain(from regionCode: String?) -> String { //swiftlint:disable:this cyclomatic_complexity switch regionCode { case "US": return ".com" case "CA": return ".ca" case "MX": return ".com.mx" case "AU": return ".com.au" case "GB": return ".co.uk" case "DE": return ".de" case "IT": return ".it" case "FR": return ".fr" case "ES": return ".es" case "NL": return ".nl" case "SE": return ".se" case "CN": return ".cn" case "BR": return ".com.br" case "IN": return ".in" case "JP": return ".co.jp" default: return ".com" } } private static func tag(from regionCode: String?) -> String? { switch regionCode { case "GB": return "&tag=readinglistio-21" case "US": return "&tag=readinglistio-20" default: return nil } } func buildAffiliateLink(fromIsbn13 isbn13: Int64) -> URL? { return URL(string: "https://www.amazon\(topLevelDomain)/s?k=\(isbn13.string)&i=stripbooks\(tag ?? "")") } }
79b09e9ae4f7c210f76f2e1b17d58b25
30.431818
123
0.570499
false
false
false
false
kickstarter/ios-oss
refs/heads/main
Library/String+SimpleHTML.swift
apache-2.0
1
import Foundation import UIKit public extension String { typealias Attributes = [NSAttributedString.Key: Any] /** Interprets `self` as an HTML string to produce an attributed string. - parameter base: The base attributes to use for the attributed string. - parameter bold: Optional attributes to use on bold tags. If not specified it will be derived from `font`. - parameter italic: Optional attributes for use on italic tags. If not specified it will be derived from `font`. - returns: The attributed string, or `nil` if something goes wrong with interpreting the string as html. */ func simpleHtmlAttributedString( base: Attributes, bold optionalBold: Attributes? = nil, italic optionalItalic: Attributes? = nil ) -> NSAttributedString? { func parsedHtml() -> NSAttributedString? { let baseFont = (base[NSAttributedString.Key.font] as? UIFont) ?? UIFont.systemFont(ofSize: 12.0) // If bold or italic are not specified we can derive them from `font`. let bold = optionalBold ?? [NSAttributedString.Key.font: baseFont.bolded] let italic = optionalItalic ?? [NSAttributedString.Key.font: baseFont.italicized] guard let data = self.data(using: String.Encoding.utf8) else { return nil } let options: [NSAttributedString.DocumentReadingOptionKey: Any] = [ NSAttributedString.DocumentReadingOptionKey.documentType: NSAttributedString.DocumentType.html, NSAttributedString.DocumentReadingOptionKey.characterEncoding: String.Encoding.utf8.rawValue ] guard let string = try? NSMutableAttributedString(data: data, options: options, documentAttributes: nil) else { return nil } // Sub all bold and italic fonts in the attributed html string let stringRange = NSRange(location: 0, length: string.length) string.beginEditing() string .enumerateAttribute(NSAttributedString.Key.font, in: stringRange, options: []) { value, range, _ in guard let htmlFont = value as? UIFont else { return } let newAttributes: Attributes if htmlFont.fontDescriptor.symbolicTraits.contains(.traitBold) { newAttributes = bold } else if htmlFont.fontDescriptor.symbolicTraits.contains(.traitItalic) { newAttributes = italic } else { newAttributes = base } string.addAttributes(newAttributes, range: range) } string.endEditing() return string } if Thread.isMainThread { return parsedHtml() } else { return DispatchQueue.main.sync { parsedHtml() } } } /** Interprets `self` as an HTML string to produce an attributed string. - parameter font: The base font to use for the attributed string. - parameter bold: An optional font for bolding. If not specified it will be derived from `font`. - parameter italic: An optional font for italicizing. If not specified it will be derived from `font`. - returns: The attributed string, or `nil` if something goes wrong with interpreting the string as html. */ func simpleHtmlAttributedString( font: UIFont, bold optionalBold: UIFont? = nil, italic optionalItalic: UIFont? = nil ) -> NSAttributedString? { return self.simpleHtmlAttributedString( base: [NSAttributedString.Key.font: font], bold: optionalBold.flatMap { [NSAttributedString.Key.font: $0] }, italic: optionalItalic.flatMap { [NSAttributedString.Key.font: $0] } ) } /** Removes all HTML from `self`. - parameter trimWhitespace: If `true`, then all whitespace will be trimmed from the stripped string. Defaults to `true`. - returns: A string with all HTML stripped. */ func htmlStripped(trimWhitespace: Bool = true) -> String? { func parsedHtml() -> String? { guard let data = self.data(using: String.Encoding.utf8) else { return nil } let options: [NSAttributedString.DocumentReadingOptionKey: Any] = [ NSAttributedString.DocumentReadingOptionKey.documentType: NSAttributedString.DocumentType.html, NSAttributedString.DocumentReadingOptionKey.characterEncoding: String.Encoding.utf8.rawValue ] let string = try? NSAttributedString(data: data, options: options, documentAttributes: nil) let result = string?.string if trimWhitespace { return result?.trimmingCharacters(in: .whitespacesAndNewlines) } return result } if Thread.isMainThread { return parsedHtml() } else { return DispatchQueue.main.sync { parsedHtml() } } } } // MARK: - Functions func == (lhs: String.Attributes, rhs: String.Attributes) -> Bool { return NSDictionary(dictionary: lhs).isEqual(to: rhs) }
e347836b770e6338bfb0e2f40f9a8c56
34.289855
110
0.677823
false
false
false
false
congncif/SiFUtilities
refs/heads/master
Example/Pods/Boardy/Boardy/Core/Board/BoardProducer.swift
mit
1
// // BoardProducer.swift // Boardy // // Created by NGUYEN CHI CONG on 6/13/21. // import Foundation public protocol BoardRegistrationsConvertible { func asBoardRegistrations() -> [BoardRegistration] } extension BoardRegistration: BoardRegistrationsConvertible { public func asBoardRegistrations() -> [BoardRegistration] { [self] } } extension Array: BoardRegistrationsConvertible where Element == BoardRegistration { public func asBoardRegistrations() -> [BoardRegistration] { self } } public protocol BoardDynamicProducer: ActivableBoardProducer { func registerBoard(_ identifier: BoardID, factory: @escaping (BoardID) -> ActivatableBoard) } public final class BoardProducer: BoardDynamicProducer { public private(set) var registrations = Set<BoardRegistration>() private var externalProducer: ActivableBoardProducer public init(externalProducer: ActivableBoardProducer = NoBoardProducer(), registrations: [BoardRegistration] = []) { self.externalProducer = externalProducer self.registrations = Set(registrations) } @discardableResult public func add(registration: BoardRegistration) -> Bool { guard !registrations.contains(registration) else { return false } registrations.insert(registration) return true } @discardableResult public func remove(registration: BoardRegistration) -> Bool { guard registrations.contains(registration) else { return false } registrations.remove(registration) return true } public func produceBoard(identifier: BoardID) -> ActivatableBoard? { let registration = registrations.first { $0.identifier == identifier } return registration?.constructor(identifier) ?? externalProducer.produceBoard(identifier: identifier) } public func registerBoard(_ identifier: BoardID, factory: @escaping BoardConstructor) { let registration = BoardRegistration(identifier, constructor: factory) add(registration: registration) } public func matchBoard(withIdentifier identifier: BoardID, to anotherIdentifier: BoardID) -> ActivatableBoard? { if let registration = registrations.first(where: { $0.identifier == identifier }) { return registration.constructor(anotherIdentifier) } else if let board = externalProducer.matchBoard(withIdentifier: identifier, to: anotherIdentifier) { return board } else { return nil } } } public extension BoardDynamicProducer where Self: AnyObject { /// Boxed the producer as a ValueType without retaining to avoid working with reference counter var boxed: BoardDynamicProducer { return BoardDynamicProducerBox(producer: self) } } struct BoardDynamicProducerBox: BoardDynamicProducer { weak var producer: (BoardDynamicProducer & AnyObject)? func produceBoard(identifier: BoardID) -> ActivatableBoard? { producer?.produceBoard(identifier: identifier) } func matchBoard(withIdentifier identifier: BoardID, to anotherIdentifier: BoardID) -> ActivatableBoard? { producer?.matchBoard(withIdentifier: identifier, to: anotherIdentifier) } func registerBoard(_ identifier: BoardID, factory: @escaping (BoardID) -> ActivatableBoard) { producer?.registerBoard(identifier, factory: factory) } } public extension ActivableBoardProducer where Self: AnyObject { /// Boxed the producer as a ValueType without retaining to avoid working with reference counter var boxed: ActivableBoardProducer { return BoardProducerBox(producer: self) } } struct BoardProducerBox: ActivableBoardProducer { weak var producer: (ActivableBoardProducer & AnyObject)? func produceBoard(identifier: BoardID) -> ActivatableBoard? { producer?.produceBoard(identifier: identifier) } func matchBoard(withIdentifier identifier: BoardID, to anotherIdentifier: BoardID) -> ActivatableBoard? { producer?.matchBoard(withIdentifier: identifier, to: anotherIdentifier) } }
9cc978b9fb1233a0b32d2b34c2786e8e
34.721739
120
0.72298
false
false
false
false
HelloCore/RXSwiftTutorialProject
refs/heads/master
Projects/03-Simple/RXSwiftPlayground.playground/Pages/04-Observable From UI.xcplaygroundpage/Contents.swift
mit
1
//: [Previous](@previous) import Foundation import UIKit import RxCocoa import RxSwift import PlaygroundSupport /*: เราสามารถใช้ property .rx เพื่อดึง Observable จาก UI ได้ */ class MyViewController: UIViewController { let disposeBag = DisposeBag() let textField = UITextField() let textField2 = UITextField() let stackView = UIStackView() let button = UIButton(type: UIButtonType.roundedRect) func initialSubScription() { // Subscribe ด้วย text textField .rx //** <--- สำคัญมาก .text .orEmpty .asObservable() .subscribe(onNext: { (str) in print("TextField1 str: [\(str)]") }) .addDisposableTo(disposeBag) // Bind ค่า TextField2 ไปที่ TextField1 textField2 .rx //** <--- สำคัญมาก .text .orEmpty .asObservable() .do(onNext: { (str) in /* Function DO จะทำงานเมื่อมี Event ผ่านเข้ามาใน Stream นี้ แต่จะไม่สามารถแก้ไขค่าอะไรได้ */ print("TextField2 str: [\(str)]") }) .bind(to: textField.rx.text) .addDisposableTo(disposeBag) button .rx //** <--- สำคัญมาก .tap .subscribe(onNext: { (value) in /* Button จะส่งค่ามาเป็น Void คือ () เท่านั้น */ print("Button always emit Void [ \(value) ]") }) .addDisposableTo(disposeBag) } override func viewDidLoad() { super.viewDidLoad() textField.borderStyle = .roundedRect textField.placeholder = "TextField1" textField2.borderStyle = .roundedRect textField2.placeholder = "TextField2" button.setTitle("Button", for: .normal) stackView.axis = .vertical stackView.distribution = .fill stackView.addArrangedSubview(UIView()) stackView.addArrangedSubview(textField) stackView.addArrangedSubview(textField2) stackView.addArrangedSubview(button) stackView.addArrangedSubview(UIView()) stackView.translatesAutoresizingMaskIntoConstraints = false self.view.addSubview(stackView) NSLayoutConstraint.activate([ stackView.leadingAnchor.constraint(equalTo: self.view.leadingAnchor), stackView.trailingAnchor.constraint(equalTo: self.view.trailingAnchor), stackView.topAnchor.constraint(equalTo: self.view.topAnchor), stackView.bottomAnchor.constraint(equalTo: self.view.bottomAnchor) ]) self.initialSubScription() } } let myVC = MyViewController() let (parent, _) = playgroundControllers(device: .phone4inch, orientation: .portrait, child: myVC) PlaygroundPage.current.liveView = parent //: [Next](@next)
fe5cb17d7711ec43275e2be937ef7986
22.538462
97
0.698121
false
false
false
false
rui4u/weibo
refs/heads/master
Rui微博/Rui微博/Classes/Module/OAuthViewController.swift
mit
1
// // OAuthViewController.swift // Rui微博 // // Created by 沙睿 on 15/10/12. // Copyright © 2015年 沙睿. All rights reserved. // import UIKit import SVProgressHUD class OAuthViewController: UIViewController,UIWebViewDelegate { private lazy var webView = UIWebView() override func loadView() { view = webView webView.delegate = self title = "新浪微博" navigationItem.rightBarButtonItem = UIBarButtonItem(title: "关闭", style: UIBarButtonItemStyle.Plain, target: self, action:"close") } override func viewDidLoad() { super.viewDidLoad() /// 请求URL webView.loadRequest(NSURLRequest(URL: NetworkTools.shareNetTooks.oauthUrl())) } func close(){ SVProgressHUD.dismiss() dismissViewControllerAnimated(true, completion: nil) } /// MARK - 代理方法 func webViewDidStartLoad(webView: UIWebView) { SVProgressHUD.show() } func webViewDidFinishLoad(webView: UIWebView) { SVProgressHUD.dismiss() } func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool { let url = request.URL!.absoluteString // print(url) // print(url.hasPrefix(NetworkTools.shareNetTooks.redirectUri)) /// 判断是否包含回调地址 if !url.hasPrefix(NetworkTools.shareNetTooks.redirectUri) { return true } //query 获取回调中的token if let query = request.URL?.query where query.hasPrefix("code=") { let code = query.substringFromIndex("code=".endIndex) // print("code = " + code) //换取TOKEN loadAccessToken(code) }else { close() } return true } private func loadAccessToken(code: String) { NetworkTools.shareNetTooks.loadAccessToken(code) { (result, error) -> () in if result == nil || error != nil { self.netError() return } //获取账户信息,并在模型中保存 UserAccout(dict: result!).loadUserInfo({ (error) -> () in if error != nil { self.netError() return } /// 发送通知 NSNotificationCenter.defaultCenter().postNotificationName(SRRootControllorSwitch, object: false) self.close() }) } } /// 网络出错处理 private func netError() { SVProgressHUD.showInfoWithStatus("您的网络不给力") // 延时一段时间再关闭 let when = dispatch_time(DISPATCH_TIME_NOW, Int64(1 * NSEC_PER_SEC)) dispatch_after(when, dispatch_get_main_queue()) { self.close() } } }
596663f99e58d4baf7e30628f1153140
29.01087
137
0.57443
false
false
false
false
antonio081014/LeetCode-CodeBase
refs/heads/main
Swift/maximum-split-of-positive-even-integers.swift
mit
1
class Solution { func maximumEvenSplit(_ finalSum: Int) -> [Int] { guard finalSum % 2 == 0 else { return [] } var result = [Int]() var sum = 0 var inc = 2 while (sum + inc) <= finalSum { result.append(inc) sum += inc inc += 2 } if sum < finalSum { result[result.count - 1] += finalSum - sum } return result } }
98dd82503e5b0e0cce72a3e00712ef95
24.823529
54
0.446469
false
false
false
false
jhurliman/NeuralSwift
refs/heads/master
NeuralSwift/NeuralSwiftTests/NeuralSwiftTests.swift
mit
1
// // NeuralSwiftTests.swift // NeuralSwiftTests // // Created by John Hurliman on 7/11/15. // Copyright (c) 2015 John Hurliman. All rights reserved. // import XCTest import NeuralSwift class ArithmeticTests: XCTestCase { func testAdd() { let a: [Float] = [1.0, 2.0, 3.0] let b: [Float] = [0.0, -5.0, 10.0] let c = add(a, b) XCTAssertEqual(1.0, c[0]) XCTAssertEqual(-3.0, c[1]) XCTAssertEqual(13.0, c[2]) } func testSubtract() { let a: [Float] = [1.0, 2.0, 3.0] let b: [Float] = [0.0, -5.0, 10.0] let c = sub(a, b) XCTAssertEqual(1.0, c[0]) XCTAssertEqual(7.0, c[1]) XCTAssertEqual(-7.0, c[2]) } } class SigmoidTests: XCTestCase { func sigmoid(z: Float) -> Float { return 1.0 / (1.0 + exp(-z)) } func testSigmoid() { // Demonstrating output from the non-vectorized sigmoid function above XCTAssertEqual(0.5, sigmoid(0.0)) XCTAssertEqualWithAccuracy(0.6224593, sigmoid(0.5), 0.000001) XCTAssertEqualWithAccuracy(0.7310586, sigmoid(1.0), 0.000001) XCTAssertEqualWithAccuracy(0.3775407, sigmoid(-0.5), 0.000001) XCTAssertEqualWithAccuracy(0.9999546, sigmoid(10.0), 0.000001) let sigmoidLayer = SigmoidLayer(layerSize: 1, prevLayerSize: 1) let sVec = sigmoidLayer.activation([0.0, 0.5, 1.0, -0.5, 10.0]) XCTAssertEqual(0.5, sVec[0]) XCTAssertEqualWithAccuracy(0.6224593, sVec[1], 0.000001) XCTAssertEqualWithAccuracy(0.7310586, sVec[2], 0.000001) XCTAssertEqualWithAccuracy(0.3775407, sVec[3], 0.000001) XCTAssertEqualWithAccuracy(0.9999546, sVec[4], 0.000001) } func testSigmoidFeedForward() { let biases: [Float] = [0, 0, 0] let weights = Matrix<Float>([ [-1, 1], [-2, 2], [-3, 3] ]) let layer = SigmoidLayer(biases: biases, weights: weights) let output = layer.feedForward([1, 1]) XCTAssertEqual(3, output.count) XCTAssertEqual(0.5, output[0]) XCTAssertEqual(0.5, output[1]) XCTAssertEqual(0.5, output[2]) } func testSigmoidBackProp() { let inputs: [Float] = [0] let targetActivations: [Float] = [1] let biases: [Float] = [0] let weights = Matrix<Float>([ [0] ]) var layer = SigmoidLayer(biases: biases, weights: weights) let initialOutput = layer.feedForward(inputs) for _ in 1...100 { let trainer = LayerTrainer(layer: layer) var activations = trainer.feedForward(inputs) var delta = sub(activations, targetActivations) var result = trainer.backPropagate(delta, prevLayerActivations: inputs) layer.biases = sub(layer.biases, trainer.biasGradients) layer.weights = sub(layer.weights, trainer.weightGradients) let output = layer.feedForward(inputs) XCTAssert(output.first! > initialOutput.first!) } let output = layer.feedForward(inputs) XCTAssertEqual(targetActivations.first!, round(output.first!)) } } class NeuralSwiftTests: XCTestCase { func testXOR() { let network = Network(sizes: [2, 3, 1]) let trainingData = [ TrainingSample(inputs: [1, 1], outputs: [0]), TrainingSample(inputs: [0, 1], outputs: [1]), TrainingSample(inputs: [1, 0], outputs: [1]), TrainingSample(inputs: [0, 0], outputs: [0]), TrainingSample(inputs: [1, 1], outputs: [0]), TrainingSample(inputs: [0, 1], outputs: [1]), TrainingSample(inputs: [1, 0], outputs: [1]), TrainingSample(inputs: [0, 0], outputs: [0]), ] measureBlock { network.train(trainingData, epochs: 3000, miniBatchSize: 4, eta: 0.8) } let _11 = network.predictValue([1, 1]) let _01 = network.predictValue([0, 1]) let _10 = network.predictValue([1, 0]) let _00 = network.predictValue([0, 0]) XCTAssert(_11 < 0.5, "\(_11) >= 0.5") XCTAssert(_01 >= 0.5, "\(_01) < 0.5") XCTAssert(_10 >= 0.5, "\(_10) < 0.5") XCTAssert(_00 < 0.5, "\(_00) >= 0.5") } } //class MNISTLoaderTests: XCTestCase { // func testLoader() { // let imagesPath = "/Users/jhurliman/Code/NeuralSwift/NeuralSwiftPlayground.playground/Resources/MNIST-train-images-idx3-ubyte" // let labelsPath = "/Users/jhurliman/Code/NeuralSwift/NeuralSwiftPlayground.playground/Resources/MNIST-train-labels-idx1-ubyte" // // let loader = MNISTLoader(imageFile: imagesPath, labelFile: labelsPath)! // // let digitNetwork = Network(sizes: [784, 100, 10]) // // digitNetwork.train(loader.samples, epochs: 30, miniBatchSize: 10, eta: 0.5) // // let testDigit = loader.samples.first! // let testDigitResult = digitNetwork.predictLabels(testDigit.inputs) // } //} class DecisionTreeTests: XCTestCase { func testMultiType() { let data = [ DecisionTree.Datum(features: [.Category("A"), .Numeric(70), .Category("True")], classification: "CLASS1"), DecisionTree.Datum(features: [.Category("A"), .Numeric(90), .Category("True")], classification: "CLASS2"), DecisionTree.Datum(features: [.Category("A"), .Numeric(85), .Category("False")], classification: "CLASS2"), DecisionTree.Datum(features: [.Category("A"), .Numeric(95), .Category("False")], classification: "CLASS2"), DecisionTree.Datum(features: [.Category("A"), .Numeric(70), .Category("False")], classification: "CLASS1"), DecisionTree.Datum(features: [.Category("B"), .Numeric(90), .Category("True")], classification: "CLASS1"), DecisionTree.Datum(features: [.Category("B"), .Numeric(78), .Category("False")], classification: "CLASS1"), DecisionTree.Datum(features: [.Category("B"), .Numeric(65), .Category("True")], classification: "CLASS1"), DecisionTree.Datum(features: [.Category("B"), .Numeric(75), .Category("False")], classification: "CLASS1"), DecisionTree.Datum(features: [.Category("C"), .Numeric(80), .Category("True")], classification: "CLASS2"), DecisionTree.Datum(features: [.Category("C"), .Numeric(70), .Category("True")], classification: "CLASS2"), DecisionTree.Datum(features: [.Category("C"), .Numeric(80), .Category("False")], classification: "CLASS1"), DecisionTree.Datum(features: [.Category("C"), .Numeric(80), .Category("False")], classification: "CLASS1"), DecisionTree.Datum(features: [.Category("C"), .Numeric(96), .Category("False")], classification: "CLASS1"), ] if let tree = DecisionTree(data: data) { for datum in data { let result = tree.classify(datum.features) XCTAssertNotNil(result) if let result = result { XCTAssertEqual(datum.classification, result) } } } else { XCTFail("Failed to construct tree") } } func testMultiClass() { let data = [ DecisionTree.Datum(features: [.Category("slashdot"), .Category("USA"), .Category("yes"), .Numeric(18)], classification: "None"), DecisionTree.Datum(features: [.Category("google"), .Category("France"), .Category("yes"), .Numeric(23)], classification: "Premium"), DecisionTree.Datum(features: [.Category("digg"), .Category("USA"), .Category("yes"), .Numeric(24)], classification: "Basic"), DecisionTree.Datum(features: [.Category("kiwitobes"), .Category("France"), .Category("yes"), .Numeric(23)], classification: "Basic"), DecisionTree.Datum(features: [.Category("google"), .Category("UK"), .Category("no"), .Numeric(21)], classification: "Premium"), DecisionTree.Datum(features: [.Category("(direct)"), .Category("New Zealand"), .Category("no"), .Numeric(12)], classification: "None"), DecisionTree.Datum(features: [.Category("(direct)"), .Category("UK"), .Category("no"), .Numeric(21)], classification: "Basic"), DecisionTree.Datum(features: [.Category("google"), .Category("USA"), .Category("no"), .Numeric(24)], classification: "Premium"), DecisionTree.Datum(features: [.Category("slashdot"), .Category("France"), .Category("yes"), .Numeric(19)], classification: "None"), DecisionTree.Datum(features: [.Category("digg"), .Category("USA"), .Category("no"), .Numeric(18)], classification: "None"), DecisionTree.Datum(features: [.Category("google"), .Category("UK"), .Category("no"), .Numeric(18)], classification: "None"), DecisionTree.Datum(features: [.Category("kiwitobes"), .Category("UK"), .Category("no"), .Numeric(19)], classification: "None"), DecisionTree.Datum(features: [.Category("digg"), .Category("New Zealand"), .Category("yes"), .Numeric(12)], classification: "Basic"), DecisionTree.Datum(features: [.Category("slashdot"), .Category("UK"), .Category("no"), .Numeric(21)], classification: "None"), DecisionTree.Datum(features: [.Category("google"), .Category("UK"), .Category("yes"), .Numeric(18)], classification: "Basic"), DecisionTree.Datum(features: [.Category("kiwitobes"), .Category("France"), .Category("yes"), .Numeric(19)], classification: "Basic"), ] if let tree = DecisionTree(data: data) { for datum in data { let result = tree.classify(datum.features) XCTAssertNotNil(result) if let result = result { XCTAssertEqual(datum.classification, result) } } let result1 = tree.classify([.Category("(direct)"), .Category("USA"), .Category("yes"), .Numeric(5)]) XCTAssertNotNil(result1) if let result1 = result1 { XCTAssertEqual("Basic", result1) } } else { XCTFail("Failed to construct tree") } } }
836fed6bcc93c765f1c910731e2c470e
48.275362
147
0.591569
false
true
false
false
eurofurence/ef-app_ios
refs/heads/release/4.0.0
Packages/EurofurenceApplication/Tests/EurofurenceApplicationTests/Content Router/Route Tests/Announcement/AnnouncementRouteTests.swift
mit
1
import EurofurenceApplication import EurofurenceModel import XCTComponentBase import XCTest class AnnouncementRouteTests: XCTestCase { func testShowsDetailContentControllerForAnnouncement() { let identifier = AnnouncementIdentifier.random let content = AnnouncementRouteable(identifier: identifier) let announcementModuleFactory = StubAnnouncementDetailComponentFactory() let contentWireframe = CapturingContentWireframe() let route = AnnouncementRoute( announcementModuleFactory: announcementModuleFactory, contentWireframe: contentWireframe ) route.route(content) XCTAssertEqual(identifier, announcementModuleFactory.capturedModel) XCTAssertEqual(contentWireframe.replacedDetailContentController, announcementModuleFactory.stubInterface) } }
9854ec7c2cc116fb286562041ef0342a
35.375
113
0.754868
false
true
false
false
rockgarden/swift_language
refs/heads/swift3
Playground/Temp.playground/Pages/Sequence.xcplaygroundpage/Contents.swift
mit
1
//: [Previous](@previous) import UIKit import Foundation /// A type that provides sequential, iterated access to its elements. /// /// A sequence is a list of values that you can step through one at a time. The /// most common way to iterate over the elements of a sequence is to use a /// `for`-`in` loop: /// /// let oneTwoThree = 1...3 /// for number in oneTwoThree { /// print(number) /// } /// // Prints "1" /// // Prints "2" /// // Prints "3" /// /// While seemingly simple, this capability gives you access to a large number /// of operations that you can perform on any sequence. As an example, to /// check whether a sequence includes a particular value, you can test each /// value sequentially until you've found a match or reached the end of the /// sequence. This example checks to see whether a particular insect is in an /// array. /// /// let bugs = ["Aphid", "Bumblebee", "Cicada", "Damselfly", "Earwig"] /// var hasMosquito = false /// for bug in bugs { /// if bug == "Mosquito" { /// hasMosquito = true /// break /// } /// } /// print("'bugs' has a mosquito: \(hasMosquito)") /// // Prints "'bugs' has a mosquito: false" /// /// The `Sequence` protocol provides default implementations for many common /// operations that depend on sequential access to a sequence's values. For /// clearer, more concise code, the example above could use the array's /// `contains(_:)` method, which every sequence inherits from `Sequence`, /// instead of iterating manually: /// /// if bugs.contains("Mosquito") { /// print("Break out the bug spray.") /// } else { /// print("Whew, no mosquitos!") /// } /// // Prints "Whew, no mosquitos!" /// /// Repeated Access /// =============== /// /// The `Sequence` protocol makes no requirement on conforming types regarding /// whether they will be destructively consumed by iteration. As a /// consequence, don't assume that multiple `for`-`in` loops on a sequence /// will either resume iteration or restart from the beginning: /// /// for element in sequence { /// if ... some condition { break } /// } /// /// for element in sequence { /// // No defined behavior /// } /// /// In this case, you cannot assume either that a sequence will be consumable /// and will resume iteration, or that a sequence is a collection and will /// restart iteration from the first element. A conforming sequence that is /// not a collection is allowed to produce an arbitrary sequence of elements /// in the second `for`-`in` loop. /// /// To establish that a type you've created supports nondestructive iteration, /// add conformance to the `Collection` protocol. /// /// Conforming to the Sequence Protocol /// =================================== /// /// Making your own custom types conform to `Sequence` enables many useful /// operations, like `for`-`in` looping and the `contains` method, without /// much effort. To add `Sequence` conformance to your own custom type, add a /// `makeIterator()` method that returns an iterator. /// /// Alternatively, if your type can act as its own iterator, implementing the /// requirements of the `IteratorProtocol` protocol and declaring conformance /// to both `Sequence` and `IteratorProtocol` are sufficient. /// /// /// Expected Performance /// ==================== /// /// A sequence should provide its iterator in O(1). The `Sequence` protocol /// makes no other requirements about element access, so routines that /// traverse a sequence should be considered O(*n*) unless documented /// otherwise. //过滤数组中的数字 //extension Sequence{ // typealias Element = Self.Iterator.Element // func partitionBy(fu: (Element)->Bool)->([Element],[Element]){ // var first=[Element]() // var second=[Element]() // for el in self { // if fu(el) { // first.append(el) // }else{ // second.append(el) // } // } // return (first,second) // } //} //let part = [82, 58, 76, 49, 88, 90].partitionBy{$0 < 60} //part // ([58, 49], [82, 76, 88, 90]) do { struct Countdown: Sequence, IteratorProtocol { var count: Int mutating func next() -> Int? { if count == 0 { return nil } else { defer { count -= 1 } return count } } } let threeToGo = Countdown(count: 3) for i in threeToGo { print(i) } // Prints "3" // Prints "2" // Prints "1" } /*: Sequence 就离不开IteratorProtocol这个protocol,它是Sequence的基础。 public protocol IteratorProtocol { associatedtype Element public mutating func next() -> Self.Element? } */ do { class ReverseIterator: IteratorProtocol{ var element:Int init<T>(array:[T]) { self.element = array.count-1 } func next() ->Int?{ let result:Int? = self.element < 0 ? nil : element element -= 1 return result } } let arr = ["A","B","C","D","E"] let itertator = ReverseIterator(array:arr) while let i = itertator.next(){ print("element \(i) of the array is \(arr[i])") } } extension Sequence{ /// Sequence 实现 PartitionBy /// /// - Parameter fu: <#fu description#> /// - Returns: <#return value description#> func anotherPartitionBy(fu: (Self.Iterator.Element)->Bool)->([Self.Iterator.Element],[Self.Iterator.Element]){ return (self.filter(fu),self.filter({!fu($0)})) } } do { let part2 = [82, 58, 76, 49, 88, 90].anotherPartitionBy{$0 < 60} part2 // ([58, 49], [82, 76, 88, 90]) //构建了包含两个分区的结果元组,一次一个元素,使用过滤函数测试初始序列中的每个元素,并根据过滤结果追加该元素到第一或第二分区数组中,即分区数组通过追加被构建 var part3 = [82, 58, 76, 49, 88, 90].reduce(([],[]), { (a:([Int],[Int]),n:Int) in (n<60) ? (a.0+[n], a.1) : (a.0, a.1+[n]) }) part3 // ([58, 49], [82, 76, 88, 90]) } do { // 图书 struct Book { var name: String } // 书架 class BookShelf { //图书集合 private var books: [Book] = [] //添加新书 func append(book: Book) { self.books.append(book) } //创建Iterator func makeIterator() -> AnyIterator<Book> { var index : Int = 0 return AnyIterator<Book> { defer { index = index + 1 } return index < self.books.count ? self.books[index] : nil } } } let bookShelf1 = BookShelf() bookShelf1.append(book: Book(name: "平凡的世界")) bookShelf1.append(book: Book(name: "活着")) bookShelf1.append(book: Book(name: "围城")) bookShelf1.append(book: Book(name: "三国演义")) //外文书架 let bookShelf2 = BookShelf() bookShelf2.append(book: Book(name: "The Kite Runner")) bookShelf2.append(book: Book(name: "Cien anos de soledad")) bookShelf2.append(book: Book(name: "Harry Potter")) //创建两个书架图书的交替序列 for book in sequence(state: (false, bookShelf1.makeIterator(), bookShelf2.makeIterator()), next: { (state:inout (Bool,AnyIterator<Book>,AnyIterator<Book>)) -> Book? in state.0 = !state.0 return state.0 ? state.1.next() : state.2.next() }) { print(book.name) } } //: [Next](@next)
308a6cf71dd82812e845c06d76b936ff
28.868
114
0.579483
false
false
false
false
kickstarter/ios-oss
refs/heads/main
Kickstarter-iOS/Features/ProjectPage/Views/Cells/ProjectPamphletMainCell.swift
apache-2.0
1
import KsApi import Library import Prelude import UIKit internal protocol ProjectPamphletMainCellDelegate: VideoViewControllerDelegate { func projectPamphletMainCell(_ cell: ProjectPamphletMainCell, addChildController child: UIViewController) func projectPamphletMainCell( _ cell: ProjectPamphletMainCell, goToCampaignForProjectWith data: ProjectPamphletMainCellData ) func projectPamphletMainCell(_ cell: ProjectPamphletMainCell, goToCreatorForProject project: Project) } internal final class ProjectPamphletMainCell: UITableViewCell, ValueCell { internal weak var delegate: ProjectPamphletMainCellDelegate? { didSet { self.viewModel.inputs.delegateDidSet() } } fileprivate let viewModel: ProjectPamphletMainCellViewModelType = ProjectPamphletMainCellViewModel() fileprivate weak var videoController: VideoViewController? @IBOutlet fileprivate var backersSubtitleLabel: UILabel! @IBOutlet fileprivate var backersTitleLabel: UILabel! @IBOutlet fileprivate var blurbAndReadMoreStackView: UIStackView! @IBOutlet fileprivate var blurbStackView: UIStackView! @IBOutlet fileprivate var categoryStackView: UIStackView! @IBOutlet fileprivate var categoryAndLocationStackView: UIStackView! @IBOutlet fileprivate var categoryIconImageView: UIImageView! @IBOutlet fileprivate var categoryNameLabel: UILabel! @IBOutlet fileprivate var contentStackView: UIStackView! @IBOutlet fileprivate var conversionLabel: UILabel! @IBOutlet fileprivate var creatorButton: UIButton! @IBOutlet fileprivate var creatorImageView: UIImageView! @IBOutlet fileprivate var creatorLabel: UILabel! @IBOutlet fileprivate var creatorStackView: UIStackView! @IBOutlet fileprivate var deadlineSubtitleLabel: UILabel! @IBOutlet fileprivate var deadlineTitleLabel: UILabel! @IBOutlet fileprivate var fundingProgressBarView: UIView! @IBOutlet fileprivate var fundingProgressContainerView: UIView! @IBOutlet fileprivate var locationImageView: UIImageView! @IBOutlet fileprivate var locationNameLabel: UILabel! @IBOutlet fileprivate var locationStackView: UIStackView! @IBOutlet fileprivate var pledgeSubtitleLabel: UILabel! @IBOutlet fileprivate var pledgedTitleLabel: UILabel! @IBOutlet fileprivate var projectBlurbLabel: UILabel! @IBOutlet fileprivate var projectImageContainerView: UIView! @IBOutlet fileprivate var projectNameAndCreatorStackView: UIStackView! @IBOutlet fileprivate var projectNameLabel: UILabel! @IBOutlet fileprivate var progressBarAndStatsStackView: UIStackView! @IBOutlet fileprivate var readMoreButton: UIButton! @IBOutlet fileprivate var readMoreStackView: UIStackView! @IBOutlet fileprivate var stateLabel: UILabel! @IBOutlet fileprivate var statsStackView: UIStackView! @IBOutlet fileprivate var youreABackerContainerView: UIView! @IBOutlet fileprivate var youreABackerContainerViewLeadingConstraint: NSLayoutConstraint! @IBOutlet fileprivate var youreABackerLabel: UILabel! internal override func awakeFromNib() { super.awakeFromNib() self.creatorButton.addTarget( self, action: #selector(self.creatorButtonTapped), for: .touchUpInside ) self.readMoreButton.addTarget( self, action: #selector(self.readMoreButtonTapped), for: .touchUpInside ) self.viewModel.inputs.awakeFromNib() } internal func configureWith(value: ProjectPamphletMainCellData) { self.viewModel.inputs.configureWith(value: value) } internal func scrollContentOffset(_ offset: CGFloat) { let height = self.projectImageContainerView.bounds.height let translation = offset / 2 let scale: CGFloat if offset < 0 { scale = (height + abs(offset)) / height } else { scale = max(1, 1 - 0.5 * offset / height) } self.projectImageContainerView.transform = CGAffineTransform( a: scale, b: 0, c: 0, d: scale, tx: 0, ty: translation ) } internal override func bindStyles() { super.bindStyles() // maintain vertical spacing in one place so that it's consistent in nested stackviews let verticalSpacing = Styles.grid(3) _ = self |> baseTableViewCellStyle() |> UITableViewCell.lens.clipsToBounds .~ true |> UITableViewCell.lens.accessibilityElements .~ self.subviews let subtitleLabelStyling = UILabel.lens.font .~ .ksr_caption1(size: 13) <> UILabel.lens.numberOfLines .~ 1 <> UILabel.lens.backgroundColor .~ .ksr_white _ = [self.backersSubtitleLabel, self.deadlineSubtitleLabel] ||> UILabel.lens.textColor .~ .ksr_support_400 ||> subtitleLabelStyling _ = self.pledgeSubtitleLabel |> subtitleLabelStyling _ = [self.backersTitleLabel, self.deadlineTitleLabel, self.pledgedTitleLabel] ||> UILabel.lens.font .~ .ksr_headline(size: 13) ||> UILabel.lens.numberOfLines .~ 1 ||> UILabel.lens.backgroundColor .~ .ksr_white _ = self.categoryStackView |> UIStackView.lens.spacing .~ Styles.grid(1) _ = self.categoryIconImageView |> UIImageView.lens.contentMode .~ .scaleAspectFit |> UIImageView.lens.tintColor .~ .ksr_support_400 |> UIImageView.lens.image .~ UIImage(named: "category-icon") |> UIImageView.lens.backgroundColor .~ .ksr_white _ = self.categoryNameLabel |> UILabel.lens.textColor .~ .ksr_support_400 |> UILabel.lens.font .~ .ksr_body(size: 12) |> UILabel.lens.backgroundColor .~ .ksr_white let leftRightInsetValue: CGFloat = self.traitCollection.isRegularRegular ? Styles.grid(16) : Styles.grid(4) _ = self.categoryAndLocationStackView |> UIStackView.lens.isLayoutMarginsRelativeArrangement .~ true |> UIStackView.lens.layoutMargins .~ UIEdgeInsets( leftRight: leftRightInsetValue ) _ = self.contentStackView |> UIStackView.lens.layoutMargins %~~ { _, stackView in stackView.traitCollection.isRegularRegular ? .init(topBottom: Styles.grid(6)) : .init(top: Styles.grid(4), left: 0, bottom: Styles.grid(3), right: 0) } |> UIStackView.lens.isLayoutMarginsRelativeArrangement .~ true |> UIStackView.lens.spacing .~ verticalSpacing _ = (self.projectNameAndCreatorStackView, self.contentStackView) |> ksr_setCustomSpacing(Styles.grid(4)) _ = self.blurbAndReadMoreStackView |> \.spacing .~ verticalSpacing _ = self.blurbStackView |> UIStackView.lens.layoutMargins .~ UIEdgeInsets(leftRight: leftRightInsetValue) |> UIStackView.lens.isLayoutMarginsRelativeArrangement .~ true _ = self.readMoreStackView |> UIStackView.lens.layoutMargins .~ UIEdgeInsets(leftRight: leftRightInsetValue) |> UIStackView.lens.isLayoutMarginsRelativeArrangement .~ true _ = self.conversionLabel |> UILabel.lens.textColor .~ .ksr_support_400 |> UILabel.lens.font .~ UIFont.ksr_caption2().italicized |> UILabel.lens.numberOfLines .~ 2 _ = self.creatorImageView |> ignoresInvertColorsImageViewStyle _ = self.creatorButton |> UIButton.lens.accessibilityHint %~ { _ in Strings.Opens_creator_profile() } _ = self.creatorImageView |> UIImageView.lens.clipsToBounds .~ true |> UIImageView.lens.contentMode .~ .scaleAspectFill _ = self.creatorLabel |> UILabel.lens.textColor .~ .ksr_support_700 |> UILabel.lens.font .~ .ksr_headline(size: 13) |> UILabel.lens.backgroundColor .~ .ksr_white _ = self.creatorStackView |> UIStackView.lens.alignment .~ .center |> UIStackView.lens.spacing .~ Styles.grid(1) _ = self.fundingProgressContainerView |> UIView.lens.backgroundColor .~ .ksr_support_300 _ = self.locationImageView |> UIImageView.lens.contentMode .~ .scaleAspectFit |> UIImageView.lens.tintColor .~ .ksr_support_400 |> UIImageView.lens.image .~ UIImage(named: "location-icon") |> UIImageView.lens.backgroundColor .~ .ksr_white _ = self.locationNameLabel |> UILabel.lens.textColor .~ .ksr_support_400 |> UILabel.lens.font .~ .ksr_body(size: 12) |> UILabel.lens.backgroundColor .~ .ksr_white _ = self.locationStackView |> UIStackView.lens.spacing .~ Styles.grid(1) _ = self.projectBlurbLabel |> UILabel.lens.font %~~ { _, label in label.traitCollection.isRegularRegular ? .ksr_body(size: 18) : .ksr_body(size: 15) } |> UILabel.lens.textColor .~ .ksr_support_400 |> UILabel.lens.numberOfLines .~ 0 |> UILabel.lens.backgroundColor .~ .ksr_white _ = self.projectNameAndCreatorStackView |> UIStackView.lens.spacing .~ (verticalSpacing / 2) |> UIStackView.lens.layoutMargins .~ UIEdgeInsets(leftRight: leftRightInsetValue) |> UIStackView.lens.isLayoutMarginsRelativeArrangement .~ true _ = self.projectNameLabel |> UILabel.lens.font %~~ { _, label in label.traitCollection.isRegularRegular ? .ksr_title3(size: 28) : .ksr_title3(size: 20) } |> UILabel.lens.textColor .~ .ksr_support_700 |> UILabel.lens.numberOfLines .~ 0 |> UILabel.lens.backgroundColor .~ .ksr_white _ = self.progressBarAndStatsStackView |> UIStackView.lens.layoutMargins .~ UIEdgeInsets(leftRight: leftRightInsetValue) |> UIStackView.lens.isLayoutMarginsRelativeArrangement .~ true |> UIStackView.lens.spacing .~ verticalSpacing _ = self.stateLabel |> UILabel.lens.font .~ .ksr_headline(size: 12) |> UILabel.lens.numberOfLines .~ 2 _ = self.statsStackView |> UIStackView.lens.isAccessibilityElement .~ true |> UIStackView.lens.backgroundColor .~ .ksr_white _ = self.youreABackerContainerViewLeadingConstraint |> \.constant .~ leftRightInsetValue _ = self.youreABackerContainerView |> roundedStyle(cornerRadius: 2) |> UIView.lens.backgroundColor .~ .ksr_create_700 |> UIView.lens.layoutMargins .~ .init(topBottom: Styles.grid(1), leftRight: Styles.gridHalf(3)) _ = self.youreABackerLabel |> UILabel.lens.textColor .~ .ksr_white |> UILabel.lens.font .~ .ksr_headline(size: 12) |> UILabel.lens.text %~ { _ in Strings.Youre_a_backer() } _ = self.readMoreButton |> readMoreButtonStyle |> UIButton.lens.title(for: .normal) %~ { _ in Strings.Read_more_about_the_campaign_arrow() } } internal override func bindViewModel() { super.bindViewModel() self.readMoreButton.rac.hidden = self.viewModel.outputs.campaignTabShown self.backersSubtitleLabel.rac.text = self.viewModel.outputs.backersSubtitleLabelText self.backersTitleLabel.rac.text = self.viewModel.outputs.backersTitleLabelText self.backersTitleLabel.rac.textColor = self.viewModel.outputs.projectUnsuccessfulLabelTextColor self.categoryNameLabel.rac.text = self.viewModel.outputs.categoryNameLabelText self.conversionLabel.rac.hidden = self.viewModel.outputs.conversionLabelHidden self.conversionLabel.rac.text = self.viewModel.outputs.conversionLabelText self.creatorButton.rac.accessibilityLabel = self.viewModel.outputs.creatorLabelText self.creatorLabel.rac.text = self.viewModel.outputs.creatorLabelText self.deadlineSubtitleLabel.rac.text = self.viewModel.outputs.deadlineSubtitleLabelText self.deadlineTitleLabel.rac.text = self.viewModel.outputs.deadlineTitleLabelText self.deadlineTitleLabel.rac.textColor = self.viewModel.outputs.projectUnsuccessfulLabelTextColor self.fundingProgressBarView.rac.backgroundColor = self.viewModel.outputs.fundingProgressBarViewBackgroundColor self.locationNameLabel.rac.text = self.viewModel.outputs.locationNameLabelText self.pledgeSubtitleLabel.rac.text = self.viewModel.outputs.pledgedSubtitleLabelText self.pledgeSubtitleLabel.rac.textColor = self.viewModel.outputs.pledgedTitleLabelTextColor self.pledgedTitleLabel.rac.text = self.viewModel.outputs.pledgedTitleLabelText self.pledgedTitleLabel.rac.textColor = self.viewModel.outputs.pledgedTitleLabelTextColor self.projectBlurbLabel.rac.text = self.viewModel.outputs.projectBlurbLabelText self.projectNameLabel.rac.text = self.viewModel.outputs.projectNameLabelText self.stateLabel.rac.text = self.viewModel.outputs.projectStateLabelText self.stateLabel.rac.textColor = self.viewModel.outputs.projectStateLabelTextColor self.stateLabel.rac.hidden = self.viewModel.outputs.stateLabelHidden self.statsStackView.rac.accessibilityLabel = self.viewModel.outputs.statsStackViewAccessibilityLabel self.youreABackerContainerView.rac.hidden = self.viewModel.outputs.youreABackerLabelHidden self.viewModel.outputs.configureVideoPlayerController .observeForUI() .observeValues { [weak self] in self?.configureVideoPlayerController(forProject: $0) } self.viewModel.outputs.creatorImageUrl .observeForUI() .on(event: { [weak self] _ in self?.creatorImageView.image = nil }) .skipNil() .observeValues { [weak self] in self?.creatorImageView.af.setImage(withURL: $0) } self.viewModel.outputs.notifyDelegateToGoToCampaignWithData .observeForControllerAction() .observeValues { [weak self] in guard let self = self else { return } self.delegate?.projectPamphletMainCell(self, goToCampaignForProjectWith: $0) } self.viewModel.outputs.notifyDelegateToGoToCreator .observeForControllerAction() .observeValues { [weak self] in guard let self = self else { return } self.delegate?.projectPamphletMainCell(self, goToCreatorForProject: $0) } self.viewModel.outputs.opacityForViews .observeForUI() .observeValues { [weak self] alpha in guard let self = self else { return } UIView.animate( withDuration: alpha == 0.0 ? 0.0 : 0.3, delay: 0.0, options: .curveEaseOut, animations: { self.creatorStackView.alpha = alpha self.statsStackView.alpha = alpha self.blurbAndReadMoreStackView.alpha = alpha }, completion: nil ) } self.viewModel.outputs.progressPercentage .observeForUI() .observeValues { [weak self] progress in let anchorX = progress == 0 ? 0 : 0.5 / progress self?.fundingProgressBarView.layer.anchorPoint = CGPoint(x: CGFloat(anchorX), y: 0.5) self?.fundingProgressBarView.transform = CGAffineTransform(scaleX: CGFloat(progress), y: 1.0) } } fileprivate func configureVideoPlayerController(forProject project: Project) { let vc = VideoViewController.configuredWith(project: project) vc.delegate = self vc.view.translatesAutoresizingMaskIntoConstraints = false self.projectImageContainerView.addSubview(vc.view) NSLayoutConstraint.activate([ vc.view.topAnchor.constraint(equalTo: self.projectImageContainerView.topAnchor), vc.view.leadingAnchor.constraint(equalTo: self.projectImageContainerView.leadingAnchor), vc.view.bottomAnchor.constraint(equalTo: self.projectImageContainerView.bottomAnchor), vc.view.trailingAnchor.constraint(equalTo: self.projectImageContainerView.trailingAnchor) ]) self.delegate?.projectPamphletMainCell(self, addChildController: vc) self.videoController = vc self.videoController?.playbackDelegate = vc } @objc fileprivate func readMoreButtonTapped() { self.viewModel.inputs.readMoreButtonTapped() } @objc fileprivate func creatorButtonTapped() { self.viewModel.inputs.creatorButtonTapped() } } extension ProjectPamphletMainCell: VideoViewControllerDelegate { internal func videoViewControllerDidFinish(_ controller: VideoViewController) { self.delegate?.videoViewControllerDidFinish(controller) self.viewModel.inputs.videoDidFinish() } internal func videoViewControllerDidStart(_ controller: VideoViewController) { self.delegate?.videoViewControllerDidStart(controller) self.viewModel.inputs.videoDidStart() } } extension ProjectPamphletMainCell: AudioVideoViewControllerPlaybackDelegate { func pauseAudioVideoPlayback() { self.videoController?.playbackDelegate?.pauseAudioVideoPlayback() } }
63bccc2fa0057699f810a7d4805cd998
40.137056
107
0.730874
false
false
false
false
toggl/superday
refs/heads/develop
teferi/UI/Modules/Timeline/PagerViewModel.swift
bsd-3-clause
1
import RxSwift import RxCocoa import Foundation class PagerViewModel { //MARK: Public Properties private(set) lazy var dateObservable : Observable<DateChange> = { return self.selectedDateService .currentlySelectedDateObservable .map(self.toDateChange) .filterNil() }() private(set) lazy var newDayObservable : Observable<Void> = { return self.appLifecycleService.movedToForegroundObservable .filter { self.lastRefresh.differenceInDays(toDate:self.timeService.now) > 0 } .do(onNext: { self.lastRefresh = self.timeService.now }) }() var dailyVotingNotificationDateObservable : Observable<Date> { return appLifecycleService.startedOnDailyVotingNotificationDateObservable } var editingChangedObservable: Observable<Bool> { return Observable.merge( NotificationCenter.default.rx.typedNotification(OnEditStarted.self).mapTo(true), NotificationCenter.default.rx.typedNotification(OnEditEnded.self).mapTo(false) ) } var currentDate : Date { return self.timeService.now } var currentlySelectedDate : Date { get { return self.selectedDate.ignoreTimeComponents() } set(value) { self.selectedDate = value self.selectedDateService.currentlySelectedDate = value } } var activitiesObservable : Driver<[Activity]> { let timelineEdit = Observable.merge([ NotificationCenter.default.rx.typedNotification(OnTimeSlotCreated.self).mapTo(()), NotificationCenter.default.rx.typedNotification(OnTimeSlotDeleted.self).mapTo(()), NotificationCenter.default.rx.typedNotification(OnTimeSlotStartTimeEdited.self).mapTo(()), NotificationCenter.default.rx.typedNotification(OnTimeSlotCategoriesEdited.self).mapTo(()), ]) let dateChage = selectedDateService.currentlySelectedDateObservable .mapTo(()) let movedToForeground = appLifecycleService.movedToForegroundObservable return Observable.of(timelineEdit, dateChage, movedToForeground).merge() .startWith(()) .flatMap(activitiesForCurrentDate) .asDriver(onErrorJustReturn: []) } //MARK: Private Properties private var lastRefresh : Date private let timeService : TimeService private let settingsService : SettingsService private let appLifecycleService : AppLifecycleService private var selectedDateService : SelectedDateService private var selectedDate : Date //MARK: Initializers init(timeService: TimeService, settingsService: SettingsService, appLifecycleService: AppLifecycleService, selectedDateService: SelectedDateService) { self.timeService = timeService self.appLifecycleService = appLifecycleService self.settingsService = settingsService self.selectedDateService = selectedDateService lastRefresh = timeService.now selectedDate = timeService.now } //MARK: Public Methods func canScroll(toDate date: Date) -> Bool { let minDate = settingsService.installDate!.ignoreTimeComponents() let maxDate = timeService.now.ignoreTimeComponents() let dateWithNoTime = date.ignoreTimeComponents() return dateWithNoTime >= minDate && dateWithNoTime <= maxDate } //MARK: Private Methods private func toDateChange(_ date: Date) -> DateChange? { if date.ignoreTimeComponents() != currentlySelectedDate { let dateChange = DateChange(newDate: date, oldDate: selectedDate) selectedDate = date return dateChange } return nil } private func activitiesForCurrentDate() -> Observable<[Activity]> { let startDate = selectedDate.ignoreTimeComponents() let endDate = selectedDate.tomorrow.ignoreTimeComponents() let getActivities = InteractorFactory.shared.createGetActivitiesForDateRange(startDate: startDate, endDate: endDate) return getActivities.execute() .map { activities in activities.sorted(by: { $0.duration > $1.duration }) } } }
562efc1a4e6a79147e7e806eb0e7b56b
33.175573
124
0.650882
false
false
false
false
tinrobots/CoreDataPlus
refs/heads/master
Tests/Utils/Utils.swift
mit
1
// CoreDataPlus import CoreData @testable import CoreDataPlus let model = SampleModelVersion.version1.managedObjectModel() // MARK: - URL extension URL { static func newDatabaseURL(withID id: UUID) -> URL { newDatabaseURL(withName: id.uuidString) } static func newDatabaseURL(withName name: String) -> URL { let cachesURL = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask).first! let testsURL = cachesURL.appendingPathComponent(bundleIdentifier) var directory: ObjCBool = ObjCBool(true) let directoryExists = FileManager.default.fileExists(atPath: testsURL.path, isDirectory: &directory) if !directoryExists { try! FileManager.default.createDirectory(at: testsURL, withIntermediateDirectories: true, attributes: nil) } let databaseURL = testsURL.appendingPathComponent("\(name).sqlite") return databaseURL } static var temporaryDirectoryURL: URL { let url = URL(fileURLWithPath: NSTemporaryDirectory(), isDirectory:true) .appendingPathComponent(bundleIdentifier) .appendingPathComponent(UUID().uuidString) try! FileManager.default.createDirectory(at: url, withIntermediateDirectories: true, attributes: nil) return url } } extension Foundation.Bundle { fileprivate class Dummy { } /// Returns the resource bundle associated with the current Swift module. /// Note: the implementation is very close to the one provided by the Swift Package with `Bundle.module` (that is not available for XCTests). static var tests: Bundle = { let bundleName = "CoreDataPlus_Tests" let candidates = [ // Bundle should be present here when the package is linked into an App. Bundle.main.resourceURL, // Bundle should be present here when the package is linked into a framework. Bundle(for: Dummy.self).resourceURL, // For command-line tools. Bundle.main.bundleURL, ] // Search for resources bundle when running Swift Package tests from Xcode for candidate in candidates { let bundlePath = candidate?.appendingPathComponent(bundleName + ".bundle") if let bundle = bundlePath.flatMap(Bundle.init(url:)) { return bundle } } // Search for resources bundle when running Swift Package tests from terminal (swift test) // It's probably a fix for this: // https://forums.swift.org/t/5-3-resources-support-not-working-on-with-swift-test/40381/10 // https://github.com/apple/swift-package-manager/pull/2905 // https://bugs.swift.org/browse/SR-13560 let url = Bundle(for: Dummy.self).bundleURL.deletingLastPathComponent().appendingPathComponent(bundleName + ".bundle") if let bundle = Bundle(url: url) { return bundle } // XCTests Fallback return Bundle(for: Dummy.self) }() } // MARK: - NSManagedObjectContext extension NSManagedObjectContext { convenience init(model: NSManagedObjectModel, storeURL: URL) { let psc = NSPersistentStoreCoordinator(managedObjectModel: model) try! psc.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: storeURL, options: nil) self.init(concurrencyType: .mainQueueConcurrencyType) persistentStoreCoordinator = psc } func _fix_sqlite_warning_when_destroying_a_store() { /// If SQLITE_ENABLE_FILE_ASSERTIONS is set to 1 tests crash without this fix. /// solve the warning: "BUG IN CLIENT OF libsqlite3.dylib: database integrity compromised by API violation: vnode unlinked while in use..." try! persistentStoreCoordinator!.removeAllStores() } }
8821c99096b852bdf8cf0bf82d5ef369
37.290323
143
0.72929
false
true
false
false
Shark/GlowingRemote
refs/heads/master
GlowingRemote/GlowingRoomAPI.swift
isc
1
// // GlowingRoomAPI.swift // GlowingRemote // // Created by Felix Seidel on 17/07/15. // Copyright © 2015 Felix Seidel. All rights reserved. // import Foundation class GlowingRoomAPI { static func getAllDevices(baseUrl: NSURL, completionHandler: ((NSArray?) -> Void)?) -> Void { let allDevicesUrl = baseUrl.URLByAppendingPathComponent("/devices") let session = NSURLSession.sharedSession() let task = session.dataTaskWithURL(allDevicesUrl, completionHandler: {data, response, error -> Void in guard error == nil && data != nil else { completionHandler?(nil); return } var devices : NSArray? if let json = try? NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) { devices = json as? NSArray } else { devices = nil } completionHandler?(devices) }) task.resume() } static func switchOn(baseUrl: NSURL, device : Device, completionHandler: ((Bool) -> Void)?) -> Void { switchAction(baseUrl, device: device, action: true, completionHandler: completionHandler) } static func switchOff(baseUrl: NSURL, device : Device, completionHandler: ((Bool) -> Void)?) -> Void { switchAction(baseUrl, device: device, action: false, completionHandler: completionHandler) } private static func switchAction(baseUrl: NSURL, device: Device, action: Bool, completionHandler: ((Bool) -> Void)?) -> Void { let id = device.id let type = device.type var switchUrl : NSURL? var actionString : String if(action) { actionString = "on" } else { actionString = "off" } if type == "RGBStrip" { switchUrl = baseUrl.URLByAppendingPathComponent("/lights/\(actionString)/\(id)") } else if type == "RCSwitch" { switchUrl = baseUrl.URLByAppendingPathComponent("/switches/\(actionString)/\(id)") } if(switchUrl != nil) { let session = NSURLSession.sharedSession() let urlRequest = NSMutableURLRequest(URL: switchUrl!) urlRequest.HTTPMethod = "POST" let task = session.dataTaskWithRequest(urlRequest, completionHandler: {data, response, error -> Void in if error != nil && completionHandler != nil { completionHandler!(false) } else if(completionHandler != nil) { completionHandler!(true) } }) task.resume() } else { if(completionHandler != nil) { completionHandler!(false) } } } }
ec35b3589b5b2001592066eb4e21d25c
36.381579
130
0.570775
false
false
false
false
Neku/GEOSwift
refs/heads/master
GEOSwift/QuickLook.swift
mit
4
// // QuickLook.swift // // Created by Andrea Cremaschi on 21/05/15. // Copyright (c) 2015 andreacremaschi. All rights reserved. // import Foundation import MapKit protocol GEOSwiftQuickLook { func drawInSnapshot(snapshot: MKMapSnapshot, mapRect: MKMapRect) } extension Geometry : GEOSwiftQuickLook { func drawInSnapshot(snapshot: MKMapSnapshot, mapRect: MKMapRect) { // This is a workaround for a Swift bug (IMO): // drawInSnapshot is not called if implemenented as an override function in GeometryCollection subclass // var image = snapshot.image // let finalImageRect = CGRectMake(0, 0, image.size.width, image.size.height) // UIGraphicsBeginImageContextWithOptions(image.size, true, image.scale); // image.drawAtPoint(CGPointMake(0, 0)) if let geometryCollection = self as? GeometryCollection { for geometry in geometryCollection.geometries { geometry.drawInSnapshot(snapshot, mapRect: mapRect) } } else if let geometryCollection = self as? MultiPoint { for geometry in geometryCollection.geometries { geometry.drawInSnapshot(snapshot, mapRect: mapRect) } } else if let geometryCollection = self as? MultiLineString { for geometry in geometryCollection.geometries { geometry.drawInSnapshot(snapshot, mapRect: mapRect) } } else if let geometryCollection = self as? MultiPolygon { for geometry in geometryCollection.geometries { geometry.drawInSnapshot(snapshot, mapRect: mapRect) } } } } public extension Geometry { public func debugQuickLookObject() -> AnyObject? { let region: MKCoordinateRegion if let point = self as? Waypoint { let center = CLLocationCoordinate2DMake(point.coordinate.y, point.coordinate.x) let span = MKCoordinateSpanMake(0.1, 0.1) region = MKCoordinateRegionMake(center,span) } else { if let envelope = self.envelope() as? Polygon { let centroid = envelope.centroid() let center = CLLocationCoordinate2DMake(centroid.coordinate.y, centroid.coordinate.x) let exteriorRing = envelope.exteriorRing let upperLeft = exteriorRing.points[2] let lowerRight = exteriorRing.points[0] let span = MKCoordinateSpanMake(upperLeft.y - lowerRight.y, upperLeft.x - lowerRight.x) region = MKCoordinateRegionMake(center, span) } else { return nil } } var mapView = MKMapView() mapView.mapType = .Standard mapView.frame = CGRectMake(0, 0, 400, 400) mapView.region = region var options = MKMapSnapshotOptions.new() options.region = mapView.region options.scale = UIScreen.mainScreen().scale options.size = mapView.frame.size // take a snapshot of the map with MKMapSnapshot: // it is designed to work in background, so we have to block the main thread using a semaphore var mapViewImage: UIImage? let qualityOfServiceClass = QOS_CLASS_BACKGROUND let backgroundQueue = dispatch_get_global_queue(qualityOfServiceClass, 0) let snapshotter = MKMapSnapshotter(options: options) let semaphore = dispatch_semaphore_create(0); let mapRect = mapView.visibleMapRect let boundingBox = MKMapRect(region) snapshotter.startWithQueue(backgroundQueue, completionHandler: { (snapshot: MKMapSnapshot!, error: NSError!) -> Void in // let the single geometry draw itself on the map var image = snapshot.image let finalImageRect = CGRectMake(0, 0, image.size.width, image.size.height) UIGraphicsBeginImageContextWithOptions(image.size, true, image.scale); image.drawAtPoint(CGPointMake(0, 0)) let context = UIGraphicsGetCurrentContext() let scaleX = image.size.width / CGFloat(mapRect.size.width) let scaleY = image.size.height / CGFloat(mapRect.size.height) // CGContextTranslateCTM(context, (image.size.width - CGFloat(boundingBox.size.width) * scaleX) / 2, (image.size.height - CGFloat(boundingBox.size.height) * scaleY) / 2) CGContextScaleCTM(context, scaleX, scaleY) self.drawInSnapshot(snapshot, mapRect: mapRect) let finalImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() mapViewImage = finalImage dispatch_semaphore_signal(semaphore) }) let delayTime = dispatch_time(DISPATCH_TIME_NOW, Int64(3 * Double(NSEC_PER_SEC))) dispatch_semaphore_wait(semaphore, delayTime) // Sometimes this fails.. Fallback to WKT representation if let mapViewImage = mapViewImage { return mapViewImage } else { return self.WKT } } } private func MKMapRect(region: MKCoordinateRegion) ->MKMapRect { let a = MKMapPointForCoordinate(CLLocationCoordinate2DMake( region.center.latitude + region.span.latitudeDelta / 2, region.center.longitude - region.span.longitudeDelta / 2)); let b = MKMapPointForCoordinate(CLLocationCoordinate2DMake( region.center.latitude - region.span.latitudeDelta / 2, region.center.longitude + region.span.longitudeDelta / 2)); return MKMapRectMake(min(a.x,b.x), min(a.y,b.y), abs(a.x-b.x), abs(a.y-b.y)); } extension Waypoint : GEOSwiftQuickLook { override func drawInSnapshot(snapshot: MKMapSnapshot, mapRect: MKMapRect) { var image = snapshot.image let finalImageRect = CGRectMake(0, 0, image.size.width, image.size.height) let pin = MKPinAnnotationView(annotation: nil, reuseIdentifier: "") let pinImage = pin.image UIGraphicsBeginImageContextWithOptions(image.size, true, image.scale); image.drawAtPoint(CGPointMake(0, 0)) // draw center/home marker let coord = CLLocationCoordinate2DMake(self.coordinate.y, self.coordinate.x) var homePoint = snapshot.pointForCoordinate(coord) var rect = CGRectMake(0, 0, pinImage.size.width, pinImage.size.height) rect = CGRectOffset(rect, homePoint.x-rect.size.width/2.0, homePoint.y-rect.size.height) pinImage.drawInRect(rect) } } extension LineString : GEOSwiftQuickLook { override func drawInSnapshot(snapshot: MKMapSnapshot, mapRect: MKMapRect) { if let overlay = self.mapShape() as? MKOverlay { let zoomScale = snapshot.image.size.width / CGFloat(mapRect.size.width) var renderer = MKPolylineRenderer(overlay: overlay) renderer.lineWidth = 2 renderer.strokeColor = UIColor.blueColor().colorWithAlphaComponent(0.7) let context = UIGraphicsGetCurrentContext() CGContextSaveGState(context); // the renderer will draw the geometry at 0;0, so offset CoreGraphics by the right measure let upperCorner = renderer.mapPointForPoint(CGPointZero) CGContextTranslateCTM(context, CGFloat(upperCorner.x - mapRect.origin.x), CGFloat(upperCorner.y - mapRect.origin.y)); renderer.drawMapRect(mapRect, zoomScale: zoomScale, inContext: context) CGContextRestoreGState(context); } } } extension Polygon : GEOSwiftQuickLook { override func drawInSnapshot(snapshot: MKMapSnapshot, mapRect: MKMapRect) { if let overlay = self.mapShape() as? MKOverlay { let zoomScale = snapshot.image.size.width / CGFloat(mapRect.size.width) var polygonRenderer = MKPolygonRenderer(overlay: overlay) polygonRenderer.lineWidth = 2 polygonRenderer.strokeColor = UIColor.blueColor().colorWithAlphaComponent(0.7) polygonRenderer.fillColor = UIColor.cyanColor().colorWithAlphaComponent(0.2) let context = UIGraphicsGetCurrentContext() CGContextSaveGState(context); // the renderer will draw the geometry at 0;0, so offset CoreGraphics by the right measure let upperCorner = polygonRenderer.mapPointForPoint(CGPointZero) CGContextTranslateCTM(context, CGFloat(upperCorner.x - mapRect.origin.x), CGFloat(upperCorner.y - mapRect.origin.y)); polygonRenderer.drawMapRect(mapRect, zoomScale: zoomScale, inContext: context) CGContextRestoreGState(context); } } } //extension GeometryCollection : GEOSwiftQuickLook { // override func drawInSnapshot(snapshot: MKMapSnapshot) { // var image = snapshot.image // // let finalImageRect = CGRectMake(0, 0, image.size.width, image.size.height) // // UIGraphicsBeginImageContextWithOptions(image.size, true, image.scale); // // image.drawAtPoint(CGPointMake(0, 0)) // // // draw geometry collection // for geometry in geometries { // geometry.drawInSnapshot(snapshot) // } // } //}
e2c328843b28abb4808b289a12fafecb
42.827907
192
0.642645
false
false
false
false
ZZZZZZZP/DouYuZB
refs/heads/master
DYZB/DYZB/Classes/Main/View/ZPAnchorCell.swift
mit
1
// // ZPAnchorCell.swift // DYZB // // Created by 张鹏 on 16/10/10. // Copyright © 2016年 张鹏. All rights reserved. // import UIKit class ZPAnchorCell: UICollectionViewCell { // MARK: - 控件属性 @IBOutlet weak var iconImgV: UIImageView! @IBOutlet weak var onlineBtn: UIButton! @IBOutlet weak var nickNameL: UILabel! // MARK: - 模型属性 var anchor: ZPAnchorModel? { didSet{ // 验证是否有值 guard let anchor = anchor else {return} var onlineStr = "" if anchor.online >= 10000 { onlineStr = String(format: "%.1f万", arguments: [CGFloat(anchor.online) / 10000.0]) } else { onlineStr = "\(anchor.online)" } onlineBtn.setTitle(onlineStr, for: .normal) nickNameL.text = anchor.nickname let url = URL(string: anchor.vertical_src) iconImgV.kf.setImage(with: url) } } }
aa19ac77fa3c45e81c844fb76242a611
23.833333
98
0.509108
false
false
false
false
nodekit-io/nodekit-darwin
refs/heads/master
src/nodekit/NKScripting/util/NKArchive/NKAR_EndRecord.swift
apache-2.0
1
/* * nodekit.io * * Copyright (c) 2016 OffGrid Networks. All Rights Reserved. * Portions Copyright (c) 2013 GitHub, Inc. under MIT License * Portions Copyright (c) 2015 lazyapps. 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. */ struct NKAR_EndRecord { let numEntries: UInt16 let centralDirectoryOffset: UInt32 } extension NKAR_EndRecord { /* ZIP FILE FORMAT: CENTRAL DIRECTORY AT END OF THE FILE end of central dir signature 4 bytes (0x06054b50) number of this disk 2 bytes number of the disk with the start of the central directory 2 bytes total number of entries in the central directory on this disk 2 bytes total number of entries in the central directory 2 bytes size of the central directory 4 bytes offset of start of central directory with respect to the starting disk number 4 bytes .ZIP file comment length 2 bytes .ZIP file comment (variable size) */ static let signature: [UInt8] = [0x06, 0x05, 0x4b, 0x50] static func findEndRecordInBytes(bytes: UnsafePointer<UInt8>, length: Int) -> NKAR_EndRecord? { var reader = NKAR_BytesReader(bytes: bytes, index: length - 1 - signature.count) let maxTry = Int(UInt16.max) let minReadTo = max(length-maxTry, 0) let rng = 0..<4 let indexFound: Bool = { while reader.index > minReadTo { for i in rng { if reader.byteb() != self.signature[i] { break } if i == rng.endIndex.predecessor() { reader.skip(1); return true } } } return false }() if !indexFound { return nil } reader.skip(4) let numDisks = reader.le16() reader.skip(2) reader.skip(2) let numEntries = reader.le16() reader.skip(4) let centralDirectoryOffset = reader.le32() if numDisks > 1 { return nil } return NKAR_EndRecord(numEntries: numEntries, centralDirectoryOffset: centralDirectoryOffset) } }
519c5185ed07b048e674efe389efb453
28.571429
101
0.583362
false
false
false
false
barabashd/WeatherApp
refs/heads/master
WeatherApp/WeatherViewController+MKMapViewDelegate.swift
mit
1
// // WeatherViewController+MKMapViewDelegate.swift // WeatherApp // // Created by Dmytro Barabash on 2/16/18. // Copyright © 2018 Dmytro. All rights reserved. // import MapKit extension WeatherViewController: MKMapViewDelegate { func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer { if overlay is MKTileOverlay { return MKTileOverlayRenderer(overlay:overlay) } return MKTileOverlayRenderer() } func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? { if annotation is MKUserLocation { let pin = mapView.view(for: annotation) ?? MKAnnotationView(annotation: annotation, reuseIdentifier: nil) pin.canShowCallout = true pin.image = #imageLiteral(resourceName: "home") let point = MKPointAnnotation() let weather = WeatherGetter() let coord = locationManager.location!.coordinate let smallSquare = CGSize(width: 30, height: 30) let button = PlacemarkButton(frame: CGRect(origin: CGPoint.zero, size: smallSquare)) weather.getWeather(coord.latitude, lon: coord.longitude, completion: { finished in guard finished else { return } point.title = "\(weather.values.city), \(weather.values.country)" let temp = weather.values.temp! let subValue = temp - Constants.celsiusKelvinDifference point.subtitle = String(format: Strings.format, subValue) + Strings.Search.annotationTail pin.annotation = point DispatchQueue.main.async { button.setBackgroundImage(weather.curreentImage, for: UIControlState()) button.coordinates = coord button.addTarget(self, action: #selector(WeatherViewController.getDirections(button:)), for: .touchUpInside) pin.leftCalloutAccessoryView = button } }) return pin } else { let reuseId = Strings.Identifiers.pinId var pinView = mapView.dequeueReusableAnnotationView(withIdentifier: reuseId) if pinView == nil { pinView = MKAnnotationView(annotation: annotation, reuseIdentifier: reuseId) } pinView?.canShowCallout = true pinView?.image = #imageLiteral(resourceName: "thunder") let smallSquare = CGSize(width: 30, height: 30) let button = PlacemarkButton(frame: CGRect(origin: CGPoint.zero, size: smallSquare)) let weather = WeatherGetter() weather.getWeather(annotation.coordinate.latitude, lon: annotation.coordinate.longitude, completion: { finished in guard finished else { return } DispatchQueue.main.async { button.setBackgroundImage(weather.curreentImage, for: UIControlState()) button.coordinates = annotation.coordinate button.addTarget(self, action: #selector(WeatherViewController.getDirections(button:)), for: .touchUpInside) pinView?.leftCalloutAccessoryView = button } }) return pinView } } }
7576359ffde19955a3783d733d5e5ff7
39.131868
128
0.564348
false
false
false
false
Johnykutty/JSONModeller
refs/heads/master
JSONModeller/View/SaveAccessoryView.swift
mit
1
// // SaveAccessoryView.swift // JSONModeller // // Created by Johnykutty on 28/05/15. // Copyright (c) 2015 Johnykutty.All rights reserved. // import Cocoa class SaveAccessoryView : NSView { fileprivate var useCoreDataButton: NSButton fileprivate var rootClassNameField: NSTextField fileprivate var classPrefixField: NSTextField fileprivate var languageSelector: NSPopUpButton override init(frame frameRect: NSRect) { var y: CGFloat = 0.0 let labelX: CGFloat = 0.0 let fieldX: CGFloat = 117.0 self.useCoreDataButton = NSButton(frame: NSMakeRect(fieldX, y, 350.0, 22.0)) self.useCoreDataButton.setButtonType(.switch) self.useCoreDataButton.bezelStyle = .smallSquare self.useCoreDataButton.title = "Use core data - (currently unavailable)" self.useCoreDataButton.isEnabled = false y += 30.0 self.languageSelector = NSPopUpButton(frame: NSMakeRect(fieldX, y, 150, 25)) self.languageSelector.addItems(withTitles: ["Objective C", "Swift"]) y += 5.0 let languageLabel = NSTextField(frame: NSMakeRect(labelX, y, 115, 17)) languageLabel.stringValue = "Language :" languageLabel.isBezeled = false languageLabel.drawsBackground = false languageLabel.isEditable = false languageLabel.isSelectable = false languageLabel.alignment = .right y += 30.0 self.classPrefixField = NSTextField(frame: NSMakeRect(fieldX, y, 150, 21)) (self.classPrefixField.cell as! NSTextFieldCell).placeholderString = "CP" (self.classPrefixField.cell as! NSTextFieldCell).stringValue = "" y += 3.0 let classPrefixLabel = NSTextField(frame: NSMakeRect(labelX, y, 115, 17)) classPrefixLabel.stringValue = "Class Prefix :" classPrefixLabel.isBezeled = false classPrefixLabel.drawsBackground = false classPrefixLabel.isEditable = false classPrefixLabel.isSelectable = false classPrefixLabel.alignment = .right y += 30.0 self.rootClassNameField = NSTextField(frame: NSMakeRect(fieldX, y, 150, 21)) (self.rootClassNameField.cell as! NSTextFieldCell).placeholderString = "RootClass" (self.rootClassNameField.cell as! NSTextFieldCell).stringValue = "" y += 3.0 let rootClassLabel = NSTextField(frame: NSMakeRect(labelX, y, 115, 17)) rootClassLabel.stringValue = "Root Class Name :" rootClassLabel.isBezeled = false rootClassLabel.drawsBackground = false rootClassLabel.isEditable = false rootClassLabel.isSelectable = false rootClassLabel.alignment = .right super.init(frame: frameRect) self.useCoreDataButton.target = self self.addSubview(self.useCoreDataButton) self.addSubview(self.languageSelector) self.addSubview(languageLabel) self.addSubview(self.classPrefixField) self.addSubview(classPrefixLabel) self.addSubview(self.rootClassNameField) self.addSubview(rootClassLabel) } func rootClassName() -> String { return (self.rootClassNameField.stringValue.characters.count == 0) ? "RootClass" : self.rootClassNameField.stringValue } func clasPrefix() -> String { return self.classPrefixField.stringValue } func language() -> Languagetype { return Languagetype(rawValue: languageSelector.indexOfSelectedItem)! } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func draw(_ dirtyRect: NSRect) { super.draw(dirtyRect) // Drawing code here. } }
c4c777372045b92e4c41733cf3433f9b
34.324074
126
0.656881
false
false
false
false
algolia/algoliasearch-client-swift
refs/heads/master
Sources/AlgoliaSearchClient/Models/Internal/HTTP/HTTPError.swift
mit
1
// // HTTPError.swift // // // Created by Vladislav Fitc on 02/03/2020. // import Foundation #if canImport(FoundationNetworking) import FoundationNetworking #endif public struct HTTPError: Error, CustomStringConvertible { public let statusCode: HTTPStatusСode public let message: ErrorMessage? public init?(response: HTTPURLResponse?, data: Data?) { guard let response = response, !response.statusCode.belongs(to: .success) else { return nil } let message = data.flatMap { try? JSONDecoder().decode(ErrorMessage.self, from: $0) } self.init(statusCode: response.statusCode, message: message) } public init(statusCode: HTTPStatusСode, message: ErrorMessage?) { self.statusCode = statusCode self.message = message } public var description: String { return "Status code: \(statusCode) Message: \(message.flatMap { $0.description } ?? "No message")" } } public struct ErrorMessage: Codable, CustomStringConvertible { enum CodingKeys: String, CodingKey { case description = "message" } public let description: String }
f95401204a5e5b92efb4bd5f8823423c
22.673913
102
0.714417
false
false
false
false
vmachiel/swift
refs/heads/main
LearningSwift.playground/Pages/Functions and Closures.xcplaygroundpage/Contents.swift
mit
1
// Functions are declared with func and you state the parameters and types and the // return type func greet(person: String, day: String) -> String { return "Hello \(person), today is \(day)" } greet(person: "Bob", day: "Wednesday") // You can use custom parameter tags, so you can use a different parameter name inside // the function, and a different tag when you call the function for clarity. // (2nd parameter) // You can also add a _ before the parameter definition if you want to be able to // omit it when you call the function. THIS IS ALL FOR CLARITY! (1st parameter) // Also, default values work similar to python (3rd parameter) // Example: 'person' can be omitted, and day is used inside the function and is labelled // 'on' when calling the function. shouting has a default of false func greet(_ person: String, on day: String, shouting: Bool = false) -> String { var message = "Hi \(person) today is \(day)" if shouting { message = message.uppercased() } return message } greet("Henk", on:"Wednesday") // easy to read later! : no person label, on instea of day, // and shouting can be omitted because of the default // Return multiple values using a tuple. They can be adressed with both name and index // Also assign the return value(s) to a variable func calculateStatistics(scores: [Int]) -> (min: Int, max: Int, sum: Int) { // initial values, made with array values var min = scores[0] var max = scores[0] var sum = 0 for score in scores { if score > max { max = score } else if score < min { min = score } sum += score } return (min, max, sum) } let statistics = calculateStatistics(scores: [4, 130, 34, 9, 11, 94]) statistics.sum // access by name! statistics.2 // access by index! // Optional variant: exit early and return nil if array is empty: func minMax(array: [Int]) -> (min: Int, max: Int)? { if array.isEmpty { return nil } var currentMin = array[0] var currentMax = array[0] for value in array[1..<array.count] { if value < currentMin { currentMin = value } else if value > currentMax { currentMax = value } } return (currentMin, currentMax) } // Variable number of arguments (*args) which are use as an array in the func func sumOf(numbers: Int...) -> Int { var sum = 0 for num in numbers { sum += num } return sum } sumOf() // called with 0 argumens sumOf(numbers: 4, 6, 123, 23) // called with 4 arguments // In Out parameters are NOT constant (all others are). They are fed to a function, // that changes them and their changes persist after the call. Function does not return // anything in this case. Basically, the nonlocal or global keyword in python. var a = 4 var b = 9 func swapInts(_ a: inout Int, _ b: inout Int) { let tempA = a a = b b = tempA } // You pass a "pointer" to the function when calling it, using &: swap(&a, &b) print(a) print(b) // Function types: specify a function as a type for a variable: func addTwoNumbers(a: Int, b:Int) -> Int { return a + b } let mathFunction: (Int, Int) -> Int mathFunction = addTwoNumbers // This variable can now be used like this: print("The result of adding 2 and 3 is: \(mathFunction(2, 3))") // !!! NOTICE !!! you don't call it using external parameter. // because mathFunction is technically any constant that takes two int and returns one // Functions as parameter types func addTwoInts(_ a: Int, _ b: Int) -> Int { return a + b } func printMathResult(_ mathFunction: (Int, Int) -> Int, _ a: Int, _ b: Int) { print("Result: \(mathFunction(a, b))") } printMathResult(addTwoInts, 3, 5) // Prints "Result: 8 // Nested functions: inner functions have access to variables of the outer. func returnFifteen() -> Int { var y = 10 func add() { y += 5 } add() return y } returnFifteen() // And just like python, they are first class citizens, so they can be a return func and // be a closure. func makeIncrementer() -> ((Int) -> Int) { func addOne(number: Int) -> Int { return 1 + number } return addOne } var incrementer = makeIncrementer() incrementer(8) // or a version where you set the ammount to be added: func incrementBy(adder: Int) -> ((Int) -> Int) { func addAdder(number: Int) -> Int { return adder + number } return addAdder } var incrementer2 = incrementBy(adder: 4) incrementer2(5) // Functions can take functions as one of their arguments, like the condition argument. // You don't include () when passing a function: you're not executed it, just passing it // to the main function so it can use and execute it. // So for each item in the list, pas it to condition. If one of them returns true, // return true // The lessThanTen function is passed, so each number in the list gets checked, if one // is smaller than 10, the whole thing returns true func hasAnyMatches(list: [Int], condition: (Int) -> Bool) -> Bool { for item in list { if condition(item) { return true } } return false } func lessThanTen(number: Int) -> Bool { return number < 10 } var numbers = [44, 66, 23, 1, 69, 349] hasAnyMatches(list: numbers, condition: lessThanTen) // Another example here is a function that checks if a number is divisible by two: func divisibleByTwo(_ number: Int) -> Bool { return number % 2 == 0 } // And this function takes a list of numbers and a criteria, and any number that meets // the criteria gets added to a list that gets returned. func filterInts(_ numbers: [Int], _ includeNumber: (Int) -> Bool) -> [Int] { var result: [Int] = [] for number in numbers { if includeNumber(number) { result.append(number) } } return result } let evenNumbers = filterInts(numbers, divisibleByTwo) // Closure 1: closure expressions 1 // Function are special closures. Closures have access to variables and function in // the scope they were created in, as well as their own, even if they are in // a different scope when executed!! // You can write one (a closure that is) withouth a name by surrounding it with ({}). // seperate the arg/return type from the body with 'in' numbers.map({ (number: Int) -> Int in let result = 3 * number return result }) // so for each element in numbers map the following function: take the humber, // multiply *3 and return it. Here is one that returns false if the number is odd // and true if even numbers.map({ (number:Int) -> Bool in return number % 2 == 0 }) // And a more consice way if the argument type or return type is already known. // Also, it's only 1 return statement so return can be omitted. numbers = [4, 99, 23, 22, 0, 64] let mappedNumbers = numbers.map({ number in 3 * number }) print(mappedNumbers) // And even shorter if the closure is the only function argument: no parans let mappedNumbers2 = numbers.map { number in 3 * number } // Or resplace the arguments with $0, $1 etc let sortedNumbers = numbers.sorted { $0 > $1 } print(sortedNumbers) // Here is the filterInts function from before, but with the the divisibleByTwo function // as a closure expression. You don't need that as a function a lot: let numbers2 = [44, 32, 11, 49491, 0, 94] var evenNumbers2 = filterInts(numbers2, {(number: Int) -> Bool in return number % 2 == 0}) evenNumbers2 // you can again! write it more conceice (however you spell that) evenNumbers2 = filterInts(numbers2, {(number) in return number % 2 == 0}) // and shorter again, if it's only one return statement: evenNumbers2 = filterInts(numbers2, {(number) in number % 2 == 0}) // and shorter again by using $0 for the first argument $1 for the second etc: evenNumbers2 = filterInts(numbers2, {$0 % 2 == 0}) // or write it outside the parenthasis when it's the last argument: trailer closure: evenNumbers2 = filterInts(numbers2) {$0 % 2 == 0} // CLOSURE 2 // A closure is basically a portable function. For example, the following function // that adds 2 numbers. func add(num: Int, num2: Int) -> Int { return num + num2 } // If you were to declare a closure like above, it would be like this. // Notice the type of the closure. It accepts 2 integers that return an integer. let someClosure: (Int, Int) -> Int = { (num, num2) in return num + num2 } // You can also pass closures to functions. Here's the function declaration // that accepts a parameter closure that accepts 2 integers and returns an integer: // it also takes one more interger and finally returns a string. func usingClosures(closure: (Int, Int) -> Int, devider: Int) -> String { //other stff let sum = closure(16, 5) //the closure is executed here let final = sum / devider return "The final product is \(final)" } usingClosures(closure: someClosure, devider: 3) // When you call the function, you can basically write the closure inside the parameter. // Closures must be inside curly braces, unless it's a trailing closure. //something({ num1, num2 in //return num1 + num2 //}) // Trailing closure works if the closure is the last or only parameter //something2() { num1, num2 in // return num1 + num2 //} // These are dumb examples, but a good use of a closure is when you're making an // API call and want part of code to execute ONLY if the data call works. For example: // func makeAPICall(using: String, completion: () -> Void) { //Run some call asynchronously using NSURLSession //Reach this point if it worked // completion // } // And when you call the function, you can use a trailing closure to tell it what to do. // makeAPICall(linkString) { in //code in here will run only if the api call succeeds //Like updating the view // } // Example of the filter method: generic method that can be called on the arrays // of standard lib types. It takes a closure as an argument let names = ["snor", "barry", "Machiel", "kaljdflkasdjf", "kees"] let shortNames = names.filter{$0.count < 5} shortNames // Example of the map method: it maps a given closure to each element of the array: let upperCaseNames = names.map {name in name.uppercased()} upperCaseNames // Or do them both, with . syntax let bothFilters = names.filter {$0.count < 5}.map {name in name.uppercased()} bothFilters // Capturing values terminology: Closure can "capture" values like parameters passed // to a outer function, or variables set within that function. This function creates // another function. The creator gets an argument passed, and set its own variable. Those // are captured by the returned closure and used when you call it later. // NOTE This returns a function that returns an Int func makeIncrementer3(forIncrement ammount: Int) -> () -> Int { var runningTotal = 0 func incrementer3() -> Int { runningTotal += ammount return runningTotal } return incrementer3 } // So runningtotal (var) and ammount (parameter) are captured and used when called: let incrementByTen = makeIncrementer3(forIncrement: 10) // and whenever called, it holds it's runningtotal and increment value: incrementByTen() incrementByTen() incrementByTen() // You can make a new one, and the old ones hold their captured values let incrementBySeven = makeIncrementer3(forIncrement: 7) incrementBySeven() incrementByTen() // And they are !!!!reference types!!!! let alsoIncrementByTen = incrementByTen alsoIncrementByTen() // 50
fc2e2510ed393af7a476817dbc1f0be8
32.225434
90
0.686674
false
false
false
false
getsocial-im/getsocial-ios-sdk
refs/heads/master
example/GetSocialDemo/Views/Communities/Polls/VotesList/VoteView.swift
apache-2.0
1
// // VoteView.swift // GetSocialDemo // // Created by Gábor Vass on 07/05/2021. // Copyright © 2021 GrambleWorld. All rights reserved. // import Foundation import UIKit import GetSocialSDK class VoteView: UIView { let userName = UILabel() let votes = UILabel() required override init(frame: CGRect) { super.init(frame: frame) layout() } required init?(coder: NSCoder) { super.init(coder: coder) layout() } func update(_ vote: UserVotes) { self.userName.text = "User: \(vote.user.displayName)" self.votes.text = "Votes: \(vote.votes)" } func layout() { self.translatesAutoresizingMaskIntoConstraints = false let stack = UIStackView() stack.translatesAutoresizingMaskIntoConstraints = false stack.axis = .vertical stack.spacing = 4 stack.addArrangedSubview(userName) stack.addArrangedSubview(votes) self.addSubview(stack) NSLayoutConstraint.activate([ stack.leadingAnchor.constraint(equalTo: self.leadingAnchor), stack.trailingAnchor.constraint(equalTo: self.trailingAnchor), stack.topAnchor.constraint(equalTo: self.topAnchor), stack.bottomAnchor.constraint(equalTo: self.bottomAnchor), ]) } }
332e9687359f9b4121642cde70509578
21.384615
65
0.7311
false
false
false
false
B-Lach/PocketCastsKit
refs/heads/develop
SharedTests/Model/PCKNetworkTests.swift
mit
1
// // PCKNetworkTests.swift // PocketCastsKitTests // // Created by Benny Lach on 21.08.17. // Copyright © 2017 Benny Lach. All rights reserved. // import XCTest @testable import PocketCastsKit class PCKNetworkTests: XCTestCase { let id = 12 let title = "CNET" let networkDescription = "Reviews & first looks" let imgURL = URL(string: "http://static.pocketcasts.com/discover/images/networks/thumbnails/12/original/cnet.png")! let color = "#222224" func testInitFromValues() { let network = PCKNetwork(id: id, title: title, description: networkDescription, imgURL: imgURL, color: color) XCTAssertEqual(network.id, id) XCTAssertEqual(network.title, title) XCTAssertEqual(network.description, networkDescription) XCTAssertEqual(network.imgURL, imgURL) XCTAssertEqual(network.color, color) } func testInitFromDecoder() throws { let decoder = TestHelper.Decoding.jsonDecoder let net = try decoder.decode(PCKNetwork.self, from: TestHelper.TestData.networkData) XCTAssertEqual(net.id, id) XCTAssertEqual(net.title, title) XCTAssertEqual(net.description, networkDescription) XCTAssertEqual(net.imgURL, imgURL) XCTAssertEqual(net.color, color) } }
02160ca29be878c03f321ef631d91edf
31.395349
119
0.646088
false
true
false
false
devxoul/Drrrible
refs/heads/master
Drrrible/Sources/ViewControllers/VersionViewController.swift
mit
1
// // VersionViewController.swift // Drrrible // // Created by Suyeol Jeon on 19/04/2017. // Copyright © 2017 Suyeol Jeon. All rights reserved. // import UIKit import ReactorKit import ReusableKit final class VersionViewController: BaseViewController, View { // MARK: Constants fileprivate struct Reusable { static let cell = ReusableCell<VersionCell>() } fileprivate struct Metric { static let iconViewTop = 35.f static let iconViewSize = 100.f static let iconViewBottom = 0.f } // MARK: UI fileprivate let iconView = UIImageView(image: #imageLiteral(resourceName: "Icon512")).then { $0.layer.borderColor = UIColor.db_border.cgColor $0.layer.borderWidth = 1 $0.layer.cornerRadius = Metric.iconViewSize * 13.5 / 60 $0.layer.minificationFilter = CALayerContentsFilter.trilinear $0.clipsToBounds = true } fileprivate let tableView = UITableView(frame: .zero, style: .grouped).then { $0.register(Reusable.cell) } // MARK: Initializing init(reactor: VersionViewReactor) { defer { self.reactor = reactor } super.init() self.title = "version".localized } required convenience init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: View Life Cycle override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = .db_background self.tableView.dataSource = self self.tableView.contentInset.top = Metric.iconViewTop + Metric.iconViewSize + Metric.iconViewBottom self.tableView.addSubview(self.iconView) self.view.addSubview(self.tableView) } override func setupConstraints() { self.tableView.snp.makeConstraints { make in make.edges.equalToSuperview() } self.iconView.snp.makeConstraints { make in make.top.equalTo(Metric.iconViewTop - self.tableView.contentInset.top) make.centerX.equalToSuperview() make.size.equalTo(Metric.iconViewSize) } } // MARK: Binding func bind(reactor: VersionViewReactor) { // Action self.rx.viewWillAppear .map { _ in Reactor.Action.checkForUpdates } .bind(to: reactor.action) .disposed(by: self.disposeBag) // State reactor.state .subscribe(onNext: { [weak self] _ in self?.tableView.reloadData() }) .disposed(by: self.disposeBag) } } extension VersionViewController: UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 2 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeue(Reusable.cell, for: indexPath) if indexPath.row == 0 { cell.textLabel?.text = "current_version".localized cell.detailTextLabel?.text = self.reactor?.currentState.currentVersion cell.isLoading = false } else { cell.textLabel?.text = "latest_version".localized cell.detailTextLabel?.text = self.reactor?.currentState.latestVersion cell.isLoading = self.reactor?.currentState.isLoading ?? false } return cell } } private final class VersionCell: UITableViewCell { fileprivate let activityIndicatorView = UIActivityIndicatorView(style: .gray) override var accessoryView: UIView? { didSet { if self.accessoryView === self.activityIndicatorView { self.activityIndicatorView.startAnimating() } else { self.activityIndicatorView.stopAnimating() } } } var isLoading: Bool { get { return self.activityIndicatorView.isAnimating } set { self.accessoryView = newValue ? self.activityIndicatorView : nil } } override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: .value1, reuseIdentifier: reuseIdentifier) self.selectionStyle = .none } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
bf8a4dcc2665ee9345b98868c035da1c
25.959184
102
0.698965
false
false
false
false
linbin00303/Dotadog
refs/heads/master
DotaDog/DotaDog/Classes/Home/Controller/DDogHomeController.swift
mit
1
// // DDogHomeController.swift // DotaDog // // Created by 林彬 on 16/5/9. // Copyright © 2016年 linbin. All rights reserved. // import UIKit protocol homeDelegate : NSObjectProtocol { func getMainSCVEnabled(isEnable : Bool) } class DDogHomeController: UIViewController { var delegate : homeDelegate? var tranP : CGPoint? var titleSCV = UIScrollView() var mainSCV = UIScrollView() var isInital : Bool = false var buttonArr = [UIButton]() var preButton = UIButton() var underLineView = UIView() override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = randomColor // 取消系统自动为导航控制器预留的64高度,避免错位 automaticallyAdjustsScrollViewInsets = false navigationItem.title = "首页" // 加载主页面 setUpChildVC() // 添加标题栏 setUpTitleScrollView() // 添加内容滚动条 setUpMainScrollView() } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) if self.isInital == false { addTitleButtons() addTitleUnderLine() self.isInital = true } } } extension DDogHomeController { // MARK:- 添加子控制器 private func setUpChildVC() { let newTVC = DDogNewViewController() newTVC.title = "新闻资讯" self.addChildViewController(newTVC) let matchInfoTVC = DDogMatchInfoViewController() matchInfoTVC.title = "赛事新闻" self.addChildViewController(matchInfoTVC) let officialTVC = DDogOfficialViewController() officialTVC.title = "热点新闻" self.addChildViewController(officialTVC) let renovateTVC = DDogRenovateViewController() renovateTVC.title = "更新公告" self.addChildViewController(renovateTVC) } // MARK:- 添加标题滚动视图 private func setUpTitleScrollView() { let titleSCV = UIScrollView() let y : CGFloat = self.navigationController!.navigationBarHidden ? 20.0 : 64.0 titleSCV.frame = CGRectMake(0, y, ScreenW, 45) titleSCV.backgroundColor = UIColor.whiteColor() self.titleSCV = titleSCV self.view .addSubview(titleSCV) } // MARK:- 添加内容滚动视图 private func setUpMainScrollView() { let count = self.childViewControllers.count let mainSCV = UIScrollView() let y = CGRectGetMaxY(self.titleSCV.frame) mainSCV.frame = CGRectMake(0, y, ScreenW, ScreenH - y - 49) mainSCV.showsHorizontalScrollIndicator = false mainSCV.showsVerticalScrollIndicator = false // 其他设置 mainSCV.contentSize = CGSizeMake(CGFloat(count) * mainSCV.width, 0) mainSCV.pagingEnabled = true mainSCV.bounces = false mainSCV.delegate = self // mainSCV.scrollEnabled = false self.view.addSubview(mainSCV) self.mainSCV = mainSCV } // MARK:- 添加标题滚动视图中的按钮 private func addTitleButtons() { let count = self.childViewControllers.count let btnW = ScreenW / CGFloat(count) let btnH : CGFloat = 45 let btnY : CGFloat = 0 var btnX : CGFloat = 0 for i in 0 ..< count { let button = UIButton(type: .Custom) button.tag = i btnX = CGFloat(i) * btnW button.frame = CGRectMake(btnX, btnY, btnW, btnH) button.setTitleColor(garyColor, forState: .Normal) button.titleLabel?.font = UIFont.systemFontOfSize(14) button.setTitle(self.childViewControllers[i].title, forState: .Normal) button.addTarget(self, action: #selector(DDogHomeController.buttonClick(_:)), forControlEvents: .TouchUpInside) self.titleSCV.addSubview(button) self.buttonArr.append(button) // 默认点中"新闻资讯" if i == 0 { buttonClick(button) } } self.titleSCV.contentSize = CGSizeMake(CGFloat(count) * btnW, 0) self.titleSCV.showsHorizontalScrollIndicator = false } // MARK:- 添加标题滚动视图中的下划线 private func addTitleUnderLine() { // 获取第一个按钮.因为一开始就是选中的第一个按钮.要的是这个按钮的颜色,文字宽度 let firstButton = self.buttonArr.first let underLineView = UIView() let underLineH : CGFloat = 2 let underLineY : CGFloat = self.titleSCV.height - underLineH underLineView.frame = CGRectMake(0, underLineY, 0, underLineH) underLineView.backgroundColor = firstButton?.titleColorForState(.Normal) self.titleSCV.addSubview(underLineView) self.underLineView = underLineView firstButton?.titleLabel?.sizeToFit() self.underLineView.width = (firstButton?.titleLabel?.width)! + 10 self.underLineView.centerX = (firstButton?.centerX)! } } extension DDogHomeController { // MARK:- 按钮点击事件 @objc func buttonClick(curButton : UIButton) { // 恢复上一个按钮选中标题的颜色 self.preButton.setTitleColor(garyColor, forState: .Normal) self.preButton.transform = CGAffineTransformIdentity curButton.setTitleColor(mainColor, forState: .Normal) self.preButton = curButton // 点击的时候,对文字也进行缩放 // 标题缩放 curButton.transform = CGAffineTransformMakeScale(1.2, 1.2) // 获取点击按钮的角标 let index = curButton.tag // 添加动画 UIView.animateWithDuration(0.25, animations: { [weak self]() -> Void in // 按钮点击的时候,下划线位移 // 做下划线的滑动动画 self?.underLineView.width = curButton.titleLabel!.width + 10 // self.underLineView.centerX = currentButton.centerX; // 点击按钮,切换对应角标的子控制器的view self?.changeChildVCInMainSCV(index) // 让内容滚动条滚动对应位置,就是"直播"出现在第一个位置 let x = CGFloat(index) * ScreenW; // 获得偏移量 self?.mainSCV.contentOffset = CGPointMake(x, 0); }) { [weak self](finished : Bool) -> Void in // 动画结束的时候,加载控制器(方便实现懒加载) self?.addCurrentChildView(index) } } // MARK:- 切换子界面 private func changeChildVCInMainSCV(index : NSInteger) { let x : CGFloat = CGFloat(index) * ScreenW self.mainSCV.contentOffset = CGPointMake(x, 0) } // MARK:- 添加子界面 private func addCurrentChildView(index : NSInteger) { let vc = self.childViewControllers[index] if vc.view.superview != nil { return } let x :CGFloat = CGFloat(index) * ScreenW vc.view.frame = CGRectMake(x, 0, ScreenW, self.mainSCV.height) self.mainSCV.addSubview(vc.view) } } extension DDogHomeController : UIScrollViewDelegate { func scrollViewDidEndDecelerating(scrollView: UIScrollView) { // 获取当前偏移量和屏幕宽度的商,就是角标 let i = Int(scrollView.contentOffset.x / ScreenW) // 根据对应的角标,获得对应的按钮 let button = self.buttonArr[i] // 调用按钮选中方法. // 就相当于滚动完毕后,调用了标题的按钮点击事件. self.buttonClick(button) } func scrollViewWillBeginDragging(scrollView: UIScrollView) { if scrollView.contentOffset.x > 0 { // print("111") // scrollView.scrollEnabled = true }else { // print("222") // scrollView.scrollEnabled = false } } func scrollViewWillBeginDecelerating(scrollView: UIScrollView) { // print("333") } func scrollViewDidEndDragging(scrollView: UIScrollView, willDecelerate decelerate: Bool) { // print("444") // print(decelerate) } func scrollViewDidScroll(scrollView: UIScrollView) { // // 解决手势冲突 // if scrollView.contentOffset.x > 0 { // scrollView.scrollEnabled = true //// delegate?.getMainSCVEnabled(true) // }else if scrollView.contentOffset.x == 0{ // /* // // 新思路:在==0的时候,scrollEnabled = false,添加轻扫手势.左扫点击第二个标题按钮 // 可尝试 // // */ // scrollView.scrollEnabled = false // if tranP?.x > 0 { // scrollView.scrollEnabled = false // delegate?.getMainSCVEnabled(false) // }else { // scrollView.scrollEnabled = true // delegate?.getMainSCVEnabled(true) // } // }else { // scrollView.scrollEnabled = false // delegate?.getMainSCVEnabled(false) // } changeColor(scrollView) changeText(scrollView) // 下划线随内容scrollView的滚动而滚动,发生位移 // CGAffineTransformMakeTranslation 方法 // 左滑: 0到1; // 右滑: 0到-1; let offset = scrollView.contentOffset.x / ScreenW; let btn = self.buttonArr.first; self.underLineView.transform = CGAffineTransformMakeTranslation(offset * btn!.width, 0); } } // MARK:- 颜色和字体的渐变 extension DDogHomeController { private func changeColor(scrollView : UIScrollView) { let leftI = Int(scrollView.contentOffset.x / ScreenW) // 获取左边按钮 let leftButton = self.buttonArr[leftI] // 获取右边按钮 6 let rightI = leftI + 1 var rightButton = UIButton() if rightI < buttonArr.count { rightButton = buttonArr[rightI] } // 获取缩放比例 // 0 ~ 1 => 1 ~ 1.2 let rightScale : CGFloat = scrollView.contentOffset.x / ScreenW - CGFloat(leftI) let leftScale = 1 - rightScale // 左滑,leftScale是 从 1 到 0,再变回1 ;rightScale 是从 0 到 1,再变回0 // 右滑,leftScale是 从 0 到 1, ;rightScale 是从 1 到 0 /* 左滑的时候,leftButton 是从 红到灰 ,rightButton是从灰到红. 右滑的时候,leftButton 是从 灰到红 ,rightButton是从红到灰. 255 107 0 */ let redR = (213 + 32 * (1 - leftScale)) / 255.0 let greenR = (213 - 108 * (1 - leftScale)) / 255.0 let blueR = (213 - 213 * (1 - leftScale)) / 255.0 let rightColor = UIColor(red: redR, green: greenR, blue: blueR, alpha: 1) rightButton.setTitleColor(rightColor, forState: .Normal) let redL = (255 - 32 * (rightScale)) / 255.0 let greenL = (107 + 108 * (rightScale)) / 255.0 let blueL = (0 + 213 * (rightScale)) / 255.0 let leftColor = UIColor(red: redL, green: greenL, blue: blueL, alpha: 1) leftButton.setTitleColor(leftColor, forState: .Normal) } private func changeText(scrollView : UIScrollView) { let leftI = Int(scrollView.contentOffset.x / ScreenW) // 获取左边按钮 let leftButton = self.buttonArr[leftI] // 获取右边按钮 6 let rightI = leftI + 1 var rightButton = UIButton() if rightI < buttonArr.count { rightButton = buttonArr[rightI]; } // 获取缩放比例 // 0 ~ 1 => 1 ~ 1.3 let rightScale = scrollView.contentOffset.x / ScreenW - CGFloat(leftI); let leftScale = 1 - rightScale; // 对标题按钮进行缩放 1 ~ 1.3 leftButton.transform = CGAffineTransformMakeScale(leftScale * 0.2 + 1, leftScale * 0.2 + 1); rightButton.transform = CGAffineTransformMakeScale(rightScale * 0.2 + 1, rightScale * 0.2 + 1); } } extension DDogHomeController{ override func shouldAutorotate() -> Bool { return false } override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask { return UIInterfaceOrientationMask.Portrait } } extension DDogHomeController { }
17cb46726904e4b9eb407affb8fa2bfd
29.601036
123
0.579798
false
false
false
false
googlemaps/codelab-maps-platform-101-swift
refs/heads/main
solution/SolutionApp/ViewController.swift
apache-2.0
1
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import UIKit import GoogleMaps import GoogleMapsUtils class ViewController: UIViewController, GMSMapViewDelegate { private var mapView: GMSMapView! private var clusterManager: GMUClusterManager! private var circle: GMSCircle? = nil override func loadView() { // Load the map at set latitude/longitude and zoom level let camera = GMSCameraPosition.camera(withLatitude: -33.86, longitude: 151.20, zoom: 11) let mapID = GMSMapID(identifier: "YOUR_MAP_ID") mapView = GMSMapView(frame: .zero, mapID: mapID, camera: camera) self.view = mapView mapView.delegate = self } override func viewDidLoad() { super.viewDidLoad() // Add a single marker with a custom icon let mapCenter = CLLocationCoordinate2DMake(mapView.camera.target.latitude, mapView.camera.target.longitude) let marker = GMSMarker(position: mapCenter) marker.icon = UIImage(named: "custom_pin.png") marker.map = mapView // Generate many markers let markerArray = MarkerGenerator(near: mapCenter, count: 100).markerArray // Comment the following code out if using the marker clusterer // to manage markers instead. // for marker in markerArray { // marker.map = mapView // } // Set up the cluster manager with a supplied icon generator and renderer. let algorithm = GMUNonHierarchicalDistanceBasedAlgorithm() let iconGenerator = GMUDefaultClusterIconGenerator() let renderer = GMUDefaultClusterRenderer(mapView: mapView, clusterIconGenerator: iconGenerator) clusterManager = GMUClusterManager(map: mapView, algorithm: algorithm, renderer: renderer) clusterManager.setMapDelegate(self) clusterManager.add(markerArray) clusterManager.cluster() } // MARK: GMSMapViewDelegate func mapView(_ mapView: GMSMapView, didTap marker: GMSMarker) -> Bool { // Clear previous circles circle?.map = nil // Animate to the marker mapView.animate(toLocation: marker.position) // If the tap was on a marker cluster, zoom in on the cluster if let _ = marker.userData as? GMUCluster { mapView.animate(toZoom: mapView.camera.zoom + 1) return true } // Draw a new circle around the tapped marker circle = GMSCircle(position: marker.position, radius: 800) circle?.fillColor = UIColor(red: 0.67, green: 0.67, blue: 0.67, alpha: 0.5) circle?.map = mapView return false } }
df5533df70528a5f4f445e77bf84ee41
32.808989
111
0.719176
false
false
false
false
JTWang4778/JTLive
refs/heads/master
MuXueLive/UIViewExt.swift
mit
1
import UIKit import Foundation extension UIView { func x()->CGFloat { return self.frame.origin.x } func right()-> CGFloat { return self.frame.origin.x + self.frame.size.width } func y()->CGFloat { return self.frame.origin.y } func bottom()->CGFloat { return self.frame.origin.y + self.frame.size.height } func width()->CGFloat { return self.frame.size.width } func height()-> CGFloat { return self.frame.size.height } func setX(x: CGFloat) { var rect:CGRect = self.frame rect.origin.x = x self.frame = rect } func setRight(right: CGFloat) { var rect:CGRect = self.frame rect.origin.x = right - rect.size.width self.frame = rect } func setY(y: CGFloat) { var rect:CGRect = self.frame rect.origin.y = y self.frame = rect } func setBottom(bottom: CGFloat) { var rect:CGRect = self.frame rect.origin.y = bottom - rect.size.height self.frame = rect } func setWidth(width: CGFloat) { var rect:CGRect = self.frame rect.size.width = width self.frame = rect } func setHeight(height: CGFloat) { var rect:CGRect = self.frame rect.size.height = height self.frame = rect } class func showAlertView(title:String,message:String) { // 创建 } }
a52f6f09f739306d066b63bf4a06f27b
18.175
59
0.533246
false
false
false
false
livio/HelloTrello
refs/heads/master
Pod/Classes/Trello.swift
bsd-3-clause
1
// // Trello.swift // Pods // // Created by Joel Fischer on 4/8/16. // // import Foundation import Alamofire import AlamofireImage public enum Result<T> { case failure(Error) case success(T) public var value: T? { switch self { case .success(let value): return value case .failure: return nil } } public var error: Error? { switch self { case .success: return nil case .failure(let error): return error } } } public enum TrelloError: Error { case networkError(error: Error?) case jsonError(error: Error?) } public enum ListType: String { case All = "all" case Closed = "closed" case None = "none" case Open = "open" } public enum CardType: String { case All = "all" case Closed = "closed" case None = "none" case Open = "open" case Visible = "visible" } public enum MemberType: String { case Admins = "admins" case All = "all" case None = "none" case Normal = "normal" case Owners = "owners" } open class Trello { let jsonDecoder = JSONDecoder() let authParameters: [String: AnyObject] public init(apiKey: String, authToken: String) { self.authParameters = ["key": apiKey as AnyObject, "token": authToken as AnyObject] jsonDecoder.dateDecodingStrategy = .iso8601 } // TODO: The response end of this is tough // public func search(query: String, partial: Bool = true) { // let parameters = authParameters + ["query": query] + ["partial": partial] // // Alamofire.request(.GET, Router.Search, parameters: parameters).responseJSON { (let response) in // print("Search Response \(response.result)") // // Returns a list of actions, boards, cards, members, and orgs that match the query // } // } } extension Trello { // MARK: Boards public func getAllBoards(_ completion: @escaping (Result<[Board]>) -> Void) { Alamofire.request(Router.allBoards, parameters: self.authParameters).response { (response: DefaultDataResponse) in guard let jsonData = response.data else { completion(.failure(TrelloError.networkError(error: response.error))) return } do { let boards = try self.jsonDecoder.decode([Board].self, from: jsonData) completion(.success(boards)) } catch (let error) { completion(.failure(TrelloError.jsonError(error: error))) } } } public func getBoard(_ id: String, includingLists listType: ListType = .None, includingCards cardType: CardType = .None, includingMembers memberType: MemberType = .None, completion: @escaping (Result<Board>) -> Void) { let parameters = self.authParameters + ["cards": cardType.rawValue as AnyObject] + ["lists": listType.rawValue as AnyObject] + ["members": memberType.rawValue as AnyObject] Alamofire.request(Router.board(boardId: id).URLString, parameters: parameters).response { (response) in guard let jsonData = response.data else { completion(.failure(TrelloError.networkError(error: response.error))) return } do { let board = try self.jsonDecoder.decode(Board.self, from: jsonData) completion(.success(board)) } catch (let error) { completion(.failure(TrelloError.jsonError(error: error))) } } } } // MARK: Lists extension Trello { public func getListsForBoard(_ id: String, filter: ListType = .Open, completion: @escaping (Result<[CardList]>) -> Void) { let parameters = self.authParameters + ["filter": filter.rawValue as AnyObject] Alamofire.request(Router.lists(boardId: id).URLString, parameters: parameters).response { (response) in guard let jsonData = response.data else { completion(.failure(TrelloError.networkError(error: response.error))) return } do { let lists = try self.jsonDecoder.decode([CardList].self, from: jsonData) completion(.success(lists)) } catch (let error) { completion(.failure(TrelloError.jsonError(error: error))) } } } public func getListsForBoard(_ board: Board, filter: ListType = .Open, completion: @escaping (Result<[CardList]>) -> Void) { getListsForBoard(board.id, filter: filter, completion: completion) } } // MARK: Cards extension Trello { public func getCardsForList(_ id: String, withMembers: Bool = false, completion: @escaping (Result<[Card]>) -> Void) { let parameters = self.authParameters + ["members": withMembers as AnyObject] Alamofire.request(Router.cardsForList(listId: id).URLString, parameters: parameters).response { (response) in guard let jsonData = response.data else { completion(.failure(TrelloError.networkError(error: response.error))) return } do { let cards = try self.jsonDecoder.decode([Card].self, from: jsonData) completion(.success(cards)) } catch (let error) { completion(.failure(TrelloError.jsonError(error: error))) } } } } // Member API extension Trello { public func getMember(_ id: String, completion: @escaping (Result<Member>) -> Void) { let parameters = self.authParameters Alamofire.request(Router.member(id: id).URLString, parameters: parameters).response { (response) in guard let jsonData = response.data else { completion(.failure(TrelloError.networkError(error: response.error))) return } do { let member = try self.jsonDecoder.decode(Member.self, from: jsonData) completion(.success(member)) } catch (let error) { completion(.failure(TrelloError.jsonError(error: error))) } } } public func getMembersForCard(_ cardId: String, completion: @escaping (Result<[Member]>) -> Void) { let parameters = self.authParameters Alamofire.request(Router.member(id: cardId).URLString, parameters: parameters).response { (response) in guard let jsonData = response.data else { completion(.failure(TrelloError.networkError(error: response.error))) return } do { let members = try self.jsonDecoder.decode([Member].self, from: jsonData) completion(.success(members)) } catch (let error) { completion(.failure(TrelloError.jsonError(error: error))) } } } public func getAvatarImage(_ avatarHash: String, size: AvatarSize, completion: @escaping (Result<Image>) -> Void) { Alamofire.request("https://trello-avatars.s3.amazonaws.com/\(avatarHash)/\(size.rawValue).png").responseImage { response in guard let image = response.result.value else { completion(.failure(TrelloError.networkError(error: response.result.error))) return } completion(.success(image)) } } public enum AvatarSize: Int { case small = 30 case large = 170 } } private enum Router: URLConvertible { static let baseURLString = "https://api.trello.com/1/" case search case allBoards case board(boardId: String) case lists(boardId: String) case cardsForList(listId: String) case member(id: String) case membersForCard(cardId: String) var URLString: String { switch self { case .search: return Router.baseURLString + "search/" case .allBoards: return Router.baseURLString + "members/me/boards/" case .board(let boardId): return Router.baseURLString + "boards/\(boardId)/" case .lists(let boardId): return Router.baseURLString + "boards/\(boardId)/lists/" case .cardsForList(let listId): return Router.baseURLString + "lists/\(listId)/cards/" case .member(let memberId): return Router.baseURLString + "members/\(memberId)/" case .membersForCard(let cardId): return Router.baseURLString + "cards/\(cardId)/members/" } } func asURL() throws -> URL { return URL(string: self.URLString)! } } // MARK: Dictionary Operator Overloading // http://stackoverflow.com/questions/24051904/how-do-you-add-a-dictionary-of-items-into-another-dictionary/ func += <K, V> (left: inout [K:V], right: [K:V]) { for (k, v) in right { left[k] = v } } func +<K, V> (left: [K: V], right: [K: V]) -> [K: V] { var newDict: [K: V] = [:] for (k, v) in left { newDict[k] = v } for (k, v) in right { newDict[k] = v } return newDict }
7416409c27bea7acdbf22d676702453e
32.129032
222
0.589311
false
false
false
false
Jackysonglanlan/Scripts
refs/heads/master
swift/learn/OOP-FP-show.swift
unlicense
1
/////////// OOP + FP // Do one thing and do it well // 分页 class Paginator { private var initPage: Int = 0 private var currPage: Int = 0 private var contentLoader: (Int) -> [String] private var content: [String]? private var uiUpdater: (([String]) -> Void)? private init(contentLoader loader: @escaping (Int) -> [String]) { // 这个闭包在方法返回后还存在,所以需要 escape contentLoader = loader } static func build(contentLoader loader: @escaping (Int) -> [String]) -> // 柯里化组装第1步, 配置 contentLoader ((([String]) -> Void)?) -> // 第2步, 配置 uiUpdater (Int) -> // 第3步,initPage Paginator { // 最后的成品,Paginator return { uiUpdater in { initPage in let pager = Paginator(contentLoader: loader) pager.uiUpdater = uiUpdater pager.initPage = initPage pager.currPage = initPage return pager } } } func nextPage() -> Paginator { currPage += 1 content = nil return self } func prevPage() -> Paginator { currPage -= 1 content = nil return self } func resetToInitPage() -> Paginator { currPage = initPage content = nil return self } func load() -> [String] { if content == nil { content = contentLoader(currPage) } return content! } func updateUI() { if let ui = uiUpdater { ui(load()) } } } // 按需构造 // let classMsg = Paginator.build(){currPage in // return Array(repeating: "classMsg", count: currPage) // } // let classMsg_InMainView = classMsg(){content in // print("in main view \(content)") // } // let classMsg_InMainView_startAtPage1 = classMsg_InMainView(1) // classMsg_InMainView_startAtPage1.updateUI() // classMsg_InMainView_startAtPage1.nextPage().updateUI() // 其他场景 // let classMsg_InMainView_startAtPage5 = classMsg_InMainView(5) // classMsg_InMainView_startAtPage5.updateUI() // let classMsg_InTeacherMeView = classMsg(){content in // print("in teacher me view \(content)") // } // let classMsg_InTeacherMeView_startAtPage2 = classMsg_InTeacherMeView(2) // classMsg_InTeacherMeView_startAtPage2.updateUI() // 柯里化 // let homework = Paginator.build(){currPage in // return Array(repeating: "homework", count: currPage) // } // let homework_sendView = homework(){content in // print("in send view \(content)") // } // let homework_sendView_startAt1 = homework_sendView(1) // homework_sendView_startAt1.updateUI() // homework_sendView_startAt1.resetToInitPage() // 用户疯狂翻页 // homework_sendView_startAt1.nextPage() // homework_sendView_startAt1.nextPage() // homework_sendView_startAt1.nextPage() // homework_sendView_startAt1.nextPage() // homework_sendView_startAt1.nextPage() // homework_sendView_startAt1.nextPage() // homework_sendView_startAt1.nextPage() // homework_sendView_startAt1.nextPage() // homework_sendView_startAt1.nextPage() // homework_sendView_startAt1.nextPage() // homework_sendView_startAt1.updateUI() // 缓存 头3页数据 到内存 // let classMsgs_without_uiUpdater = classMsg(nil) // // lazy cache // let lazyCache = (1...3).map(){page in // return classMsgs_without_uiUpdater(page) // } // print(lazyCache) // // 当你真正想要数据的时候 // let readData = lazyCache.map(){pager in // return pager.load() // } // print(readData) // // OOP + FP // // . 更好的代码复用 // // . 更好的封装 // // . 更好的扩展 (lazy 持久化当前页、thread safe) // // 可测试 // import AppKit // print(NSAppKitVersion.current)
82f2b0adba8403c5cfccc23b809200ab
21.426667
103
0.664685
false
false
false
false
luizlopezm/ios-Luis-Trucking
refs/heads/master
Pods/Eureka/Source/Core/Core.swift
mit
1
// Core.swift // Eureka ( https://github.com/xmartlabs/Eureka ) // // Copyright (c) 2015 Xmartlabs ( http://xmartlabs.com ) // // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation import UIKit // MARK: Row internal class RowDefaults { static var cellUpdate = Dictionary<String, (BaseCell, BaseRow) -> Void>() static var cellSetup = Dictionary<String, (BaseCell, BaseRow) -> Void>() static var onCellHighlight = Dictionary<String, (BaseCell, BaseRow) -> Void>() static var onCellUnHighlight = Dictionary<String, (BaseCell, BaseRow) -> Void>() static var rowInitialization = Dictionary<String, BaseRow -> Void>() static var rawCellUpdate = Dictionary<String, Any>() static var rawCellSetup = Dictionary<String, Any>() static var rawOnCellHighlight = Dictionary<String, Any>() static var rawOnCellUnHighlight = Dictionary<String, Any>() static var rawRowInitialization = Dictionary<String, Any>() } // MARK: FormCells public struct CellProvider<Cell: BaseCell where Cell: CellType> { /// Nibname of the cell that will be created. public private (set) var nibName: String? /// Bundle from which to get the nib file. public private (set) var bundle: NSBundle! public init(){} public init(nibName: String, bundle: NSBundle? = nil){ self.nibName = nibName self.bundle = bundle ?? NSBundle(forClass: Cell.self) } /** Creates the cell with the specified style. - parameter cellStyle: The style with which the cell will be created. - returns: the cell */ func createCell(cellStyle: UITableViewCellStyle) -> Cell { if let nibName = self.nibName { return bundle.loadNibNamed(nibName, owner: nil, options: nil).first as! Cell } return Cell.init(style: cellStyle, reuseIdentifier: nil) } } /** Enumeration that defines how a controller should be created. - Callback->VCType: Creates the controller inside the specified block - NibFile: Loads a controller from a nib file in some bundle - StoryBoard: Loads the controller from a Storyboard by its storyboard id */ public enum ControllerProvider<VCType: UIViewController>{ /** * Creates the controller inside the specified block */ case Callback(builder: (() -> VCType)) /** * Loads a controller from a nib file in some bundle */ case NibFile(name: String, bundle: NSBundle?) /** * Loads the controller from a Storyboard by its storyboard id */ case StoryBoard(storyboardId: String, storyboardName: String, bundle: NSBundle?) func createController() -> VCType { switch self { case .Callback(let builder): return builder() case .NibFile(let nibName, let bundle): return VCType.init(nibName: nibName, bundle:bundle ?? NSBundle(forClass: VCType.self)) case .StoryBoard(let storyboardId, let storyboardName, let bundle): let sb = UIStoryboard(name: storyboardName, bundle: bundle ?? NSBundle(forClass: VCType.self)) return sb.instantiateViewControllerWithIdentifier(storyboardId) as! VCType } } } /** * Responsible for the options passed to a selector view controller */ public struct DataProvider<T: Equatable> { public let arrayData: [T]? public init(arrayData: [T]){ self.arrayData = arrayData } } /** Defines how a controller should be presented. - Show?: Shows the controller with `showViewController(...)`. - PresentModally?: Presents the controller modally. - SegueName?: Performs the segue with the specified identifier (name). - SegueClass?: Performs a segue from a segue class. */ public enum PresentationMode<VCType: UIViewController> { /** * Shows the controller, created by the specified provider, with `showViewController(...)`. */ case Show(controllerProvider: ControllerProvider<VCType>, completionCallback: (UIViewController->())?) /** * Presents the controller, created by the specified provider, modally. */ case PresentModally(controllerProvider: ControllerProvider<VCType>, completionCallback: (UIViewController->())?) /** * Performs the segue with the specified identifier (name). */ case SegueName(segueName: String, completionCallback: (UIViewController->())?) /** * Performs a segue from a segue class. */ case SegueClass(segueClass: UIStoryboardSegue.Type, completionCallback: (UIViewController->())?) case Popover(controllerProvider: ControllerProvider<VCType>, completionCallback: (UIViewController->())?) var completionHandler: (UIViewController ->())? { switch self{ case .Show(_, let completionCallback): return completionCallback case .PresentModally(_, let completionCallback): return completionCallback case .SegueName(_, let completionCallback): return completionCallback case .SegueClass(_, let completionCallback): return completionCallback case .Popover(_, let completionCallback): return completionCallback } } /** Present the view controller provided by PresentationMode. Should only be used from custom row implementation. - parameter viewController: viewController to present if it makes sense (normally provided by createController method) - parameter row: associated row - parameter presentingViewController: form view controller */ public func presentViewController(viewController: VCType!, row: BaseRow, presentingViewController:FormViewController){ switch self { case .Show(_, _): presentingViewController.showViewController(viewController, sender: row) case .PresentModally(_, _): presentingViewController.presentViewController(viewController, animated: true, completion: nil) case .SegueName(let segueName, _): presentingViewController.performSegueWithIdentifier(segueName, sender: row) case .SegueClass(let segueClass, _): let segue = segueClass.init(identifier: row.tag, source: presentingViewController, destination: viewController) presentingViewController.prepareForSegue(segue, sender: row) segue.perform() case .Popover(_, _): guard let porpoverController = viewController.popoverPresentationController else { fatalError() } porpoverController.sourceView = porpoverController.sourceView ?? presentingViewController.tableView porpoverController.sourceRect = porpoverController.sourceRect ?? row.baseCell.frame presentingViewController.presentViewController(viewController, animated: true, completion: nil) } } /** Creates the view controller specified by presentation mode. Should only be used from custom row implementation. - returns: the created view controller or nil depending on the PresentationMode type. */ public func createController() -> VCType? { switch self { case .Show(let controllerProvider, let completionCallback): let controller = controllerProvider.createController() let completionController = controller as? RowControllerType if let callback = completionCallback { completionController?.completionCallback = callback } return controller case .PresentModally(let controllerProvider, let completionCallback): let controller = controllerProvider.createController() let completionController = controller as? RowControllerType if let callback = completionCallback { completionController?.completionCallback = callback } return controller case .Popover(let controllerProvider, let completionCallback): let controller = controllerProvider.createController() controller.modalPresentationStyle = .Popover let completionController = controller as? RowControllerType if let callback = completionCallback { completionController?.completionCallback = callback } return controller default: return nil } } } /** * Protocol to be implemented by custom formatters. */ public protocol FormatterProtocol { func getNewPosition(forPosition forPosition: UITextPosition, inTextInput textInput: UITextInput, oldValue: String?, newValue: String?) -> UITextPosition } //MARK: Predicate Machine enum ConditionType { case Hidden, Disabled } /** Enumeration that are used to specify the disbaled and hidden conditions of rows - Function: A function that calculates the result - Predicate: A predicate that returns the result */ public enum Condition { /** * Calculate the condition inside a block * * @param Array of tags of the rows this function depends on * @param Form->Bool The block that calculates the result * * @return If the condition is true or false */ case Function([String], Form->Bool) /** * Calculate the condition using a NSPredicate * * @param NSPredicate The predicate that will be evaluated * * @return If the condition is true or false */ case Predicate(NSPredicate) } extension Condition : BooleanLiteralConvertible { /** Initialize a condition to return afixed boolean value always */ public init(booleanLiteral value: Bool){ self = Condition.Function([]) { _ in return value } } } extension Condition : StringLiteralConvertible { /** Initialize a Condition with a string that will be converted to a NSPredicate */ public init(stringLiteral value: String){ self = .Predicate(NSPredicate(format: value)) } /** Initialize a Condition with a string that will be converted to a NSPredicate */ public init(unicodeScalarLiteral value: String) { self = .Predicate(NSPredicate(format: value)) } /** Initialize a Condition with a string that will be converted to a NSPredicate */ public init(extendedGraphemeClusterLiteral value: String) { self = .Predicate(NSPredicate(format: value)) } } //MARK: Errors /** Errors thrown by Eureka - DuplicatedTag: When a section or row is inserted whose tag dows already exist */ public enum EurekaError : ErrorType { case DuplicatedTag(tag: String) } //Mark: FormViewController /** * A protocol implemented by FormViewController */ public protocol FormViewControllerProtocol { func beginEditing<T:Equatable>(cell: Cell<T>) func endEditing<T:Equatable>(cell: Cell<T>) func insertAnimationForRows(rows: [BaseRow]) -> UITableViewRowAnimation func deleteAnimationForRows(rows: [BaseRow]) -> UITableViewRowAnimation func reloadAnimationOldRows(oldRows: [BaseRow], newRows: [BaseRow]) -> UITableViewRowAnimation func insertAnimationForSections(sections : [Section]) -> UITableViewRowAnimation func deleteAnimationForSections(sections : [Section]) -> UITableViewRowAnimation func reloadAnimationOldSections(oldSections: [Section], newSections:[Section]) -> UITableViewRowAnimation } /** * Navigation options for a form view controller. */ public struct RowNavigationOptions : OptionSetType { private enum NavigationOptions : Int { case Disabled = 0, Enabled = 1, StopDisabledRow = 2, SkipCanNotBecomeFirstResponderRow = 4 } public let rawValue: Int public init(rawValue: Int){ self.rawValue = rawValue} private init(_ options:NavigationOptions ){ self.rawValue = options.rawValue } @available(*, unavailable, renamed="Disabled") /// No navigation. public static let None = RowNavigationOptions(.Disabled) /// No navigation. public static let Disabled = RowNavigationOptions(.Disabled) /// Full navigation. public static let Enabled = RowNavigationOptions(.Enabled) /// Break navigation when next row is disabled. public static let StopDisabledRow = RowNavigationOptions(.StopDisabledRow) /// Break navigation when next row cannot become first responder. public static let SkipCanNotBecomeFirstResponderRow = RowNavigationOptions(.SkipCanNotBecomeFirstResponderRow) } /** * Defines the configuration for the keyboardType of FieldRows. */ public struct KeyboardReturnTypeConfiguration { /// Used when the next row is available. public var nextKeyboardType = UIReturnKeyType.Next /// Used if next row is not available. public var defaultKeyboardType = UIReturnKeyType.Default public init(){} public init(nextKeyboardType: UIReturnKeyType, defaultKeyboardType: UIReturnKeyType){ self.nextKeyboardType = nextKeyboardType self.defaultKeyboardType = defaultKeyboardType } } /** * Options that define when an inline row should collapse. */ public struct InlineRowHideOptions : OptionSetType { private enum _InlineRowHideOptions : Int { case Never = 0, AnotherInlineRowIsShown = 1, FirstResponderChanges = 2 } public let rawValue: Int public init(rawValue: Int){ self.rawValue = rawValue} private init(_ options:_InlineRowHideOptions ){ self.rawValue = options.rawValue } /// Never collapse automatically. Only when user taps inline row. public static let Never = InlineRowHideOptions(.Never) /// Collapse qhen another inline row expands. Just one inline row will be expanded at a time. public static let AnotherInlineRowIsShown = InlineRowHideOptions(.AnotherInlineRowIsShown) /// Collapse when first responder changes. public static let FirstResponderChanges = InlineRowHideOptions(.FirstResponderChanges) } /// View controller that shows a form. public class FormViewController : UIViewController, FormViewControllerProtocol { @IBOutlet public var tableView: UITableView? private lazy var _form : Form = { [weak self] in let form = Form() form.delegate = self return form }() public var form : Form { get { return _form } set { _form.delegate = nil tableView?.endEditing(false) _form = newValue _form.delegate = self if isViewLoaded() && tableView?.window != nil { tableView?.reloadData() } } } /// Accessory view that is responsible for the navigation between rows lazy public var navigationAccessoryView : NavigationAccessoryView = { [unowned self] in let naview = NavigationAccessoryView(frame: CGRectMake(0, 0, self.view.frame.width, 44.0)) naview.tintColor = self.view.tintColor return naview }() /// Defines the behaviour of the navigation between rows public var navigationOptions : RowNavigationOptions? private var tableViewStyle: UITableViewStyle = .Grouped public init(style: UITableViewStyle) { super.init(nibName: nil, bundle: nil) tableViewStyle = style } public override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } public override func viewDidLoad() { super.viewDidLoad() if tableView == nil { tableView = UITableView(frame: view.bounds, style: tableViewStyle) tableView?.autoresizingMask = UIViewAutoresizing.FlexibleWidth.union(.FlexibleHeight) if #available(iOS 9.0, *){ tableView?.cellLayoutMarginsFollowReadableWidth = false } } if tableView?.superview == nil { view.addSubview(tableView!) } if tableView?.delegate == nil { tableView?.delegate = self } if tableView?.dataSource == nil { tableView?.dataSource = self } tableView?.estimatedRowHeight = BaseRow.estimatedRowHeight } public override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) if let selectedIndexPath = tableView?.indexPathForSelectedRow { tableView?.reloadRowsAtIndexPaths([selectedIndexPath], withRowAnimation: .None) tableView?.selectRowAtIndexPath(selectedIndexPath, animated: false, scrollPosition: .None) tableView?.deselectRowAtIndexPath(selectedIndexPath, animated: true) } NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(FormViewController.keyboardWillShow(_:)), name: UIKeyboardWillShowNotification, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(FormViewController.keyboardWillHide(_:)), name: UIKeyboardWillHideNotification, object: nil) } public override func viewDidDisappear(animated: Bool) { super.viewDidDisappear(animated) NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillShowNotification, object: nil) NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillHideNotification, object: nil) } public override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { super.prepareForSegue(segue, sender: sender) let baseRow = sender as? BaseRow baseRow?.prepareForSegue(segue) } //MARK: FormDelegate public func rowValueHasBeenChanged(row: BaseRow, oldValue: Any?, newValue: Any?) {} //MARK: FormViewControllerProtocol /** Called when a cell becomes first responder */ public final func beginEditing<T:Equatable>(cell: Cell<T>) { cell.row.hightlightCell() guard let _ = tableView where (form.inlineRowHideOptions ?? Form.defaultInlineRowHideOptions).contains(.FirstResponderChanges) else { return } let row = cell.baseRow let inlineRow = row._inlineRow for row in form.allRows.filter({ $0 !== row && $0 !== inlineRow && $0._inlineRow != nil }) { if let inlineRow = row as? BaseInlineRowType { inlineRow.collapseInlineRow() } } } /** Called when a cell resigns first responder */ public final func endEditing<T:Equatable>(cell: Cell<T>) { cell.row.unhighlightCell() } /** Returns the animation for the insertion of the given rows. */ public func insertAnimationForRows(rows: [BaseRow]) -> UITableViewRowAnimation { return .Fade } /** Returns the animation for the deletion of the given rows. */ public func deleteAnimationForRows(rows: [BaseRow]) -> UITableViewRowAnimation { return .Fade } /** Returns the animation for the reloading of the given rows. */ public func reloadAnimationOldRows(oldRows: [BaseRow], newRows: [BaseRow]) -> UITableViewRowAnimation { return .Automatic } /** Returns the animation for the insertion of the given sections. */ public func insertAnimationForSections(sections: [Section]) -> UITableViewRowAnimation { return .Automatic } /** Returns the animation for the deletion of the given sections. */ public func deleteAnimationForSections(sections: [Section]) -> UITableViewRowAnimation { return .Automatic } /** Returns the animation for the reloading of the given sections. */ public func reloadAnimationOldSections(oldSections: [Section], newSections: [Section]) -> UITableViewRowAnimation { return .Automatic } //MARK: TextField and TextView Delegate public func textInputShouldBeginEditing<T>(textInput: UITextInput, cell: Cell<T>) -> Bool { return true } public func textInputDidBeginEditing<T>(textInput: UITextInput, cell: Cell<T>) { if let row = cell.row as? KeyboardReturnHandler { let nextRow = nextRowForRow(cell.row, withDirection: .Down) if let textField = textInput as? UITextField { textField.returnKeyType = nextRow != nil ? (row.keyboardReturnType?.nextKeyboardType ?? (form.keyboardReturnType?.nextKeyboardType ?? Form.defaultKeyboardReturnType.nextKeyboardType )) : (row.keyboardReturnType?.defaultKeyboardType ?? (form.keyboardReturnType?.defaultKeyboardType ?? Form.defaultKeyboardReturnType.defaultKeyboardType)) } else if let textView = textInput as? UITextView { textView.returnKeyType = nextRow != nil ? (row.keyboardReturnType?.nextKeyboardType ?? (form.keyboardReturnType?.nextKeyboardType ?? Form.defaultKeyboardReturnType.nextKeyboardType )) : (row.keyboardReturnType?.defaultKeyboardType ?? (form.keyboardReturnType?.defaultKeyboardType ?? Form.defaultKeyboardReturnType.defaultKeyboardType)) } } } public func textInputShouldEndEditing<T>(textInput: UITextInput, cell: Cell<T>) -> Bool { return true } public func textInputDidEndEditing<T>(textInput: UITextInput, cell: Cell<T>) { } public func textInput<T>(textInput: UITextInput, shouldChangeCharactersInRange range: NSRange, replacementString string: String, cell: Cell<T>) -> Bool { return true } public func textInputShouldClear<T>(textInput: UITextInput, cell: Cell<T>) -> Bool { return true } public func textInputShouldReturn<T>(textInput: UITextInput, cell: Cell<T>) -> Bool { if let nextRow = nextRowForRow(cell.row, withDirection: .Down){ if nextRow.baseCell.cellCanBecomeFirstResponder(){ nextRow.baseCell.cellBecomeFirstResponder() return true } } tableView?.endEditing(true) return true } //MARK: Private private var oldBottomInset : CGFloat? } extension FormViewController : UITableViewDelegate { //MARK: UITableViewDelegate public func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) { guard tableView == self.tableView else { return } form[indexPath].updateCell() } public func tableView(tableView: UITableView, willSelectRowAtIndexPath indexPath: NSIndexPath) -> NSIndexPath? { return indexPath } public func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { guard tableView == self.tableView else { return } let row = form[indexPath] // row.baseCell.cellBecomeFirstResponder() may be cause InlineRow collapsed then section count will be changed. Use orignal indexPath will out of section's bounds. if !row.baseCell.cellCanBecomeFirstResponder() || !row.baseCell.cellBecomeFirstResponder() { self.tableView?.endEditing(true) } row.didSelect() } public func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { guard tableView == self.tableView else { return tableView.rowHeight } let row = form[indexPath.section][indexPath.row] return row.baseCell.height?() ?? tableView.rowHeight } public func tableView(tableView: UITableView, estimatedHeightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { guard tableView == self.tableView else { return tableView.rowHeight } let row = form[indexPath.section][indexPath.row] return row.baseCell.height?() ?? tableView.estimatedRowHeight } public func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { return form[section].header?.viewForSection(form[section], type: .Header, controller: self) } public func tableView(tableView: UITableView, viewForFooterInSection section: Int) -> UIView? { return form[section].footer?.viewForSection(form[section], type:.Footer, controller: self) } public func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { if let height = form[section].header?.height { return height() } guard let view = form[section].header?.viewForSection(form[section], type: .Header, controller: self) else{ return UITableViewAutomaticDimension } guard view.bounds.height != 0 else { return UITableViewAutomaticDimension } return view.bounds.height } public func tableView(tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { if let height = form[section].footer?.height { return height() } guard let view = form[section].footer?.viewForSection(form[section], type: .Footer, controller: self) else{ return UITableViewAutomaticDimension } guard view.bounds.height != 0 else { return UITableViewAutomaticDimension } return view.bounds.height } } extension FormViewController : UITableViewDataSource { //MARK: UITableViewDataSource public func numberOfSectionsInTableView(tableView: UITableView) -> Int { return form.count } public func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return form[section].count } public func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { return form[indexPath].baseCell } public func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return form[section].header?.title } public func tableView(tableView: UITableView, titleForFooterInSection section: Int) -> String? { return form[section].footer?.title } } extension FormViewController: FormDelegate { //MARK: FormDelegate public func sectionsHaveBeenAdded(sections: [Section], atIndexes: NSIndexSet){ tableView?.beginUpdates() tableView?.insertSections(atIndexes, withRowAnimation: insertAnimationForSections(sections)) tableView?.endUpdates() } public func sectionsHaveBeenRemoved(sections: [Section], atIndexes: NSIndexSet){ tableView?.beginUpdates() tableView?.deleteSections(atIndexes, withRowAnimation: deleteAnimationForSections(sections)) tableView?.endUpdates() } public func sectionsHaveBeenReplaced(oldSections oldSections:[Section], newSections: [Section], atIndexes: NSIndexSet){ tableView?.beginUpdates() tableView?.reloadSections(atIndexes, withRowAnimation: reloadAnimationOldSections(oldSections, newSections: newSections)) tableView?.endUpdates() } public func rowsHaveBeenAdded(rows: [BaseRow], atIndexPaths: [NSIndexPath]) { tableView?.beginUpdates() tableView?.insertRowsAtIndexPaths(atIndexPaths, withRowAnimation: insertAnimationForRows(rows)) tableView?.endUpdates() } public func rowsHaveBeenRemoved(rows: [BaseRow], atIndexPaths: [NSIndexPath]) { tableView?.beginUpdates() tableView?.deleteRowsAtIndexPaths(atIndexPaths, withRowAnimation: deleteAnimationForRows(rows)) tableView?.endUpdates() } public func rowsHaveBeenReplaced(oldRows oldRows:[BaseRow], newRows: [BaseRow], atIndexPaths: [NSIndexPath]){ tableView?.beginUpdates() tableView?.reloadRowsAtIndexPaths(atIndexPaths, withRowAnimation: reloadAnimationOldRows(oldRows, newRows: newRows)) tableView?.endUpdates() } } extension FormViewController : UIScrollViewDelegate { //MARK: UIScrollViewDelegate public func scrollViewWillBeginDragging(scrollView: UIScrollView) { tableView?.endEditing(true) } } extension FormViewController { //MARK: KeyBoard Notifications /** Called when the keyboard will appear. Adjusts insets of the tableView and scrolls it if necessary. */ public func keyboardWillShow(notification: NSNotification){ guard let table = tableView, let cell = table.findFirstResponder()?.formCell() else { return } let keyBoardInfo = notification.userInfo! let keyBoardFrame = table.window!.convertRect((keyBoardInfo[UIKeyboardFrameEndUserInfoKey]?.CGRectValue)!, toView: table.superview) let newBottomInset = table.frame.origin.y + table.frame.size.height - keyBoardFrame.origin.y var tableInsets = table.contentInset var scrollIndicatorInsets = table.scrollIndicatorInsets oldBottomInset = oldBottomInset ?? tableInsets.bottom if newBottomInset > oldBottomInset { tableInsets.bottom = newBottomInset scrollIndicatorInsets.bottom = tableInsets.bottom UIView.beginAnimations(nil, context: nil) UIView.setAnimationDuration(keyBoardInfo[UIKeyboardAnimationDurationUserInfoKey]!.doubleValue) UIView.setAnimationCurve(UIViewAnimationCurve(rawValue: keyBoardInfo[UIKeyboardAnimationCurveUserInfoKey]!.integerValue)!) table.contentInset = tableInsets table.scrollIndicatorInsets = scrollIndicatorInsets if let selectedRow = table.indexPathForCell(cell) { table.scrollToRowAtIndexPath(selectedRow, atScrollPosition: .None, animated: false) } UIView.commitAnimations() } } /** Called when the keyboard will disappear. Adjusts insets of the tableView. */ public func keyboardWillHide(notification: NSNotification){ guard let table = tableView, let oldBottom = oldBottomInset else { return } let keyBoardInfo = notification.userInfo! var tableInsets = table.contentInset var scrollIndicatorInsets = table.scrollIndicatorInsets tableInsets.bottom = oldBottom scrollIndicatorInsets.bottom = tableInsets.bottom oldBottomInset = nil UIView.beginAnimations(nil, context: nil) UIView.setAnimationDuration(keyBoardInfo[UIKeyboardAnimationDurationUserInfoKey]!.doubleValue) UIView.setAnimationCurve(UIViewAnimationCurve(rawValue: keyBoardInfo[UIKeyboardAnimationCurveUserInfoKey]!.integerValue)!) table.contentInset = tableInsets table.scrollIndicatorInsets = scrollIndicatorInsets UIView.commitAnimations() } } public enum Direction { case Up, Down } extension FormViewController { //MARK: Navigation Methods func navigationDone(sender: UIBarButtonItem) { tableView?.endEditing(true) } func navigationAction(sender: UIBarButtonItem) { navigateToDirection(sender == navigationAccessoryView.previousButton ? .Up : .Down) } private func navigateToDirection(direction: Direction){ guard let currentCell = tableView?.findFirstResponder()?.formCell() else { return } guard let currentIndexPath = tableView?.indexPathForCell(currentCell) else { assertionFailure(); return } guard let nextRow = nextRowForRow(form[currentIndexPath], withDirection: direction) else { return } if nextRow.baseCell.cellCanBecomeFirstResponder(){ tableView?.scrollToRowAtIndexPath(nextRow.indexPath()!, atScrollPosition: .None, animated: false) nextRow.baseCell.cellBecomeFirstResponder(direction) } } private func nextRowForRow(currentRow: BaseRow, withDirection direction: Direction) -> BaseRow? { let options = navigationOptions ?? Form.defaultNavigationOptions guard options.contains(.Enabled) else { return nil } guard let nextRow = direction == .Down ? form.nextRowForRow(currentRow) : form.previousRowForRow(currentRow) else { return nil } if nextRow.isDisabled && options.contains(.StopDisabledRow) { return nil } if !nextRow.baseCell.cellCanBecomeFirstResponder() && !nextRow.isDisabled && !options.contains(.SkipCanNotBecomeFirstResponderRow){ return nil } if (!nextRow.isDisabled && nextRow.baseCell.cellCanBecomeFirstResponder()){ return nextRow } return nextRowForRow(nextRow, withDirection:direction) } /** Returns the navigation accessory view if it is enabled. Returns nil otherwise. */ public func inputAccessoryViewForRow(row: BaseRow) -> UIView? { let options = navigationOptions ?? Form.defaultNavigationOptions guard options.contains(.Enabled) else { return nil } guard row.baseCell.cellCanBecomeFirstResponder() else { return nil} navigationAccessoryView.previousButton.enabled = nextRowForRow(row, withDirection: .Up) != nil navigationAccessoryView.doneButton.target = self navigationAccessoryView.doneButton.action = #selector(FormViewController.navigationDone(_:)) navigationAccessoryView.previousButton.target = self navigationAccessoryView.previousButton.action = #selector(FormViewController.navigationAction(_:)) navigationAccessoryView.nextButton.target = self navigationAccessoryView.nextButton.action = #selector(FormViewController.navigationAction(_:)) navigationAccessoryView.nextButton.enabled = nextRowForRow(row, withDirection: .Down) != nil return navigationAccessoryView } }
0370a94ed36d612853e1387ee6f45372
39.094533
352
0.680709
false
false
false
false
izotx/iTenWired-Swift
refs/heads/master
Conference App/AgendaDataLoader.swift
bsd-2-clause
1
// Copyright (c) 2016, Izotx // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of Izotx nor the names of its contributors may be used to // endorse or promote products derived from this software without specific // prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. // AgendaDataLoader.swift // Agenda1 // // Created by Felipe Neves Brito on 4/5/16. import Foundation /// Loads agenda data class AgendaDataLoader{ /// App data loader let appData = AppData() /** Returns a Agenda with the events - Returns: A agenda with the events */ func getAgenda() -> Agenda { let agenda = Agenda() guard let data = appData.getDataFromFile() else { return agenda } if let eventsData = data["events"] as? [NSDictionary]{ for eventData in eventsData{ let event = Event(dictionary: eventData) agenda.addEvent(event) } } return agenda } func getEvents(completion: (events:[Event]) -> Void){ appData.getDataFromFile { (dictionary) in var events : [Event] = [] if let eventsData = dictionary["events"] as? [NSDictionary]{ for eventData in eventsData{ let event = Event(dictionary: eventData) events.append(event) } completion(events: events) } } } }
7b38477fc18beebc5a36715458db7ba2
35
82
0.632164
false
false
false
false
calebd/swift
refs/heads/master
test/SILGen/objc_nonnull_lie_hack.swift
apache-2.0
4
// RUN: %empty-directory(%t/APINotes) // RUN: %clang_apinotes -yaml-to-binary %S/Inputs/gizmo.apinotes -o %t/APINotes/gizmo.apinotesc // RUN: %target-swift-frontend -emit-silgen -sdk %S/Inputs -I %S/Inputs -I %t/APINotes -enable-source-import -primary-file %s | %FileCheck -check-prefix=SILGEN %s // RUN: %target-swift-frontend -emit-sil -O -sdk %S/Inputs -I %S/Inputs -I %t/APINotes -enable-source-import -primary-file %s | %FileCheck -check-prefix=OPT %s // REQUIRES: objc_interop // REQUIRES: rdar28313536 import Foundation import gizmo // SILGEN-LABEL: sil hidden @_TF21objc_nonnull_lie_hack10makeObjectFT_GSqCSo8NSObject_ // SILGEN: [[INIT:%.*]] = function_ref @_TFCSo8NSObjectC // SILGEN: [[NONOPTIONAL:%.*]] = apply [[INIT]] // SILGEN: [[OPTIONAL:%.*]] = unchecked_ref_cast [[NONOPTIONAL]] // OPT-LABEL: sil hidden @_TF21objc_nonnull_lie_hack10makeObjectFT_GSqCSo8NSObject_ // OPT: [[OPT:%.*]] = unchecked_ref_cast // OPT: switch_enum [[OPT]] : $Optional<NSObject>, case #Optional.none!enumelt: [[NIL:bb[0-9]+]] func makeObject() -> NSObject? { let foo: NSObject? = NSObject() if foo == nil { print("nil") } return foo } // OPT-LABEL: sil hidden @_TF21objc_nonnull_lie_hack15callClassMethod // OPT: [[METATYPE:%[0-9]+]] = metatype $@thick Gizmo.Type // OPT: [[METHOD:%[0-9]+]] = class_method [volatile] [[METATYPE]] : $@thick Gizmo.Type, #Gizmo.nonNilGizmo!1.foreign : (Gizmo.Type) -> () -> Gizmo, $@convention(objc_method) (@objc_metatype Gizmo.Type) -> @autoreleased Gizmo // OPT: [[OBJC_METATYPE:%[0-9]+]] = metatype $@objc_metatype Gizmo.Type // OPT: [[NONOPTIONAL:%[0-9]+]] = apply [[METHOD]]([[OBJC_METATYPE]]) : $@convention(objc_method) (@objc_metatype Gizmo.Type) -> @autoreleased Gizmo // OPT: [[OPTIONAL:%[0-9]+]] = unchecked_ref_cast [[NONOPTIONAL]] : $Gizmo to $Optional<Gizmo> // OPT: switch_enum [[OPTIONAL]] : $Optional<Gizmo> func callClassMethod() -> Gizmo? { let foo: Gizmo? = Gizmo.nonNilGizmo() if foo == nil { print("nil") } return foo } // OPT-LABEL: sil hidden @_TTSf4g___TF21objc_nonnull_lie_hack18callInstanceMetho // OPT: [[METHOD:%[0-9]+]] = class_method [volatile] [[OBJ:%[0-9]+]] : $Gizmo, #Gizmo.nonNilGizmo!1.foreign : (Gizmo) -> () -> Gizmo, $@convention(objc_method) (Gizmo) -> @autoreleased Gizmo // OPT: [[NONOPTIONAL:%[0-9]+]] = apply [[METHOD]]([[OBJ]]) : $@convention(objc_method) (Gizmo) -> @autoreleased Gizmo // OPT: [[OPTIONAL:%[0-9]+]] = unchecked_ref_cast [[NONOPTIONAL]] // OPT: switch_enum [[OPTIONAL]] : $Optional<Gizmo> func callInstanceMethod(gizmo: Gizmo) -> Gizmo? { let foo: Gizmo? = gizmo.nonNilGizmo() if foo == nil { print("nil") } return foo } // OPT-LABEL: sil hidden @_TTSf4g___TF21objc_nonnull_lie_hack12loadPropertyFT5gizmoCSo5Gizmo_GSqS0__ // OPT: [[GETTER:%[0-9]+]] = class_method [volatile] [[OBJ:%[0-9]+]] : $Gizmo, #Gizmo.nonNilGizmoProperty!getter.1.foreign : (Gizmo) -> () -> Gizmo, $@convention(objc_method) (Gizmo) -> @autoreleased Gizmo // OPT: [[NONOPTIONAL:%[0-9]+]] = apply [[GETTER]]([[OBJ]]) : $@convention(objc_method) (Gizmo) -> @autoreleased Gizmo // OPT: [[OPTIONAL:%[0-9]+]] = unchecked_ref_cast [[NONOPTIONAL]] : $Gizmo to $Optional<Gizmo> // OPT: switch_enum [[OPTIONAL]] : $Optional<Gizmo>, func loadProperty(gizmo: Gizmo) -> Gizmo? { let foo: Gizmo? = gizmo.nonNilGizmoProperty if foo == nil { print("nil") } return foo } // OPT-LABEL: sil hidden @_TTSf4g___TF21objc_nonnull_lie_hack19loadUnownedPropertyFT5gizmoCSo5Gizmo_GSqS0__ // OPT: [[GETTER:%[0-9]+]] = class_method [volatile] [[OBJ:%[0-9]+]] : $Gizmo, #Gizmo.unownedNonNilGizmoProperty!getter.1.foreign : (Gizmo) -> () -> Gizmo, $@convention(objc_method) (Gizmo) -> @autoreleased Gizmo // OPT: [[NONOPTIONAL:%[0-9]+]] = apply [[GETTER]]([[OBJ]]) : $@convention(objc_method) (Gizmo) -> @autoreleased Gizmo // OPT: [[OPTIONAL:%[0-9]+]] = unchecked_ref_cast [[NONOPTIONAL]] : $Gizmo to $Optional<Gizmo> // OPT: switch_enum [[OPTIONAL]] : $Optional<Gizmo> func loadUnownedProperty(gizmo: Gizmo) -> Gizmo? { let foo: Gizmo? = gizmo.unownedNonNilGizmoProperty if foo == nil { print("nil") } return foo }
9a9118b2cc65ed6c0b342e59e145805a
50.382716
224
0.653292
false
false
false
false
BugMomon/weibo
refs/heads/master
NiceWB/NiceWB/Classes/Home(主页)/Model/HomeViewModel.swift
apache-2.0
1
// // HomeViewModel.swift // NiceWB // // Created by HongWei on 2017/4/10. // Copyright © 2017年 HongWei. All rights reserved. // import UIKit class HomeViewModel: NSObject { var homeStatuses : HomeStatuses? //处理数据 var sourceText : String? var created_time : String? var verifiedImage : UIImage? //认证用户类型图片 var vipLevelImage : UIImage? //会员等级显示图片 var headImageUrl : URL? //用户头像的地址 var picUrls : [URL]? = [URL]() init(statuses : HomeStatuses) { super.init() self.homeStatuses = statuses //处理时间 if let created_at = statuses.created_at{ created_time = NSDate.createDateString(createAtStr: created_at) } // <a href="http://app.weibo.com/t/feed/6vtZb0" rel="nofollow">微博 weibo.com</a> //处理来源 if let source = statuses.source, source != "" { let startIndex = (source as NSString).range(of: ">").location+1 let endIndex = (source as NSString).range(of: "</").location let length = endIndex - startIndex let subText = (source as NSString).substring(with: NSRange.init(location: startIndex, length: length)) sourceText = "来自:"+subText } //新的是否加vip图标 verifiedImage = UIImage(named: statuses.user?.verified == true ? "avatar_enterprise_vip" : "") //老的处理认证类型 // let verifiedType = statuses.user?.verified_type ?? -1 // // switch verifiedType { // case 0: // verifiedImage = UIImage(named: "avatar_enterprise_vip") // case 2,3,5: // verifiedImage = UIImage(named: "avatar_grassroot") // case 220: // verifiedImage = UIImage(named: "avatar_vip") // default: // verifiedImage = nil // } //处理认证等级 let level = statuses.user?.verified_type ?? 0 if level>0 , level<=6 { vipLevelImage = UIImage(named: "common_icon_membership_level\(level)") } //处理用户头像 let str = statuses.user?.profile_image_url ?? "" headImageUrl = URL(string: str) //处理配图数据,如果微博正文里没有配图,就在转发配图数据中遍历 if let picUrlsDic = statuses.pic_urls?.count != 0 ? statuses.pic_urls : statuses.retweeted_status?.pic_urls { for dic in picUrlsDic{ guard let str = dic["thumbnail_pic"] else { continue } let url = URL(string: str) picUrls?.append(url!) } } } }
30d0ad74bace4a0ff97a243d4dd55cf3
31.15
117
0.550933
false
false
false
false
Pluto-Y/SwiftyEcharts
refs/heads/master
DemoOptions/GraphOptions.swift
mit
1
// // GraphOptions.swift // SwiftyEcharts // // Created by Pluto-Y on 16/01/2017. // Copyright © 2017 com.pluto-y. All rights reserved. // import SwiftyEcharts public final class GraphOptions { // MARK: Les Miserables /// 地址: http://echarts.baidu.com/demo.html#graph-circular-layout static func graphCircularLayoutOption() -> Option { // TODO: 添加实现 return Option( ) } // MARK: 力引导布局 /// 地址: http://echarts.baidu.com/demo.html#graph-force static func graphForceOption() -> Option { // TODO: 添加实现 return Option( ) } // MARK: 力引导布局 /// 地址: http://echarts.baidu.com/demo.html#graph-force2 static func graphForce2Option() -> Option { let createNodes: (Int) -> [Jsonable] = { count in var nodes: [Jsonable] = [] for i in 0..<count { nodes.append([["id": i]]) } return nodes } let createEdges: (Int) -> [[Jsonable]] = { count in var edges: [[Jsonable]] = [] if count == 2 { return [[0, 1]] } for i in 0..<count { edges.append([i, (i + 1) % count]) } return edges } var datas: [[String: Jsonable]] = [] for i in 0..<16 { datas.append([ "nodes": createNodes(i+2), "edges": createEdges(i+2) ]) } var series: [Serie] = [] var idx = 0 for item in datas { series.append(GraphSerie( .layout(.force), .animation(false), .data(item["nodes"] as! [Jsonable]), .left(.value(((idx % 4) * 25)%)), .top(.value((Int(idx / 4) * 25)%)), .width(25%), .height(25%), .force(GraphSerie.Force( .repulsion(60), .edgeLength(2) )), .edges((item["edges"] as! [[Jsonable]]).map { e in return GraphSerie.Link( .source(e[0]), .target(e[1]) ) }) )) idx += 1 } return Option( .series(series) ) } // MARK: 笛卡尔坐标系上的 Graph /// 地址: http://echarts.baidu.com/demo.html#graph-grid static func graphGridOption() -> Option { let axisData = ["周一","周二","周三","很长很长的周四","周五","周六","周日"] var data: [Float] = [] for i in 0..<axisData.count { data.append(Float(arc4random_uniform(1000)) * Float(i + 1)) } var links: [GraphSerie.Link] = [] for i in 0..<axisData.count { links.append(GraphSerie.Link( .source(i), .target(i+1) )) } links.removeLast() return Option( .title(Title( .text("笛卡尔坐标系上的 Graph") )), .tooltip(Tooltip()), .xAxis(Axis( .type(.category), .boundaryGap(false), .data(axisData.map { $0 as Jsonable }) )), .yAxis(Axis( .type(.value) )), .series([ GraphSerie( .layout(.none), .coordinateSystem(.cartesian2d), .symbolSize(40), .label(EmphasisLabel( .normal(LabelStyle( .show(true) )) )), .edgeSymbols([.circle, .arrow]), .edgeSymbolSize([4, 10]), .data(data.map { $0 as Jsonable }), .links(links), .lineStyle(EmphasisLineStyle( .normal(LineStyle( .color(.hexColor("#2f4554")) )) )) ) ]) ) } // MARK: Graph Life Expectancy /// 地址: http://echarts.baidu.com/demo.html#graph-life-expectancy static func graphLifeExpectancyOption() -> Option { // TODO: 添加实现 return Option( ) } // MARK: NPM Dependencies /// 地址: http://echarts.baidu.com/demo.html#graph-npm static func graphNpmOption() -> Option { guard let jsonUrl = Bundle.main.url(forResource: "npmdepgraph.min10", withExtension: "json"), let jsonData = try? Data(contentsOf: jsonUrl), let jsonObj = try? JSONSerialization.jsonObject(with: jsonData, options: []) else { return Option() } let json = jsonObj as! NSDictionary var data: [GraphSerie.Data] = [] (json["nodes"] as! NSArray).enumerateObjects({ (nodeObj, _, _) in let nodeDic = nodeObj as! NSDictionary let d = GraphSerie.Data() if let x = nodeDic["x"] as? Float { d.x = x } if let y = nodeDic["y"] as? Float { d.y = y } if let name = nodeDic["label"] as? String { d.name = name } if let size = nodeDic["size"] as? Float { d.symbolSize = FunctionOrFloatOrPair.value(size/2.0) } if let color = nodeDic["color"] as? String { d.itemStyle = ItemStyle( .normal(CommonItemStyleContent( .color(Color.hexColor(color)) )) ) } data.append(d) }) var edges: [GraphSerie.Link] = [] (json["edges"] as! NSArray).enumerateObjects({ (edgeObj, _, _) in let edgeDic = edgeObj as! NSDictionary let e = GraphSerie.Link() if let source = edgeDic["sourceID"] as? String { e.source = source } if let target = edgeDic["targetID"] as? String { e.target = target } edges.append(e) }) return Option( .title(Title( .text("NPM Dependencies") )), .animationDurationUpdate(1500), .animationEasingUpdate(.quinticInOut), .series([ GraphSerie( .layout(.none), .data(data.map { $0 as Jsonable }), .edges(edges), .label(EmphasisLabel( .emphasis(LabelStyle( .position(.right), .show(true) )) )), .roam(true), .focusNodeAdjacency(true), .lineStyle(EmphasisLineStyle( .normal(LineStyle( .width(0.5), .curveness(0.3), .opacity(0.7) )) )) ) ]) ) } // MARK: Graph 简单示例 /// 地址: http://echarts.baidu.com/demo.html#graph-simple static func graphSimpleOption() -> Option { return Option( .title(Title( .text("Graph 简单示例") )), .tooltip(Tooltip()), .animationDurationUpdate(1500), .animationEasingUpdate(.quinticInOut), .series([ GraphSerie( .layout(.none), .symbolSize(50), .roam(true), .label(EmphasisLabel( .normal(LabelStyle( .show(true) )) )), .edgeSymbols([.circle, .arrow]), .edgeSymbolSize([4, 10]), .edgeLabel(EmphasisLabel( .normal(LabelStyle( .fontSize(20) )) )), .data([ GraphSerie.Data( .name("节点1"), .x(300), .y(300) ), GraphSerie.Data( .name("节点2"), .x(800), .y(300) ), GraphSerie.Data( .name("节点3"), .x(550), .y(100) ), GraphSerie.Data( .name("节点4"), .x(550), .y(500) ), ]), .links([ GraphSerie.Link( .source(0), .target(1), .symbolSize([5, 20]), .label(EmphasisLabel( .normal(LabelStyle( .show(true) )) )), .lineStyle(EmphasisLineStyle( .normal(LineStyle( .width(5), .curveness(0.2) )) )) ), GraphSerie.Link( .source("节点2"), .target("节点1"), .label(EmphasisLabel( .normal(LabelStyle( .show(true) )) )), .lineStyle(EmphasisLineStyle( .normal(LineStyle( .curveness(0.2) )) )) ), GraphSerie.Link( .source("节点1"), .target("节点3") ), GraphSerie.Link( .source("节点2"), .target("节点3") ), GraphSerie.Link( .source("节点2"), .target("节点4") ), GraphSerie.Link( .source("节点1"), .target("节点4") ) ]), .lineStyle(EmphasisLineStyle( .normal(LineStyle( .opacity(0.9), .width(2), .curveness(0) )) )) ) ]) ) } // MARK: Graph Webkit Dep /// 地址: http://echarts.baidu.com/demo.html#graph-webkit-dep static func graphWebkitDepOption() -> Option { guard let jsonUrl = Bundle.main.url(forResource: "webkit-dep", withExtension: "json"), let jsonData = try? Data(contentsOf: jsonUrl), let jsonObj = try? JSONSerialization.jsonObject(with: jsonData, options: []) else { return Option() } let webkitDep = jsonObj as! NSDictionary var data: [Jsonable] = [] (webkitDep["nodes"] as! NSArray).enumerateObjects({ (nodeObj, idx, _) in let nodeDic = NSMutableDictionary(dictionary: (nodeObj as! NSDictionary)) nodeDic.setValue(idx, forKey: "id") data.append(nodeDic) }) var categories: [GraphSerie.Category] = [] (webkitDep["categories"] as! NSArray).enumerateObjects({ (categoryObj, _, _) in let categoryDic = categoryObj as! NSDictionary let category = GraphSerie.Category() if let name = categoryDic["name"] { category.name = (name as! String) } categories.append(category) }) var edges: [GraphSerie.Link] = [] (webkitDep["links"] as! NSArray).enumerateObjects({ (linkObj, _, _) in let linkDic = linkObj as! NSDictionary let link = GraphSerie.Link() link.target = (linkDic["target"] as! Jsonable) link.source = (linkDic["source"] as! Jsonable) edges.append(link) }) return Option( .legend(Legend( .data(["HTMLElement", "WebGL", "SVG", "CSS", "Other"]) )), .series([ GraphSerie( .layout(.force), .animation(false), .label(EmphasisLabel( .normal(LabelStyle( .position(.right), .formatter(.string("{b}")) )) )), .draggable(true), .data(data), .categories(categories), .force(GraphSerie.Force( .edgeLength(5), .repulsion(20), .gravity(0.2) )), .edges(edges) ) ]) ) } // MARK: Les Miserables /// 地址: http://echarts.baidu.com/demo.html#graph static func graphOption() -> Option { // TODO: 添加实现 return Option( ) } // MARK: Calendar Graph /// 地址: http://echarts.baidu.com/demo.html#calendar-graph static func calendarGraphOption() -> Option { let graphData: [Jsonable] = [ [ 1485878400000, 260 ], [ 1486137600000, 200 ], [ 1486569600000, 279 ], [ 1486915200000, 847 ], [ 1487347200000, 241 ], [ 1487779200000 + 3600 * 24 * 1000 * 15, 411 ], [ 1488124800000 + 3600 * 24 * 1000 * 23, 985 ] ] var links: [GraphSerie.Link] = [] for i in 0..<graphData.count { links.append(GraphSerie.Link( .source(i), .target(i+1) )) } links.removeLast() return Option( .tooltip(Tooltip()), .calendar(Calendar( .top(.middle), .left(.center), .cellSize(40), .yearLabel(YearLabel( .margin(50), .fontSize(30) )), .dayLabel(DayLabel( .firstDay(1), .nameMap("cn") )), .monthLabel(MonthLabel( .nameMap("cn"), .margin(15), .fontSize(20), .color("#999") )), .range(["2017-02", "2017-03-31"]) )), .visualMap(PiecewiseVisualMap( .min(0), .max(1000), .left(.center), .bottom(20), .inRange([ "color": ["#5291FF", "#C7DBFF"] ]), .seriesIndex([1]), .orient(.horizontal) )), .series([ GraphSerie( .edgeSymbols([.none, .arrow]), .coordinateSystem(.calendar), .links(links), .symbolSize(15), .calendarIndex(0), .itemStyle(ItemStyle( .normal(CommonItemStyleContent( .color(.yellow), .shadowBlur(9), .shadowOffsetX(1.5), .shadowOffsetY(3), .shadowColor(.hexColor("#555")) )) )), .lineStyle(EmphasisLineStyle( .normal(LineStyle( .color("#D10E00"), .width(1), .opacity(1) )) )), .data(graphData), .z(20) ), HeatmapSerie( .coordinateSystem(.calendar), .data(HeatmapOptions.getVirtualData(2017)) ) ]) ) } }
2b791e05cf80030c54f48827b6c013ee
32.579655
232
0.358274
false
false
false
false
ghfghfg23/SwiBLE
refs/heads/master
FakeCoreBluetooth/FakePeripheral.swift
mit
1
// // FakePeripheral.swift // SwiBLE // // Created by Andrey Ryabov on 16.11.16. // Copyright © 2016 Andrey Ryabov. All rights reserved. // import CoreBluetooth public class FakePeripheral: CBPeripheral { var fakeDelegate: CBPeripheralDelegate? var fakeIdentifier: UUID var fakeName: String? var fakeRssi: NSNumber? var fakeState: CBPeripheralState = .disconnected var fakeServices: [CBService]? init(uuid: UUID = UUID()) { self.fakeIdentifier = uuid super.init() FakePeripheral.dispose.append(self) } static var dispose = [FakePeripheral]() override public func readRSSI() { } override public func discoverServices(_ serviceUUIDs: [CBUUID]?) { } override public func discoverIncludedServices(_ includedServiceUUIDs: [CBUUID]?, for service: CBService) { } override public func discoverCharacteristics(_ characteristicUUIDs: [CBUUID]?, for service: CBService) { } override public func readValue(for characteristic: CBCharacteristic) { } override public func maximumWriteValueLength(for type: CBCharacteristicWriteType) -> Int { return 0 } override public func writeValue(_ data: Data, for characteristic: CBCharacteristic, type: CBCharacteristicWriteType) { } override public func setNotifyValue(_ enabled: Bool, for characteristic: CBCharacteristic) { } override public func discoverDescriptors(for characteristic: CBCharacteristic) { } override public func readValue(for descriptor: CBDescriptor) { } override public func writeValue(_ data: Data, for descriptor: CBDescriptor) { } override public func isEqual(_ object: Any?) -> Bool { guard let obj = object as? FakePeripheral else { return false } return obj.fakeIdentifier == self.fakeIdentifier } override public var identifier: UUID { get { return fakeIdentifier } } }
cb12fe46dfbc5e9ef7bd0fcb6fb4efcc
23.626506
110
0.659491
false
false
false
false
lexrus/LexNightmare
refs/heads/master
LexNightmare/GameViewControllerWithAds.swift
mit
1
// // GameViewControllerWithAds.swift // LexNightmare // // Created by Lex on 3/15/15. // Copyright (c) 2015 LexTang.com. All rights reserved. // import UIKit import StoreKit import iAd class GameViewControllerWithAds: GameViewController, SKProductsRequestDelegate, SKPaymentTransactionObserver , ADBannerViewDelegate { @IBOutlet weak var restoreButton: UIButton! @IBOutlet weak var removeAdsButton: UIButton! @IBOutlet weak var adBanner: ADBannerView! var inAppProductIdentifiers = NSSet() let removeAdsProductIdentifier = "com.LexTang.LexNightmare.remove_ads" override func viewDidLoad() { super.viewDidLoad() if GameDefaults.sharedDefaults.removeAds { removeAdsButton.hidden = true restoreButton.hidden = true adBanner.removeFromSuperview() } restoreButton.titleLabel!.text = NSLocalizedString("Restore previous purchase", comment: "Restore button title") removeAdsButton.titleLabel!.text = NSLocalizedString("Remove ads", comment: "Remove ads button title") SKPaymentQueue.defaultQueue().addTransactionObserver(self) } func fetchProducts() { if SKPaymentQueue.canMakePayments() { var productsRequest = SKProductsRequest(productIdentifiers: Set(arrayLiteral: removeAdsProductIdentifier) as Set<NSObject>) productsRequest.delegate = self productsRequest.start() } } func buyProduct(product: SKProduct) { println("Sending the Payment Request to Apple") var payment = SKPayment(product: product) SKPaymentQueue.defaultQueue().addPayment(payment) } @IBAction func restoreCompletedTransactions() { SKPaymentQueue.defaultQueue().restoreCompletedTransactions() } @IBAction func didTapRemoveAds(sender: UIButton) { fetchProducts() } func removeAds() { removeAdsButton.hidden = true restoreButton.hidden = true adBanner.hidden = true } // MARK: - Delegate methods of IAP func productsRequest(request: SKProductsRequest!, didReceiveResponse response: SKProductsResponse!) { var count = response.products.count if count > 0 { var validProducts = response.products var validProduct = response.products.first as! SKProduct! if validProduct.productIdentifier == removeAdsProductIdentifier { buyProduct(validProduct) } } } func request(request: SKRequest!, didFailWithError error: NSError!) { } func paymentQueue(queue: SKPaymentQueue!, updatedTransactions transactions: [AnyObject]!) { for transaction in transactions { if let trans = transaction as? SKPaymentTransaction { switch trans.transactionState { case .Purchased, .Restored: println("Product purchased.") SKPaymentQueue.defaultQueue().finishTransaction(trans) removeAds() break case .Purchased: self.restoreCompletedTransactions() SKPaymentQueue.defaultQueue().finishTransaction(trans) removeAds() case .Failed: SKPaymentQueue.defaultQueue().finishTransaction(trans) break default: () } } } } func paymentQueue(queue: SKPaymentQueue!, removedTransactions transactions: [AnyObject]!) { } // MARK: - Ad delegate func bannerViewDidLoadAd(banner: ADBannerView!) { banner.alpha = 1.0 } func bannerView(banner: ADBannerView!, didFailToReceiveAdWithError error: NSError!) { banner.alpha = 0.0 } }
6cb496ca4e561a569a146a8e8a36c2d7
31.487603
135
0.622234
false
false
false
false
laszlokorte/reform-swift
refs/heads/master
ReformCore/ReformCore/Axis.swift
mit
1
// // Axis.swift // ReformCore // // Created by Laszlo Korte on 21.08.15. // Copyright © 2015 Laszlo Korte. All rights reserved. // import ReformMath public enum RuntimeAxis : Equatable { case none case named(String, from: RuntimePoint, to: RuntimePoint) } extension RuntimeAxis { func getVectorFor<R:Runtime>(_ runtime: R) -> Vec2d? { switch self { case .none: return Vec2d() case .named(_, let from, let to): guard let start = from.getPositionFor(runtime), let end = to.getPositionFor(runtime) else { return nil } return normalize((end - start)) } } } public func ==(lhs: RuntimeAxis, rhs: RuntimeAxis) -> Bool { switch (lhs, rhs) { case (.none, .none): return true case (.named(let nameA, let fromA, let toA),.named(let nameB, let formB, let toB)): return nameA == nameB && fromA.isEqualTo(formB) && toA.isEqualTo(toB) default: return false } }
00bd5c4021304d40df11036c1307ae7b
25.538462
87
0.578744
false
false
false
false
vector-im/riot-ios
refs/heads/develop
Riot/Modules/KeyVerification/User/Start/UserVerificationStartViewModel.swift
apache-2.0
1
// File created from ScreenTemplate // $ createScreen.sh Start UserVerificationStart /* Copyright 2020 New Vector Ltd Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import Foundation enum UserVerificationStartViewModelError: Error { case keyVerificationRequestExpired } struct UserVerificationStartViewData { let userId: String let userDisplayName: String? let userAvatarURL: String? } final class UserVerificationStartViewModel: UserVerificationStartViewModelType { // MARK: - Properties // MARK: Private private let session: MXSession private let roomMember: MXRoomMember private let verificationManager: MXKeyVerificationManager private let keyVerificationService: KeyVerificationService private var keyVerificationRequest: MXKeyVerificationRequest? private var viewData: UserVerificationStartViewData { return UserVerificationStartViewData(userId: self.roomMember.userId, userDisplayName: self.roomMember.displayname, userAvatarURL: self.roomMember.avatarUrl) } // MARK: Public weak var viewDelegate: UserVerificationStartViewModelViewDelegate? weak var coordinatorDelegate: UserVerificationStartViewModelCoordinatorDelegate? // MARK: - Setup init(session: MXSession, roomMember: MXRoomMember) { self.session = session self.verificationManager = session.crypto.keyVerificationManager self.roomMember = roomMember self.keyVerificationService = KeyVerificationService() } deinit { } // MARK: - Public func process(viewAction: UserVerificationStartViewAction) { switch viewAction { case .loadData: self.loadData() case .startVerification: self.startVerification() case .cancel: self.cancelKeyVerificationRequest() self.coordinatorDelegate?.userVerificationStartViewModelDidCancel(self) } } // MARK: - Private private func loadData() { self.update(viewState: .loaded(self.viewData)) } private func startVerification() { self.update(viewState: .verificationPending) self.verificationManager.requestVerificationByDM(withUserId: self.roomMember.userId, roomId: nil, fallbackText: "", methods: self.keyVerificationService.supportedKeyVerificationMethods(), success: { [weak self] (keyVerificationRequest) in guard let self = self else { return } self.keyVerificationRequest = keyVerificationRequest self.update(viewState: .loaded(self.viewData)) self.registerKeyVerificationRequestDidChangeNotification(for: keyVerificationRequest) }, failure: { [weak self] error in self?.update(viewState: .error(error)) }) } private func update(viewState: UserVerificationStartViewState) { self.viewDelegate?.userVerificationStartViewModel(self, didUpdateViewState: viewState) } private func cancelKeyVerificationRequest() { guard let keyVerificationRequest = self.keyVerificationRequest else { return } keyVerificationRequest.cancel(with: MXTransactionCancelCode.user(), success: nil, failure: nil) } // MARK: - MXKeyVerificationRequestDidChange private func registerKeyVerificationRequestDidChangeNotification(for keyVerificationRequest: MXKeyVerificationRequest) { NotificationCenter.default.addObserver(self, selector: #selector(keyVerificationRequestDidChange(notification:)), name: .MXKeyVerificationRequestDidChange, object: keyVerificationRequest) } private func unregisterKeyVerificationRequestDidChangeNotification() { NotificationCenter.default.removeObserver(self, name: .MXKeyVerificationRequestDidChange, object: nil) } @objc private func keyVerificationRequestDidChange(notification: Notification) { guard let keyVerificationRequest = notification.object as? MXKeyVerificationByDMRequest else { return } guard let currentKeyVerificationRequest = self.keyVerificationRequest, keyVerificationRequest.requestId == currentKeyVerificationRequest.requestId else { return } switch keyVerificationRequest.state { case MXKeyVerificationRequestStateAccepted: self.unregisterKeyVerificationRequestDidChangeNotification() self.coordinatorDelegate?.userVerificationStartViewModel(self, otherDidAcceptRequest: currentKeyVerificationRequest) case MXKeyVerificationRequestStateReady: self.unregisterKeyVerificationRequestDidChangeNotification() self.coordinatorDelegate?.userVerificationStartViewModel(self, otherDidAcceptRequest: currentKeyVerificationRequest) case MXKeyVerificationRequestStateCancelled: guard let reason = keyVerificationRequest.reasonCancelCode else { return } self.unregisterKeyVerificationRequestDidChangeNotification() self.update(viewState: .cancelled(reason)) case MXKeyVerificationRequestStateCancelledByMe: guard let reason = keyVerificationRequest.reasonCancelCode else { return } self.unregisterKeyVerificationRequestDidChangeNotification() self.update(viewState: .cancelledByMe(reason)) case MXKeyVerificationRequestStateExpired: self.unregisterKeyVerificationRequestDidChangeNotification() self.update(viewState: .error(UserVerificationStartViewModelError.keyVerificationRequestExpired)) default: break } } }
57db682da1b0108487478a8e2ce2ed56
41.277778
195
0.656738
false
false
false
false
Eonil/EditorLegacy
refs/heads/trial1
Modules/Editor/Sources/Features/FileNavigating/FileTreeViewController3.swift
mit
2
//// //// FileTreeViewController3.swift //// RustCodeEditor //// //// Created by Hoon H. on 11/12/14. //// Copyright (c) 2014 Eonil. All rights reserved. //// // //import Foundation //import AppKit // //class FileTreeViewController3 : NSViewController, NSOutlineViewDataSource, NSOutlineViewDelegate { // // let userIsWantingToEditFileAtPath = Notifier<String>() // // private var _fileTreeRepository = FileTreeRepository3() // private var _channelsHolding = [] as [AnyObject] // // var URLRepresentation:NSURL? { // get { // return self.representedObject as NSURL? // } // set(v) { // self.representedObject = v // } // } // private func onError(e:NSError) { // NSAlert(error: e).runModal() // } // private func onAddingNodes(ns:[FileNode3]) { // let ns2 = ns.map({$0.supernode}).filter({$0 != nil}).map({$0!}) // let ns3 = deduplicate(ns2) // println(ns3) // // self.outlineView.beginUpdates() // for n in ns3 { // self.outlineView.reloadItem(n, reloadChildren: true) // } // self.outlineView.endUpdates() // } // private func onRemovingNodes(ns:[FileNode3]) { //// let ns2 = ns.map({$0.supernode}).filter({$0 != nil}).map({$0!}) //// let ns3 = deduplicate(ns2) //// //// self.outlineView.beginUpdates() //// for n in ns3 { //// self.outlineView.reloadItem(n, reloadChildren: true) //// } //// self.outlineView.endUpdates() // // self.outlineView.beginUpdates() // for n in ns { // let idx1 = self.outlineView.rowForItem(n) // self.outlineView.removeItemsAtIndexes(NSIndexSet(index: idx1), inParent: n.supernode!, withAnimation: NSTableViewAnimationOptions.EffectFade) // } // self.outlineView.endUpdates() // } // // // // // // // // // // // // // // // // override var representedObject:AnyObject? { // willSet(v) { // precondition(v is NSURL) // _fileTreeRepository.rootLocationURL = nil // } // didSet { // if let v3 = URLRepresentation { // _fileTreeRepository.rootLocationURL = v3 // } // self.outlineView.reloadData() // } // } // // var outlineView:NSOutlineView { // get { // return self.view as NSOutlineView // } // set(v) { // self.view = v // } // } // override func loadView() { // super.view = NSOutlineView() // } // override func viewDidLoad() { // super.viewDidLoad() // // let col1 = NSTableColumn(identifier: NAME, title: "Name", width: 100) // // outlineView.focusRingType = NSFocusRingType.None // outlineView.headerView = nil // outlineView.addTableColumn <<< col1 // outlineView.outlineTableColumn = col1 // outlineView.rowSizeStyle = NSTableViewRowSizeStyle.Small // outlineView.selectionHighlightStyle = NSTableViewSelectionHighlightStyle.SourceList // outlineView.sizeLastColumnToFit() // // outlineView.setDataSource(self) // outlineView.setDelegate(self) // // _channelsHolding = [ // channel(_fileTreeRepository.notifyError, onError), // channel(_fileTreeRepository.notifyAddingNodes, onAddingNodes), // channel(_fileTreeRepository.notifyRemovingNodes, onRemovingNodes), // ] // } // // // // //// func outlineView(outlineView: NSOutlineView, heightOfRowByItem item: AnyObject) -> CGFloat { //// return 16 //// } // // func outlineView(outlineView: NSOutlineView, numberOfChildrenOfItem item: AnyObject?) -> Int { // let n1 = item as FileNode3? // if let n2 = n1 { // return n2.subnodes.count // } else { // return _fileTreeRepository.rootNode == nil ? 0 : 1 // } // } // func outlineView(outlineView: NSOutlineView, child index: Int, ofItem item: AnyObject?) -> AnyObject { // let n1 = item as FileNode3? // if let n2 = n1 { // return n2.subnodes[index] // } else { // return _fileTreeRepository.rootNode! // } // } //// func outlineView(outlineView: NSOutlineView, isGroupItem item: AnyObject) -> Bool { //// let n1 = item as FileNode3 //// let ns2 = n1.subnodes //// return ns2 != nil //// } // func outlineView(outlineView: NSOutlineView, isItemExpandable item: AnyObject) -> Bool { // let n1 = item as FileNode3 // return n1.directory // } //// func outlineView(outlineView: NSOutlineView, objectValueForTableColumn tableColumn: NSTableColumn?, byItem item: AnyObject?) -> AnyObject? { //// let n1 = item as FileNode3 //// return n1.relativePath //// } // func outlineView(outlineView: NSOutlineView, viewForTableColumn tableColumn: NSTableColumn?, item: AnyObject) -> NSView? { // let tv1 = NSTextField() // let iv1 = NSImageView() // let cv1 = NSTableCellView() // cv1.textField = tv1 // cv1.imageView = iv1 // cv1.addSubview(tv1) // cv1.addSubview(iv1) // // let n1 = item as FileNode3 // assert(n1.existing) // iv1.image = NSWorkspace.sharedWorkspace().iconForFile(n1.absoluteURL.path!) // cv1.textField!.stringValue = n1.displayName // cv1.textField!.bordered = false // cv1.textField!.backgroundColor = NSColor.clearColor() // cv1.textField!.editable = false // (cv1.textField!.cell() as NSCell).lineBreakMode = NSLineBreakMode.ByTruncatingHead // return cv1 // } // // // // func outlineViewSelectionDidChange(notification: NSNotification) { //// let idx1 = self.outlineView.selectedRow //// let n1 = self.outlineView.itemAtRow(idx1) as FileNode3 //// userIsWantingToEditFileAtPath.signal(n1.absolutePath) // } //} // // // // // // // // // // // // // // // // // // // // // // // // // // //private let NAME = "NAME" // // // // // // // // // // // // // //
985dace9252bdf4239ba68c763c60c9a
23.0625
146
0.654731
false
false
false
false
KrishMunot/swift
refs/heads/master
test/SILGen/coverage_smoke.swift
apache-2.0
3
// RUN: rm -rf %t && mkdir %t // RUN: %target-build-swift %s -profile-generate -profile-coverage-mapping -o %t/main // RUN: env LLVM_PROFILE_FILE=%t/default.profraw %target-run %t/main // RUN: %llvm-profdata merge %t/default.profraw -o %t/default.profdata // RUN: %llvm-profdata show %t/default.profdata -function=main | FileCheck %s --check-prefix=CHECK-PROF // RUN: %llvm-cov show %t/main -instr-profile=%t/default.profdata | FileCheck %s --check-prefix=CHECK-COV // RUN: rm -rf %t // REQUIRES: profile_runtime // REQUIRES: OS=macosx // XFAIL: asan func main() { // CHECK-PROF: Counters: 2 // CHECK-PROF: Function count: 1 // CHECK-COV: 1|{{.*}}[[@LINE+1]]|{{.*}}if (true) if (true) {} } main()
9fabbd6c6ab3093d12e0bd79886d949a
34.1
105
0.663818
false
false
false
false
InsectQY/HelloSVU_Swift
refs/heads/master
HelloSVU_Swift/Classes/Expand/Tools/NetTool/QYRequestTool.swift
apache-2.0
1
// // QYRequestTool.swift // DouYuLive // // Created by Insect on 2017/4/9. // Copyright © 2017年 Insect. All rights reserved. // import UIKit import Alamofire import SwiftyJSON import HandyJSON enum MethodType { case GET case POST } class QYRequestTool { class func requestData(_ method: MethodType, _ URL: String, _ parameters: [String: Any]? = nil, successComplete: ((_ result: JSON) -> ())?, failureComplete: ((_ error: Error) -> ())?) { let requestType = method == .GET ? HTTPMethod.get: HTTPMethod.post // 请求头 // let headers: HTTPHeaders = [ // "Accept": "application/json", // "Accept": "text/javascript", // "Accept": "text/html", // "Accept": "text/plain" // ] Alamofire.request(URL, method: requestType, parameters: parameters).responseJSON { (response) in switch(response.result) { case .success(let Value): let json = JSON(Value) successComplete?(json) break case .failure(let error): failureComplete?(error) print("返回的错误信息是---\(error)") break } } } }
302217a40e0240d14929d9a58f1cd4c4
23.730769
189
0.521773
false
false
false
false
IngmarStein/swift
refs/heads/master
validation-test/compiler_crashers_fixed/01456-getselftypeforcontainer.swift
apache-2.0
11
// This source file is part of the Swift.org open source project // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -parse pe>(c>(Any, c: AnyObject) -> T! { } typealias B } let t: d = { case s(f) } class B : () { return """"A, object2) return [c<T> (b) -> { return nil self)) protocol b in x } let b { } let v: Int = c, object2) print() -> { } func b<d, object2: k) { return nil } } } } func a) convenience init(mx : (true } assert() for (start, 3] { return self.h: (() var a<c<U { typealias e : b = { extension A { func a } let start = A.c>) typealias d() (AnyObject.a() { x } case c: A { typealias e where T>(Any, object2) protocol P { return { _, length: Any, e: Hashable> { protocol a { typealias e = i: e: NSManagedObject { } class func g> U.f = compose("] var b> : A, q: } protocol A { typealias e : d where T : b> { var b in return self.d<T: e: String { import Foundation convenience init(t: b: Int { protocol b { enum a: (b> T) -> {} init(A<T> T { print(Any) -> Int = ") protocol d : a { b(") } class b() { init <T : () -> S<Y> T>?) {} } enum a func a(a() p
b13c99c364688c9f503c15b0dab30f97
17.287671
78
0.624719
false
false
false
false
SuperAwesomeLTD/sa-mobile-sdk-ios
refs/heads/develop
Pod/Classes/UI/Banner/BannerView.swift
lgpl-3.0
1
// // Banner.swift // SuperAwesome // // Created by Gunhan Sancar on 20/08/2020. // import UIKit /// Class that abstracts away the process of loading & displaying Banner type Ad. @objc(SABannerAd) public class BannerView: UIView, Injectable { private lazy var imageProvider: ImageProviderType = dependencies.resolve() private lazy var controller: AdControllerType = dependencies.resolve() private lazy var logger: LoggerType = dependencies.resolve(param: BannerView.self) private lazy var sknetworkManager: SKAdNetworkManager = dependencies.resolve() private var webView: WebView? private var padlock: UIButton? private var viewableDetector: ViewableDetectorType? private var hasBeenVisible: VoidBlock? private var moatRepository: MoatRepositoryType? public override init(frame: CGRect) { super.init(frame: frame) initialize() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) initialize() } // MARK: - Internal functions func configure(adResponse: AdResponse, delegate: AdEventCallback?, hasBeenVisible: VoidBlock?) { self.hasBeenVisible = hasBeenVisible setAdResponse(adResponse) setCallback(delegate) } // MARK: - Public functions /** * Method that loads an ad into the queue. * Ads can only be loaded once and then can be reloaded after they've * been played. * * - Parameter placementId: the Ad placement id to load data for */ @objc public func load(_ placementId: Int) { logger.info("load() for: \(placementId)") controller.load(placementId, makeAdRequest()) } public func getAd() -> Ad? { return controller.adResponse?.advert } /** * Method that loads an ad into the queue. * Ads can only be loaded once and then can be reloaded after they've * been played. * * - Parameters: * - placementId: the Ad placement id to load data for * - lineItemId: id of the line item * - creativeId: id of the creative */ @objc public func load(_ placementId: Int, lineItemId: Int, creativeId: Int) { logger.info("load() for placement Id: \(placementId) lineItemId: \(lineItemId), creativeId: \(creativeId)") controller.load(placementId, lineItemId: lineItemId, creativeId: creativeId, makeAdRequest()) } /// Method that, if an ad data is loaded, will play the content for the user @objc public func play() { logger.info("play()") // guard against invalid ad formats guard let adResponse = controller.adResponse, let html = adResponse.html, adResponse.advert.creative.format != CreativeFormatType.video, !controller.closed else { controller.adFailedToShow() return } addWebView() controller.triggerImpressionEvent() showPadlockIfNeeded() if #available(iOS 14.5, *) { sknetworkManager.startImpression(lineItemId: adResponse.advert.lineItemId, creativeId: adResponse.advert.creative.id) } let fullHtml = startMoat(adResponse: adResponse, html: html) webView?.loadHTML(fullHtml, withBase: adResponse.baseUrl, sourceSize: CGSize(width: adResponse.advert.creative.details.width, height: adResponse.advert.creative.details.height)) } private func startMoat(adResponse: AdResponse, html: String) -> String { moatRepository = dependencies.resolve(param: adResponse, controller.moatLimiting) as MoatRepositoryType let moatScript = moatRepository?.startMoatTracking(forDisplay: webView) return "\(html)\(moatScript ?? "")" } private func showPadlockIfNeeded() { guard controller.showPadlock, let webView = webView else { return } let padlock = UIButton(frame: CGRect.zero) padlock.translatesAutoresizingMaskIntoConstraints = false padlock.setImage(imageProvider.safeAdImage, for: .normal) padlock.addTarget(self, action: #selector(padlockAction), for: .touchUpInside) webView.addSubview(padlock) NSLayoutConstraint.activate([ padlock.widthAnchor.constraint(equalToConstant: 77.0), padlock.heightAnchor.constraint(equalToConstant: 31.0), padlock.leadingAnchor.constraint(equalTo: webView.safeLeadingAnchor, constant: 12.0), padlock.topAnchor.constraint(equalTo: webView.safeTopAnchor, constant: 12.0) ]) self.padlock = padlock } /// Method that is called to close the ad @objc public func close() { viewableDetector = nil _ = moatRepository?.stopMoatTrackingForDisplay() moatRepository = nil controller.close() removeWebView() if #available(iOS 14.5, *) { sknetworkManager.endImpression() } } /** * Method that returns whether ad data for a certain placement * has already been loaded * * @return true or false */ @objc public func hasAdAvailable() -> Bool { controller.adResponse != nil } /// Method that gets whether the banner is closed or not @objc public func isClosed() -> Bool { controller.closed } /// Callback function @objc public func setCallback(_ callback: AdEventCallback?) { controller.callback = callback } @objc public func setTestMode(_ value: Bool) { controller.testEnabled = value } @objc public func enableTestMode() { setTestMode(true) } @objc public func disableTestMode() { setTestMode(false) } @available(*, deprecated, message: "Use `AwesomeAds.initSDK()` to select configuration") @objc public func setConfigurationProduction() { } @available(*, deprecated, message: "Use `AwesomeAds.initSDK()` to select configuration") @objc public func setConfigurationStaging() { } @objc public func setParentalGate(_ value: Bool) { controller.parentalGateEnabled = value } @objc public func enableParentalGate() { setParentalGate(true) } @objc public func disableParentalGate() { setParentalGate(false) } @objc public func setBumperPage(_ value: Bool) { controller.bumperPageEnabled = value } @objc public func enableBumperPage() { setBumperPage(true) } @objc public func disableBumperPage() { setBumperPage(false) } @objc public func setColorTransparent() { setColor(true) } @objc public func setColorGray() { setColor(false) } @objc public func setColor(_ value: Bool) { backgroundColor = value ? UIColor.clear : Constants.backgroundGray } @objc public func disableMoatLimiting() { controller.moatLimiting = false } // MARK: - Private functions private func initialize() { setColor(false) } private func setAdResponse(_ adResponse: AdResponse) { controller.adResponse = adResponse } private func makeAdRequest() -> AdRequest { AdRequest(test: controller.testEnabled, position: AdRequest.Position.aboveTheFold, skip: AdRequest.Skip.no, playbackMethod: AdRequest.Playback.soundOn.rawValue, startDelay: AdRequest.StartDelay.preRoll, instl: AdRequest.FullScreen.off, width: Int(frame.size.width), height: Int(frame.size.height)) } private func addWebView() { removeWebView() webView = WebView(frame: CGRect.zero, configuration: WebView.defaultConfiguration()) if let view = webView { view.delegate = self view.translatesAutoresizingMaskIntoConstraints = false addSubview(view) let aspectRatio = controller.adResponse?.aspectRatio() ?? 1.0 logger.info("aspectRatio(): \(aspectRatio)") NSLayoutConstraint.activate([ view.widthAnchor.constraint(lessThanOrEqualTo: self.widthAnchor, multiplier: 1.0, constant: 0), view.heightAnchor.constraint(lessThanOrEqualTo: self.heightAnchor, multiplier: 1.0, constant: 0), view.centerXAnchor.constraint(equalTo: self.centerXAnchor, constant: 0), view.centerYAnchor.constraint(equalTo: self.centerYAnchor, constant: 0) ]) } } private func removeWebView() { padlock?.removeFromSuperview() padlock = nil webView?.removeFromSuperview() webView = nil } @objc private func padlockAction() { controller.handleSafeAdTap() } } extension BannerView: WebViewDelegate { func webViewOnStart() { logger.info("webViewOnStart") controller.adShown() viewableDetector = dependencies.resolve() as ViewableDetectorType viewableDetector?.start(for: self, hasBeenVisible: { [weak self] in self?.controller.triggerViewableImpression() self?.hasBeenVisible?() }) } func webViewOnError() { logger.info("webViewOnError") controller.adFailedToShow() } func webViewOnClick(url: URL) { logger.info("webViewOnClick") controller.handleAdTap(url: url) } }
5e2b1f19a280209366e005d6eaa7d579
32.106383
129
0.649207
false
false
false
false
alexander-ray/StudyOutlet
refs/heads/master
StudyOutlet/StudyOutlet/LoginViewController.swift
mit
1
// // LoginViewController.swift // StudyOutlet // // Created by Alex Ray on 4/8/17. // Copyright © 2017 StudyOutletGroup. All rights reserved. // import UIKit import Alamofire import SwiftyJSON let defaults = UserDefaults.standard // Headers for API requests var headers = [ "Content-Type": "application/x-www-form-urlencoded", "Authorization": "Bearer " + (defaults.string(forKey: "api_access_key") ?? "-1") // Set access key from user defaults, -1 if doesn't exist ] // Parameters for API requests var parameters = [ "email": "", "password": "" ] // Login view controller // Login page shown on app open class LoginViewController: UIViewController { // MARK: Outlets @IBOutlet weak var usernameField: UITextField! @IBOutlet weak var passwordField: UITextField! @IBOutlet weak var loginButton: UIButton! @IBOutlet weak var registerButton: UIButton! // Load view override func viewDidLoad() { super.viewDidLoad() } // Action on "login" button push @IBAction func sendCredentials (_ sender: UIButton) { // Setup let email = usernameField.text let password = passwordField.text let url = "https://studyoutlet.herokuapp.com/api/login" // Setting parameters for request parameters["email"] = email parameters["password"] = password // Request with url, JWT, and parameters Alamofire.request(url, method: .post, parameters: parameters, encoding: URLEncoding.default, headers: headers).responseString { response in // Reset parameters["email"] = "" parameters["password"] = "" // Convert response to string if let key = response.value { do { // If credentials are valid if (response.response?.statusCode == 200 && response.description != "SUCCESS: Invalid Credentials" && response.description != "SUCCESS: Missing username or password") { // Set api key for future use defaults.set(key, forKey: "api_access_key") // Update authorization header for API calls headers["Authorization"] = "Bearer " + key // Go to menu self.performSegue(withIdentifier: "MainMenu", sender: self) } else { // Set up "invalid login" alert let alert = UIAlertController(title: "Incorrect Login Credentials", message: "Please try again", preferredStyle: UIAlertControllerStyle.alert) // If incorrect credentials, send alert and reset fields let okAction = UIAlertAction(title: "Ok", style: UIAlertActionStyle.default) { (result : UIAlertAction) -> Void in self.usernameField.text = "" self.usernameField.becomeFirstResponder() self.passwordField.text = "" } alert.addAction(okAction) self.present(alert, animated: true, completion: nil) } } catch let error as NSError { print(error.localizedDescription) } } } } // Registration button push @IBAction func goToRegister(_ sender: UIButton) { // Go to register page self.performSegue(withIdentifier: "Register", sender: self) } }
337430f4bac4847eb0c1858b47bff1f6
37.208333
188
0.560796
false
false
false
false
Xinext/RemainderCalc
refs/heads/master
src/RemainderCalc/AdModMgr.swift
mit
1
// // AdModMgr.swift // import UIKit import GoogleMobileAds /** AdMod管理用 UIViewController - Author: xinext HF - Copyright: xinext - Date: 2017/09/24 - Version: 1.0.3 - Remark: ADMOD_UNITID 及び、ADMOD_TESTID を別途定義する必要があります。 それぞれのIDはGoogle AdModの仕様に従って取得してください。 また、リリース時は、ADMOD_TESTIDをセットしない様にTestModeをfalseへ設定してください。 */ class AdModMgr: UIViewController, GADBannerViewDelegate { // MARK: - Internal variable let adBannerView = GADBannerView(adSize:kGADAdSizeSmartBannerPortrait) // MARK: - Privet variable private var _contentsView: UIView! private var _layoutConstraint: NSLayoutConstraint? = nil enum DISP_POSITION: Int { case TOP = 0 case BOTTOM } // MARK: - Public method /** ADマネージャーの初期化 - parameter pvc: ADをつけるUIViewの親UIViewController - parameter cv: ADをつけるUIView(コンテナビュー) - parameter lc: 表示位置により上下どちらかのLayoutConstraintを渡す。 */ func InitManager(pvc: UIViewController, cv: UIView, lc: NSLayoutConstraint) { GADMobileAds.configure(withApplicationID: ADMOD_APPID) pvc.addChildViewController(self) _contentsView = cv _layoutConstraint = lc adBannerView.isHidden = true adBannerView.adUnitID = ADMOD_UNITID adBannerView.delegate = self adBannerView.rootViewController = self let gadRequest:GADRequest = GADRequest() #if false // Test mode gadRequest.testDevices = [ADMOD_TESTID] notifyDebugMode(pvc: pvc) #endif adBannerView.load(gadRequest) self.parent?.view.addSubview(adBannerView) } /** Display AdView. - parameter pos: DISP_POSITION - returns: nothing */ func DispAdView(pos: DISP_POSITION) { var rectBanner: CGRect let banner_x: CGFloat = 0.0 let banner_width: CGFloat = adBannerView.frame.size.width let banner_height: CGFloat = adBannerView.frame.size.height let banner_y: CGFloat switch pos { case DISP_POSITION.TOP: // バナーの縦位置 = メインコンテンツの縦位置 banner_y = _contentsView!.frame.origin.y default: // bottom // バナーの縦位置 = (メインコンテンツの高さ - バナーの高さ) + メインコンテンツの縦位置 banner_y = (_contentsView.frame.height - adBannerView.frame.size.height) + _contentsView.frame.origin.y } rectBanner = CGRect(x: banner_x, y: banner_y, width: banner_width, height: banner_height) adBannerView.frame = rectBanner if ( adBannerView.isHidden == true ) { _layoutConstraint?.constant += adBannerView.frame.size.height } else { // do nothign. } adBannerView.isHidden = false } /** Hide AdView. - parameter pos: DISP_POSITION - returns: nothing */ func HideAdView() { if ( adBannerView.isHidden == false ) { _layoutConstraint?.constant -= adBannerView.frame.size.height } else { // do nothign. } adBannerView.isHidden = true } // MARK: - private method private func notifyDebugMode( pvc: UIViewController ) { let alertController: UIAlertController = UIAlertController(title: "***注意***", message: "AdMod is debug mode.", preferredStyle: .alert) let actionOK = UIAlertAction(title: "OK", style: .default){ (action) -> Void in } alertController.addAction(actionOK) pvc.present(alertController, animated: true, completion: nil) } }
84407166617f253db030cdfe531c7d52
28.095238
142
0.608838
false
false
false
false
mattdaw/SwiftBoard
refs/heads/master
SwiftBoard/ViewModels/RootViewModel.swift
mit
1
// // RootViewModel.swift // SwiftBoard // // Created by Matt Daw on 2014-11-15. // Copyright (c) 2014 Matt Daw. All rights reserved. // import Foundation protocol RootViewModelDelegate: class { func rootViewModelFolderOpened(folderViewModel: FolderViewModel) func rootViewModelFolderClosed(folderViewModel: FolderViewModel) func rootViewModelWillMoveAppToFolder(appViewModel: AppViewModel, folderViewModel: FolderViewModel, open: Bool) func rootViewModelDidMoveAppToFolder(appViewModel: AppViewModel, folderViewModel: FolderViewModel, open: Bool) } class RootViewModel: ListViewModel { weak var rootViewModelDelegate: RootViewModelDelegate? var editingModeEnabled: Bool = false { didSet { for var i = 0; i < numberOfItems(); i++ { let item = itemAtIndex(i) item.editing = editingModeEnabled } } } private var openFolderViewModel: FolderViewModel? { didSet { let zoomed = openFolderViewModel != nil for var i = 0; i < numberOfItems(); i++ { let item = itemAtIndex(i) item.zoomed = zoomed } } } func moveAppToFolder(appViewModel: AppViewModel, folderViewModel: FolderViewModel, open: Bool) { if let index = indexOfItem(appViewModel) { rootViewModelDelegate?.rootViewModelWillMoveAppToFolder(appViewModel, folderViewModel: folderViewModel, open: open) let addIndex = folderViewModel.numberOfItems() appViewModel.parentListViewModel = folderViewModel removeItemAtIndex(index) folderViewModel.appendItem(appViewModel) if open { openFolder(folderViewModel) } rootViewModelDelegate?.rootViewModelDidMoveAppToFolder(appViewModel, folderViewModel: folderViewModel, open: open) } else { assertionFailure("moveAppToFolder: AppViewModel isn't in the RootViewModel") } } func moveAppFromFolder(appViewModel: AppViewModel, folderViewModel: FolderViewModel) { if let removeIndex = folderViewModel.indexOfItem(appViewModel) { let addIndex = numberOfItems() appViewModel.parentListViewModel = self folderViewModel.removeItemAtIndex(removeIndex) appendItem(appViewModel) } else { assertionFailure("moveAppFromFolder: AppViewModel isn't in the FolderViewModel") } } func openFolder(folderViewModel: FolderViewModel) { if openFolderViewModel == nil { openFolderViewModel = folderViewModel folderViewModel.state = .Open rootViewModelDelegate?.rootViewModelFolderOpened(folderViewModel) } else { assertionFailure("openFolder: Tried to open a folder when another is open.") } } func closeFolder(folderViewModel: FolderViewModel) { if openFolderViewModel != nil { openFolderViewModel = nil folderViewModel.state = .Closed rootViewModelDelegate?.rootViewModelFolderClosed(folderViewModel) } else { assertionFailure("closeFolder: Tried to close a folder when no folder is open.") } } }
d46a20600272e1c9053f3cc062446003
34.863158
127
0.636524
false
false
false
false
OscarSwanros/swift
refs/heads/master
stdlib/public/core/StringLegacy.swift
apache-2.0
2
//===----------------------------------------------------------------------===// // // 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 // //===----------------------------------------------------------------------===// import SwiftShims extension String { /// Creates a new string representing the given string repeated the specified /// number of times. /// /// For example, you can use this initializer to create a string with ten /// `"ab"` strings in a row. /// /// let s = String(repeating: "ab", count: 10) /// print(s) /// // Prints "abababababababababab" /// /// - Parameters: /// - repeatedValue: The string to repeat. /// - count: The number of times to repeat `repeatedValue` in the resulting /// string. @_inlineable // FIXME(sil-serialize-all) public init(repeating repeatedValue: String, count: Int) { if count == 0 { self = "" return } precondition(count > 0, "Negative count not allowed") let s = repeatedValue self = String(_storage: _StringBuffer( capacity: s._core.count * count, initialSize: 0, elementWidth: s._core.elementWidth)) for _ in 0..<count { self += s } } /// A Boolean value indicating whether a string has no characters. @_inlineable // FIXME(sil-serialize-all) public var isEmpty: Bool { return _core.count == 0 } } extension String { @_inlineable // FIXME(sil-serialize-all) public init(_ _c: Unicode.Scalar) { self = String._fromWellFormedCodeUnitSequence( UTF32.self, input: repeatElement(_c.value, count: 1)) } } #if _runtime(_ObjC) /// Determines if `theString` starts with `prefix` comparing the strings under /// canonical equivalence. @_inlineable // FIXME(sil-serialize-all) @_versioned // FIXME(sil-serialize-all) @_silgen_name("swift_stdlib_NSStringHasPrefixNFD") internal func _stdlib_NSStringHasPrefixNFD( _ theString: AnyObject, _ prefix: AnyObject) -> Bool @_inlineable // FIXME(sil-serialize-all) @_versioned // FIXME(sil-serialize-all) @_silgen_name("swift_stdlib_NSStringHasPrefixNFDPointer") internal func _stdlib_NSStringHasPrefixNFDPointer( _ theString: OpaquePointer, _ prefix: OpaquePointer) -> Bool /// Determines if `theString` ends with `suffix` comparing the strings under /// canonical equivalence. @_inlineable // FIXME(sil-serialize-all) @_versioned // FIXME(sil-serialize-all) @_silgen_name("swift_stdlib_NSStringHasSuffixNFD") internal func _stdlib_NSStringHasSuffixNFD( _ theString: AnyObject, _ suffix: AnyObject) -> Bool @_inlineable // FIXME(sil-serialize-all) @_versioned // FIXME(sil-serialize-all) @_silgen_name("swift_stdlib_NSStringHasSuffixNFDPointer") internal func _stdlib_NSStringHasSuffixNFDPointer( _ theString: OpaquePointer, _ suffix: OpaquePointer) -> Bool extension String { /// Returns a Boolean value indicating whether the string begins with the /// specified prefix. /// /// The comparison is both case sensitive and Unicode safe. The /// case-sensitive comparison will only match strings whose corresponding /// characters have the same case. /// /// let cafe = "Café du Monde" /// /// // Case sensitive /// print(cafe.hasPrefix("café")) /// // Prints "false" /// /// The Unicode-safe comparison matches Unicode scalar values rather than the /// code points used to compose them. The example below uses two strings /// with different forms of the `"é"` character---the first uses the composed /// form and the second uses the decomposed form. /// /// // Unicode safe /// let composedCafe = "Café" /// let decomposedCafe = "Cafe\u{0301}" /// /// print(cafe.hasPrefix(composedCafe)) /// // Prints "true" /// print(cafe.hasPrefix(decomposedCafe)) /// // Prints "true" /// /// - Parameter prefix: A possible prefix to test against this string. /// - Returns: `true` if the string begins with `prefix`; otherwise, `false`. @_inlineable // FIXME(sil-serialize-all) public func hasPrefix(_ prefix: String) -> Bool { let selfCore = self._core let prefixCore = prefix._core let prefixCount = prefixCore.count if prefixCount == 0 { return true } if let selfASCIIBuffer = selfCore.asciiBuffer, let prefixASCIIBuffer = prefixCore.asciiBuffer { if prefixASCIIBuffer.count > selfASCIIBuffer.count { // Prefix is longer than self. return false } return _swift_stdlib_memcmp( selfASCIIBuffer.baseAddress!, prefixASCIIBuffer.baseAddress!, prefixASCIIBuffer.count) == (0 as CInt) } if selfCore.hasContiguousStorage && prefixCore.hasContiguousStorage { let lhsStr = _NSContiguousString(selfCore) let rhsStr = _NSContiguousString(prefixCore) return lhsStr._unsafeWithNotEscapedSelfPointerPair(rhsStr) { return _stdlib_NSStringHasPrefixNFDPointer($0, $1) } } return _stdlib_NSStringHasPrefixNFD( self._bridgeToObjectiveCImpl(), prefix._bridgeToObjectiveCImpl()) } /// Returns a Boolean value indicating whether the string ends with the /// specified suffix. /// /// The comparison is both case sensitive and Unicode safe. The /// case-sensitive comparison will only match strings whose corresponding /// characters have the same case. /// /// let plans = "Let's meet at the café" /// /// // Case sensitive /// print(plans.hasSuffix("Café")) /// // Prints "false" /// /// The Unicode-safe comparison matches Unicode scalar values rather than the /// code points used to compose them. The example below uses two strings /// with different forms of the `"é"` character---the first uses the composed /// form and the second uses the decomposed form. /// /// // Unicode safe /// let composedCafe = "café" /// let decomposedCafe = "cafe\u{0301}" /// /// print(plans.hasSuffix(composedCafe)) /// // Prints "true" /// print(plans.hasSuffix(decomposedCafe)) /// // Prints "true" /// /// - Parameter suffix: A possible suffix to test against this string. /// - Returns: `true` if the string ends with `suffix`; otherwise, `false`. @_inlineable // FIXME(sil-serialize-all) public func hasSuffix(_ suffix: String) -> Bool { let selfCore = self._core let suffixCore = suffix._core let suffixCount = suffixCore.count if suffixCount == 0 { return true } if let selfASCIIBuffer = selfCore.asciiBuffer, let suffixASCIIBuffer = suffixCore.asciiBuffer { if suffixASCIIBuffer.count > selfASCIIBuffer.count { // Suffix is longer than self. return false } return _swift_stdlib_memcmp( selfASCIIBuffer.baseAddress! + (selfASCIIBuffer.count - suffixASCIIBuffer.count), suffixASCIIBuffer.baseAddress!, suffixASCIIBuffer.count) == (0 as CInt) } if selfCore.hasContiguousStorage && suffixCore.hasContiguousStorage { let lhsStr = _NSContiguousString(selfCore) let rhsStr = _NSContiguousString(suffixCore) return lhsStr._unsafeWithNotEscapedSelfPointerPair(rhsStr) { return _stdlib_NSStringHasSuffixNFDPointer($0, $1) } } return _stdlib_NSStringHasSuffixNFD( self._bridgeToObjectiveCImpl(), suffix._bridgeToObjectiveCImpl()) } } #else // FIXME: Implement hasPrefix and hasSuffix without objc // rdar://problem/18878343 #endif // Conversions to string from other types. extension String { /// Creates a string representing the given value in base 10, or some other /// specified base. /// /// The following example converts the maximal `Int` value to a string and /// prints its length: /// /// let max = String(Int.max) /// print("\(max) has \(max.count) digits.") /// // Prints "9223372036854775807 has 19 digits." /// /// Numerals greater than 9 are represented as Roman letters. These letters /// start with `"A"` if `uppercase` is `true`; otherwise, with `"a"`. /// /// let v = 999_999 /// print(String(v, radix: 2)) /// // Prints "11110100001000111111" /// /// print(String(v, radix: 16)) /// // Prints "f423f" /// print(String(v, radix: 16, uppercase: true)) /// // Prints "F423F" /// /// - Parameters: /// - value: The value to convert to a string. /// - radix: The base to use for the string representation. `radix` must be /// at least 2 and at most 36. The default is 10. /// - uppercase: Pass `true` to use uppercase letters to represent numerals /// greater than 9, or `false` to use lowercase letters. The default is /// `false`. // FIXME(integers): support a more general BinaryInteger protocol // FIXME(integers): support larger bitwidths than 64 @_inlineable // FIXME(sil-serialize-all) public init<T : FixedWidthInteger>( _ value: T, radix: Int = 10, uppercase: Bool = false ) { _precondition(radix > 1, "Radix must be greater than 1") self = _int64ToString( Int64(value), radix: Int64(radix), uppercase: uppercase) } /// Creates a string representing the given value in base 10, or some other /// specified base. /// /// The following example converts the maximal `Int` value to a string and /// prints its length: /// /// let max = String(Int.max) /// print("\(max) has \(max.count) digits.") /// // Prints "9223372036854775807 has 19 digits." /// /// Numerals greater than 9 are represented as Roman letters. These letters /// start with `"A"` if `uppercase` is `true`; otherwise, with `"a"`. /// /// let v = 999_999 /// print(String(v, radix: 2)) /// // Prints "11110100001000111111" /// /// print(String(v, radix: 16)) /// // Prints "f423f" /// print(String(v, radix: 16, uppercase: true)) /// // Prints "F423F" /// /// - Parameters: /// - value: The value to convert to a string. /// - radix: The base to use for the string representation. `radix` must be /// at least 2 and at most 36. The default is 10. /// - uppercase: Pass `true` to use uppercase letters to represent numerals /// greater than 9, or `false` to use lowercase letters. The default is /// `false`. // FIXME(integers): tiebreaker between T : FixedWidthInteger and other obsoleted @_inlineable // FIXME(sil-serialize-all) @available(swift, obsoleted: 4) public init<T : FixedWidthInteger>( _ value: T, radix: Int = 10, uppercase: Bool = false ) where T : SignedInteger { _precondition(radix > 1, "Radix must be greater than 1") self = _int64ToString( Int64(value), radix: Int64(radix), uppercase: uppercase) } /// Creates a string representing the given value in base 10, or some other /// specified base. /// /// The following example converts the maximal `Int` value to a string and /// prints its length: /// /// let max = String(Int.max) /// print("\(max) has \(max.count) digits.") /// // Prints "9223372036854775807 has 19 digits." /// /// Numerals greater than 9 are represented as Roman letters. These letters /// start with `"A"` if `uppercase` is `true`; otherwise, with `"a"`. /// /// let v: UInt = 999_999 /// print(String(v, radix: 2)) /// // Prints "11110100001000111111" /// /// print(String(v, radix: 16)) /// // Prints "f423f" /// print(String(v, radix: 16, uppercase: true)) /// // Prints "F423F" /// /// - Parameters: /// - value: The value to convert to a string. /// - radix: The base to use for the string representation. `radix` must be /// at least 2 and at most 36. The default is 10. /// - uppercase: Pass `true` to use uppercase letters to represent numerals /// greater than 9, or `false` to use lowercase letters. The default is /// `false`. // FIXME(integers): support a more general BinaryInteger protocol @_inlineable // FIXME(sil-serialize-all) public init<T : FixedWidthInteger>( _ value: T, radix: Int = 10, uppercase: Bool = false ) where T : UnsignedInteger { _precondition(radix > 1, "Radix must be greater than 1") self = _uint64ToString( UInt64(value), radix: Int64(radix), uppercase: uppercase) } /// Creates a string representing the given value in base 10, or some other /// specified base. /// /// The following example converts the maximal `Int` value to a string and /// prints its length: /// /// let max = String(Int.max) /// print("\(max) has \(max.count) digits.") /// // Prints "9223372036854775807 has 19 digits." /// /// Numerals greater than 9 are represented as Roman letters. These letters /// start with `"A"` if `uppercase` is `true`; otherwise, with `"a"`. /// /// let v = 999_999 /// print(String(v, radix: 2)) /// // Prints "11110100001000111111" /// /// print(String(v, radix: 16)) /// // Prints "f423f" /// print(String(v, radix: 16, uppercase: true)) /// // Prints "F423F" /// /// - Parameters: /// - value: The value to convert to a string. /// - radix: The base to use for the string representation. `radix` must be /// at least 2 and at most 36. The default is 10. /// - uppercase: Pass `true` to use uppercase letters to represent numerals /// greater than 9, or `false` to use lowercase letters. The default is /// `false`. @_inlineable // FIXME(sil-serialize-all) @available(swift, obsoleted: 4, message: "Please use the version for FixedWidthInteger instead.") public init<T : SignedInteger>( _ value: T, radix: Int = 10, uppercase: Bool = false ) { _precondition(radix > 1, "Radix must be greater than 1") self = _int64ToString( Int64(value), radix: Int64(radix), uppercase: uppercase) } /// Creates a string representing the given value in base 10, or some other /// specified base. /// /// The following example converts the maximal `Int` value to a string and /// prints its length: /// /// let max = String(Int.max) /// print("\(max) has \(max.count) digits.") /// // Prints "9223372036854775807 has 19 digits." /// /// Numerals greater than 9 are represented as Roman letters. These letters /// start with `"A"` if `uppercase` is `true`; otherwise, with `"a"`. /// /// let v: UInt = 999_999 /// print(String(v, radix: 2)) /// // Prints "11110100001000111111" /// /// print(String(v, radix: 16)) /// // Prints "f423f" /// print(String(v, radix: 16, uppercase: true)) /// // Prints "F423F" /// /// - Parameters: /// - value: The value to convert to a string. /// - radix: The base to use for the string representation. `radix` must be /// at least 2 and at most 36. The default is 10. /// - uppercase: Pass `true` to use uppercase letters to represent numerals /// greater than 9, or `false` to use lowercase letters. The default is /// `false`. @_inlineable // FIXME(sil-serialize-all) @available(swift, obsoleted: 4, message: "Please use the version for FixedWidthInteger instead.") public init<T : UnsignedInteger>( _ value: T, radix: Int = 10, uppercase: Bool = false ) { _precondition(radix > 1, "Radix must be greater than 1") self = _uint64ToString( UInt64(value), radix: Int64(radix), uppercase: uppercase) } }
a9becccebcfcab3f6facfdb7ff177ff8
37.074879
99
0.635793
false
false
false
false
UW-AppDEV/AUXWave
refs/heads/master
AUXWave/MediaItemExporter.swift
gpl-2.0
1
// // MediaItemExporter.swift // AUXWave // // Created by Nico Cvitak on 2015-03-15. // Copyright (c) 2015 UW-AppDEV. All rights reserved. // import UIKit import AVFoundation import MediaPlayer class MediaItemExporter: NSObject { private var exportSession: AVAssetExportSession var progress: Float { return exportSession.progress } var status: AVAssetExportSessionStatus { return exportSession.status } var error: NSError! { return exportSession.error } var estimatedOutputFileLength: Int64 { return exportSession.estimatedOutputFileLength } var m4aOutputURL: NSURL! { set { exportSession.outputURL = newValue } get { return exportSession.outputURL } } init(mediaItem: MPMediaItem) { self.exportSession = AVAssetExportSession(asset: AVURLAsset(URL: mediaItem.assetURL, options: nil), presetName: AVAssetExportPresetAppleM4A) super.init() let titleMetadataItem = AVMutableMetadataItem() titleMetadataItem.keySpace = AVMetadataKeySpaceCommon titleMetadataItem.key = AVMetadataCommonKeyTitle titleMetadataItem.value = mediaItem.title let artistMetadataItem = AVMutableMetadataItem() artistMetadataItem.keySpace = AVMetadataKeySpaceCommon artistMetadataItem.key = AVMetadataCommonKeyArtist artistMetadataItem.value = mediaItem.artist let albumNameMetadataItem = AVMutableMetadataItem() albumNameMetadataItem.keySpace = AVMetadataKeySpaceCommon albumNameMetadataItem.key = AVMetadataCommonKeyAlbumName albumNameMetadataItem.value = mediaItem.albumTitle let artworkMetadataItem = AVMutableMetadataItem() artworkMetadataItem.keySpace = AVMetadataKeySpaceCommon artworkMetadataItem.key = AVMetadataCommonKeyArtwork artworkMetadataItem.value = UIImageJPEGRepresentation(mediaItem.artwork.imageWithSize(kAlbumArtworkSize), 0.5) exportSession.outputFileType = AVFileTypeAppleM4A exportSession.metadata = [ titleMetadataItem, artistMetadataItem, albumNameMetadataItem, artworkMetadataItem ] } func exportAsynchronouslyWithCompletionHandler(handler: (() -> Void)!) { exportSession.exportAsynchronouslyWithCompletionHandler(handler) } func cancelExport() { exportSession.cancelExport() } }
3707bb54210f50501b2c8ac08caa79be
29.951807
148
0.681199
false
false
false
false
siyana/SwiftMaps
refs/heads/master
PhotoMaps/PhotoMaps/HomeScreenTableViewController.swift
mit
1
// // HomeScreenTableViewController.swift // PhotoMaps // // Created by Siyana Slavova on 4/8/15. // Copyright (c) 2015 Siyana Slavova. All rights reserved. // import UIKit struct CellHeigh { static let LandscapeCellHeigh:CGFloat = (UIScreen.mainScreen().bounds.width) / 3 static let PortraitCellHeigh:CGFloat = (UIScreen.mainScreen().bounds.height) / 3 } class HomeScreenTableViewController: UITableViewController { @IBOutlet weak var placesImagesCollectionView: UICollectionView! let collectionViewController = PlacesImagesCollectionViewController() override func viewDidLoad() { super.viewDidLoad() self.clearsSelectionOnViewWillAppear = true collectionViewController.presenter = self self.placesImagesCollectionView.delegate = collectionViewController self.placesImagesCollectionView.dataSource = collectionViewController // Uncomment the following line to display an Edit button in the navigation bar for this view controller. // self.navigationItem.rightBarButtonItem = self.editButtonItem() } //MARK: Table View Delegate override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { var result: CGFloat switch UIDevice.currentDevice().orientation{ case .LandscapeLeft, .LandscapeRight: result = CellHeigh.LandscapeCellHeigh default: result = CellHeigh.PortraitCellHeigh } return result } }
64bf62843ce22a70cf07daa39213a701
30.938776
113
0.70607
false
false
false
false
felipesantolim/e-Deploy_Test
refs/heads/master
e-deploy/e-deploy/View/EPLYDetailsView.swift
mit
1
// // EPLYDetailsView.swift // e-deploy // // Created by Felipe Henrique Santolim on 03/10/17. // Copyright © 2017 Felipe Santolim. All rights reserved. // import UIKit final class EPLYDetailsView: UIView { fileprivate let labelDescription: UILabel = { let view = UILabel() view.translatesAutoresizingMaskIntoConstraints = false view.numberOfLines = 0 view.text = "" view.font = UIFont.applyOpificioBoldFontStyle(size: 18.0) return view }() override func layoutSubviews() { super.layoutSubviews() layout() } } // MARK: - Layout - extension EPLYDetailsView { fileprivate func layout() { self.addSubview(labelDescription) /* LabelDescription setup */ labelDescription.topAnchor.constraint(equalTo: self.topAnchor, constant:30).isActive = true labelDescription.leadingAnchor.constraint(equalTo: self.leadingAnchor, constant: 20).isActive = true labelDescription.heightAnchor.constraint(equalToConstant: 80).isActive = true labelDescription.trailingAnchor.constraint(equalTo: self.trailingAnchor, constant: -20).isActive = true } } // MARK: - Setup - extension EPLYDetailsView { public func configure(_ city: String, desc: String) { let paragraphStyle = NSMutableParagraphStyle() paragraphStyle.lineSpacing = 10 let attrString = NSMutableAttributedString(string: "A pontuação da Cidade \(city) é \(desc)") attrString.addAttribute(NSAttributedStringKey.paragraphStyle, value:paragraphStyle, range:NSMakeRange(0, attrString.length)) labelDescription.attributedText = attrString labelDescription.textAlignment = .center } }
2cfecb34ce89f649a794cbe7ebb8f0e8
30.192982
132
0.676603
false
false
false
false
AgentFeeble/pgoapi
refs/heads/Swift3.0
Example/Pods/ProtocolBuffers-Swift/Source/AbstractMessage.swift
apache-2.0
2
// Protocol Buffers for Swift // // Copyright 2014 Alexey Khohklov(AlexeyXo). // Copyright 2008 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License") // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import Foundation public typealias ONEOF_NOT_SET = Int public protocol ProtocolBuffersMessageInit { } public enum ProtocolBuffersError: Error { case obvious(String) //Streams case invalidProtocolBuffer(String) case illegalState(String) case illegalArgument(String) case outOfSpace } public protocol ProtocolBuffersMessage:ProtocolBuffersMessageInit { var unknownFields:UnknownFieldSet{get} func serializedSize() -> Int32 func isInitialized() -> Bool func writeTo(codedOutputStream:CodedOutputStream) throws func writeTo(outputStream:OutputStream) throws func data() throws -> Data static func classBuilder()-> ProtocolBuffersMessageBuilder func classBuilder()-> ProtocolBuffersMessageBuilder //JSON func encode() throws -> Dictionary<String,Any> static func decode(jsonMap:Dictionary<String,Any>) throws -> Self func toJSON() throws -> Data static func fromJSON(data:Data) throws -> Self } public protocol ProtocolBuffersMessageBuilder { var unknownFields:UnknownFieldSet{get set} func clear() -> Self func isInitialized()-> Bool func build() throws -> AbstractProtocolBuffersMessage func merge(unknownField:UnknownFieldSet) throws -> Self func mergeFrom(codedInputStream:CodedInputStream) throws -> Self func mergeFrom(codedInputStream:CodedInputStream, extensionRegistry:ExtensionRegistry) throws -> Self func mergeFrom(data:Data) throws -> Self func mergeFrom(data:Data, extensionRegistry:ExtensionRegistry) throws -> Self func mergeFrom(inputStream:InputStream) throws -> Self func mergeFrom(inputStream:InputStream, extensionRegistry:ExtensionRegistry) throws -> Self //Delimited Encoding/Decoding func mergeDelimitedFrom(inputStream:InputStream) throws -> Self? static func decodeToBuilder(jsonMap:Dictionary<String,AnyObject>) throws -> Self static func fromJSONToBuilder(data:Data) throws -> Self } public func == (lhs: AbstractProtocolBuffersMessage, rhs: AbstractProtocolBuffersMessage) -> Bool { return lhs.hashValue == rhs.hashValue } open class AbstractProtocolBuffersMessage:Hashable, ProtocolBuffersMessage { public var unknownFields:UnknownFieldSet required public init() { unknownFields = UnknownFieldSet(fields: Dictionary()) } final public func data() -> Data { let ser_size = serializedSize() let data = Data(count: Int(ser_size)) let stream:CodedOutputStream = CodedOutputStream(data: data) do { try writeTo(codedOutputStream: stream) } catch {} return stream.buffer.buffer } open func isInitialized() -> Bool { return false } open func serializedSize() -> Int32 { return 0 } open func getDescription(indent:String) throws -> String { throw ProtocolBuffersError.obvious("Override") } open func writeTo(codedOutputStream: CodedOutputStream) throws { throw ProtocolBuffersError.obvious("Override") } final public func writeTo(outputStream: OutputStream) throws { let codedOutput:CodedOutputStream = CodedOutputStream(stream:outputStream) try! writeTo(codedOutputStream: codedOutput) try codedOutput.flush() } public func writeDelimitedTo(outputStream: OutputStream) throws { let serializedDataSize = serializedSize() let codedOutputStream = CodedOutputStream(stream: outputStream) try codedOutputStream.writeRawVarint32(value: serializedDataSize) try writeTo(codedOutputStream: codedOutputStream) try codedOutputStream.flush() } open class func classBuilder() -> ProtocolBuffersMessageBuilder { return AbstractProtocolBuffersMessageBuilder() } open func classBuilder() -> ProtocolBuffersMessageBuilder { return AbstractProtocolBuffersMessageBuilder() } open var hashValue: Int { get { return unknownFields.hashValue } } //JSON open func encode() throws -> Dictionary<String, Any> { throw ProtocolBuffersError.obvious("JSON Encoding/Decoding available only in syntax=\"proto3\"") } open class func decode(jsonMap: Dictionary<String, Any>) throws -> Self { throw ProtocolBuffersError.obvious("JSON Encoding/Decoding available only in syntax=\"proto3\"") } open func toJSON() throws -> Data { let json = try JSONSerialization.data(withJSONObject: encode(), options: JSONSerialization.WritingOptions(rawValue: 0)) return json } open class func fromJSON(data:Data) throws -> Self { throw ProtocolBuffersError.obvious("JSON Encoding/Decoding available only in syntax=\"proto3\"") } } open class AbstractProtocolBuffersMessageBuilder:ProtocolBuffersMessageBuilder { open var unknownFields:UnknownFieldSet public init() { unknownFields = UnknownFieldSet(fields:Dictionary()) } open func build() throws -> AbstractProtocolBuffersMessage { return AbstractProtocolBuffersMessage() } open func clone() throws -> Self { return self } open func clear() -> Self { return self } open func isInitialized() -> Bool { return false } open func mergeFrom(codedInputStream:CodedInputStream) throws -> Self { return try mergeFrom(codedInputStream: codedInputStream, extensionRegistry:ExtensionRegistry()) } open func mergeFrom(codedInputStream:CodedInputStream, extensionRegistry:ExtensionRegistry) throws -> Self { throw ProtocolBuffersError.obvious("Override") } open func merge(unknownField: UnknownFieldSet) throws -> Self { let merged:UnknownFieldSet = try UnknownFieldSet.builderWithUnknownFields(copyFrom: unknownFields).merge(unknownFields: unknownField).build() unknownFields = merged return self } final public func mergeFrom(data:Data) throws -> Self { let input:CodedInputStream = CodedInputStream(data:data) _ = try mergeFrom(codedInputStream: input) try input.checkLastTagWas(value: 0) return self } final public func mergeFrom(data:Data, extensionRegistry:ExtensionRegistry) throws -> Self { let input:CodedInputStream = CodedInputStream(data:data) _ = try mergeFrom(codedInputStream: input, extensionRegistry:extensionRegistry) try input.checkLastTagWas(value: 0) return self } final public func mergeFrom(inputStream: InputStream) throws -> Self { let codedInput:CodedInputStream = CodedInputStream(stream: inputStream) _ = try mergeFrom(codedInputStream: codedInput) try codedInput.checkLastTagWas(value: 0) return self } final public func mergeFrom(inputStream: InputStream, extensionRegistry:ExtensionRegistry) throws -> Self { let codedInput:CodedInputStream = CodedInputStream(stream: inputStream) _ = try mergeFrom(codedInputStream: codedInput, extensionRegistry:extensionRegistry) try codedInput.checkLastTagWas(value: 0) return self } //Delimited Encoding/Decoding public func mergeDelimitedFrom(inputStream: InputStream) throws -> Self? { var firstByte:UInt8 = 0 if inputStream.read(&firstByte, maxLength: 1) != 1 { return nil } let rSize = try CodedInputStream.readRawVarint32(firstByte: firstByte, inputStream: inputStream) let data = Data(bytes: [0],count: Int(rSize)) let pointer = UnsafeMutablePointerUInt8From(data: data) inputStream.read(pointer, maxLength: Int(rSize)) return try mergeFrom(data: data) } //JSON class open func decodeToBuilder(jsonMap: Dictionary<String, AnyObject>) throws -> Self { throw ProtocolBuffersError.obvious("JSON Encoding/Decoding available only in syntax=\"proto3\"") } open class func fromJSONToBuilder(data: Data) throws -> Self { throw ProtocolBuffersError.obvious("JSON Encoding/Decoding available only in syntax=\"proto3\"") } }
21b1c4299848d3bd462196da46150931
35.247967
149
0.698778
false
false
false
false
thomassnielsen/SwiftyJSONAPI
refs/heads/master
SwiftyJSONAPI/JSONAPIError.swift
mit
1
// // JSONAPIError.swift // SwiftyJSONAPI // // Created by Billy Tobon on 10/15/15. // Copyright © 2015 Thomas Sunde Nielsen. All rights reserved. // import Foundation open class JSONAPIError: JSONPrinter, Error { open var id = "" open var links: [String:URL] = [:] open var status = "" open var code = "" open var title = "" open var detail = "" open var source: JSONAPIErrorSource? open var meta: Dictionary<String,Any>? public init(){} public convenience init(_ json: NSDictionary) { self.init(json as! [String:Any]) } public convenience init(_ json: [String:Any]) { self.init() if let objectId = json["id"] { id = "\(objectId)" } if let strings = json["links"] as? [String:String] { for (key, value) in strings { links[key] = URL(string: value)! } } if let objectStatus = json["status"] { status = "\(objectStatus)" } if let objectCode = json["code"] { code = "\(objectCode)" } if let objectTitle = json["title"] { title = "\(objectTitle)" } if let objectDetail = json["details"] { detail = "\(objectDetail)" } if let objectSource = json["source"] as? [String:Any] { source = JSONAPIErrorSource(objectSource) } if let objectMeta = json["meta"] as? [String:Any] { meta = objectMeta } } open func toDict() -> [String:Any] { var dict: [String:Any] = [ "id":id as Any, "links":links as Any, "status":status as Any, "code":code as Any, "title":title as Any, "detail":detail as Any, ] if let source = source { dict["source"] = source } if let meta = meta { dict["meta"] = meta as Any? } return dict } }
9ac3ead6dae2ad96ba2ef6e94f20b342
22.617978
63
0.478116
false
false
false
false
MathieuRenard/Poker-Stats
refs/heads/master
Poker-Stats/Poker-Stats/ViewController.swift
mit
1
// // ViewController.swift // Poker-Stats // // Created by Mathieu Renard on 19/07/2016. // Copyright © 2016 Mathieu Renard. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet var playerNumber : UITextField! @IBOutlet var validationButton : UIButton! override func viewDidLoad() { super.viewDidLoad() validationButton.hidden = true // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } //Ouvre une popup func alert(title: String, message: String){ let alert = UIAlertController(title: title, message: message, preferredStyle: .Alert) let ok = UIAlertAction (title: "Ok", style: UIAlertActionStyle.Cancel, handler: nil) alert.addAction(ok) self.presentViewController(alert, animated: true, completion: nil) } // fonction pour afficher le boutton @IBAction func showbutton (sender : UITextField) { let playerNumber = Int(sender.text!) if playerNumber < 7 && playerNumber > 1 { validationButton.hidden = false } else if sender.text == ""{ validationButton.hidden = true } else { alert ( " Erreur ", message: " veuillez rentrer un chiffre compris entre 1 et 7 " ) validationButton.hidden = true } } }
3ff6fbcf67ef951f7a50a0cd77bf2d16
28.09434
95
0.63035
false
false
false
false
RunningCharles/Arithmetic
refs/heads/master
src/5BSSumPath.swift
bsd-3-clause
1
#!/usr/bin/swift class BSTreeNode { var value: Int! var leftNode: BSTreeNode? var rightNode: BSTreeNode? init(_ value: Int) { self.value = value } } func insertTree(_ root: BSTreeNode?, _ value: Int) { guard let root = root else { return } if value == root.value { return } if value < root.value { guard let leftNode = root.leftNode else { root.leftNode = BSTreeNode(value) return } insertTree(leftNode, value) } else { guard let rightNode = root.rightNode else { root.rightNode = BSTreeNode(value) return } insertTree(rightNode, value) } } func printTree(_ root: BSTreeNode?) { guard let root = root else { return } printTree(root.leftNode) print(root.value) printTree(root.rightNode) } func handler(_ root: BSTreeNode, _ sum: Int, _ path: [Int]) { var path = path path.append(root.value) let sum = sum - root.value if root.leftNode == nil && root.rightNode == nil { if sum == 0 { print("path: ", path) } } if let leftNode = root.leftNode { handler(leftNode, sum, path) } if let rightNode = root.rightNode { handler(rightNode, sum, path) } } func printSumPath(_ root: BSTreeNode, _ sum: Int) { let path: [Int] = [] handler(root, sum, path) } var root = BSTreeNode(10) insertTree(root, 5) insertTree(root, 4) insertTree(root, 7) insertTree(root, 12) printTree(root) print("===========") printSumPath(root, 22)
b27a7021af336a5312a8b54760f1454f
20.547945
61
0.581691
false
false
false
false
daisukenagata/BLEView
refs/heads/master
BLEView/Classes/BlTextPeripheral.swift
mit
1
// // blText.swift // Pods // // Created by 永田大祐 on 2016/12/27. // // import Foundation import CoreBluetooth import UserNotifications import AVFoundation class BlTextPeripheral:NSObject,CBPeripheralDelegate,CBPeripheralManagerDelegate,UNUserNotificationCenterDelegate { var peripheral:[CBPeripheral] = [] var characteristic:CBCharacteristic! let serviceUUID = CBUUID(string: "DD9B8295-E177-4F8A-A5E1-DC5FED19556D") var peripheralManager: CBPeripheralManager! var characteristicCBC:CBMutableCharacteristic! var serString : String! var charaCount : Int! var nsDat: NSArray! func bleSetting(){ let option : Dictionary = [ CBCentralManagerRestoredStatePeripheralsKey: "dddaisuke" ] peripheralManager = CBPeripheralManager(delegate: self, queue: nil , options:option) } func peripheralManager(_ peripheral: CBPeripheralManager, willRestoreState dict: [String : Any]) { let option : Dictionary = [ CBCentralManagerRestoredStatePeripheralsKey: "dddaisuke" ] peripheralManager = CBPeripheralManager(delegate: self, queue: nil , options:option) print("Peripheral Manager Restored") } func peripheral(_ peripheral : CBPeripheral, didDiscoverServices error : Error?){ if let error = error { print("エラー\(error)") return } let services = peripheral.services as NSArray? print("\(String(describing: services?.count))サービスを発見",services!.count, services!) charaCount = services?.count for service in services! { // キャラクタリスティック探索開始 peripheral.discoverCharacteristics(nil, for: service as! CBService) //サービス情報の付与 nsDat = services } } func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?){ if let error = error { print("エラー\(error)") return } let characteristics = service.characteristics print(" \(String(describing: characteristics?.count))個のキャラクタリスティックを発見!",characteristics!.count, characteristics!) let uuid = CBUUID(string:"45088E4B-B847-4E20-ACD7-0BEA181075C2") for aCharacteristic:CBCharacteristic in characteristics! { if aCharacteristic.uuid.isEqual(uuid) { self.characteristic = aCharacteristic break; } } } func peripheral(_ peripheral: CBPeripheral, didModifyServices invalidatedServices: [CBService]){ print("サービスの再接続") BlModel.sharedBlTextPeripheral.peripheralManager.removeAllServices() } func peripheral (_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) { if let error = error { print("Read失敗", error, characteristic.uuid) return } print("Read成功",characteristic.service.uuid, characteristic.uuid, characteristic.value!) } func peripheral(_ peripheral: CBPeripheral, didWriteValueFor characteristic: CBCharacteristic, error: Error?){ print("Write成功!") } func startAdvertise() { // アドバタイズメントデータを作成する let advertisementData = [ CBAdvertisementDataLocalNameKey: "Test Device", CBAdvertisementDataServiceUUIDsKey: [serviceUUID] ] as [String : Any] peripheralManager.startAdvertising(advertisementData) } func stopAdvertise() { peripheralManager.stopAdvertising() } // ペリフェラルマネージャの状態が変化すると呼ばれる func peripheralManagerDidUpdateState(_ peripheral: CBPeripheralManager) { print("state: \(peripheral.state)") switch peripheral.state { case .poweredOn: // サービス登録開始 publishservice() case.poweredOff: BlModel.sharedBlTextCentral.pushCut() default: break } } func publishservice() { // サービスを作成 let service = CBMutableService(type: serviceUUID, primary: true) let characteristicUUID = CBUUID(string: "45088E4B-B847-4E20-ACD7-0BEA181075C2") let properties: CBCharacteristicProperties = [.read, .write] let permissions: CBAttributePermissions = [.readable, .writeable] BlModel.sharedBlTextPeripheral.stopAdvertise() BlModel.sharedBlTextPeripheral.startAdvertise() BlModel.sharedBlTextPeripheral.characteristic = nil characteristicCBC = CBMutableCharacteristic( type: characteristicUUID, properties: properties, value: nil, permissions: permissions) // キャラクタリスティックをサービスにセット service.characteristics = [characteristicCBC] BlModel.sharedBlTextPeripheral.peripheralManager.add(service) } // サービス追加処理が完了すると呼ばれる func peripheralManager(_ peripheral: CBPeripheralManager, didAdd service: CBService, error: Error?) { if let error = error { print("サービス追加失敗! error: \(error)") return } print("サービス追加成功!") startAdvertise() } // アドバタイズ開始処理が完了すると呼ばれる func peripheralManagerDidStartAdvertising(_ peripheral: CBPeripheralManager, error: Error?) { if let error = error { print("アドバタイズ開始失敗! error: \(error)") return } print("アドバタイズ開始成功!") //スキャン開始 BlModel.sharedBlTextCentral.centralManager.scanForPeripherals(withServices: [serviceUUID], options: nil) } // Writeリクエスト受信時に呼ばれる @available(iOS 10.0, *) func peripheralManager(_ peripheral: CBPeripheralManager, didReceiveWrite requests: [CBATTRequest]) { print("\(requests.count) 件のWriteリクエストを受信!") for request in requests { if characteristicCBC != nil { if request.characteristic.uuid.isEqual(characteristicCBC.uuid){ // CBMutableCharacteristicのvalueに、CBATTRequestのvalueをセット characteristicCBC.value = request.value } } serString = String(data: characteristicCBC.value!,encoding: String.Encoding.utf8) // リクエストに応答 peripheralManager.respond(to: requests[0] , withResult: CBATTError.Code.success) BlModel.sharedSoundNotification.soundSet() } } }
f435a8b248e26a6dea94bb40a13d4876
31.143519
121
0.596284
false
false
false
false
petester42/RxMoya
refs/heads/master
Example/RxMoyaExample/UIViewControllerExtensions.swift
mit
1
// // UIViewControllerExtensions.swift // ReactiveMoyaExample // // Created by Justin Makaila on 8/9/15. // Copyright (c) 2015 Justin Makaila. All rights reserved. // import Foundation import UIKit extension UIViewController { func showErrorAlert(title: String, error: NSError, action: (Void -> Void)? = nil) { showAlert(title, message: error.description, action: action) } func showAlert(title: String, message: String, action: (Void -> Void)? = nil) { let alertController = UIAlertController(title: title, message: message, preferredStyle: .Alert) let okAction = UIAlertAction(title: "OK", style: .Default, handler: { _ in action?() }) alertController.addAction(okAction) presentViewController(alertController, animated: true, completion: nil) } func showInputPrompt(title: String, message: String, action: (String -> Void)? = nil) { var inputTextField: UITextField? let promptController = UIAlertController(title: title, message: message, preferredStyle: .Alert) let okAction = UIAlertAction(title: "OK", style: .Default, handler: { _ in if let input = inputTextField?.text { action?(input) } }) let cancelAction = UIAlertAction(title: "Cancel", style: .Cancel, handler: nil) promptController.addAction(okAction) promptController.addAction(cancelAction) promptController.addTextFieldWithConfigurationHandler { textField in inputTextField = textField } presentViewController(promptController, animated: true, completion: nil) } }
a4791a3a675ed675abe0583b81ba8b27
34.163265
104
0.639954
false
false
false
false
nmdias/FeedParser
refs/heads/master
Example iOS/View Controllers/FeedTableViewController.swift
mit
2
// // FeedTableViewController.swift // // Copyright (c) 2016 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 UIKit import FeedParser let feedURL = NSURL(string: "http://images.apple.com/main/rss/hotnews/hotnews.rss")! class FeedTableViewController: UITableViewController { var feed: RSSFeed? override func viewDidLoad() { super.viewDidLoad() self.title = "Feed" FeedParser(URL: feedURL)!.parse { (result) in self.feed = result.rssFeed self.tableView.reloadData() } } } // MARK: - Table View Data Source extension FeedTableViewController { override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 2 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { switch section { case 0: return 3 case 1: return self.feed?.items?.count ?? 0 default: fatalError() } } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = reusableCell() guard let layout = TableViewLayout(indexPath: indexPath) else { fatalError() } switch layout { case .Title: cell.textLabel?.text = self.feed?.title ?? "[no title]" case .Link: cell.textLabel?.text = self.feed?.link ?? "[no link]" case .Description: cell.textLabel?.text = self.feed?.description ?? "[no description]" case .Items: cell.textLabel?.text = self.feed?.items?[indexPath.row].title ?? "[no title]" } return cell } } // MARK: - Table View Delegate extension FeedTableViewController { override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { guard let layout = TableViewLayout(indexPath: indexPath) else { fatalError() } switch layout { case .Title: self.showDetailViewControllerWithText(self.feed?.title ?? "[no title]") case .Link: self.showDetailViewControllerWithText(self.feed?.link ?? "[no link]") case .Description: self.showDetailViewControllerWithText(self.feed?.description ?? "[no link]") case .Items: self.showDetailViewControllerWithText(self.feed?.items?[indexPath.row].description ?? "[no description]") } } } // MARK: - Navigation extension FeedTableViewController { // MARK: - Navigation func showDetailViewControllerWithText(text: String) { let viewController = FeedDetailTableViewController(text: text) self.showViewController(viewController, sender: self) } }
864a82a0a35f94106d6a261b0a4501cb
35.238095
133
0.673764
false
false
false
false
Candyroot/Fonts
refs/heads/master
Fonts/MasterViewController.swift
apache-2.0
1
// // MasterViewController.swift // Fonts // // Created by Liu Bing on 3/30/15. // Copyright (c) 2015 UnixOSS. All rights reserved. // import UIKit class MasterViewController: UITableViewController { var detailViewController: DetailViewController? = nil var fontDictionary = [String: [String : [CTFontDescriptorRef]]]() var languages: [String]? 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() if let split = self.splitViewController { let controllers = split.viewControllers self.detailViewController = controllers[controllers.count-1].topViewController as? DetailViewController } let activityIndicator = UIActivityIndicatorView(activityIndicatorStyle: .Gray) activityIndicator.startAnimating() let footerView = UIView(frame: CGRect(x: 0, y: 0, width: tableView.frame.width, height: 44)) activityIndicator.center = CGPoint(x: tableView.frame.width/2.0, y: 22) footerView.addSubview(activityIndicator) tableView.tableFooterView = footerView dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) { let descriptorOptions = [kCTFontDownloadableAttribute as String: true] let descriptor = CTFontDescriptorCreateWithAttributes(descriptorOptions) let fontDescriptors = CTFontDescriptorCreateMatchingFontDescriptors(descriptor, nil) as [CTFontDescriptorRef] fontDescriptors.map { fontDescriptor -> Void in let kCTFontDesignLanguagesAttribute = "NSCTFontDesignLanguagesAttribute" let languages = CTFontDescriptorCopyAttribute(fontDescriptor, kCTFontDesignLanguagesAttribute) as? [String] let fontFamily = CTFontDescriptorCopyLocalizedAttribute(fontDescriptor, kCTFontFamilyNameAttribute, nil) as? String ?? "other" languages?.map { language -> Void in var fontFamilyArray = self.fontDictionary[language] ?? [String : [CTFontDescriptorRef]]() var fontArray = fontFamilyArray[fontFamily] ?? [CTFontDescriptorRef]() fontArray.append(fontDescriptor) fontFamilyArray[fontFamily] = fontArray self.fontDictionary[language] = fontFamilyArray } return } self.languages = Array(self.fontDictionary.keys) self.languages?.sort { $0 < $1 } dispatch_async(dispatch_get_main_queue()) { self.tableView.reloadData() self.tableView.tableFooterView = nil } } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Segues override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "show" { if let indexPath = self.tableView.indexPathForSelectedRow() { let controller = segue.destinationViewController as SecondMasterViewController controller.fontFamilyIndex = indexPath.row let language = languages?[indexPath.section] controller.language = language controller.fontFamilyArray = language != nil ? fontDictionary[language!] : nil controller.navigationItem.leftItemsSupplementBackButton = true } } } // MARK: - Table View override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return fontDictionary.count } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { let key = languages?[section] let fonts = key != nil ? fontDictionary[key!] : nil return fonts?.count ?? 0 } override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return languages?[section] } override func sectionIndexTitlesForTableView(tableView: UITableView) -> [AnyObject]! { return languages } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as UITableViewCell let key = languages?[indexPath.section] var fontFamilies: [String]? if key != nil { if let families = fontDictionary[key!]?.keys { fontFamilies = Array(families) } } cell.textLabel!.text = fontFamilies?[indexPath.row] return cell } }
00cfe73764ae7493e2101184c7ce61ba
40.081967
142
0.648643
false
false
false
false
novi/todoapi-example
refs/heads/master
todoapi/todoapi/Controllers.swift
mit
1
// // TodoController.swift // todoapi // // Created by Yusuke Ito on 1/12/16. // Copyright © 2016 Yusuke Ito. All rights reserved. // import Kunugi import Nest import Inquiline import MySQL struct RequestParameterId: ContextType { let id: Int } struct TodoController: ControllerMiddleware, AnyRequestHandleable { func before(ctx: ContextBox) throws -> MiddlewareResult { let ctx = ctx as! Context guard let id = Int(ctx.parameters["id"] ?? "") else { return .Respond( Response(.BadRequest) ) } try ctx.put(RequestParameterId(id: id)) return .Next } func get(ctx: ContextBox) throws -> MiddlewareResult { let id = (try ctx.get() as RequestParameterId).id let ctx = ctx as! Context let todos: [Row.Todo] = try ctx.pool.execute{ conn in try conn.query("SELECT * FROM todos WHERE id = ?", [id]) } if let first = todos.first { return .Respond( Response(status: .Ok, json: first.json) ) } else { return .Respond( Response(.NotFound)) } } func delete(ctx: ContextBox) throws -> MiddlewareResult { let id = (try ctx.get() as RequestParameterId).id let ctx = ctx as! Context let status: QueryStatus = try ctx.pool.execute { conn in try conn.query("DELETE FROM todos WHERE id = ? LIMIT 1", [id]) } if status.affectedRows == 0 { return .Respond( Response(.NotFound)) } else { return .Respond( Response(.Ok)) } } func put(ctx: ContextBox) throws -> MiddlewareResult { let id = (try ctx.get() as RequestParameterId).id let ctx = ctx as! Context let body = ctx.body var params: [String: QueryParameter?] = [:] if let title = body["title"]?.stringValue { params["title"] = title } if let done = body["done"]?.boolValue { params["done"] = done } if params.count == 0 { return .Respond( Response(.BadRequest) ) } let _: QueryStatus = try ctx.pool.execute { conn in try conn.query("UPDATE todos SET ? WHERE id = ? LIMIT 1", [QueryDictionary(params), id]) } return try get(ctx) } } struct TodoListController: ControllerMiddleware, AnyRequestHandleable { func get(ctx: ContextBox) throws -> MiddlewareResult { let ctx = ctx as! Context let limit: Int = Int(ctx.query["count"] ?? "") ?? 100 let todos: [Row.Todo] = try ctx.pool.execute{ conn in try conn.query("SELECT * FROM todos ORDER BY updated_at DESC LIMIT ?", [limit]) } let json: JSON = [ "todos": JSON.from(todos.map({ $0.json })) ] return .Respond( Response(status: .Ok, json: json)) } func post(ctx: ContextBox) throws -> MiddlewareResult { let ctx = ctx as! Context let body = ctx.body guard let title = body["title"]?.stringValue else { return .Respond(Response(.BadRequest)) } let todo = Row.Todo(id: 0, title: title, done: false, updatedAt: SQLDate.now(timeZone: ctx.pool.options.timeZone)) let status: QueryStatus = try ctx.pool.execute { conn in try conn.query("INSERT INTO todos SET ?", [todo]) } let created = Row.Todo(id: status.insertedId, title: todo.title, done: todo.done, updatedAt: todo.updatedAt) return .Respond(Response(status: .Created, json: created.json)) } }
a5e96376760a5a2783bdd83064b00dce
33.932039
122
0.577704
false
false
false
false
RocketChat/Rocket.Chat.iOS
refs/heads/develop
Rocket.ChatTests/API/Requests/Message/StarMessageRequestSpec.swift
mit
1
// // StarMessageRequestSpec.swift // Rocket.ChatTests // // Created by Matheus Cardoso on 4/26/18. // Copyright © 2018 Rocket.Chat. All rights reserved. // import XCTest import SwiftyJSON @testable import Rocket_Chat class StarMessageRequestSpec: APITestCase { func testRequest() { let starRequest = StarMessageRequest(msgId: "msgId", star: true) guard let request = starRequest.request(for: api) else { return XCTFail("request is not nil") } guard let httpBody = request.httpBody else { return XCTFail("body is not nil") } guard let bodyJson = try? JSON(data: httpBody) else { return XCTFail("body is valid json") } XCTAssertEqual(request.url?.path, "/api/v1/chat.starMessage", "path is correct") XCTAssertEqual(request.httpMethod, "POST", "http method is correct") XCTAssertEqual(request.value(forHTTPHeaderField: "Content-Type"), "application/json", "content type is correct") XCTAssertEqual(bodyJson["messageId"].string, "msgId", "messageId is correct") } func testRequestFalse() { let starRequest = StarMessageRequest(msgId: "msgId", star: false) guard let request = starRequest.request(for: api) else { return XCTFail("request is not nil") } guard let httpBody = request.httpBody else { return XCTFail("body is not nil") } guard let bodyJson = try? JSON(data: httpBody) else { return XCTFail("body is valid json") } XCTAssertEqual(request.url?.path, "/api/v1/chat.unStarMessage", "path is correct") XCTAssertEqual(request.httpMethod, "POST", "http method is correct") XCTAssertEqual(request.value(forHTTPHeaderField: "Content-Type"), "application/json", "content type is correct") XCTAssertEqual(bodyJson["messageId"].string, "msgId", "messageId is correct") } func testResult() { let rawResult = JSON([ "success": true ]) let result = StarMessageResource(raw: rawResult) XCTAssert(result.success == true) let nilResult = StarMessageResource(raw: nil) XCTAssertNil(nilResult.success, "success is nil if raw is nil") } }
c860cb38fa5106e87acddba339b9d847
34.59375
120
0.640913
false
true
false
false
JasonChen2015/Paradise-Lost
refs/heads/master
Paradise Lost/Classes/ViewControllers/Game/SudokuVC.swift
mit
3
// // SudokuVC.swift // Paradise Lost // // Created by Jason Chen on 6/1/16. // Copyright © 2016 Jason Chen. All rights reserved. // import UIKit class SudokuVC: UIViewController, SudokuViewDelegate, SudokuGridViewDelegate, SudokuPanelViewDelegate { var mainView: SudokuView! var gridView: SudokuGridView! /// the dictionary of puzzles in plist var sudokuDict: NSDictionary = [:] // the dictionary of puzzles from user var userDict: [String: AnyObject] = [:] /// the total of puzzles in plist var totalNum: Int = 0 // 0 means no puzzle in sudokuDict /// current number of puzzle in sudokuDict var currentNum: Int = 1 { didSet { // set when loading if mainView != nil { mainView.setNumber(currentNum) } } } /// include the stable number of puzzle var stableSudoku: [Int] = [] { didSet { // set when loading if gridView != nil { gridView.stableSudoku = stableSudoku } } } /// the state shown on user interface var userSudoku: [Int] = [] { didSet { // save to user default let str = SudokuManager.getStringFromSudoku(userSudoku) userDict["\(currentNum)"] = str as AnyObject UserDefaultManager.setObject(userDict as AnyObject, forKeyEnum: .sudokuUserGrid) // check if SudokuManager.checkCorrect(userSudoku) { if mainView != nil { // because when game first loading will update here, gameOver() // but view still being initialized } } } } /// the time used var currentSecond: Int = 0 { didSet { // save to user default userDict["s-\(currentNum)"] = currentSecond as AnyObject UserDefaultManager.setObject(userDict as AnyObject, forKeyEnum: .sudokuUserGrid) } } var runGame: Bool = false { didSet { if gridView != nil { gridView.canEnable = runGame } } } var loadDataSuccess: Bool = true // MARK: life cycle override var shouldAutorotate : Bool { return false } override var supportedInterfaceOrientations : UIInterfaceOrientationMask { return .portrait } override var prefersStatusBarHidden : Bool { return true } override func viewDidLoad() { super.viewDidLoad() // load data loadDict() if let num = UserDefaultManager.objectFromKeyEnum(.sudokuNumber) { currentNum = num as! Int } else { currentNum = 1 } if !loadCurrentPuzzle() { loadDataSuccess = false setAllDefault() } // load view mainView = SudokuView(frame: UIScreen.main.bounds) mainView.delegate = self view.addSubview(mainView) gridView = SudokuGridView(frame: CGRect(x: 20, y: 95, width: 374, height: 374)) gridView.delegate = self view.addSubview(gridView) let panel = SudokuPanelView(frame: CGRect(x: 132, y: 489, width: 150, height: 200)) panel.delegate = self view.addSubview(panel) prepareGame() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) if !loadDataSuccess { AlertManager.showTips(self, message: LanguageManager.getGameString(forKey: "sudoku.loadfailed.message"), handler: nil) } // do not let the screen display closed until dismiss UIApplication.shared.isIdleTimerDisabled = true } override func viewWillDisappear(_ animated: Bool) { mainView.stopTimer() if runGame { currentSecond = mainView.seconds } UIApplication.shared.isIdleTimerDisabled = false super.viewWillDisappear(animated) } func setAllDefault() { currentNum = 1 let data = "530070000600195000098000060800060003400803001700020006060000280000419005000080079" (stableSudoku, _) = SudokuManager.getSudokuFromString(data) userSudoku = stableSudoku currentSecond = 0 } func prepareGame() { mainView.seconds = currentSecond mainView.setNumber(currentNum) gridView.stableSudoku = stableSudoku gridView.sudoku = userSudoku runGame = false mainView.resetScreen() } /** get the sudoku and user history */ func loadDict() { // get dictionary from plist guard let dictPath = Bundle.main.path(forResource: "SudokuPuzzles", ofType: "plist") else { return } guard let dict = NSDictionary(contentsOfFile: dictPath) else { return } sudokuDict = dict // get the total number of sudoku in dictionary guard let total = sudokuDict.object(forKey: "count") else { sudokuDict = [:] totalNum = 0 return } totalNum = total as! Int guard let udict = UserDefaultManager.objectFromKeyEnum(.sudokuUserGrid) else { return } userDict = udict as! [String: AnyObject] return } func loadCurrentPuzzle() -> Bool { var success = true if !sudokuDict.isEqual([:]) { // origin (stableSudoku, success) = SudokuManager.getSudokuFromDictionary(sudokuDict, atIndex: currentNum) // user if success { loadUserSudokuOfCurrentNum() } } else { success = false } return success } func loadUserSudokuOfCurrentNum() { if let str = userDict["\(currentNum)"] { var temp = true (userSudoku, temp) = SudokuManager.getSudokuFromString(str as! String) if !temp { userSudoku = stableSudoku currentSecond = 0 return } } else { userSudoku = stableSudoku currentSecond = 0 return } // get time if let t = userDict["s-\(currentNum)"] { currentSecond = t as! Int } else { currentSecond = 0 } } // MARK: SudokuViewDelegate func startGameAction(_ didStartGame: Bool, usedSec: Int) { runGame = didStartGame if !runGame { // tap pause button currentSecond = usedSec } } func resetGameAction(_ needAlert: Bool) { if needAlert { AlertManager.showTips(self, message: LanguageManager.getGameString(forKey: "sudoku.reset.message"), handler: nil) } gridView.stableSudoku = stableSudoku gridView.sudoku = stableSudoku userSudoku = stableSudoku mainView.seconds = 0 runGame = false } func exitGameAction(_ usedSec: Int) { currentSecond = usedSec self.dismiss(animated: true, completion: nil) } // MARK: SudokuGridViewDelegate func didRefreshSudoku(_ uSudoku: [Int]) { userSudoku = uSudoku } // MARK: SudokuPanelViewDelegate func didTapNumber(_ number: Int) { if number > 9 { switch number { case 10: loadPrevPuzzle() return case 11: clearGame() return case 12: loadNextPuzzle() return default: return } } if !runGame { return } gridView.putNumberToPoint(number) } // MARK: event response func gameOver() { AlertManager.showTips(self, message: LanguageManager.getGameString(forKey: "sudoku.gameover.message"), handler: nil) runGame = false mainView.stopTimer() } func clearGame() { if runGame { gridView.sudoku = stableSudoku userSudoku = stableSudoku } } func loadNextPuzzle() { if !runGame { if currentNum < totalNum { currentNum = currentNum + 1 if !loadCurrentPuzzle() { setAllDefault() } prepareGame() AlertManager.showTips(self, message: LanguageManager.getGameString(forKey: "sudoku.runnext.message"), handler: nil) } else { AlertManager.showTips(self, message: LanguageManager.getGameString(forKey: "sudoku.nonext.message"), handler: nil) } } } func loadPrevPuzzle() { if !runGame { if currentNum > 1 { currentNum = currentNum - 1 if !loadCurrentPuzzle() { setAllDefault() } prepareGame() AlertManager.showTips(self, message: LanguageManager.getGameString(forKey: "sudoku.runprev.message"), handler: nil) } else { AlertManager.showTips(self, message: LanguageManager.getGameString(forKey: "sudoku.noprev.message"), handler: nil) } } } }
d9132b7b2a8542b9f14a23fb1bcd2687
27.739521
131
0.541306
false
false
false
false
romainPellerin/SilverCalc
refs/heads/master
SilverCalc-shrd/Calculator.swift
apache-2.0
2
import Sugar class Calculator{ var firstMbrs : Sugar.Collections.List<Double> = Sugar.Collections.List<Double>() var secondMbrs : Sugar.Collections.List<Double> = Sugar.Collections.List<Double>() var value: Double = 0.0 var mem: Double = 0.0 var inverted : Boolean = false var afterdot : Boolean = false var op: Integer = -1 static let ADD_OPERATOR : Integer = 0 static let MINUS_OPERATOR : Integer = 1 static let MULTIPLY_OPERATOR : Integer = 2 static let DIVIDE_OPERATOR : Integer = 3 // add 2 numbers func add(){ storeInMem() op = ADD_OPERATOR } func minus(){ storeInMem() op = MINUS_OPERATOR } func multiply(){ storeInMem() op = MULTIPLY_OPERATOR } func divide(){ storeInMem() op = DIVIDE_OPERATOR } func process(){ switch op { case ADD_OPERATOR: value = mem+value case MINUS_OPERATOR: value = mem-value case MULTIPLY_OPERATOR: value = mem*value case DIVIDE_OPERATOR: if value == 0 { value = mem } else { value = mem/value } default: } op = -1 } /** IN-MEMORY NUMBER MANAGEMENT **/ // add a char to the in memory number func composeNumber(a:Double){ if (a == ","){ } else { if (afterdot){ secondMbrs.Add(a) } else { firstMbrs.Add(a) } } computeDoubleValue() } // reinit in memory number func clearNumber(){ firstMbrs.Clear() secondMbrs.Clear() afterdot = false inverted = false value = 0.0 } // get the value of in memory number func getStringValue() -> String{ var d = getDoubleValue() // this trick avoid to display 0E+00 on 0.0 to string conversion var result: String = "0.0" if d != 0.0 { result = Convert.ToString(d) } return result } func computeDoubleValue() { var fp : Double = 0.0 if firstMbrs.Count > 0 { var l : Double = Convert.ToDouble(firstMbrs.Count) for c in firstMbrs { var p:Double = Sugar.Math.Pow(10.0,l-1) fp += c*p l--; } } if secondMbrs.Count > 0 { var l : Double = 1.0 for c in secondMbrs { var p:Double = Sugar.Math.Pow(0.1,l) fp += c*p l++; } } var result: Double = fp if inverted { result *= -1.0 } value = result } func getDoubleValue() -> Double{ return value } func storeInMem(){ mem = getDoubleValue() value = 0.0 clearNumber() } func invert(){ inverted = !inverted computeDoubleValue() } }
940c3d9ed317ce27d4a1d7ea190b70ca
15.271523
83
0.57099
false
false
false
false