repo_name
stringlengths
6
91
path
stringlengths
8
968
copies
stringclasses
210 values
size
stringlengths
2
7
content
stringlengths
61
1.01M
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6
99.8
line_max
int64
12
1k
alpha_frac
float64
0.3
0.91
ratio
float64
2
9.89
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
findmybusnj/findmybusnj-swift
findmybusnj/Model/PlacesAnnotation.swift
1
1524
// // PlacesAnnotation.swift // Creates an annotation for buses on map // findmybusnj // // Created by David Aghassi on 10/12/15. // Copyright © 2015 David Aghassi. All rights reserved. // import Foundation import MapKit import Contacts class PlacesAnnotation: NSObject { // MARK: Properties let title: String? let coordinate: CLLocationCoordinate2D // inititalize the subtitle variable to nil so we don't have one var subtitle: String? { return nil } /** Initializer method to create a new annotation with a name and coordinates - Parameters: - title: Title of the place marker - coordinate: The `CLLocationCoordinate2D` that defines the x,y coordinates for the annotation */ init(title: String, coordinate: CLLocationCoordinate2D) { self.title = title self.coordinate = coordinate super.init() } } // MARK: MKAnnotation extension PlacesAnnotation: MKAnnotation { /** Creates an `MKMapItem` based on the `MKPlacemark` created out of this current object coordinates and title - returns: An MKMapItem containing the title and coordinates of the annotation */ func mapItem() -> MKMapItem { // MKPlacemark only takes a String, not an optional string let addressDictionary = [String(CNPostalAddress().street): String(describing: title)] let placemark = MKPlacemark(coordinate: coordinate, addressDictionary: addressDictionary) let mapItem = MKMapItem(placemark: placemark) mapItem.name = title return mapItem } }
gpl-3.0
0f76e19379107f57d210b0998c501a2e
25.719298
109
0.720289
4.519288
false
false
false
false
jairoeli/Instasheep
InstagramFirebase/InstagramFirebase/UserProfileHeader/UserProfileController.swift
1
7606
// // UserProfileController.swift // InstagramFirebase // // Created by Jairo Eli de Leon on 3/22/17. // Copyright © 2017 DevMountain. All rights reserved. // import UIKit import Firebase class UserProfileController: UICollectionViewController { // MARK: - Properties fileprivate let headerID = "headerId" fileprivate let cellId = "cellId" fileprivate let homePostCellID = "homePostCellID" var user: User? var posts = [Post]() var userID: String? var isFinishedPaging = false var isGridView = true // MARK: - View Life Cycle override func viewDidLoad() { super.viewDidLoad() collectionView?.backgroundColor = .white collectionView?.register(UserProfileHeader.self, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: headerID) collectionView?.register(UserProfilePhotoCell.self, forCellWithReuseIdentifier: cellId) collectionView?.register(HomePostCell.self, forCellWithReuseIdentifier: homePostCellID) setupLogOutButton() fetchUser() // fetchOrderedPosts() } // MARK: - Fetch User & Post fileprivate func fetchOrderedPosts() { guard let uid = self.user?.uid else { return } let ref = Database.database().reference().child("posts").child(uid) // perhaps later on we'll implement some pagination of data ref.queryOrdered(byChild: "creationDate").observe(.childAdded, with: { (snapshot) in guard let dictionary = snapshot.value as? [String: Any] else { return } guard let user = self.user else { return } let post = Post(user: user, dictionary: dictionary) self.posts.insert(post, at: 0) // self.posts.append(post) self.collectionView?.reloadData() }) { (err) in print("Failed to fetch ordered posts:", err) } } fileprivate func fetchUser() { let uid = userID ?? (Auth.auth().currentUser?.uid ?? "") //guard let uid = Auth.auth().currentUser?.uid else { return } Database.fetchUserWith(uid: uid) { (user) in self.user = user self.navigationItem.title = self.user?.username self.collectionView?.reloadData() self.paginatePosts() } } // MARK: - Pagination fileprivate func paginatePosts() { print("Start paging for more posts") guard let uid = self.user?.uid else { return } let ref = Database.database().reference().child("posts").child(uid) var query = ref.queryOrdered(byChild: "creationDate") // var query = ref.queryOrderedByKey() if posts.count > 0 { // let value = posts.last?.id let value = posts.last?.creationDate.timeIntervalSince1970 query = query.queryEnding(atValue: value) } query.queryLimited(toLast: 4).observeSingleEvent(of: .value, with: { (snapshot) in guard var allObjects = snapshot.children.allObjects as? [DataSnapshot] else { return } allObjects.reverse() if allObjects.count < 4 { self.isFinishedPaging = true } if self.posts.count > 0 && allObjects.count > 0 { allObjects.removeFirst() } guard let user = self.user else { return } allObjects.forEach({ (snapshot) in guard let dictionary = snapshot.value as? [String: Any] else { return } var post = Post(user: user, dictionary: dictionary) post.id = snapshot.key self.posts.append(post) // print(snapshot.key) }) self.posts.forEach({ (post) in print(post.id ?? "") }) self.collectionView?.reloadData() }) { (err) in print("Failed to paginate for posts:", err) } } // MARK: - Log out fileprivate func setupLogOutButton() { navigationItem.rightBarButtonItem = UIBarButtonItem(image: #imageLiteral(resourceName: "gear").withRenderingMode(.alwaysOriginal), style: .plain, target: self, action: #selector(handleLogOut)) } @objc func handleLogOut() { let alertController = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet) alertController.addAction(UIAlertAction(title: "Log Out", style: .destructive, handler: { (_) in do { try Auth.auth().signOut() // what happens? we need to present some kind of login controller let loginController = LoginController() let navController = UINavigationController(rootViewController: loginController) self.present(navController, animated: true, completion: nil) } catch let signOutError { print("Failed to sign out:", signOutError) } })) alertController.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil)) present(alertController, animated: true, completion: nil) } // MARK: - Collectin View data source override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return posts.count } override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { // fire off the paginate cell if indexPath.item == self.posts.count - 1 && !isFinishedPaging { print("Paginating for posts") paginatePosts() } if isGridView { guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath) as? UserProfilePhotoCell else { return UICollectionViewCell() } cell.post = posts[indexPath.item] return cell } else { guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: homePostCellID, for: indexPath) as? HomePostCell else { return UICollectionViewCell() } cell.post = posts[indexPath.item] return cell } } } // MARK: - Collection View Flow Layout extension UserProfileController: UICollectionViewDelegateFlowLayout { func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { if isGridView { let width = (view.frame.width - 2) / 3 return CGSize(width: width, height: width) } else { var height: CGFloat = 40 + 8 + 8 // username userprofileimageview height += view.frame.width height += 50 height += 60 return CGSize(width: view.frame.width, height: height) } } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat { return 1 } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat { return 1 } // MARK: - Header override func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView { guard let header = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: headerID, for: indexPath) as? UserProfileHeader else { return UICollectionViewCell() } header.user = self.user header.delegate = self return header } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize { return CGSize(width: view.frame.height, height: 200) } } // MARK: - Grid & List extension UserProfileController: UserProfileHeaderDelegate { func didChangeToGridView() { isGridView = true collectionView?.reloadData() } func didChangeToListView() { isGridView = false collectionView?.reloadData() } }
mit
3e61ca459c4112262c2d1f827e258ed1
31.224576
196
0.69783
4.756098
false
false
false
false
lanjing99/iOSByTutorials
iOS 8 by tutorials/Chapter 26 - iOS 8 Visual Effects/Grimm-Starter/Grimm/Theme (Ray Wenderlich's conflicted copy 2014-10-28).swift
1
3602
/* * Copyright (c) 2014 Razeware LLC * * 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 enum Font: Int { case FiraSans = 0, NotoSans, OpenSans, PTSans, SourceSansPro, System } enum ReadingMode: Int { case Daytime = 0, NightTime } enum TitleAlignment: Int { case Center = 0, Left } let ThemeDidChangeNotification = "ThemeDidChangeNotification" protocol ThemeAdopting { func reloadTheme() } private let _singletonThemeInstance = Theme() class Theme { class var sharedInstance: Theme { return _singletonThemeInstance } private let fonts = [ ["FiraSans-Regular", "NotoSans", "OpenSans-Regular", "PTSans-Regular", "SourceSansPro-Regular"], ["FiraSans-SemiBold", "NotoSans-Bold", "OpenSans-Semibold", "PTSans-Bold", "SourceSansPro-Semibold"] ] private let textBackgroundColors = [UIColor.whiteColor(), UIColor.nightTimeTextBackgroundColor()] private let textColors = [UIColor.darkTextColor(), UIColor.nightTimeTextColor()] var font: Font = .FiraSans { didSet { notifyObservers() } } var readingMode: ReadingMode = .Daytime { didSet { notifyObservers() } } var titleAlignment: TitleAlignment = .Center { didSet { notifyObservers() } } var barTintColor: UIColor { let color = textBackgroundColors[readingMode.toRaw()] return color.colorForTranslucency() } var tintColor: UIColor? { if readingMode == .Daytime { return nil } else { return UIColor.nightTimeTintColor() } } var separatorColor: UIColor { if readingMode == .Daytime { return UIColor.defaultSeparatorColor() } else { return UIColor.nightTimeTintColor() } } var textBackgroundColor: UIColor { return textBackgroundColors[readingMode.toRaw()] } var textColor: UIColor { return textColors[readingMode.toRaw()] } func preferredFontForTextStyle(style: String) -> UIFont { let systemFont = UIFont.preferredFontForTextStyle(style) if font == .System { return systemFont } let size = systemFont.pointSize var preferredFont: UIFont if style == UIFontTextStyleHeadline { preferredFont = UIFont(name: fonts[1][font.toRaw()], size: size) } else { preferredFont = UIFont(name: fonts[0][font.toRaw()], size: size) } return preferredFont } private func notifyObservers() { NSNotificationCenter.defaultCenter().postNotificationName(ThemeDidChangeNotification, object: nil) } }
mit
c86343d77e91eb1cad081c49ce8158f3
25.688889
102
0.698223
4.457921
false
false
false
false
Huanhoo/VRDemo-Swift
VRDemo/VRPlayer/VKGLTexture.swift
1
5110
// // VKGLTexture.swift // VRDemo // // Created by huhuan on 2016/12/5. // Copyright © 2016年 Huanhoo. All rights reserved. // import UIKit class VKGLTexture: NSObject { var lumaTexture: CVOpenGLESTexture? var chromaTexture: CVOpenGLESTexture? var videoTextureCache: CVOpenGLESTextureCache? var glContext: EAGLContext? init(context: EAGLContext) { super.init() glContext = context configureVideoCache() } func configureVideoCache() { if videoTextureCache == nil { let result: CVReturn = CVOpenGLESTextureCacheCreate(kCFAllocatorDefault, nil, glContext!, nil, &videoTextureCache); if result != noErr { print("create CVOpenGLESTextureCacheCreate failure") } } } func refreshTextureWithPixelBuffer(pixelBuffer: CVPixelBuffer?) { if pixelBuffer == nil { return } var result: CVReturn ; var textureWidth: GLsizei = GLsizei(CVPixelBufferGetWidth(pixelBuffer!)) var textureHeight: GLsizei = GLsizei(CVPixelBufferGetHeight(pixelBuffer!)) if videoTextureCache == nil { print("no video texture cache"); return; } cleanTextures() glActiveTexture(GLenum(GL_TEXTURE0)); result = CVOpenGLESTextureCacheCreateTextureFromImage(kCFAllocatorDefault, videoTextureCache!, pixelBuffer!, nil, GLenum(GL_TEXTURE_2D), GL_RED_EXT, textureWidth, textureHeight, GLenum(GL_RED_EXT), GLenum(GL_UNSIGNED_BYTE), 0, &lumaTexture); if result != 0 { print("create CVOpenGLESTextureCacheCreateTextureFromImage failure 1 %d", result); } glBindTexture(CVOpenGLESTextureGetTarget(lumaTexture!), CVOpenGLESTextureGetName(lumaTexture!)); glTexParameteri(GLenum(GL_TEXTURE_2D), GLenum(GL_TEXTURE_MIN_FILTER), GL_LINEAR); glTexParameteri(GLenum(GL_TEXTURE_2D), GLenum(GL_TEXTURE_MAG_FILTER), GL_LINEAR); glTexParameterf(GLenum(GL_TEXTURE_2D), GLenum(GL_TEXTURE_WRAP_S), GLfloat(GL_CLAMP_TO_EDGE)); glTexParameterf(GLenum(GL_TEXTURE_2D), GLenum(GL_TEXTURE_WRAP_T), GLfloat(GL_CLAMP_TO_EDGE)); // UV-plane. glActiveTexture(GLenum(GL_TEXTURE1)); result = CVOpenGLESTextureCacheCreateTextureFromImage(kCFAllocatorDefault, videoTextureCache!, pixelBuffer!, nil, GLenum(GL_TEXTURE_2D), GL_RG_EXT, textureWidth/2, textureHeight/2, GLenum(GL_RG_EXT), GLenum(GL_UNSIGNED_BYTE), 1, &chromaTexture); if result != 0 { print("create CVOpenGLESTextureCacheCreateTextureFromImage failure 2 %d", result); } glBindTexture(CVOpenGLESTextureGetTarget(chromaTexture!), CVOpenGLESTextureGetName(chromaTexture!)); glTexParameteri(GLenum(GL_TEXTURE_2D), GLenum(GL_TEXTURE_MIN_FILTER), GL_LINEAR); glTexParameteri(GLenum(GL_TEXTURE_2D), GLenum(GL_TEXTURE_MAG_FILTER), GL_LINEAR); glTexParameterf(GLenum(GL_TEXTURE_2D), GLenum(GL_TEXTURE_WRAP_S), GLfloat(GL_CLAMP_TO_EDGE)); glTexParameterf(GLenum(GL_TEXTURE_2D), GLenum(GL_TEXTURE_WRAP_T), GLfloat(GL_CLAMP_TO_EDGE)); } deinit { cleanTextures() clearVideoCache() } func clearVideoCache() { videoTextureCache = nil } func cleanTextures() { if self.lumaTexture != nil { self.lumaTexture = nil; } if self.chromaTexture != nil { self.chromaTexture = nil; } CVOpenGLESTextureCacheFlush(videoTextureCache!, 0); } }
mit
53cdd31e7ffd6376d0b20d50014f5b02
38.589147
128
0.46074
5.569248
false
false
false
false
shyamalschandra/Design-Patterns-In-Swift
Design-Patterns.playground/Pages/Behavioral.xcplaygroundpage/Contents.swift
11
15358
//: Behavioral | //: [Creational](Creational) | //: [Structural](Structural) /*: Behavioral ========== >In software engineering, behavioral design patterns are design patterns that identify common communication patterns between objects and realize these patterns. By doing so, these patterns increase flexibility in carrying out this communication. > >**Source:** [wikipedia.org](http://en.wikipedia.org/wiki/Behavioral_pattern) */ import Swift import Foundation /*: 🐝 Chain Of Responsibility -------------------------- The chain of responsibility pattern is used to process varied requests, each of which may be dealt with by a different handler. ### Example: */ class MoneyPile { let value: Int var quantity: Int var nextPile: MoneyPile? init(value: Int, quantity: Int, nextPile: MoneyPile?) { self.value = value self.quantity = quantity self.nextPile = nextPile } func canWithdraw(var v: Int) -> Bool { func canTakeSomeBill(want: Int) -> Bool { return (want / self.value) > 0 } var q = self.quantity while canTakeSomeBill(v) { if q == 0 { break } v -= self.value q -= 1 } if v == 0 { return true } else if let next = self.nextPile { return next.canWithdraw(v) } return false } } class ATM { private var hundred: MoneyPile private var fifty: MoneyPile private var twenty: MoneyPile private var ten: MoneyPile private var startPile: MoneyPile { return self.hundred } init(hundred: MoneyPile, fifty: MoneyPile, twenty: MoneyPile, ten: MoneyPile) { self.hundred = hundred self.fifty = fifty self.twenty = twenty self.ten = ten } func canWithdraw(value: Int) -> String { return "Can withdraw: \(self.startPile.canWithdraw(value))" } } /*: ### Usage */ // Create piles of money and link them together 10 < 20 < 50 < 100.** let ten = MoneyPile(value: 10, quantity: 6, nextPile: nil) let twenty = MoneyPile(value: 20, quantity: 2, nextPile: ten) let fifty = MoneyPile(value: 50, quantity: 2, nextPile: twenty) let hundred = MoneyPile(value: 100, quantity: 1, nextPile: fifty) // Build ATM. var atm = ATM(hundred: hundred, fifty: fifty, twenty: twenty, ten: ten) atm.canWithdraw(310) // Cannot because ATM has only 300 atm.canWithdraw(100) // Can withdraw - 1x100 atm.canWithdraw(165) // Cannot withdraw because ATM doesn't has bill with value of 5 atm.canWithdraw(30) // Can withdraw - 1x20, 2x10 /*: 👫 Command ---------- The command pattern is used to express a request, including the call to be made and all of its required parameters, in a command object. The command may then be executed immediately or held for later use. ### Example: */ protocol DoorCommand { func execute() -> String } class OpenCommand : DoorCommand { let doors:String required init(doors: String) { self.doors = doors } func execute() -> String { return "Opened \(doors)" } } class CloseCommand : DoorCommand { let doors:String required init(doors: String) { self.doors = doors } func execute() -> String { return "Closed \(doors)" } } class HAL9000DoorsOperations { let openCommand: DoorCommand let closeCommand: DoorCommand init(doors: String) { self.openCommand = OpenCommand(doors:doors) self.closeCommand = CloseCommand(doors:doors) } func close() -> String { return closeCommand.execute() } func open() -> String { return openCommand.execute() } } /*: ### Usage: */ let podBayDoors = "Pod Bay Doors" let doorModule = HAL9000DoorsOperations(doors:podBayDoors) doorModule.open() doorModule.close() /*: 🎶 Interpreter -------------- The interpreter pattern is used to evaluate sentences in a language. ### Example */ protocol IntegerExp { func evaluate(context: IntegerContext) -> Int func replace(character: Character, integerExp: IntegerExp) -> IntegerExp func copy() -> IntegerExp } class IntegerContext { private var data: [Character:Int] = [:] func lookup(name: Character) -> Int { return self.data[name]! } func assign(integerVarExp: IntegerVarExp, value: Int) { self.data[integerVarExp.name] = value } } class IntegerVarExp: IntegerExp { let name: Character init(name: Character) { self.name = name } func evaluate(context: IntegerContext) -> Int { return context.lookup(self.name) } func replace(name: Character, integerExp: IntegerExp) -> IntegerExp { if name == self.name { return integerExp.copy() } else { return IntegerVarExp(name: self.name) } } func copy() -> IntegerExp { return IntegerVarExp(name: self.name) } } class AddExp: IntegerExp { private var operand1: IntegerExp private var operand2: IntegerExp init(op1: IntegerExp, op2: IntegerExp) { self.operand1 = op1 self.operand2 = op2 } func evaluate(context: IntegerContext) -> Int { return self.operand1.evaluate(context) + self.operand2.evaluate(context) } func replace(character: Character, integerExp: IntegerExp) -> IntegerExp { return AddExp(op1: operand1.replace(character, integerExp: integerExp), op2: operand2.replace(character, integerExp: integerExp)) } func copy() -> IntegerExp { return AddExp(op1: self.operand1, op2: self.operand2) } } /*: ### Usage */ var expression: IntegerExp? var intContext = IntegerContext() var a = IntegerVarExp(name: "A") var b = IntegerVarExp(name: "B") var c = IntegerVarExp(name: "C") expression = AddExp(op1: a, op2: AddExp(op1: b, op2: c)) // a + (b + c) intContext.assign(a, value: 2) intContext.assign(b, value: 1) intContext.assign(c, value: 3) var result = expression?.evaluate(intContext) /*: 🍫 Iterator ----------- The iterator pattern is used to provide a standard interface for traversing a collection of items in an aggregate object without the need to understand its underlying structure. ### Example: */ struct NovellasCollection<T> { let novellas: [T] } extension NovellasCollection: SequenceType { typealias Generator = AnyGenerator<T> func generate() -> AnyGenerator<T> { var i = 0 return anyGenerator{ return i >= self.novellas.count ? nil : self.novellas[i++] } } } /*: ### Usage */ let greatNovellas = NovellasCollection(novellas:["Mist"]) for novella in greatNovellas { print("I've read: \(novella)") } /*: 💐 Mediator ----------- The mediator pattern is used to reduce coupling between classes that communicate with each other. Instead of classes communicating directly, and thus requiring knowledge of their implementation, the classes send messages via a mediator object. ### Example */ class Colleague { let mediator: Mediator init(mediator: Mediator) { self.mediator = mediator } func send(message: String) { mediator.send(message, colleague: self) } func receive(message: String) { assert(false, "Method should be overriden") } } protocol Mediator { func send(message: String, colleague: Colleague) } class MessageMediator: Mediator { private var colleagues: [Colleague] = [] func addColleague(colleague: Colleague) { colleagues.append(colleague) } func send(message: String, colleague: Colleague) { for c in colleagues { if c !== colleague { //for simplicity we compare object references colleague.receive(message) } } } } class ConcreteColleague: Colleague { override func receive(message: String) { print("Colleague received: \(message)") } } /*: ### Usage */ let messagesMediator = MessageMediator() let user0 = ConcreteColleague(mediator: messagesMediator) let user1 = ConcreteColleague(mediator: messagesMediator) messagesMediator.addColleague(user0) messagesMediator.addColleague(user1) user0.send("Hello") // user1 receives message /*: 💾 Memento ---------- The memento pattern is used to capture the current state of an object and store it in such a manner that it can be restored at a later time without breaking the rules of encapsulation. ### Example */ typealias Memento = Dictionary<NSObject, AnyObject> let DPMementoKeyChapter = "com.valve.halflife.chapter" let DPMementoKeyWeapon = "com.valve.halflife.weapon" let DPMementoGameState = "com.valve.halflife.state" /*: Originator */ class GameState { var chapter: String = "" var weapon: String = "" func toMemento() -> Memento { return [ DPMementoKeyChapter:chapter, DPMementoKeyWeapon:weapon ] } func restoreFromMemento(memento: Memento) { chapter = memento[DPMementoKeyChapter] as? String ?? "n/a" weapon = memento[DPMementoKeyWeapon] as? String ?? "n/a" } } /*: Caretaker */ class CheckPoint { class func saveState(memento: Memento, keyName: String = DPMementoGameState) { let defaults = NSUserDefaults.standardUserDefaults() defaults.setObject(memento, forKey: keyName) defaults.synchronize() } class func restorePreviousState(keyName keyName: String = DPMementoGameState) -> Memento { let defaults = NSUserDefaults.standardUserDefaults() return defaults.objectForKey(keyName) as? Memento ?? Memento() } } /*: ### Usage */ var gameState = GameState() gameState.restoreFromMemento(CheckPoint.restorePreviousState()) gameState.chapter = "Black Mesa Inbound" gameState.weapon = "Crowbar" CheckPoint.saveState(gameState.toMemento()) gameState.chapter = "Anomalous Materials" gameState.weapon = "Glock 17" gameState.restoreFromMemento(CheckPoint.restorePreviousState()) gameState.chapter = "Unforeseen Consequences" gameState.weapon = "MP5" CheckPoint.saveState(gameState.toMemento(), keyName: "gameState2") gameState.chapter = "Office Complex" gameState.weapon = "Crossbow" CheckPoint.saveState(gameState.toMemento()) gameState.restoreFromMemento(CheckPoint.restorePreviousState(keyName: "gameState2")) /*: 👓 Observer ----------- The observer pattern is used to allow an object to publish changes to its state. Other objects subscribe to be immediately notified of any changes. ### Example */ protocol PropertyObserver : class { func willChangePropertyName(propertyName:String, newPropertyValue:AnyObject?) func didChangePropertyName(propertyName:String, oldPropertyValue:AnyObject?) } class TestChambers { weak var observer:PropertyObserver? var testChamberNumber: Int = 0 { willSet(newValue) { observer?.willChangePropertyName("testChamberNumber", newPropertyValue:newValue) } didSet { observer?.didChangePropertyName("testChamberNumber", oldPropertyValue:oldValue) } } } class Observer : PropertyObserver { func willChangePropertyName(propertyName: String, newPropertyValue: AnyObject?) { if newPropertyValue as? Int == 1 { print("Okay. Look. We both said a lot of things that you're going to regret.") } } func didChangePropertyName(propertyName: String, oldPropertyValue: AnyObject?) { if oldPropertyValue as? Int == 0 { print("Sorry about the mess. I've really let the place go since you killed me.") } } } /*: ### Usage */ var observerInstance = Observer() var testChambers = TestChambers() testChambers.observer = observerInstance testChambers.testChamberNumber++ /*: 🐉 State --------- The state pattern is used to alter the behaviour of an object as its internal state changes. The pattern allows the class for an object to apparently change at run-time. ### Example */ class Context { private var state: State = UnauthorizedState() var isAuthorized: Bool { get { return state.isAuthorized(self) } } var userId: String? { get { return state.userId(self) } } func changeStateToAuthorized(userId userId: String) { state = AuthorizedState(userId: userId) } func changeStateToUnauthorized() { state = UnauthorizedState() } } protocol State { func isAuthorized(context: Context) -> Bool func userId(context: Context) -> String? } class UnauthorizedState: State { func isAuthorized(context: Context) -> Bool { return false } func userId(context: Context) -> String? { return nil } } class AuthorizedState: State { let userId: String init(userId: String) { self.userId = userId } func isAuthorized(context: Context) -> Bool { return true } func userId(context: Context) -> String? { return userId } } /*: ### Usage */ let context = Context() (context.isAuthorized, context.userId) context.changeStateToAuthorized(userId: "admin") (context.isAuthorized, context.userId) // now logged in as "admin" context.changeStateToUnauthorized() (context.isAuthorized, context.userId) /*: 💡 Strategy ----------- The strategy pattern is used to create an interchangeable family of algorithms from which the required process is chosen at run-time. ### Example */ protocol PrintStrategy { func printString(string: String) -> String } class Printer { let strategy: PrintStrategy func printString(string: String) -> String { return self.strategy.printString(string) } init(strategy: PrintStrategy) { self.strategy = strategy } } class UpperCaseStrategy : PrintStrategy { func printString(string:String) -> String { return string.uppercaseString } } class LowerCaseStrategy : PrintStrategy { func printString(string:String) -> String { return string.lowercaseString } } /*: ### Usage */ var lower = Printer(strategy:LowerCaseStrategy()) lower.printString("O tempora, o mores!") var upper = Printer(strategy:UpperCaseStrategy()) upper.printString("O tempora, o mores!") /*: 🏃 Visitor ---------- The visitor pattern is used to separate a relatively complex set of structured data classes from the functionality that may be performed upon the data that they hold. ### Example */ protocol PlanetVisitor { func visit(planet: PlanetAlderaan) func visit(planet: PlanetCoruscant) func visit(planet: PlanetTatooine) } protocol Planet { func accept(visitor: PlanetVisitor) } class PlanetAlderaan: Planet { func accept(visitor: PlanetVisitor) { visitor.visit(self) } } class PlanetCoruscant: Planet { func accept(visitor: PlanetVisitor) { visitor.visit(self) } } class PlanetTatooine: Planet { func accept(visitor: PlanetVisitor) { visitor.visit(self) } } class NameVisitor: PlanetVisitor { var name = "" func visit(planet: PlanetAlderaan) { name = "Alderaan" } func visit(planet: PlanetCoruscant) { name = "Coruscant" } func visit(planet: PlanetTatooine) { name = "Tatooine" } } /*: ### Usage */ let planets: [Planet] = [PlanetAlderaan(), PlanetCoruscant(), PlanetTatooine()] let names = planets.map { (planet: Planet) -> String in let visitor = NameVisitor() planet.accept(visitor) return visitor.name } names
gpl-3.0
a375f432aea2eb8fd04cec63f4b68795
24.16913
245
0.672691
3.936312
false
false
false
false
JoeHolt/BetterReminders
BetterReminders/JHSchoolClass.swift
1
4566
// // File.swift // BetterReminders // // Created by Joe Holt on 3/27/17. // Copyright © 2017 Joe Holt. All rights reserved. // import Foundation @objc(JHSchoolClass) class JHSchoolClass: NSObject, NSCoding { // MARK: - Properties internal var name: String! internal var startDate: Date! internal var endDate: Date! internal var day: String! internal var notifyAtEnd: Bool! internal var tasks: [JHTask] = [] internal var id: Int! override var description: String { return name } // MARK: - Init functions init(name: String, startDate: Date, endDate: Date, day: String, notify: Bool = true) { self.name = name self.startDate = startDate self.endDate = endDate self.day = day self.notifyAtEnd = notify self.id = Int(arc4random_uniform(999999999)) } required init(coder decoder: NSCoder) { self.name = decoder.decodeObject(forKey: "name") as! String self.startDate = decoder.decodeObject(forKey: "startDate") as! Date self.endDate = decoder.decodeObject(forKey: "endDate") as! Date self.day = decoder.decodeObject(forKey: "day") as! String self.id = decoder.decodeObject(forKey: "id") as! Int self.notifyAtEnd = decoder.decodeObject(forKey: "notifyAtEnd") as! Bool if decoder.decodeObject(forKey: "tasks") as? [JHTask] != nil { self.tasks = decoder.decodeObject(forKey: "tasks") as! [JHTask] } else { self.tasks = [] } } internal func encode(with coder: NSCoder) { coder.encode(name, forKey: "name") coder.encode(startDate, forKey: "startDate") coder.encode(endDate, forKey: "endDate") coder.encode(day, forKey: "day") coder.encode(tasks, forKey: "tasks") coder.encode(id, forKey: "id") coder.encode(id, forKey: "notifyAtEnd") } // MARK: - Time functinos /** Finds time to complete class tasks - returns: Time to complete in minutes and hours: (hours, minutes) */ internal func timeToCompleteTasks() -> (Int, Int) { //Returns time to finish tasks in (hour, minute) format var hours = 0 var minutes = 0 for t in tasks { if t.completed == false { if let ttc = t.estimatedTimeToComplete { let tComps = Calendar.current.dateComponents(in: .current, from: ttc) hours += tComps.hour! minutes += tComps.minute! while minutes >= 60 { minutes = minutes - 60 hours += 1 } } } } return (hours, minutes) } // MARK: - Task functinos /** Returns array of uncompleted tasks - returns: array of uncompleted tasks */ internal func uncompletedTasks() -> [JHTask] { var uTasks = [JHTask]() for task in tasks { if task.completed == false { uTasks.append(task) } } return uTasks } /** Returns array of completed tasks - returns: array of completed tasks */ internal func completedTasks() -> [JHTask] { var uTasks = [JHTask]() for task in tasks { if task.completed == true { uTasks.append(task) } } return uTasks } /** Marks all tasks in class completed */ internal func markAllTasksCompleted() { for task in tasks { task.completed = true } } /** Adds new task to class - parameter task: Task to be added - parameter atStart: Add task at start? */ internal func addTask(task: JHTask, atStart: Bool = false) { if atStart { tasks.insert(task, at: 0) } else { tasks.append(task) } } /** Removes task - parameter index: Index of task to be removed */ internal func removeTask(at index: Int) { tasks.remove(at: index) } /** Removes a task - parameter id: id of task to be removed */ internal func removeTask(withId id: Int) { for i in 0...tasks.count - 1 { if tasks[i].id == id { removeTask(at: i) break } } } }
apache-2.0
bea9e89491fbb5a25051b7b10e958a0f
25.695906
90
0.530559
4.380998
false
false
false
false
RMizin/PigeonMessenger-project
FalconMessenger/ChatsControllers/MessageSender.swift
1
17609
// // MessageSender.swift // FalconMessenger // // Created by Roman Mizin on 9/13/18. // Copyright © 2018 Roman Mizin. All rights reserved. // import UIKit import Firebase import Photos protocol MessageSenderDelegate: class { func update(with arrayOfvalues: [[String: AnyObject]]) func update(mediaSending progress: Double, animated: Bool) } class MessageSender: NSObject { fileprivate let storageUploader = StorageMediaUploader() fileprivate var conversation: Conversation? fileprivate var attachedMedia = [MediaObject]() fileprivate var text: String? fileprivate var dataToUpdate = [[String: AnyObject]]() weak var delegate: MessageSenderDelegate? init(_ conversation: Conversation?, text: String?, media: [MediaObject]) { self.conversation = conversation self.text = text self.attachedMedia = media } public func sendMessage() { syncronizeMediaSending() sendTextMessage() attachedMedia.forEach { (mediaObject) in let isVoiceMessage = mediaObject.audioObject != nil let isPhotoMessage = (mediaObject.phAsset?.mediaType == PHAssetMediaType.image || mediaObject.phAsset == nil) && mediaObject.audioObject == nil && mediaObject.localVideoURL == nil let isVideoMessage = mediaObject.phAsset?.mediaType == PHAssetMediaType.video || mediaObject.localVideoURL != nil if isVoiceMessage { sendVoiceMessage(object: mediaObject) } else if isPhotoMessage { sendPhotoMessage(object: mediaObject) } else if isVideoMessage { sendVideoMessage(object: mediaObject) } } } fileprivate var mediaUploadGroup = DispatchGroup() fileprivate var localUpdateGroup = DispatchGroup() fileprivate var mediaCount = CGFloat() fileprivate var mediaToSend = [(values: [String: AnyObject], reference: DatabaseReference)]() fileprivate var progress = [UploadProgress]() fileprivate func syncronizeMediaSending() { guard let toID = conversation?.chatID, let fromID = Auth.auth().currentUser?.uid else { return } mediaUploadGroup = DispatchGroup() localUpdateGroup = DispatchGroup() mediaCount = CGFloat() mediaToSend.removeAll() progress.removeAll() mediaUploadGroup.enter() // for text message localUpdateGroup.enter() mediaCount += 1 // for text message attachedMedia.forEach { (media) in mediaUploadGroup.enter() localUpdateGroup.enter() mediaCount += 1 } localUpdateGroup.notify(queue: .main) { self.delegate?.update(with: self.dataToUpdate) self.dataToUpdate.removeAll() } mediaUploadGroup.notify(queue: .global(qos: .default), execute: { self.mediaToSend.forEach({ (element) in self.updateDatabase(at: element.reference, with: element.values, toID: toID, fromID: fromID) }) }) } // MARK: TEXT MESSAGE fileprivate func sendTextMessage() { guard let toID = conversation?.chatID, let fromID = Auth.auth().currentUser?.uid, let text = self.text else { self.mediaCount -= 1 self.mediaUploadGroup.leave() self.localUpdateGroup.leave() return } guard text != "" else { self.mediaCount -= 1 self.mediaUploadGroup.leave() self.localUpdateGroup.leave() return } let reference = Database.database().reference().child("messages").childByAutoId() guard let messageUID = reference.key else { return } let messageStatus = messageStatusDelivered let timestamp = NSNumber(value: Int(Date().timeIntervalSince1970)) let defaultData: [String: AnyObject] = ["messageUID": messageUID as AnyObject, "toId": toID as AnyObject, "status": messageStatus as AnyObject, "seen": false as AnyObject, "fromId": fromID as AnyObject, "timestamp": timestamp, "text": text as AnyObject] dataToUpdate.append(defaultData) self.localUpdateGroup.leave() // delegate?.update(with: defaultData) self.mediaToSend.append((values: defaultData, reference: reference)) self.mediaUploadGroup.leave() self.progress.setProgress(1.0, id: messageUID) self.updateProgress(self.progress, mediaCount: self.mediaCount) } // MARK: PHOTO MESSAGE fileprivate func sendPhotoMessage(object: MediaObject) { guard let toID = conversation?.chatID, let fromID = Auth.auth().currentUser?.uid else { self.mediaUploadGroup.leave() self.localUpdateGroup.leave() return } let reference = Database.database().reference().child("messages").childByAutoId() guard let messageUID = reference.key else { return } let messageStatus = messageStatusDelivered let timestamp = NSNumber(value: Int(Date().timeIntervalSince1970)) let defaultData: [String: AnyObject] = ["messageUID": messageUID as AnyObject, "toId": toID as AnyObject, "status": messageStatus as AnyObject, "seen": false as AnyObject, "fromId": fromID as AnyObject, "timestamp": timestamp, "imageWidth": object.object!.asUIImage!.size.width as AnyObject, "imageHeight": object.object!.asUIImage!.size.height as AnyObject] var localData: [String: AnyObject] = ["localImage": object.object!.asUIImage!] defaultData.forEach({ localData[$0] = $1 }) //delegate?.update(with: localData) dataToUpdate.append(localData) localUpdateGroup.leave() storageUploader.uploadThumbnail(createImageThumbnail(object.object!.asUIImage!), progress: { (snapshot) in // if let progressCount = snapshot?.progress?.fractionCompleted { // // self.progress.setProgress(progressCount * 0.98, id: messageUID) // self.updateProgress(self.progress, mediaCount: self.mediaCount) // } }) { (thumbnailImageUrl) in self.uploadOriginalImage(object: object, defaultData: defaultData, messageUID: messageUID, reference: reference, thumbnailImageUrl: thumbnailImageUrl) } } fileprivate func uploadOriginalImage(object: MediaObject, defaultData: [String: AnyObject], messageUID: String, reference: DatabaseReference, thumbnailImageUrl: String) { storageUploader.upload(object.object!.asUIImage!, progress: { (snapshot) in if let progressCount = snapshot?.progress?.fractionCompleted { self.progress.setProgress(progressCount * 0.98, id: messageUID) self.updateProgress(self.progress, mediaCount: self.mediaCount) } }) { (imageURL) in self.progress.setProgress(1.0, id: messageUID) self.updateProgress(self.progress, mediaCount: self.mediaCount) var remoteData: [String: AnyObject] = ["imageUrl": imageURL as AnyObject, "thumbnailImageUrl": thumbnailImageUrl as AnyObject] defaultData.forEach({ remoteData[$0] = $1 }) self.mediaToSend.append((values: remoteData, reference: reference)) self.mediaUploadGroup.leave() } } // MARK: VIDEO MESSAGE fileprivate func sendVideoMessage(object: MediaObject) { guard let toID = conversation?.chatID, let fromID = Auth.auth().currentUser?.uid, let path = object.fileURL else { self.mediaUploadGroup.leave() self.localUpdateGroup.leave() return } let reference = Database.database().reference().child("messages").childByAutoId() guard let messageUID = reference.key else { return } // guard let imageIDKey = reference.key else { return } let messageStatus = messageStatusDelivered let timestamp = NSNumber(value: Int(Date().timeIntervalSince1970)) let videoID = messageUID let imageID = messageUID + "image" let defaultData: [String: AnyObject] = ["messageUID": messageUID as AnyObject, "toId": toID as AnyObject, "status": messageStatus as AnyObject, "seen": false as AnyObject, "fromId": fromID as AnyObject, "timestamp": timestamp, "imageWidth": object.object!.asUIImage!.size.width as AnyObject, "imageHeight": object.object!.asUIImage!.size.height as AnyObject] var localData: [String: AnyObject] = ["localImage": object.object!.asUIImage!, "localVideoUrl": path as AnyObject, "localVideoIdentifier": object.phAsset?.localIdentifier as AnyObject] defaultData.forEach({ localData[$0] = $1 }) // delegate?.update(with: localData) dataToUpdate.append(localData) self.localUpdateGroup.leave() storageUploader.upload(object.videoObject!, progress: { [unowned self] (snapshot) in if let progressCount = snapshot?.progress?.fractionCompleted { self.progress.setProgress(progressCount * 0.98, id: videoID) self.updateProgress(self.progress, mediaCount: self.mediaCount) } }) { (videoURL) in self.progress.setProgress(1.0, id: messageUID) self.updateProgress(self.progress, mediaCount: self.mediaCount) self.storageUploader.uploadThumbnail(createImageThumbnail(object.object!.asUIImage!), progress: { (snapshot) in // if let progressCount = snapshot?.progress?.fractionCompleted { // // self.progress.setProgress(progressCount * 0.98, id: messageUID) // self.updateProgress(self.progress, mediaCount: self.mediaCount) // } }) { (thumbnailImageUrl) in self.uploadVideoPreviewImage(object: object, defaultData: defaultData, messageUID: messageUID, reference: reference, thumbnailImageUrl: thumbnailImageUrl, imageID: imageID, videoURL: videoURL) } } } fileprivate func uploadVideoPreviewImage(object: MediaObject, defaultData: [String: AnyObject], messageUID: String, reference: DatabaseReference, thumbnailImageUrl: String, imageID: String, videoURL: String) { storageUploader.upload(object.object!.asUIImage!, progress: { [unowned self] (snapshot) in if let progressCount = snapshot?.progress?.fractionCompleted { self.progress.setProgress(progressCount * 0.98, id: imageID) self.updateProgress(self.progress, mediaCount: self.mediaCount) } }, completion: { (imageURL) in self.progress.setProgress(1.0, id: messageUID) self.updateProgress(self.progress, mediaCount: self.mediaCount) var remoteData: [String: AnyObject] = ["imageUrl": imageURL as AnyObject, "videoUrl": videoURL as AnyObject, "thumbnailImageUrl": thumbnailImageUrl as AnyObject] defaultData.forEach({ remoteData[$0] = $1 }) self.mediaToSend.append((values: remoteData, reference: reference)) self.mediaUploadGroup.leave() }) } // MARK: VOICE MESSAGE fileprivate func sendVoiceMessage(object: MediaObject) { guard let toID = conversation?.chatID, let fromID = Auth.auth().currentUser?.uid else { self.mediaUploadGroup.leave() self.localUpdateGroup.leave() return } let reference = Database.database().reference().child("messages").childByAutoId() guard let messageUID = reference.key else { return } let messageStatus = messageStatusDelivered let timestamp = NSNumber(value: Int(Date().timeIntervalSince1970)) let bae64string = object.audioObject?.base64EncodedString() let defaultData: [String: AnyObject] = ["messageUID": messageUID as AnyObject, "toId": toID as AnyObject, "status": messageStatus as AnyObject, "seen": false as AnyObject, "fromId": fromID as AnyObject, "timestamp": timestamp, "voiceEncodedString": bae64string as AnyObject] // delegate?.update(with: defaultData) dataToUpdate.append(defaultData) self.localUpdateGroup.leave() mediaToSend.append((values: defaultData, reference: reference)) mediaUploadGroup.leave() progress.setProgress(1.0, id: messageUID) updateProgress(progress, mediaCount: mediaCount) } fileprivate func updateProgress(_ array: [UploadProgress], mediaCount: CGFloat) { let totalProgressArray = array.map({$0.progress}) let completedUploadsCount = totalProgressArray.reduce(0, +) let progress = completedUploadsCount/Double(mediaCount) delegate?.update(mediaSending: progress, animated: true) guard progress >= 0.99999 else { return } self.delegate?.update(mediaSending: 0.0, animated: false) } fileprivate func updateDatabase(at reference: DatabaseReference, with values: [String: AnyObject], toID: String, fromID: String) { reference.updateChildValues(values) { (error, _) in guard let messageID = reference.key else { return } if let isGroupChat = self.conversation?.isGroupChat.value, isGroupChat { let groupMessagesRef = Database.database().reference().child("groupChats").child(toID).child(userMessagesFirebaseFolder) groupMessagesRef.updateChildValues([messageID: fromID]) // needed to update ui for current user as fast as possible //for other members this update handled by backend let userMessagesRef = Database.database().reference().child("user-messages").child(fromID).child(toID).child(userMessagesFirebaseFolder) userMessagesRef.updateChildValues([messageID: fromID]) //userMessagesRef.database.purgeOutstandingWrites() //userMessagesRef.database.purgeOutstandingWrites() // incrementing badge for group chats handled by backend, to reduce number of write operations from device self.updateGroupLastMessage() } else { let userMessagesRef = Database.database().reference().child("user-messages").child(fromID).child(toID).child(userMessagesFirebaseFolder) // userMessagesRef.updateChildValues([messageID: fromID]) userMessagesRef.updateChildValues([messageID: fromID], withCompletionBlock: { (error, reference) in guard error == nil else { print("Updating error"); return } print("updateing completed") }) let recipientUserMessagesRef = Database.database().reference().child("user-messages").child(toID).child(fromID).child(userMessagesFirebaseFolder) recipientUserMessagesRef.updateChildValues([messageID: fromID]) self.incrementBadge() self.updateDefaultChatLastMessage() } } } fileprivate func incrementBadge() { /* default chats only, group chats badges handled by backend */ guard let toId = conversation?.chatID, let fromId = Auth.auth().currentUser?.uid, toId != fromId else { return } runTransaction(firstChild: toId, secondChild: fromId) } fileprivate func updateDefaultChatLastMessage() { guard let fromID = Auth.auth().currentUser?.uid, let conversationID = conversation?.chatID else { return } let lastMessageQORef = Database.database().reference() .child("user-messages").child(fromID).child(conversationID).child(userMessagesFirebaseFolder).queryLimited(toLast: UInt(1)) lastMessageQORef.observeSingleEvent(of: .childAdded) { (snapshot) in let ref = Database.database().reference().child("user-messages").child(fromID).child(conversationID).child(messageMetaDataFirebaseFolder) let childValues: [String: Any] = ["chatID": conversationID, "lastMessageID": snapshot.key, "isGroupChat": false] ref.updateChildValues(childValues) } let lastMessageQIRef = Database.database().reference() .child("user-messages").child(conversationID).child(fromID).child(userMessagesFirebaseFolder).queryLimited(toLast: UInt(1)) lastMessageQIRef.observeSingleEvent(of: .childAdded) { (snapshot) in let ref = Database.database().reference().child("user-messages").child(conversationID).child(fromID).child(messageMetaDataFirebaseFolder) let childValues: [String: Any] = ["chatID": fromID, "lastMessageID": snapshot.key, "isGroupChat": false] ref.updateChildValues(childValues) } } fileprivate func updateGroupLastMessage() { // updates only for current user // for other users this update handled by Backend to reduce write operations on device guard let fromID = Auth.auth().currentUser?.uid, let conversationID = conversation?.chatID else { return } let lastMessageQRef = Database.database().reference() .child("user-messages").child(fromID).child(conversationID).child(userMessagesFirebaseFolder).queryLimited(toLast: UInt(1)) lastMessageQRef.observeSingleEvent(of: .childAdded) { (snapshot) in let ref = Database.database().reference().child("user-messages").child(fromID).child(conversationID).child(messageMetaDataFirebaseFolder) let childValues: [String: Any] = ["lastMessageID": snapshot.key] ref.updateChildValues(childValues) } } }
gpl-3.0
d2084e6299423495df36928021ef0cea
41.023866
185
0.66095
4.560477
false
false
false
false
watson-developer-cloud/ios-sdk
Sources/DiscoveryV2/Models/DefaultQueryParamsSuggestedRefinements.swift
1
1733
/** * (C) Copyright IBM Corp. 2020. * * 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 /** Object that contains suggested refinement settings. Available with Premium plans only. */ public struct DefaultQueryParamsSuggestedRefinements: Codable, Equatable { /** When `true`, suggested refinements for the query are returned by default. */ public var enabled: Bool? /** The number of suggested refinements to return by default. */ public var count: Int? // Map each property name to the key that shall be used for encoding/decoding. private enum CodingKeys: String, CodingKey { case enabled = "enabled" case count = "count" } /** Initialize a `DefaultQueryParamsSuggestedRefinements` with member variables. - parameter enabled: When `true`, suggested refinements for the query are returned by default. - parameter count: The number of suggested refinements to return by default. - returns: An initialized `DefaultQueryParamsSuggestedRefinements`. */ public init( enabled: Bool? = nil, count: Int? = nil ) { self.enabled = enabled self.count = count } }
apache-2.0
c46130cdc56cfcac28a73a111b10e288
29.403509
100
0.690133
4.548556
false
false
false
false
kunitoku/RssReader
Pods/RealmSwift/RealmSwift/List.swift
3
26291
//////////////////////////////////////////////////////////////////////////// // // Copyright 2014 Realm 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 import Realm import Realm.Private /// :nodoc: /// Internal class. Do not use directly. public class ListBase: RLMListBase { // Printable requires a description property defined in Swift (and not obj-c), // and it has to be defined as override, which can't be done in a // generic class. /// Returns a human-readable description of the objects contained in the List. @objc public override var description: String { return descriptionWithMaxDepth(RLMDescriptionMaxDepth) } @objc private func descriptionWithMaxDepth(_ depth: UInt) -> String { return RLMDescriptionWithMaxDepth("List", _rlmArray, depth) } /// Returns the number of objects in this List. public var count: Int { return Int(_rlmArray.count) } } /** `List` is the container type in Realm used to define to-many relationships. Like Swift's `Array`, `List` is a generic type that is parameterized on the type of `Object` it stores. Unlike Swift's native collections, `List`s are reference types, and are only immutable if the Realm that manages them is opened as read-only. Lists can be filtered and sorted with the same predicates as `Results<Element>`. Properties of `List` type defined on `Object` subclasses must be declared as `let` and cannot be `dynamic`. */ public final class List<Element: RealmCollectionValue>: ListBase { // MARK: Properties /// The Realm which manages the list, or `nil` if the list is unmanaged. public var realm: Realm? { return _rlmArray.realm.map { Realm($0) } } /// Indicates if the list can no longer be accessed. public var isInvalidated: Bool { return _rlmArray.isInvalidated } // MARK: Initializers /// Creates a `List` that holds Realm model objects of type `Element`. public override init() { super.init(array: Element._rlmArray()) } internal init(rlmArray: RLMArray<AnyObject>) { super.init(array: rlmArray) } // MARK: Index Retrieval /** Returns the index of an object in the list, or `nil` if the object is not present. - parameter object: An object to find. */ public func index(of object: Element) -> Int? { return notFoundToNil(index: _rlmArray.index(of: dynamicBridgeCast(fromSwift: object) as AnyObject)) } /** Returns the index of the first object in the list matching the predicate, or `nil` if no objects match. - parameter predicate: The predicate with which to filter the objects. */ public func index(matching predicate: NSPredicate) -> Int? { return notFoundToNil(index: _rlmArray.indexOfObject(with: predicate)) } /** Returns the index of the first object in the list matching the predicate, or `nil` if no objects match. - parameter predicateFormat: A predicate format string, optionally followed by a variable number of arguments. */ public func index(matching predicateFormat: String, _ args: Any...) -> Int? { return index(matching: NSPredicate(format: predicateFormat, argumentArray: unwrapOptionals(in: args))) } // MARK: Object Retrieval /** Returns the object at the given index (get), or replaces the object at the given index (set). - warning: You can only set an object during a write transaction. - parameter index: The index of the object to retrieve or replace. */ public subscript(position: Int) -> Element { get { throwForNegativeIndex(position) return dynamicBridgeCast(fromObjectiveC: _rlmArray.object(at: UInt(position))) } set { throwForNegativeIndex(position) _rlmArray.replaceObject(at: UInt(position), with: dynamicBridgeCast(fromSwift: newValue) as AnyObject) } } /// Returns the first object in the list, or `nil` if the list is empty. public var first: Element? { return _rlmArray.firstObject().map(dynamicBridgeCast) } /// Returns the last object in the list, or `nil` if the list is empty. public var last: Element? { return _rlmArray.lastObject().map(dynamicBridgeCast) } // MARK: KVC /** Returns an `Array` containing the results of invoking `valueForKey(_:)` using `key` on each of the collection's objects. */ @nonobjc public func value(forKey key: String) -> [AnyObject] { return _rlmArray.value(forKeyPath: key)! as! [AnyObject] } /** Returns an `Array` containing the results of invoking `valueForKeyPath(_:)` using `keyPath` on each of the collection's objects. - parameter keyPath: The key path to the property whose values are desired. */ @nonobjc public func value(forKeyPath keyPath: String) -> [AnyObject] { return _rlmArray.value(forKeyPath: keyPath) as! [AnyObject] } /** Invokes `setValue(_:forKey:)` on each of the collection's objects using the specified `value` and `key`. - warning: This method can only be called during a write transaction. - parameter value: The object value. - parameter key: The name of the property whose value should be set on each object. */ public override func setValue(_ value: Any?, forKey key: String) { return _rlmArray.setValue(value, forKeyPath: key) } // MARK: Filtering /** Returns a `Results` containing all objects matching the given predicate in the list. - parameter predicateFormat: A predicate format string, optionally followed by a variable number of arguments. */ public func filter(_ predicateFormat: String, _ args: Any...) -> Results<Element> { return Results<Element>(_rlmArray.objects(with: NSPredicate(format: predicateFormat, argumentArray: unwrapOptionals(in: args)))) } /** Returns a `Results` containing all objects matching the given predicate in the list. - parameter predicate: The predicate with which to filter the objects. */ public func filter(_ predicate: NSPredicate) -> Results<Element> { return Results<Element>(_rlmArray.objects(with: predicate)) } // MARK: Sorting /** Returns a `Results` containing the objects in the list, but sorted. Objects are sorted based on the values of the given key path. For example, to sort a list of `Student`s from youngest to oldest based on their `age` property, you might call `students.sorted(byKeyPath: "age", ascending: true)`. - warning: Lists may only be sorted by properties of boolean, `Date`, `NSDate`, single and double-precision floating point, integer, and string types. - parameter keyPath: The key path to sort by. - parameter ascending: The direction to sort in. */ public func sorted(byKeyPath keyPath: String, ascending: Bool = true) -> Results<Element> { return sorted(by: [SortDescriptor(keyPath: keyPath, ascending: ascending)]) } /** Returns a `Results` containing the objects in the list, but sorted. - warning: Lists may only be sorted by properties of boolean, `Date`, `NSDate`, single and double-precision floating point, integer, and string types. - see: `sorted(byKeyPath:ascending:)` */ public func sorted<S: Sequence>(by sortDescriptors: S) -> Results<Element> where S.Iterator.Element == SortDescriptor { return Results<Element>(_rlmArray.sortedResults(using: sortDescriptors.map { $0.rlmSortDescriptorValue })) } // MARK: Aggregate Operations /** Returns the minimum (lowest) value of the given property among all the objects in the list, or `nil` if the list is empty. - warning: Only a property whose type conforms to the `MinMaxType` protocol can be specified. - parameter property: The name of a property whose minimum value is desired. */ public func min<T: MinMaxType>(ofProperty property: String) -> T? { return _rlmArray.min(ofProperty: property).map(dynamicBridgeCast) } /** Returns the maximum (highest) value of the given property among all the objects in the list, or `nil` if the list is empty. - warning: Only a property whose type conforms to the `MinMaxType` protocol can be specified. - parameter property: The name of a property whose maximum value is desired. */ public func max<T: MinMaxType>(ofProperty property: String) -> T? { return _rlmArray.max(ofProperty: property).map(dynamicBridgeCast) } /** Returns the sum of the values of a given property over all the objects in the list. - warning: Only a property whose type conforms to the `AddableType` protocol can be specified. - parameter property: The name of a property whose values should be summed. */ public func sum<T: AddableType>(ofProperty property: String) -> T { return dynamicBridgeCast(fromObjectiveC: _rlmArray.sum(ofProperty: property)) } /** Returns the average value of a given property over all the objects in the list, or `nil` if the list is empty. - warning: Only a property whose type conforms to the `AddableType` protocol can be specified. - parameter property: The name of a property whose average value should be calculated. */ public func average(ofProperty property: String) -> Double? { return _rlmArray.average(ofProperty: property).map(dynamicBridgeCast) } // MARK: Mutation /** Appends the given object to the end of the list. If the object is managed by a different Realm than the receiver, a copy is made and added to the Realm managing the receiver. - warning: This method may only be called during a write transaction. - parameter object: An object. */ public func append(_ object: Element) { _rlmArray.add(dynamicBridgeCast(fromSwift: object) as AnyObject) } /** Appends the objects in the given sequence to the end of the list. - warning: This method may only be called during a write transaction. */ public func append<S: Sequence>(objectsIn objects: S) where S.Iterator.Element == Element { for obj in objects { _rlmArray.add(dynamicBridgeCast(fromSwift: obj) as AnyObject) } } /** Inserts an object at the given index. - warning: This method may only be called during a write transaction. - warning: This method will throw an exception if called with an invalid index. - parameter object: An object. - parameter index: The index at which to insert the object. */ public func insert(_ object: Element, at index: Int) { throwForNegativeIndex(index) _rlmArray.insert(dynamicBridgeCast(fromSwift: object) as AnyObject, at: UInt(index)) } /** Removes an object at the given index. The object is not removed from the Realm that manages it. - warning: This method may only be called during a write transaction. - warning: This method will throw an exception if called with an invalid index. - parameter index: The index at which to remove the object. */ public func remove(at index: Int) { throwForNegativeIndex(index) _rlmArray.removeObject(at: UInt(index)) } /** Removes all objects from the list. The objects are not removed from the Realm that manages them. - warning: This method may only be called during a write transaction. */ public func removeAll() { _rlmArray.removeAllObjects() } /** Replaces an object at the given index with a new object. - warning: This method may only be called during a write transaction. - warning: This method will throw an exception if called with an invalid index. - parameter index: The index of the object to be replaced. - parameter object: An object. */ public func replace(index: Int, object: Element) { throwForNegativeIndex(index) _rlmArray.replaceObject(at: UInt(index), with: dynamicBridgeCast(fromSwift: object) as AnyObject) } /** Moves the object at the given source index to the given destination index. - warning: This method may only be called during a write transaction. - warning: This method will throw an exception if called with invalid indices. - parameter from: The index of the object to be moved. - parameter to: index to which the object at `from` should be moved. */ public func move(from: Int, to: Int) { throwForNegativeIndex(from) throwForNegativeIndex(to) _rlmArray.moveObject(at: UInt(from), to: UInt(to)) } /** Exchanges the objects in the list at given indices. - warning: This method may only be called during a write transaction. - warning: This method will throw an exception if called with invalid indices. - parameter index1: The index of the object which should replace the object at index `index2`. - parameter index2: The index of the object which should replace the object at index `index1`. */ public func swapAt(_ index1: Int, _ index2: Int) { throwForNegativeIndex(index1, parameterName: "index1") throwForNegativeIndex(index2, parameterName: "index2") _rlmArray.exchangeObject(at: UInt(index1), withObjectAt: UInt(index2)) } // MARK: Notifications /** Registers a block to be called each time the collection changes. The block will be asynchronously called with the initial results, and then called again after each write transaction which changes either any of the objects in the collection, or which objects are in the collection. The `change` parameter that is passed to the block reports, in the form of indices within the collection, which of the objects were added, removed, or modified during each write transaction. See the `RealmCollectionChange` documentation for more information on the change information supplied and an example of how to use it to update a `UITableView`. At the time when the block is called, the collection will be fully evaluated and up-to-date, and as long as you do not perform a write transaction on the same thread or explicitly call `realm.refresh()`, accessing it will never perform blocking work. Notifications are delivered via the standard run loop, and so can't be delivered while the run loop is blocked by other activity. When notifications can't be delivered instantly, multiple notifications may be coalesced into a single notification. This can include the notification with the initial collection. For example, the following code performs a write transaction immediately after adding the notification block, so there is no opportunity for the initial notification to be delivered first. As a result, the initial notification will reflect the state of the Realm after the write transaction. ```swift let results = realm.objects(Dog.self) print("dogs.count: \(dogs?.count)") // => 0 let token = dogs.observe { changes in switch changes { case .initial(let dogs): // Will print "dogs.count: 1" print("dogs.count: \(dogs.count)") break case .update: // Will not be hit in this example break case .error: break } } try! realm.write { let dog = Dog() dog.name = "Rex" person.dogs.append(dog) } // end of run loop execution context ``` You must retain the returned token for as long as you want updates to be sent to the block. To stop receiving updates, call `invalidate()` on the token. - warning: This method cannot be called during a write transaction, or when the containing Realm is read-only. - parameter block: The block to be called whenever a change occurs. - returns: A token which must be held for as long as you want updates to be delivered. */ public func observe(_ block: @escaping (RealmCollectionChange<List>) -> Void) -> NotificationToken { return _rlmArray.addNotificationBlock { _, change, error in block(RealmCollectionChange.fromObjc(value: self, change: change, error: error)) } } } extension List where Element: MinMaxType { /** Returns the minimum (lowest) value in the list, or `nil` if the list is empty. */ public func min() -> Element? { return _rlmArray.min(ofProperty: "self").map(dynamicBridgeCast) } /** Returns the maximum (highest) value in the list, or `nil` if the list is empty. */ public func max() -> Element? { return _rlmArray.max(ofProperty: "self").map(dynamicBridgeCast) } } extension List where Element: AddableType { /** Returns the sum of the values in the list. */ public func sum() -> Element { return sum(ofProperty: "self") } /** Returns the average of the values in the list, or `nil` if the list is empty. */ public func average() -> Double? { return average(ofProperty: "self") } } extension List: RealmCollection { /// The type of the objects stored within the list. public typealias ElementType = Element // MARK: Sequence Support /// Returns a `RLMIterator` that yields successive elements in the `List`. public func makeIterator() -> RLMIterator<Element> { return RLMIterator(collection: _rlmArray) } /** Replace the given `subRange` of elements with `newElements`. - parameter subrange: The range of elements to be replaced. - parameter newElements: The new elements to be inserted into the List. */ public func replaceSubrange<C: Collection>(_ subrange: Range<Int>, with newElements: C) where C.Iterator.Element == Element { for _ in subrange.lowerBound..<subrange.upperBound { remove(at: subrange.lowerBound) } for x in newElements.reversed() { insert(x, at: subrange.lowerBound) } } // This should be inferred, but Xcode 8.1 is unable to /// :nodoc: public typealias Indices = DefaultRandomAccessIndices<List> /// The position of the first element in a non-empty collection. /// Identical to endIndex in an empty collection. public var startIndex: Int { return 0 } /// The collection's "past the end" position. /// endIndex is not a valid argument to subscript, and is always reachable from startIndex by /// zero or more applications of successor(). public var endIndex: Int { return count } public func index(after i: Int) -> Int { return i + 1 } public func index(before i: Int) -> Int { return i - 1 } /// :nodoc: public func _observe(_ block: @escaping (RealmCollectionChange<AnyRealmCollection<Element>>) -> Void) -> NotificationToken { let anyCollection = AnyRealmCollection(self) return _rlmArray.addNotificationBlock { _, change, error in block(RealmCollectionChange.fromObjc(value: anyCollection, change: change, error: error)) } } } #if swift(>=4.0) // MARK: - MutableCollection conformance, range replaceable collection emulation extension List: MutableCollection { #if swift(>=4.1) public typealias SubSequence = Slice<List> #else public typealias SubSequence = RandomAccessSlice<List> #endif /** Returns the objects at the given range (get), or replaces the objects at the given range with new objects (set). - warning: Objects may only be set during a write transaction. - parameter index: The index of the object to retrieve or replace. */ public subscript(bounds: Range<Int>) -> SubSequence { get { return SubSequence(base: self, bounds: bounds) } set { replaceSubrange(bounds.lowerBound..<bounds.upperBound, with: newValue) } } /** Removes the specified number of objects from the beginning of the list. The objects are not removed from the Realm that manages them. - warning: This method may only be called during a write transaction. */ public func removeFirst(_ number: Int = 1) { let count = Int(_rlmArray.count) guard number <= count else { throwRealmException("It is not possible to remove more objects (\(number)) from a list" + " than it already contains (\(count)).") return } for _ in 0..<number { _rlmArray.removeObject(at: 0) } } /** Removes the specified number of objects from the end of the list. The objects are not removed from the Realm that manages them. - warning: This method may only be called during a write transaction. */ public func removeLast(_ number: Int = 1) { let count = Int(_rlmArray.count) guard number <= count else { throwRealmException("It is not possible to remove more objects (\(number)) from a list" + " than it already contains (\(count)).") return } for _ in 0..<number { _rlmArray.removeLastObject() } } /** Inserts the items in the given collection into the list at the given position. - warning: This method may only be called during a write transaction. */ public func insert<C: Collection>(contentsOf newElements: C, at i: Int) where C.Iterator.Element == Element { var currentIndex = i for item in newElements { insert(item, at: currentIndex) currentIndex += 1 } } /** Removes objects from the list at the given range. - warning: This method may only be called during a write transaction. */ public func removeSubrange(_ bounds: Range<Int>) { removeSubrange(bounds.lowerBound..<bounds.upperBound) } /// :nodoc: public func removeSubrange(_ bounds: ClosedRange<Int>) { removeSubrange(bounds.lowerBound...bounds.upperBound) } //// :nodoc: public func removeSubrange(_ bounds: CountableRange<Int>) { for _ in bounds { remove(at: bounds.lowerBound) } } /// :nodoc: public func removeSubrange(_ bounds: CountableClosedRange<Int>) { for _ in bounds { remove(at: bounds.lowerBound) } } /// :nodoc: public func removeSubrange(_ bounds: DefaultRandomAccessIndices<List>) { removeSubrange(bounds.startIndex..<bounds.endIndex) } /// :nodoc: public func replaceSubrange<C: Collection>(_ subrange: ClosedRange<Int>, with newElements: C) where C.Iterator.Element == Element { removeSubrange(subrange) insert(contentsOf: newElements, at: subrange.lowerBound) } /// :nodoc: public func replaceSubrange<C: Collection>(_ subrange: CountableRange<Int>, with newElements: C) where C.Iterator.Element == Element { removeSubrange(subrange) insert(contentsOf: newElements, at: subrange.lowerBound) } /// :nodoc: public func replaceSubrange<C: Collection>(_ subrange: CountableClosedRange<Int>, with newElements: C) where C.Iterator.Element == Element { removeSubrange(subrange) insert(contentsOf: newElements, at: subrange.lowerBound) } /// :nodoc: public func replaceSubrange<C: Collection>(_ subrange: DefaultRandomAccessIndices<List>, with newElements: C) where C.Iterator.Element == Element { removeSubrange(subrange) insert(contentsOf: newElements, at: subrange.startIndex) } } #else // MARK: - RangeReplaceableCollection support extension List: RangeReplaceableCollection { /** Removes the last object in the list. The object is not removed from the Realm that manages it. - warning: This method may only be called during a write transaction. */ public func removeLast() { guard _rlmArray.count > 0 else { throwRealmException("It is not possible to remove an object from an empty list.") return } _rlmArray.removeLastObject() } #if swift(>=3.2) // The issue described below is fixed in Swift 3.2 and above. #elseif swift(>=3.1) // These should not be necessary, but Swift 3.1's compiler fails to infer the `SubSequence`, // and the standard library neglects to provide the default implementation of `subscript` /// :nodoc: public typealias SubSequence = RangeReplaceableRandomAccessSlice<List> /// :nodoc: public subscript(slice: Range<Int>) -> SubSequence { return SubSequence(base: self, bounds: slice) } #endif } #endif // MARK: - AssistedObjectiveCBridgeable extension List: AssistedObjectiveCBridgeable { internal static func bridging(from objectiveCValue: Any, with metadata: Any?) -> List { guard let objectiveCValue = objectiveCValue as? RLMArray<AnyObject> else { preconditionFailure() } return List(rlmArray: objectiveCValue) } internal var bridged: (objectiveCValue: Any, metadata: Any?) { return (objectiveCValue: _rlmArray, metadata: nil) } } // MARK: - Unavailable extension List { @available(*, unavailable, renamed: "remove(at:)") public func remove(objectAtIndex: Int) { fatalError() } }
mit
41391f72ca45c283aa290b73202938ee
36.029577
128
0.662242
4.749097
false
false
false
false
parkera/swift
test/refactoring/ConvertAsync/convert_function.swift
1
30138
// REQUIRES: concurrency // RUN: %empty-directory(%t) enum CustomError : Error { case Bad } func simple(_ completion: @escaping (String) -> Void) { } func simple2(arg: String, _ completion: @escaping (String) -> Void) { } func simpleErr(arg: String, _ completion: @escaping (String?, Error?) -> Void) { } func simpleRes(arg: String, _ completion: @escaping (Result<String, Error>) -> Void) { } func run(block: () -> Bool) -> Bool { return false } func makeOptionalError() -> Error? { return nil } func makeOptionalString() -> String? { return nil } // RUN: %refactor -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=NESTED %s func nested() { simple { simple2(arg: $0) { str2 in print(str2) } } } // NESTED: func nested() async { // NESTED-NEXT: let val0 = await simple() // NESTED-NEXT: let str2 = await simple2(arg: val0) // NESTED-NEXT: print(str2) // NESTED-NEXT: } // RUN: %refactor -convert-to-async -dump-text -source-filename %s -pos=%(line+2):9 | %FileCheck -check-prefix=ATTRIBUTES %s @available(*, deprecated, message: "Deprecated") private func functionWithAttributes() { simple { str in print(str) } } // ATTRIBUTES: convert_function.swift [[# @LINE-6]]:1 -> [[# @LINE-1]]:2 // ATTRIBUTES-NEXT: @available(*, deprecated, message: "Deprecated") // ATTRIBUTES-NEXT: private func functionWithAttributes() async { // ATTRIBUTES-NEXT: let str = await simple() // ATTRIBUTES-NEXT: print(str) // ATTRIBUTES-NEXT: } // RUN: %refactor -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=MANY-NESTED %s func manyNested() { simple { str1 in print("simple") simple2(arg: str1) { str2 in print("simple2") simpleErr(arg: str2) { str3, err in print("simpleErr") guard let str3 = str3, err == nil else { return } simpleRes(arg: str3) { res in print("simpleRes") if case .success(let str4) = res { print("\(str1) \(str2) \(str3) \(str4)") print("after") } } } } } } // MANY-NESTED: func manyNested() async { // MANY-NESTED-NEXT: let str1 = await simple() // MANY-NESTED-NEXT: print("simple") // MANY-NESTED-NEXT: let str2 = await simple2(arg: str1) // MANY-NESTED-NEXT: print("simple2") // MANY-NESTED-NEXT: let str3 = try await simpleErr(arg: str2) // MANY-NESTED-NEXT: print("simpleErr") // MANY-NESTED-NEXT: let str4 = try await simpleRes(arg: str3) // MANY-NESTED-NEXT: print("simpleRes") // MANY-NESTED-NEXT: print("\(str1) \(str2) \(str3) \(str4)") // MANY-NESTED-NEXT: print("after") // MANY-NESTED-NEXT: } // RUN: %refactor -convert-to-async -dump-text -source-filename %s -pos=%(line+2):1 | %FileCheck -check-prefix=ASYNC-SIMPLE %s // RUN: %refactor -add-async-alternative -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=ASYNC-SIMPLE %s func asyncParams(arg: String, _ completion: @escaping (String?, Error?) -> Void) { simpleErr(arg: arg) { str, err in print("simpleErr") guard let str = str, err == nil else { completion(nil, err!) return } completion(str, nil) print("after") } } // ASYNC-SIMPLE: func {{[a-zA-Z_]+}}(arg: String) async throws -> String { // ASYNC-SIMPLE-NEXT: let str = try await simpleErr(arg: arg) // ASYNC-SIMPLE-NEXT: print("simpleErr") // ASYNC-SIMPLE-NEXT: {{^}}return str{{$}} // ASYNC-SIMPLE-NEXT: print("after") // ASYNC-SIMPLE-NEXT: } // RUN: %refactor -add-async-alternative -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=ASYNC-SIMPLE %s func asyncResErrPassed(arg: String, _ completion: @escaping (Result<String, Error>) -> Void) { simpleErr(arg: arg) { str, err in print("simpleErr") guard let str = str, err == nil else { completion(.failure(err!)) return } completion(.success(str)) print("after") } } // RUN: %refactor -add-async-alternative -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=ASYNC-ERR %s func asyncResNewErr(arg: String, _ completion: @escaping (Result<String, Error>) -> Void) { simpleErr(arg: arg) { str, err in print("simpleErr") guard let str = str, err == nil else { completion(.failure(CustomError.Bad)) return } completion(.success(str)) print("after") } } // ASYNC-ERR: func asyncResNewErr(arg: String) async throws -> String { // ASYNC-ERR-NEXT: do { // ASYNC-ERR-NEXT: let str = try await simpleErr(arg: arg) // ASYNC-ERR-NEXT: print("simpleErr") // ASYNC-ERR-NEXT: {{^}}return str{{$}} // ASYNC-ERR-NEXT: print("after") // ASYNC-ERR-NEXT: } catch let err { // ASYNC-ERR-NEXT: throw CustomError.Bad // ASYNC-ERR-NEXT: } // ASYNC-ERR-NEXT: } // RUN: %refactor -add-async-alternative -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=CALL-NON-ASYNC-IN-ASYNC %s func callNonAsyncInAsync(_ completion: @escaping (String) -> Void) { simple { str in let success = run { completion(str) return true } if !success { completion("bad") } } } // CALL-NON-ASYNC-IN-ASYNC: func callNonAsyncInAsync() async -> String { // CALL-NON-ASYNC-IN-ASYNC-NEXT: let str = await simple() // CALL-NON-ASYNC-IN-ASYNC-NEXT: return await withCheckedContinuation { continuation in // CALL-NON-ASYNC-IN-ASYNC-NEXT: let success = run { // CALL-NON-ASYNC-IN-ASYNC-NEXT: continuation.resume(returning: str) // CALL-NON-ASYNC-IN-ASYNC-NEXT: {{^}} return true{{$}} // CALL-NON-ASYNC-IN-ASYNC-NEXT: } // CALL-NON-ASYNC-IN-ASYNC-NEXT: if !success { // CALL-NON-ASYNC-IN-ASYNC-NEXT: continuation.resume(returning: "bad") // CALL-NON-ASYNC-IN-ASYNC-NEXT: } // CALL-NON-ASYNC-IN-ASYNC-NEXT: } // CALL-NON-ASYNC-IN-ASYNC-NEXT: } // RUN: %refactor -add-async-alternative -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=CALL-NON-ASYNC-IN-ASYNC-COMMENT %s func callNonAsyncInAsyncComment(_ completion: @escaping (String) -> Void) { // a simple { str in // b // c let success = run { // d completion(str) // e return true // f } // g if !success { // h completion("bad") // i } // j } // k } // CALL-NON-ASYNC-IN-ASYNC-COMMENT: func callNonAsyncInAsyncComment() async -> String { // CALL-NON-ASYNC-IN-ASYNC-COMMENT-NEXT: // a // CALL-NON-ASYNC-IN-ASYNC-COMMENT-NEXT: let str = await simple() // CALL-NON-ASYNC-IN-ASYNC-COMMENT-NEXT: // b // CALL-NON-ASYNC-IN-ASYNC-COMMENT-NEXT: // c // CALL-NON-ASYNC-IN-ASYNC-COMMENT-NEXT: return await withCheckedContinuation { continuation in // CALL-NON-ASYNC-IN-ASYNC-COMMENT-NEXT: let success = run { // CALL-NON-ASYNC-IN-ASYNC-COMMENT-NEXT: // d // CALL-NON-ASYNC-IN-ASYNC-COMMENT-NEXT: continuation.resume(returning: str) // CALL-NON-ASYNC-IN-ASYNC-COMMENT-NEXT: // e // CALL-NON-ASYNC-IN-ASYNC-COMMENT-NEXT: {{^}} return true{{$}} // CALL-NON-ASYNC-IN-ASYNC-COMMENT-NEXT: // f // CALL-NON-ASYNC-IN-ASYNC-COMMENT-NEXT: } // CALL-NON-ASYNC-IN-ASYNC-COMMENT-NEXT: // g // CALL-NON-ASYNC-IN-ASYNC-COMMENT-NEXT: if !success { // CALL-NON-ASYNC-IN-ASYNC-COMMENT-NEXT: // h // CALL-NON-ASYNC-IN-ASYNC-COMMENT-NEXT: continuation.resume(returning: "bad") // CALL-NON-ASYNC-IN-ASYNC-COMMENT-NEXT: // i // CALL-NON-ASYNC-IN-ASYNC-COMMENT-NEXT: } // CALL-NON-ASYNC-IN-ASYNC-COMMENT-NEXT: // j // CALL-NON-ASYNC-IN-ASYNC-COMMENT-NEXT: {{ }} // CALL-NON-ASYNC-IN-ASYNC-COMMENT-NEXT: // k // CALL-NON-ASYNC-IN-ASYNC-COMMENT-NEXT: } // CALL-NON-ASYNC-IN-ASYNC-COMMENT-NEXT: } // RUN: %refactor -add-async-alternative -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix VOID-AND-ERROR-HANDLER %s func voidAndErrorCompletion(completion: @escaping (Void?, Error?) -> Void) { if .random() { completion((), nil) // Make sure we drop the () } else { completion(nil, CustomError.Bad) } } // VOID-AND-ERROR-HANDLER: func voidAndErrorCompletion() async throws { // VOID-AND-ERROR-HANDLER-NEXT: if .random() { // VOID-AND-ERROR-HANDLER-NEXT: return // Make sure we drop the () // VOID-AND-ERROR-HANDLER-NEXT: } else { // VOID-AND-ERROR-HANDLER-NEXT: throw CustomError.Bad // VOID-AND-ERROR-HANDLER-NEXT: } // VOID-AND-ERROR-HANDLER-NEXT: } // RUN: %refactor -add-async-alternative -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix TOO-MUCH-VOID-AND-ERROR-HANDLER %s func tooMuchVoidAndErrorCompletion(completion: @escaping (Void?, Void?, Error?) -> Void) { if .random() { completion((), (), nil) // Make sure we drop the ()s } else { completion(nil, nil, CustomError.Bad) } } // TOO-MUCH-VOID-AND-ERROR-HANDLER: func tooMuchVoidAndErrorCompletion() async throws { // TOO-MUCH-VOID-AND-ERROR-HANDLER-NEXT: if .random() { // TOO-MUCH-VOID-AND-ERROR-HANDLER-NEXT: return // Make sure we drop the ()s // TOO-MUCH-VOID-AND-ERROR-HANDLER-NEXT: } else { // TOO-MUCH-VOID-AND-ERROR-HANDLER-NEXT: throw CustomError.Bad // TOO-MUCH-VOID-AND-ERROR-HANDLER-NEXT: } // TOO-MUCH-VOID-AND-ERROR-HANDLER-NEXT: } // RUN: %refactor -add-async-alternative -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix VOID-RESULT-HANDLER %s func voidResultCompletion(completion: @escaping (Result<Void, Error>) -> Void) { if .random() { completion(.success(())) // Make sure we drop the .success(()) } else { completion(.failure(CustomError.Bad)) } } // VOID-RESULT-HANDLER: func voidResultCompletion() async throws { // VOID-RESULT-HANDLER-NEXT: if .random() { // VOID-RESULT-HANDLER-NEXT: return // Make sure we drop the .success(()) // VOID-RESULT-HANDLER-NEXT: } else { // VOID-RESULT-HANDLER-NEXT: throw CustomError.Bad // VOID-RESULT-HANDLER-NEXT: } // VOID-RESULT-HANDLER-NEXT: } // RUN: %refactor -convert-to-async -dump-text -source-filename %s -pos=%(line+2):1 | %FileCheck -check-prefix=NON-COMPLETION-HANDLER %s // RUN: %refactor -add-async-alternative -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=NON-COMPLETION-HANDLER %s func functionWithSomeHandler(handler: @escaping (String) -> Void) {} // NON-COMPLETION-HANDLER: func functionWithSomeHandler() async -> String {} // rdar://77789360 Make sure we don't print a double return statement. // RUN: %refactor -add-async-alternative -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=RETURN-HANDLING %s func testReturnHandling(_ completion: @escaping (String?, Error?) -> Void) { return completion("", nil) } // RETURN-HANDLING: func testReturnHandling() async throws -> String { // RETURN-HANDLING-NEXT: {{^}} return ""{{$}} // RETURN-HANDLING-NEXT: } // rdar://77789360 Make sure we don't print a double return statement and don't // completely drop completion(a). // RUN: %refactor -add-async-alternative -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=RETURN-HANDLING2 %s func testReturnHandling2(completion: @escaping (String) -> ()) { testReturnHandling { x, err in guard let x = x else { let a = "" return completion(a) } let b = "" return completion(b) } } // RETURN-HANDLING2: func testReturnHandling2() async -> String { // RETURN-HANDLING2-NEXT: do { // RETURN-HANDLING2-NEXT: let x = try await testReturnHandling() // RETURN-HANDLING2-NEXT: let b = "" // RETURN-HANDLING2-NEXT: {{^}}<#return#> b{{$}} // RETURN-HANDLING2-NEXT: } catch let err { // RETURN-HANDLING2-NEXT: let a = "" // RETURN-HANDLING2-NEXT: {{^}}<#return#> a{{$}} // RETURN-HANDLING2-NEXT: } // RETURN-HANDLING2-NEXT: } // RUN: %refactor-check-compiles -add-async-alternative -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=RETURN-HANDLING3 %s func testReturnHandling3(_ completion: @escaping (String?, Error?) -> Void) { return (completion("", nil)) } // RETURN-HANDLING3: func testReturnHandling3() async throws -> String { // RETURN-HANDLING3-NEXT: {{^}} return ""{{$}} // RETURN-HANDLING3-NEXT: } // RUN: %refactor -add-async-alternative -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=RETURN-HANDLING4 %s func testReturnHandling4(_ completion: @escaping (String?, Error?) -> Void) { simpleErr(arg: "xxx") { str, err in if str != nil { completion(str, err) return } print("some error stuff") completion(str, err) } } // RETURN-HANDLING4: func testReturnHandling4() async throws -> String { // RETURN-HANDLING4-NEXT: do { // RETURN-HANDLING4-NEXT: let str = try await simpleErr(arg: "xxx") // RETURN-HANDLING4-NEXT: return str // RETURN-HANDLING4-NEXT: } catch let err { // RETURN-HANDLING4-NEXT: print("some error stuff") // RETURN-HANDLING4-NEXT: throw err // RETURN-HANDLING4-NEXT: } // RETURN-HANDLING4-NEXT: } // RUN: %refactor -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=RDAR78693050 %s func rdar78693050(_ completion: @escaping () -> Void) { simple { str in print(str) } if .random() { return completion() } completion() } // RDAR78693050: func rdar78693050() async { // RDAR78693050-NEXT: let str = await simple() // RDAR78693050-NEXT: print(str) // RDAR78693050-NEXT: if .random() { // RDAR78693050-NEXT: return // RDAR78693050-NEXT: } // RDAR78693050-NEXT: return // RDAR78693050-NEXT: } // RUN: %refactor-check-compiles -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=DISCARDABLE-RESULT %s func withDefaultedCompletion(arg: String, completion: @escaping (String) -> Void = {_ in}) { completion(arg) } // DISCARDABLE-RESULT: @discardableResult // DISCARDABLE-RESULT-NEXT: func withDefaultedCompletion(arg: String) async -> String { // DISCARDABLE-RESULT-NEXT: return arg // DISCARDABLE-RESULT-NEXT: } // RUN: %refactor-check-compiles -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=DEFAULT-ARG %s func withDefaultArg(x: String = "") { } // DEFAULT-ARG: convert_function.swift [[# @LINE-3]]:1 -> [[# @LINE-2]]:2 // DEFAULT-ARG-NOT: @discardableResult // DEFAULT-ARG-NEXT: {{^}}func withDefaultArg(x: String = "") async // RUN: %refactor -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=IMPLICIT-RETURN %s func withImplicitReturn(completionHandler: @escaping (String) -> Void) { simple { completionHandler($0) } } // IMPLICIT-RETURN: func withImplicitReturn() async -> String { // IMPLICIT-RETURN-NEXT: let val0 = await simple() // IMPLICIT-RETURN-NEXT: return val0 // IMPLICIT-RETURN-NEXT: } // This code doesn't compile after refactoring because we can't return `nil` from the async function. // But there's not much else we can do here. // RUN: %refactor -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=NIL-RESULT-AND-NIL-ERROR %s func nilResultAndNilError(completion: @escaping (String?, Error?) -> Void) { completion(nil, nil) } // NIL-RESULT-AND-NIL-ERROR: func nilResultAndNilError() async throws -> String { // NIL-RESULT-AND-NIL-ERROR-NEXT: return nil // NIL-RESULT-AND-NIL-ERROR-NEXT: } // RUN: %refactor -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=NIL-RESULT-AND-OPTIONAL-RELAYED-ERROR %s func nilResultAndOptionalRelayedError(completion: @escaping (String?, Error?) -> Void) { simpleErr(arg: "test") { (res, err) in completion(nil, err) } } // NIL-RESULT-AND-OPTIONAL-RELAYED-ERROR: func nilResultAndOptionalRelayedError() async throws -> String { // NIL-RESULT-AND-OPTIONAL-RELAYED-ERROR-NEXT: let res = try await simpleErr(arg: "test") // NIL-RESULT-AND-OPTIONAL-RELAYED-ERROR-EMPTY: // NIL-RESULT-AND-OPTIONAL-RELAYED-ERROR-NEXT: } // This code doesn't compile after refactoring because we can't throw an optional error returned from makeOptionalError(). // But it's not clear what the intended result should be either. // RUN: %refactor -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=NIL-RESULT-AND-OPTIONAL-COMPLEX-ERROR %s func nilResultAndOptionalComplexError(completion: @escaping (String?, Error?) -> Void) { completion(nil, makeOptionalError()) } // NIL-RESULT-AND-OPTIONAL-COMPLEX-ERROR: func nilResultAndOptionalComplexError() async throws -> String { // NIL-RESULT-AND-OPTIONAL-COMPLEX-ERROR-NEXT: throw makeOptionalError() // NIL-RESULT-AND-OPTIONAL-COMPLEX-ERROR-NEXT: } // RUN: %refactor -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=NIL-RESULT-AND-NON-OPTIONAL-ERROR %s func nilResultAndNonOptionalError(completion: @escaping (String?, Error?) -> Void) { completion(nil, CustomError.Bad) } // NIL-RESULT-AND-NON-OPTIONAL-ERROR: func nilResultAndNonOptionalError() async throws -> String { // NIL-RESULT-AND-NON-OPTIONAL-ERROR-NEXT: throw CustomError.Bad // NIL-RESULT-AND-NON-OPTIONAL-ERROR-NEXT: } // In this case, we are previously ignoring the error returned from simpleErr but are rethrowing it in the refactored case. // That's probably fine although it changes semantics. // RUN: %refactor -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=OPTIONAL-RELAYED-RESULT-AND-NIL-ERROR %s func optionalRelayedResultAndNilError(completion: @escaping (String?, Error?) -> Void) { simpleErr(arg: "test") { (res, err) in completion(res, nil) } } // OPTIONAL-RELAYED-RESULT-AND-NIL-ERROR: func optionalRelayedResultAndNilError() async throws -> String { // OPTIONAL-RELAYED-RESULT-AND-NIL-ERROR-NEXT: let res = try await simpleErr(arg: "test") // OPTIONAL-RELAYED-RESULT-AND-NIL-ERROR-NEXT: return res // OPTIONAL-RELAYED-RESULT-AND-NIL-ERROR-NEXT: } // RUN: %refactor -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=OPTIONAL-RELAYED-RESULT-AND-OPTIONAL-RELAYED-ERROR %s func optionalRelayedResultAndOptionalRelayedError(completion: @escaping (String?, Error?) -> Void) { simpleErr(arg: "test") { (res, err) in completion(res, err) } } // OPTIONAL-RELAYED-RESULT-AND-OPTIONAL-RELAYED-ERROR: func optionalRelayedResultAndOptionalRelayedError() async throws -> String { // OPTIONAL-RELAYED-RESULT-AND-OPTIONAL-RELAYED-ERROR-NEXT: let res = try await simpleErr(arg: "test") // OPTIONAL-RELAYED-RESULT-AND-OPTIONAL-RELAYED-ERROR-NEXT: return res // OPTIONAL-RELAYED-RESULT-AND-OPTIONAL-RELAYED-ERROR-NEXT: } // RUN: %refactor -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=OPTIONAL-RELAYED-RESULT-AND-OPTIONAL-COMPLEX-ERROR %s func optionalRelayedResultAndOptionalComplexError(completion: @escaping (String?, Error?) -> Void) { simpleErr(arg: "test") { (res, err) in completion(res, makeOptionalError()) } } // OPTIONAL-RELAYED-RESULT-AND-OPTIONAL-COMPLEX-ERROR: func optionalRelayedResultAndOptionalComplexError() async throws -> String { // OPTIONAL-RELAYED-RESULT-AND-OPTIONAL-COMPLEX-ERROR-NEXT: let res = try await simpleErr(arg: "test") // OPTIONAL-RELAYED-RESULT-AND-OPTIONAL-COMPLEX-ERROR-NEXT: if let error = makeOptionalError() { // OPTIONAL-RELAYED-RESULT-AND-OPTIONAL-COMPLEX-ERROR-NEXT: throw error // OPTIONAL-RELAYED-RESULT-AND-OPTIONAL-COMPLEX-ERROR-NEXT: } else { // OPTIONAL-RELAYED-RESULT-AND-OPTIONAL-COMPLEX-ERROR-NEXT: return res // OPTIONAL-RELAYED-RESULT-AND-OPTIONAL-COMPLEX-ERROR-NEXT: } // OPTIONAL-RELAYED-RESULT-AND-OPTIONAL-COMPLEX-ERROR-NEXT: } // RUN: %refactor -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=OPTIONAL-RELAYED-RESULT-AND-NON-OPTIONAL-ERROR %s func optionalRelayedResultAndNonOptionalError(completion: @escaping (String?, Error?) -> Void) { simpleErr(arg: "test") { (res, err) in completion(res, CustomError.Bad) } } // OPTIONAL-RELAYED-RESULT-AND-NON-OPTIONAL-ERROR: func optionalRelayedResultAndNonOptionalError() async throws -> String { // OPTIONAL-RELAYED-RESULT-AND-NON-OPTIONAL-ERROR-NEXT: let res = try await simpleErr(arg: "test") // OPTIONAL-RELAYED-RESULT-AND-NON-OPTIONAL-ERROR-NEXT: throw CustomError.Bad // OPTIONAL-RELAYED-RESULT-AND-NON-OPTIONAL-ERROR-NEXT: } // RUN: %refactor -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=NON-OPTIONAL-RELAYED-RESULT-AND-NIL-ERROR %s func nonOptionalRelayedResultAndNilError(completion: @escaping (String?, Error?) -> Void) { simple { res in completion(res, nil) } } // NON-OPTIONAL-RELAYED-RESULT-AND-NIL-ERROR: func nonOptionalRelayedResultAndNilError() async throws -> String { // NON-OPTIONAL-RELAYED-RESULT-AND-NIL-ERROR-NEXT: let res = await simple() // NON-OPTIONAL-RELAYED-RESULT-AND-NIL-ERROR-NEXT: return res // NON-OPTIONAL-RELAYED-RESULT-AND-NIL-ERROR-NEXT: } // RUN: %refactor -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=NON-OPTIONAL-RELAYED-RESULT-AND-OPTIONAL-COMPLEX-ERROR %s func nonOptionalRelayedResultAndOptionalComplexError(completion: @escaping (String?, Error?) -> Void) { simple { res in completion(res, makeOptionalError()) } } // NON-OPTIONAL-RELAYED-RESULT-AND-OPTIONAL-COMPLEX-ERROR: func nonOptionalRelayedResultAndOptionalComplexError() async throws -> String { // NON-OPTIONAL-RELAYED-RESULT-AND-OPTIONAL-COMPLEX-ERROR-NEXT: let res = await simple() // NON-OPTIONAL-RELAYED-RESULT-AND-OPTIONAL-COMPLEX-ERROR-NEXT: if let error = makeOptionalError() { // NON-OPTIONAL-RELAYED-RESULT-AND-OPTIONAL-COMPLEX-ERROR-NEXT: throw error // NON-OPTIONAL-RELAYED-RESULT-AND-OPTIONAL-COMPLEX-ERROR-NEXT: } else { // NON-OPTIONAL-RELAYED-RESULT-AND-OPTIONAL-COMPLEX-ERROR-NEXT: return res // NON-OPTIONAL-RELAYED-RESULT-AND-OPTIONAL-COMPLEX-ERROR-NEXT: } // NON-OPTIONAL-RELAYED-RESULT-AND-OPTIONAL-COMPLEX-ERROR-NEXT: } // RUN: %refactor -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=NON-OPTIONAL-RELAYED-RESULT-AND-NON-OPTIONAL-ERROR %s func nonOptionalRelayedResultAndNonOptionalError(completion: @escaping (String?, Error?) -> Void) { simple { res in completion(res, CustomError.Bad) } } // NON-OPTIONAL-RELAYED-RESULT-AND-NON-OPTIONAL-ERROR: func nonOptionalRelayedResultAndNonOptionalError() async throws -> String { // NON-OPTIONAL-RELAYED-RESULT-AND-NON-OPTIONAL-ERROR-NEXT: let res = await simple() // NON-OPTIONAL-RELAYED-RESULT-AND-NON-OPTIONAL-ERROR-NEXT: throw CustomError.Bad // NON-OPTIONAL-RELAYED-RESULT-AND-NON-OPTIONAL-ERROR-NEXT: } // The refactored code doesn't compile because we can't return an optional String from the async function. // But it's not clear what the intended result should be either, because `error` is always `nil`. // RUN: %refactor -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=OPTIONAL-COMPLEX-RESULT-AND-NIL-ERROR %s func optionalComplexResultAndNilError(completion: @escaping (String?, Error?) -> Void) { completion(makeOptionalString(), nil) } // OPTIONAL-COMPLEX-RESULT-AND-NIL-ERROR: func optionalComplexResultAndNilError() async throws -> String { // OPTIONAL-COMPLEX-RESULT-AND-NIL-ERROR-NEXT: return makeOptionalString() // OPTIONAL-COMPLEX-RESULT-AND-NIL-ERROR-NEXT: } // RUN: %refactor -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=OPTIONAL-COMPLEX-RESULT-AND-OPTIONAL-RELAYED-ERROR %s func optionalComplexResultAndOptionalRelayedError(completion: @escaping (String?, Error?) -> Void) { simpleErr(arg: "test") { (res, err) in completion(makeOptionalString(), err) } } // OPTIONAL-COMPLEX-RESULT-AND-OPTIONAL-RELAYED-ERROR: func optionalComplexResultAndOptionalRelayedError() async throws -> String { // OPTIONAL-COMPLEX-RESULT-AND-OPTIONAL-RELAYED-ERROR-NEXT: let res = try await simpleErr(arg: "test") // OPTIONAL-COMPLEX-RESULT-AND-OPTIONAL-RELAYED-ERROR-NEXT: return makeOptionalString() // OPTIONAL-COMPLEX-RESULT-AND-OPTIONAL-RELAYED-ERROR-NEXT: } // RUN: %refactor -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=OPTIONAL-COMPLEX-RESULT-AND-OPTIONAL-COMPLEX-ERROR %s func optionalComplexResultAndOptionalComplexError(completion: @escaping (String?, Error?) -> Void) { completion(makeOptionalString(), makeOptionalError()) } // OPTIONAL-COMPLEX-RESULT-AND-OPTIONAL-COMPLEX-ERROR: func optionalComplexResultAndOptionalComplexError() async throws -> String { // OPTIONAL-COMPLEX-RESULT-AND-OPTIONAL-COMPLEX-ERROR-NEXT: if let error = makeOptionalError() { // OPTIONAL-COMPLEX-RESULT-AND-OPTIONAL-COMPLEX-ERROR-NEXT: throw error // OPTIONAL-COMPLEX-RESULT-AND-OPTIONAL-COMPLEX-ERROR-NEXT: } else { // OPTIONAL-COMPLEX-RESULT-AND-OPTIONAL-COMPLEX-ERROR-NEXT: return makeOptionalString() // OPTIONAL-COMPLEX-RESULT-AND-OPTIONAL-COMPLEX-ERROR-NEXT: } // OPTIONAL-COMPLEX-RESULT-AND-OPTIONAL-COMPLEX-ERROR-NEXT: } // RUN: %refactor -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=OPTIONAL-COMPLEX-RESULT-AND-NON-OPTIONAL-ERROR %s func optionalComplexResultAndNonOptionalError(completion: @escaping (String?, Error?) -> Void) { completion(makeOptionalString(), CustomError.Bad) } // OPTIONAL-COMPLEX-RESULT-AND-NON-OPTIONAL-ERROR: func optionalComplexResultAndNonOptionalError() async throws -> String { // OPTIONAL-COMPLEX-RESULT-AND-NON-OPTIONAL-ERROR-NEXT: throw CustomError.Bad // OPTIONAL-COMPLEX-RESULT-AND-NON-OPTIONAL-ERROR-NEXT: } // RUN: %refactor -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=NON-OPTIONAL-RESULT-AND-NIL-ERROR %s func nonOptionalResultAndNilError(completion: @escaping (String?, Error?) -> Void) { completion("abc", nil) } // NON-OPTIONAL-RESULT-AND-NIL-ERROR: func nonOptionalResultAndNilError() async throws -> String { // NON-OPTIONAL-RESULT-AND-NIL-ERROR-NEXT: return "abc" // NON-OPTIONAL-RESULT-AND-NIL-ERROR-NEXT: } // RUN: %refactor -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=NON-OPTIONAL-RESULT-AND-OPTIONAL-RELAYED-ERROR %s func nonOptionalResultAndOptionalRelayedError(completion: @escaping (String?, Error?) -> Void) { simpleErr(arg: "test") { (res, err) in completion("abc", err) } } // NON-OPTIONAL-RESULT-AND-OPTIONAL-RELAYED-ERROR: func nonOptionalResultAndOptionalRelayedError() async throws -> String { // NON-OPTIONAL-RESULT-AND-OPTIONAL-RELAYED-ERROR-NEXT: let res = try await simpleErr(arg: "test") // NON-OPTIONAL-RESULT-AND-OPTIONAL-RELAYED-ERROR-NEXT: return "abc" // NON-OPTIONAL-RESULT-AND-OPTIONAL-RELAYED-ERROR-NEXT: } // RUN: %refactor -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=NON-OPTIONAL-RESULT-AND-OPTIONAL-COMPLEX-ERROR %s func nonOptionalResultAndOptionalComplexError(completion: @escaping (String?, Error?) -> Void) { completion("abc", makeOptionalError()) } // NON-OPTIONAL-RESULT-AND-OPTIONAL-COMPLEX-ERROR: func nonOptionalResultAndOptionalComplexError() async throws -> String { // NON-OPTIONAL-RESULT-AND-OPTIONAL-COMPLEX-ERROR-NEXT: if let error = makeOptionalError() { // NON-OPTIONAL-RESULT-AND-OPTIONAL-COMPLEX-ERROR-NEXT: throw error // NON-OPTIONAL-RESULT-AND-OPTIONAL-COMPLEX-ERROR-NEXT: } else { // NON-OPTIONAL-RESULT-AND-OPTIONAL-COMPLEX-ERROR-NEXT: return "abc" // NON-OPTIONAL-RESULT-AND-OPTIONAL-COMPLEX-ERROR-NEXT: } // NON-OPTIONAL-RESULT-AND-OPTIONAL-COMPLEX-ERROR-NEXT: } // RUN: %refactor -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=NON-OPTIONAL-RESULT-AND-NON-OPTIONAL-ERROR %s func nonOptionalResultAndNonOptionalError(completion: @escaping (String?, Error?) -> Void) { completion("abc", CustomError.Bad) } // NON-OPTIONAL-RESULT-AND-NON-OPTIONAL-ERROR: func nonOptionalResultAndNonOptionalError() async throws -> String { // NON-OPTIONAL-RESULT-AND-NON-OPTIONAL-ERROR-NEXT: throw CustomError.Bad // NON-OPTIONAL-RESULT-AND-NON-OPTIONAL-ERROR-NEXT: } // RUN: %refactor -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=WRAP-COMPLETION-CALL-IN-PARENS %s func wrapCompletionCallInParenthesis(completion: @escaping (String?, Error?) -> Void) { simpleErr(arg: "test") { (res, err) in (completion(res, err)) } } // WRAP-COMPLETION-CALL-IN-PARENS: func wrapCompletionCallInParenthesis() async throws -> String { // WRAP-COMPLETION-CALL-IN-PARENS-NEXT: let res = try await simpleErr(arg: "test") // WRAP-COMPLETION-CALL-IN-PARENS-NEXT: return res // WRAP-COMPLETION-CALL-IN-PARENS-NEXT: } // RUN: %refactor -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=WRAP-RESULT-IN-PARENS %s func wrapResultInParenthesis(completion: @escaping (String?, Error?) -> Void) { simpleErr(arg: "test") { (res, err) in completion((res).self, err) } } // WRAP-RESULT-IN-PARENS: func wrapResultInParenthesis() async throws -> String { // WRAP-RESULT-IN-PARENS-NEXT: let res = try await simpleErr(arg: "test") // WRAP-RESULT-IN-PARENS-NEXT: return res // WRAP-RESULT-IN-PARENS-NEXT: } // RUN: %refactor -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=TWO-COMPLETION-HANDLER-CALLS %s func twoCompletionHandlerCalls(completion: @escaping (String?, Error?) -> Void) { simpleErr(arg: "test") { (res, err) in completion(res, err) completion(res, err) } } // TWO-COMPLETION-HANDLER-CALLS: func twoCompletionHandlerCalls() async throws -> String { // TWO-COMPLETION-HANDLER-CALLS-NEXT: let res = try await simpleErr(arg: "test") // TWO-COMPLETION-HANDLER-CALLS-NEXT: return res // TWO-COMPLETION-HANDLER-CALLS-NEXT: return res // TWO-COMPLETION-HANDLER-CALLS-NEXT: }
apache-2.0
d3f8f55a5fc6394567c1eaf7a1927045
48.245098
168
0.69779
3.200382
false
false
false
false
luanlzsn/pos
pos/Classes/pos_iphone/Home/View/ProductCategoriesCell.swift
1
1694
// // ProductCategoriesCell.swift // pos // // Created by luan on 2017/8/29. // Copyright © 2017年 luan. All rights reserved. // import UIKit class ProductCategoriesCell: UICollectionViewCell,UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout { @IBOutlet weak var collection: UICollectionView! var categoriesArray = [CategoriesModel]() func refreshCategories(_ array: [CategoriesModel]) { categoriesArray = array collection.reloadData() } // MARK: - UICollectionViewDelegateFlowLayout func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { let cellWidth = (kScreenWidth - 30) / 2.5 return CGSize(width: cellWidth, height: 50) } // MARK: - UICollectionViewDelegate,UICollectionViewDataSource func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return categoriesArray.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell: ProductCategoriesItemCell = collectionView.dequeueReusableCell(withReuseIdentifier: "ProductCategoriesItemCell", for: indexPath) as! ProductCategoriesItemCell cell.itemTitle.text = categoriesArray[indexPath.row].name return cell } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { viewController()!.performSegue(withIdentifier: "ProductList", sender: categoriesArray[indexPath.row]) } }
mit
bdaef6bdfe874edcd1e81274c0707b2d
39.261905
176
0.738025
5.891986
false
false
false
false
mownier/Umalahokan
Umalahokan/Source/UI/Recent Chat/RecentChatCell.swift
1
4166
// // RecentChatCell.swift // Umalahokan // // Created by Mounir Ybanez on 31/01/2017. // Copyright © 2017 Ner. All rights reserved. // import UIKit class RecentChatCell: UITableViewCell { var avatarImageView: UIImageView! var moodIndicator: UIView! var moodLabel: UILabel! var displayNameLabel: UILabel! var messageLabel: UILabel! var timeLabel: UILabel! var strip: UIView! var onlineStatusIndicator: UIView! convenience init() { self.init(style: .default, reuseIdentifier: RecentChatCell.reuseId) } override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) initSetup() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) initSetup() } override func layoutSubviews() { let spacing: CGFloat = 8 var rect = CGRect.zero rect.size.width = 80 rect.size.height = rect.width avatarImageView.frame = rect rect.origin.x = rect.maxX rect.size.width = 12 moodIndicator.frame = rect rect.origin.x = rect.maxX rect.size.height = 0.4 rect.origin.y = frame.height - rect.height rect.size.width = frame.width - rect.origin.x strip.frame = rect timeLabel.sizeToFit() rect.size = timeLabel.frame.size rect.origin.y = spacing * 2 rect.origin.x = frame.width - rect.width - (spacing * 2) timeLabel.frame = rect moodLabel.sizeToFit() rect.size = moodLabel.frame.size rect.origin.x = moodIndicator.frame.maxX + (spacing * 2) rect.size.width = frame.width - rect.origin.x - timeLabel.frame.width - (spacing * 2) moodLabel.frame = rect displayNameLabel.sizeToFit() rect.size.width = min(rect.width - 8 - spacing, displayNameLabel.frame.width) rect.size.height = displayNameLabel.frame.height rect.origin.y = rect.maxY displayNameLabel.frame = rect rect.origin.x = rect.maxX + spacing rect.origin.y += (rect.height - 8) / 2 rect.size.width = 8 rect.size.height = rect.width onlineStatusIndicator.layer.cornerRadius = rect.width / 2 onlineStatusIndicator.frame = rect messageLabel.sizeToFit() rect.size.width = moodLabel.frame.width rect.size.height = messageLabel.frame.height rect.origin.y = displayNameLabel.frame.maxY rect.origin.x = moodLabel.frame.origin.x messageLabel.frame = rect } private func initSetup() { let theme = UITheme() selectionStyle = .none avatarImageView = UIImageView() avatarImageView.backgroundColor = theme.color.gray5 moodIndicator = UIView() moodIndicator.backgroundColor = theme.color.violet3 moodLabel = UILabel() moodLabel.font = theme.font.regular.size(10) moodLabel.textColor = theme.color.gray4 displayNameLabel = UILabel() displayNameLabel.font = theme.font.medium.size(12) messageLabel = UILabel() messageLabel.font = theme.font.regular.size(12) moodLabel.textColor = theme.color.gray5 timeLabel = UILabel() timeLabel.font = theme.font.regular.size(10) timeLabel.textColor = moodLabel.textColor strip = UIView() strip.backgroundColor = theme.color.gray6 onlineStatusIndicator = UIView() onlineStatusIndicator.clipsToBounds = true onlineStatusIndicator.backgroundColor = theme.color.green addSubview(avatarImageView) addSubview(moodIndicator) addSubview(moodLabel) addSubview(displayNameLabel) addSubview(messageLabel) addSubview(timeLabel) addSubview(strip) addSubview(onlineStatusIndicator) } } extension RecentChatCell: TableViewReusableProtocol { typealias Cell = RecentChatCell }
mit
8d69be9d3e1bd94eebd5738edd3143f9
30.08209
93
0.621369
4.60221
false
false
false
false
firemuzzy/slugg
mobile/Slug/Slug/controllers/CreateRideViewController.swift
1
2633
// // RegisterDriveViewController.swift // Slug // // Created by Andrew Charkin on 3/21/15. // Copyright (c) 2015 Slug. All rights reserved. // import UIKit import Parse class CreateRideViewController: UIViewController { var maxSpaces: Int? var departure: NSDate? @IBOutlet var seats: [UIButton]! @IBOutlet var departureTimes: [UIButton]! override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) // SlugUser.currentUser()?.findMyCurrentDrivingRideInBackground({ (data, error) -> Void in // if data != nil { // let ride = Ride(parseObj: data) // self.maxSpaces = ride.maxSpaces // self.departure = ride.departure // // for seat in self.seats { // if seat.tag == ride.maxSpaces { // seat.selected = true // } // } // } // }) //get location UserLocation.sharedInstance } @IBAction func selectSeats(sender: UIButton) { for seat in self.seats { seat.selected = false } sender.selected = true self.maxSpaces = sender.tag } @IBAction func depart5Minutes(sender: UIButton) { for departureButton in self.departureTimes { departureButton.selected = false } self.departure = NSDate().dateByAddingTimeInterval(60*5) sender.selected = true; } @IBAction func depart15Minutes(sender: UIButton) { for departureButton in self.departureTimes { departureButton.selected = false } self.departure = NSDate().dateByAddingTimeInterval(60*15) sender.selected = true; } @IBAction func depart30Minutes(sender: UIButton) { for departureButton in self.departureTimes { departureButton.selected = false } self.departure = NSDate().dateByAddingTimeInterval(60*15) sender.selected = true; } @IBAction func done(sender: UIButton) { if let slugUser = SlugUser.currentUser() { if let maxSpaces = self.maxSpaces, let departure = self.departure, let currentLocation = UserLocation.sharedInstance.currentLocation, let farthestPoint = LocUtils.farthestPoint([slugUser.work, slugUser.home], from: currentLocation) { let clPoint = PFGeoPoint(latitude: currentLocation.coordinate.latitude, longitude: currentLocation.coordinate.longitude) let ride = Ride.create(slugUser, maxSpaces: maxSpaces, departure: departure, from: clPoint, to: farthestPoint) ride.parseObj.saveInBackgroundWithBlock(nil) self.performSegueWithIdentifier("unwind", sender: self) } } } }
mit
4b812c997f2a8cf539f1401a7d481237
27.619565
130
0.655146
4.281301
false
false
false
false
PrajeetShrestha/imgurdemo
MobilabDemo/Model/IMGURFilter.swift
1
4467
// // Filter.swift // MobilabDemo // // Created by [email protected] on 4/28/16. // Copyright © 2016 Prajeet Shrestha. All rights reserved. // import Foundation enum IMGURSection:String { case Hot = "hot"// Default case Top = "top" case User = "user" static let allValues = [Hot, Top, User] } //Only available with section enum IMGURSort:String { case Viral = "viral"// Default case Top = "top" case Time = "time" case Rising = "rising" static let allValues = [Viral, Top, Time, Rising] } //Change the date range of the request if section is "Top" enum IMGURWindow:String { case Day = "day"//Default case Week = "week" case Month = "month" case Year = "year" case All = "all" static let allValues = [Day, Week, Month, Year, All] } /* Show or hide viral images from the 'user' section */ enum IMGURShowViral:String { case True = "true" //Default case False = "false" static let allValues = [True, False] } class IMGURFilter { var section:IMGURSection? = .Hot var window:IMGURWindow? = .Day var sort:IMGURSort? = .Viral var shouldFilterViral:IMGURShowViral? = .True var page:Int = 0 /* Saves IMGURFilter object as Dictionary object into the userDefaults supplied by the client. If no default object is provided then standardUserDefaults is set as default. */ func saveToUserDefaultsAsDictionary(defaults:NSUserDefaults = NSUserDefaults.standardUserDefaults()) { var filterDictionary = [String:AnyObject]() filterDictionary = [ "section":self.section!.rawValue, "window":self.window!.rawValue, "sort":self.sort!.rawValue, "shouldFilterViral":self.shouldFilterViral!.rawValue, "page":0 //Page is added as 0 becausse we dont want page to be saved. User will browse from the beginning with previous filter. ] defaults.setObject(filterDictionary, forKey: kIMGURFilterDefaultKey) defaults.synchronize() } func description () -> [String:AnyObject] { var filterDictionary = [String:AnyObject]() filterDictionary = [ "section":self.section!.rawValue, "window":self.window!.rawValue, "sort":self.sort!.rawValue, "shouldFilterViral":self.shouldFilterViral!.rawValue, "page":self.page ] return filterDictionary } /* Retrieves IMGURFilter object from the defaults object provided by the client. Fetched from the standardUserDefaults by default. This method will return a default filter if no filters found stored in user defaults previously. */ class func getFilterFromUserDefaults(defaults:NSUserDefaults = NSUserDefaults.standardUserDefaults()) -> IMGURFilter? { guard let filterDic = defaults.objectForKey(kIMGURFilterDefaultKey) else { return nil } let sectionValue = filterDic.objectForKey("section") as? String let windowValue = filterDic.objectForKey("window") as? String let sortValue = filterDic.objectForKey("sort") as? String let shouldFilterViralValue = filterDic.objectForKey("shouldFilterViral") as? String let pageValue = filterDic.objectForKey("page") as? Int let filter = IMGURFilter() filter.section = IMGURSection.init(rawValue: sectionValue!) filter.window = IMGURWindow.init(rawValue: windowValue!) filter.sort = IMGURSort.init(rawValue: sortValue!) filter.shouldFilterViral = IMGURShowViral.init(rawValue: shouldFilterViralValue!) filter.page = pageValue! return filter } class func hot() -> IMGURFilter { let filter = IMGURFilter() return filter } class func top() -> IMGURFilter { let filter = IMGURFilter() filter.section = .Top filter.window = .Day return filter } class func user() -> IMGURFilter { let filter = IMGURFilter() filter.section = .User filter.sort = .Viral return filter } }
apache-2.0
8b692a4ca88a4ffac2744ffe3b910b6a
32.840909
143
0.601433
4.395669
false
false
false
false
fabiothiroki/foursquare-clone-ios
Foursquare Clone/AppDelegate.swift
1
882
// // AppDelegate.swift // Foursquare Clone // // Created by Fabio Hiroki on 08/10/17. // Copyright © 2017 Fabio Hiroki. All rights reserved. // import UIKit import ReSwift let injector: Injector = Injector() let store = Store<FetchedPlacesState>(reducer: (injector.resolve(AppReducer.self)!).reduce, state: nil) @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { let window = UIWindow(frame: UIScreen.main.bounds) self.window = window let rootViewController = injector.resolve(PlacesViewController.self) window.rootViewController = rootViewController window.makeKeyAndVisible() return true } }
mit
f549540ea62de13a4903a9cc5fb358f6
27.419355
103
0.706016
4.949438
false
false
false
false
biohazardlover/NintendoEverything
Pods/ImageViewer/ImageViewer/Source/Extensions/UIButton.swift
6
4854
// // UIButton.swift // ImageViewer // // Created by Kristian Angyal on 28/07/2016. // Copyright © 2016 MailOnline. All rights reserved. // import UIKit extension UIButton { static func circlePlayButton(_ diameter: CGFloat) -> UIButton { let button = UIButton(type: .custom) button.frame = CGRect(origin: .zero, size: CGSize(width: diameter, height: diameter)) let circleImageNormal = CAShapeLayer.circlePlayShape(UIColor.white, diameter: diameter).toImage() button.setImage(circleImageNormal, for: .normal) let circleImageHighlighted = CAShapeLayer.circlePlayShape(UIColor.lightGray, diameter: diameter).toImage() button.setImage(circleImageHighlighted, for: .highlighted) return button } static func replayButton(width: CGFloat, height: CGFloat) -> UIButton { let smallerEdge = min(width, height) let triangleEdgeLength: CGFloat = min(smallerEdge, 20) let button = UIButton(type: .custom) button.bounds.size = CGSize(width: width, height: height) button.contentHorizontalAlignment = .center let playShapeNormal = CAShapeLayer.playShape(UIColor.red, triangleEdgeLength: triangleEdgeLength).toImage() button.setImage(playShapeNormal, for: .normal) let playShapeHighlighted = CAShapeLayer.playShape(UIColor.red.withAlphaComponent(0.7), triangleEdgeLength: triangleEdgeLength).toImage() button.setImage(playShapeHighlighted, for: .highlighted) ///the geometric center of equilateral triangle is not the same as the geometric center of its smallest bounding rect. There is some offset between the two centers to the left when the triangle points to the right. We have to shift the triangle to the right by that offset. let altitude = (sqrt(3) / 2) * triangleEdgeLength let innerCircleDiameter = (sqrt(3) / 6) * triangleEdgeLength button.imageEdgeInsets.left = altitude / 2 - innerCircleDiameter return button } static func playButton(width: CGFloat, height: CGFloat) -> UIButton { let smallerEdge = min(width, height) let triangleEdgeLength: CGFloat = min(smallerEdge, 20) let button = UIButton(type: .custom) button.bounds.size = CGSize(width: width, height: height) button.contentHorizontalAlignment = .center let playShapeNormal = CAShapeLayer.playShape(UIColor.white, triangleEdgeLength: triangleEdgeLength).toImage() button.setImage(playShapeNormal, for: .normal) let playShapeHighlighted = CAShapeLayer.playShape(UIColor.white.withAlphaComponent(0.7), triangleEdgeLength: triangleEdgeLength).toImage() button.setImage(playShapeHighlighted, for: .highlighted) ///the geometric center of equilateral triangle is not the same as the geometric center of its smallest bounding rect. There is some offset between the two centers to the left when the triangle points to the right. We have to shift the triangle to the right by that offset. let altitude = (sqrt(3) / 2) * triangleEdgeLength let innerCircleDiameter = (sqrt(3) / 6) * triangleEdgeLength button.imageEdgeInsets.left = altitude / 2 - innerCircleDiameter return button } static func pauseButton(width: CGFloat, height: CGFloat) -> UIButton { let button = UIButton(type: .custom) button.contentHorizontalAlignment = .center let elementHeight = min(20, height) let elementSize = CGSize(width: elementHeight * 0.3, height: elementHeight) let distance: CGFloat = elementHeight * 0.2 let pauseImageNormal = CAShapeLayer.pauseShape(UIColor.white, elementSize: elementSize, elementDistance: distance).toImage() button.setImage(pauseImageNormal, for: .normal) let pauseImageHighlighted = CAShapeLayer.pauseShape(UIColor.white.withAlphaComponent(0.7), elementSize: elementSize, elementDistance: distance).toImage() button.setImage(pauseImageHighlighted, for: .highlighted) return button } static func closeButton() -> UIButton { let button = UIButton(frame: CGRect(origin: CGPoint.zero, size: CGSize(width: 50, height: 50))) button.setImage(CAShapeLayer.closeShape(edgeLength: 15).toImage(), for: .normal) return button } static func thumbnailsButton() -> UIButton { let button = UIButton(frame: CGRect(origin: CGPoint.zero, size: CGSize(width: 80, height: 50))) button.setTitle("See All", for: .normal) //button.titleLabel?.textColor = UIColor.redColor() return button } static func deleteButton() -> UIButton { let button = UIButton(frame: CGRect(origin: CGPoint.zero, size: CGSize(width: 80, height: 50))) button.setTitle("Delete", for: .normal) return button } }
mit
8a1d39cbe075f6bdd32de2f2f6986197
40.478632
281
0.702246
4.6
false
false
false
false
programersun/HiChongSwift
HiChongSwift/ViewControllerExtension.swift
1
1986
// // ViewControllerExtension.swift // HiChongSwift // // Created by eagle on 14/12/11. // Copyright (c) 2014年 Duostec. All rights reserved. // extension UIViewController{ func showHUDWithTips(tips: String) { let hud = MBProgressHUD.showHUDAddedTo(self.view, animated: true) hud.labelText = tips } func showHUD() { MBProgressHUD.showHUDAddedTo(self.view, animated: true) } func hideHUD() { MBProgressHUD.hideHUDForView(self.view, animated: true) } func screenWidth() -> CGFloat { return UIScreen.mainScreen().bounds.width } func addRightButton(buttonTitle: String, action: Selector) { self.navigationItem.rightBarButtonItem = nil let doneButton = UIButton(frame: CGRect(origin: CGPointZero, size: LCYCommon.sharedInstance.rightButtonSize)) doneButton.addTarget(self, action: action, forControlEvents: UIControlEvents.TouchUpInside) doneButton.backgroundColor = UIColor.LCYThemeDarkText() let doneString = NSAttributedString(string: buttonTitle, attributes: [NSForegroundColorAttributeName: UIColor.whiteColor(), NSFontAttributeName: UIFont.systemFontOfSize(12.0)]) doneButton.setAttributedTitle(doneString, forState: UIControlState.Normal) doneButton.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal) doneButton.layer.cornerRadius = 4.0 let rightItem = UIBarButtonItem(customView: doneButton) self.navigationItem.rightBarButtonItem = rightItem } func alert(message: String) { let alert = UIAlertView(title: nil, message: message, delegate: nil, cancelButtonTitle: "确定") alert.show() } func alertWithDelegate(message: String, tag: Int, delegate: UIAlertViewDelegate?) { let alert = UIAlertView(title: nil, message: message, delegate: delegate, cancelButtonTitle: "确定") alert.tag = tag alert.show() } }
apache-2.0
0e09e429721d7d9c46718a363a6e7078
37.745098
184
0.694332
4.819512
false
false
false
false
TakuSemba/DribbbleSwiftApp
Carthage/Checkouts/RxSwift/RxExample/RxExample/Examples/Dependencies.swift
1
1478
// // Dependencies.swift // WikipediaImageSearch // // Created by carlos on 13/5/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // import Foundation #if !RX_NO_MODULE import RxSwift #endif class Dependencies { // ***************************************************************************************** // !!! This is defined for simplicity sake, using singletons isn't advised !!! // !!! This is just a simple way to move services to one location so you can see Rx code !!! // ***************************************************************************************** static let sharedDependencies = Dependencies() // Singleton let URLSession = NSURLSession.sharedSession() let backgroundWorkScheduler: ImmediateSchedulerType let mainScheduler: SerialDispatchQueueScheduler let wireframe: Wireframe let reachabilityService: ReachabilityService private init() { wireframe = DefaultWireframe() let operationQueue = NSOperationQueue() operationQueue.maxConcurrentOperationCount = 2 #if !RX_NO_MODULE operationQueue.qualityOfService = NSQualityOfService.UserInitiated #endif backgroundWorkScheduler = OperationQueueScheduler(operationQueue: operationQueue) mainScheduler = MainScheduler.instance reachabilityService = try! DefaultReachabilityService() // try! is only for simplicity sake } }
apache-2.0
2dcd2d6ea7f406ca3e1084af6498d9ed
34.166667
99
0.607312
6.053279
false
false
false
false
WeirdMath/TimetableSDK
Sources/Employment.swift
1
1634
// // Employment.swift // TimetableSDK // // Created by Sergej Jaskiewicz on 04.12.2016. // // import SwiftyJSON import Foundation /// The information about an educator's employment. public final class Employment : JSONRepresentable, TimetableEntity { /// The Timetable this entity was fetched from. `nil` if it was initialized from a custom JSON object. public weak var timetable: Timetable? public let department: String public let position: String internal init(department: String, position: String) { self.department = department self.position = position } /// Creates a new entity from its JSON representation. /// /// - Parameter json: The JSON representation of the entity. /// - Throws: `TimetableError.incorrectJSONFormat` public init(from json: JSON) throws { do { department = try map(json["Department"]) position = try map(json["Position"]) } catch { throw TimetableError.incorrectJSON(json, whenConverting: Employment.self) } } } extension Employment : Equatable { /// Returns a Boolean value indicating whether two values are equal. /// /// Equality is the inverse of inequality. For any values `a` and `b`, /// `a == b` implies that `a != b` is `false`. /// /// - Parameters: /// - lhs: A value to compare. /// - rhs: Another value to compare. public static func ==(lhs: Employment, rhs: Employment) -> Bool { return lhs.department == rhs.department && rhs.position == rhs.position } }
mit
5dcf6b620661e4bd8762136c43ede9c4
28.709091
106
0.624847
4.357333
false
false
false
false
rokuz/omim
iphone/Maps/Bookmarks/Catalog/CatalogConnectionErrorView.swift
1
1525
import UIKit class CatalogConnectionErrorView: UIView { @IBOutlet var imageView: UIImageView! @IBOutlet var titleLabel: UILabel! @IBOutlet var actionButton: UIButton! var actionCallback: (() -> Void)? override init(frame: CGRect) { super.init(frame: frame) xibSetup() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) xibSetup() } convenience init(frame: CGRect, actionCallback callback: (() -> Void)?) { self.init(frame: frame) actionCallback = callback } @IBAction func actionTapHandler() { actionCallback?() } } extension CatalogConnectionErrorView { func xibSetup() { backgroundColor = UIColor.clear let nib = UINib(nibName: "CatalogConnectionErrorView", bundle: nil) let view = nib.instantiate(withOwner: self, options: nil).first as! UIView view.translatesAutoresizingMaskIntoConstraints = false addSubview(view) addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|[childView]|", options: [], metrics: nil, views: ["childView": view])) addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[childView]|", options: [], metrics: nil, views: ["childView": view])) } }
apache-2.0
998ff91ef90e3b9d8f5c29f3a32755e7
31.446809
86
0.56459
5.565693
false
false
false
false
NicolasKim/Roy
Example/TestModule/TestModule/FirstViewController.swift
1
1467
// // FirstViewController.swift // TestModule // // Created by 金秋成 on 2017/8/17. // Copyright © 2017年 DreamTracer. All rights reserved. // import UIKit import Roy class FirstViewController: UIViewController,RoyProtocol { var color : UIColor required init?(param: [String : Any]?) { let type = param?["c"] as! String switch type { case "1": color = UIColor.red case "2": color = UIColor.brown case "3": color = UIColor.gray case "4": color = UIColor.purple default: color = UIColor.black } super.init(nibName: nil, bundle: nil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = color } 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 prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
mit
04d2667556c64aef819bfb5c3a361337
22.516129
106
0.596708
4.718447
false
false
false
false
ataibarkai/TypeBurritoFramework
Tests/SemanticType-Tests/CoreStructure_Tests/SemanticType_Core_Tests.swift
1
7280
import XCTest @testable import SemanticType final class SemanticType_Core_Tests: XCTestCase { func testErrorlessModificationlessCreation() { enum Cents_Spec: ErrorlessSemanticTypeSpec { typealias RawValue = Int static func gateway(preMap: Int) -> Int { return preMap } } typealias Cents = SemanticType<Cents_Spec> let fiftyCents = Cents.create(50).get() XCTAssertEqual(fiftyCents._rawValue, 50) let fiftyCentsDebt = Cents.create(-50).get() XCTAssertEqual(fiftyCentsDebt._rawValue, -50) let adviceMoney = Cents.create(2).get() XCTAssertEqual(adviceMoney._rawValue, 2) let bezosMoney = Cents.create(2_000_000_000_000).get() XCTAssertEqual(bezosMoney._rawValue, 2_000_000_000_000) } func testErrorlessValueModifyingCreation() { enum CaselessString_Spec: ErrorlessSemanticTypeSpec { typealias RawValue = String static func gateway(preMap: String) -> String { return preMap.lowercased() } } typealias CaselessString = SemanticType<CaselessString_Spec> let str1: CaselessString = CaselessString.create("HeLlo, WorLD.").get() XCTAssertEqual(str1._rawValue, "hello, world.") let str2: CaselessString = CaselessString.create("Why would Jerry BRING anything?").get() XCTAssertEqual(str2._rawValue, "why would jerry bring anything?") let str3: CaselessString = CaselessString.create("Why would JERRY bring anything?").get() XCTAssertEqual(str3._rawValue, "why would jerry bring anything?") let str4: CaselessString = CaselessString.create("Yo-Yo Ma").get() XCTAssertEqual(str4._rawValue, "yo-yo ma") } func testErrorfullCreation() { enum FiveLetterWordArray_Spec: ValidatedSemanticTypeSpec { typealias RawValue = [String] struct Error: Swift.Error { var excludedWords: [String] } static func gateway(preMap: [String]) -> Result<[String], Error> { let excludedWords = preMap.filter { $0.count != 5 } guard excludedWords.isEmpty else { return .failure(.init(excludedWords: excludedWords)) } return .success(preMap) } } typealias FiveLetterWordArray = SemanticType<FiveLetterWordArray_Spec> let arrayThatOnlyContainsFiveLetterWords = ["12345", "Earth", "water", "melon", "12345", "great"] let shouldBeValid = FiveLetterWordArray.create(arrayThatOnlyContainsFiveLetterWords) switch shouldBeValid { case .success(let fiveLetterWordArray): XCTAssertEqual(fiveLetterWordArray._rawValue, arrayThatOnlyContainsFiveLetterWords) case .failure: XCTFail() } let oneInvalidWord = FiveLetterWordArray.create(arrayThatOnlyContainsFiveLetterWords + ["123456"]) switch oneInvalidWord { case .success: XCTFail() case .failure(let error): XCTAssertEqual(error.excludedWords, ["123456"]) } let nonFiveLetterWords = ["123456", "abc", "foo", "A", "123456", "A!"] let aFewInvalidWords = FiveLetterWordArray.create(arrayThatOnlyContainsFiveLetterWords + nonFiveLetterWords) switch aFewInvalidWords { case .success: XCTFail() case .failure(let error): XCTAssertEqual(error.excludedWords, nonFiveLetterWords) } } func testMeaningfulGatewayMetadata() { let joesEmail = try! EmailAddress.create("[email protected]").get() XCTAssertEqual(joesEmail.user, "joe1234") XCTAssertEqual(joesEmail.host, "gmail.com") let invalidEmail = EmailAddress.create("@gmail.com") switch invalidEmail { case .success: XCTFail() case .failure(let error): XCTAssertEqual(error.candidateEmailAddress, "@gmail.com") } let oneTwoThree = try! NonEmptyIntArray.create([1, 2, 3]).get() XCTAssertEqual(oneTwoThree.first as Int, 1) XCTAssertEqual(oneTwoThree.last as Int, 3) XCTAssertThrowsError( try NonEmptyIntArray.create([]).get() ) } static var allTests = [ ("testErrorlessModificationlessCreation", testErrorlessModificationlessCreation), ("testErrorlessValueModifyingCreation", testErrorlessValueModifyingCreation), ("testErrorfullCreation", testErrorfullCreation), ("testMeaningfulGatewayMetadata", testMeaningfulGatewayMetadata), ] } // we define `EmailAddress` outside of the test function so that we can write an extension for it enum EmailAddress_Spec: MetaValidatedSemanticTypeSpec { typealias RawValue = String struct Metadata { var beforeAtSign: String var afterAtSign: String } struct Error: Swift.Error { var candidateEmailAddress: String } static func gateway(preMap: String) -> Result<GatewayOutput, Error> { let preMap = preMap.lowercased() guard let indexOfFirstAtSign = preMap.firstIndex(of: "@") else { return .failure(.init(candidateEmailAddress: preMap)) } let beforeAtSign = preMap[..<indexOfFirstAtSign] let afterAtSign = preMap[indexOfFirstAtSign...].dropFirst() // make sure we have valid strings before and after the `@` guard !beforeAtSign.isEmpty && !afterAtSign.isEmpty else { return .failure(.init(candidateEmailAddress: preMap)) } return .success(.init( rawValue: preMap, metadata: .init(beforeAtSign: String(beforeAtSign), afterAtSign: String(afterAtSign)) )) } } typealias EmailAddress = SemanticType<EmailAddress_Spec> extension EmailAddress { var user: String { gatewayMetadata.beforeAtSign } var host: String { gatewayMetadata.afterAtSign } } // we define `NonEmptyIntArray_Spec` outside of the test function so that we can write an extension for it enum NonEmptyIntArray_Spec: MetaValidatedSemanticTypeSpec { typealias RawValue = [Int] struct Metadata { var first: Int var last: Int } enum Error: Swift.Error { case arrayIsEmpty } static func gateway(preMap: [Int]) -> Result<GatewayOutput, Error> { // a non-empty array will always have first/last elements: guard let first = preMap.first, let last = preMap.last else { return .failure(.arrayIsEmpty) } return .success(.init( rawValue: preMap, metadata: .init(first: first, last: last) )) } } typealias NonEmptyIntArray = SemanticType<NonEmptyIntArray_Spec> extension NonEmptyIntArray { var first: Int { return gatewayMetadata.first } var last: Int { return gatewayMetadata.last } }
mit
77f5be4ef09b9900b53f6dc25bacdaa7
33.339623
116
0.616896
4.636943
false
true
false
false
narner/AudioKit
Playgrounds/AudioKitPlaygrounds/Playgrounds/Analysis.playground/Pages/Tracking Amplitude.xcplaygroundpage/Contents.swift
1
2351
//: ## Tracking Amplitude //: Determing the amplitude of an audio signal by //: outputting the value of a generator node into the AKAmplitudeTracker. //: This node is great if you want to build an app that does audio monitoring and analysis. import AudioKitPlaygrounds import AudioKit //: First lets set up sound source to track let oscillatorNode = AKOperationGenerator { _ in // Let's set up the volume to be changing in the shape of a sine wave let volume = AKOperation.sineWave(frequency:0.2).scale(minimum: 0, maximum: 0.5) // And lets make the frequency move around to make sure it doesn't affect the amplitude tracking let frequency = AKOperation.jitter(amplitude: 200, minimumFrequency: 10, maximumFrequency: 30) + 200 // So our oscillator will move around randomly in frequency and have a smoothly varying amplitude return AKOperation.sineWave(frequency: frequency, amplitude: volume) } let trackedAmplitude = AKAmplitudeTracker(oscillatorNode) AudioKit.output = trackedAmplitude AudioKit.start() oscillatorNode.start() //: User Interface import AudioKitUI class LiveView: AKLiveViewController { var trackedAmplitudeSlider: AKSlider? override func viewDidLoad() { AKPlaygroundLoop(every: 0.1) { self.trackedAmplitudeSlider?.value = trackedAmplitude.amplitude } addTitle("Tracking Amplitude") trackedAmplitudeSlider = AKSlider(property: "Tracked Amplitude", range: 0 ... 0.55) { _ in // Do nothing, just for display } addView(trackedAmplitudeSlider) addView(AKRollingOutputPlot.createView()) } } import PlaygroundSupport PlaygroundPage.current.liveView = LiveView() //: This keeps the playground running so that audio can play for a long time PlaygroundPage.current.needsIndefiniteExecution = true //: Experiment with this playground by changing the volume function to a //: phasor or another well-known function to see how well the amplitude tracker //: can track. Also, you could change the sound source from an oscillator to a //: noise generator, or any constant sound source (some things like a physical //: model would not work because the output has an envelope to its volume). //: Instead of just plotting our results, we could use the value to drive other //: sounds or update an app's user interface.
mit
ef4a98cd25755df429f6a8b635747a3c
37.540984
104
0.743939
4.711423
false
false
false
false
stephentyrone/swift
benchmark/utils/main.swift
1
10729
//===--- main.swift -------------------------------------------*- swift -*-===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 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 // //===----------------------------------------------------------------------===// // This is just a driver for performance overview tests. import TestsUtils import DriverUtils import Ackermann import AngryPhonebook import AnyHashableWithAClass import Array2D import ArrayAppend import ArrayInClass import ArrayLiteral import ArrayOfGenericPOD import ArrayOfGenericRef import ArrayOfPOD import ArrayOfRef import ArraySetElement import ArraySubscript import BinaryFloatingPointConversionFromBinaryInteger import BinaryFloatingPointProperties import BitCount import Breadcrumbs import BucketSort import ByteSwap import COWTree import COWArrayGuaranteedParameterOverhead import CString import CSVParsing import Calculator import CaptureProp import ChaCha import ChainedFilterMap import CharacterLiteralsLarge import CharacterLiteralsSmall import CharacterProperties import Chars import ClassArrayGetter import Codable import Combos import DataBenchmarks import DeadArray import DevirtualizeProtocolComposition import DictOfArraysToArrayOfDicts import DictTest import DictTest2 import DictTest3 import DictTest4 import DictTest4Legacy import DictionaryBridge import DictionaryBridgeToObjC import DictionaryCompactMapValues import DictionaryCopy import DictionaryGroup import DictionaryKeysContains import DictionaryLiteral import DictionaryOfAnyHashableStrings import DictionaryRemove import DictionarySubscriptDefault import DictionarySwap import Diffing import DiffingMyers import DropFirst import DropLast import DropWhile import ErrorHandling import Exclusivity import ExistentialPerformance import Fibonacci import FindStringNaive import FlattenList import FloatingPointParsing import FloatingPointPrinting import Hanoi import Hash import Histogram import HTTP2StateMachine import InsertCharacter import IntegerParsing import Integrate import IterateData import Join import LazyFilter import LinkedList import LuhnAlgoEager import LuhnAlgoLazy import MapReduce import Memset import Mirror import MonteCarloE import MonteCarloPi import NibbleSort import NIOChannelPipeline import NSDictionaryCastToSwift import NSError #if os(macOS) || os(iOS) || os(watchOS) || os(tvOS) import NSStringConversion #endif import NopDeinit import ObjectAllocation #if os(macOS) || os(iOS) || os(watchOS) || os(tvOS) import ObjectiveCBridging import ObjectiveCBridgingStubs #if !(SWIFT_PACKAGE || Xcode) import ObjectiveCNoBridgingStubs #endif #endif import ObserverClosure import ObserverForwarderStruct import ObserverPartiallyAppliedMethod import ObserverUnappliedMethod import OpaqueConsumingUsers import OpenClose import Phonebook import PointerArithmetics import PolymorphicCalls import PopFront import PopFrontGeneric import Prefix import PrefixWhile import Prims import PrimsNonStrongRef import PrimsSplit import ProtocolDispatch import ProtocolDispatch2 import Queue import RC4 import RGBHistogram import Radix2CooleyTukey import RandomShuffle import RandomTree import RandomValues import RangeAssignment import RangeIteration import RangeOverlaps import RangeReplaceableCollectionPlusDefault import RecursiveOwnedParameter import ReduceInto import RemoveWhere import ReversedCollections import RomanNumbers import SequenceAlgos import SetTests import SevenBoom import Sim2DArray import SortArrayInClass import SortIntPyramids import SortLargeExistentials import SortLettersInPlace import SortStrings import StackPromo import StaticArray import StrComplexWalk import StrToInt import StringBuilder import StringComparison import StringEdits import StringEnum import StringInterpolation import StringMatch import StringRemoveDupes import StringReplaceSubrange import StringTests import StringWalk import Substring import Suffix import SuperChars import TwoSum import TypeFlood import UTF8Decode import Walsh import WordCount import XorLoop @inline(__always) private func registerBenchmark(_ bench: BenchmarkInfo) { registeredBenchmarks.append(bench) } @inline(__always) private func registerBenchmark< S : Sequence >(_ infos: S) where S.Element == BenchmarkInfo { registeredBenchmarks.append(contentsOf: infos) } registerBenchmark(Ackermann) registerBenchmark(AngryPhonebook) registerBenchmark(AnyHashableWithAClass) registerBenchmark(Array2D) registerBenchmark(ArrayAppend) registerBenchmark(ArrayInClass) registerBenchmark(ArrayLiteral) registerBenchmark(ArrayOfGenericPOD) registerBenchmark(ArrayOfGenericRef) registerBenchmark(ArrayOfPOD) registerBenchmark(ArrayOfRef) registerBenchmark(ArraySetElement) registerBenchmark(ArraySubscript) registerBenchmark(BinaryFloatingPointConversionFromBinaryInteger) registerBenchmark(BinaryFloatingPointPropertiesBinade) registerBenchmark(BinaryFloatingPointPropertiesNextUp) registerBenchmark(BinaryFloatingPointPropertiesUlp) registerBenchmark(BitCount) registerBenchmark(Breadcrumbs) registerBenchmark(BucketSort) registerBenchmark(ByteSwap) registerBenchmark(COWTree) registerBenchmark(COWArrayGuaranteedParameterOverhead) registerBenchmark(CString) registerBenchmark(CSVParsing) registerBenchmark(Calculator) registerBenchmark(CaptureProp) registerBenchmark(ChaCha) registerBenchmark(ChainedFilterMap) registerBenchmark(CharacterLiteralsLarge) registerBenchmark(CharacterLiteralsSmall) registerBenchmark(CharacterPropertiesFetch) registerBenchmark(CharacterPropertiesStashed) registerBenchmark(CharacterPropertiesStashedMemo) registerBenchmark(CharacterPropertiesPrecomputed) registerBenchmark(Chars) registerBenchmark(Codable) registerBenchmark(Combos) registerBenchmark(ClassArrayGetter) registerBenchmark(DataBenchmarks) registerBenchmark(DeadArray) registerBenchmark(DevirtualizeProtocolComposition) registerBenchmark(DictOfArraysToArrayOfDicts) registerBenchmark(Dictionary) registerBenchmark(Dictionary2) registerBenchmark(Dictionary3) registerBenchmark(Dictionary4) registerBenchmark(Dictionary4Legacy) registerBenchmark(DictionaryBridge) registerBenchmark(DictionaryBridgeToObjC) registerBenchmark(DictionaryCompactMapValues) registerBenchmark(DictionaryCopy) registerBenchmark(DictionaryGroup) registerBenchmark(DictionaryKeysContains) registerBenchmark(DictionaryLiteral) registerBenchmark(DictionaryOfAnyHashableStrings) registerBenchmark(DictionaryRemove) registerBenchmark(DictionarySubscriptDefault) registerBenchmark(DictionarySwap) registerBenchmark(Diffing) registerBenchmark(DiffingMyers) registerBenchmark(DropFirst) registerBenchmark(DropLast) registerBenchmark(DropWhile) registerBenchmark(ErrorHandling) registerBenchmark(Exclusivity) registerBenchmark(ExistentialPerformance) registerBenchmark(Fibonacci) registerBenchmark(FindStringNaive) registerBenchmark(FlattenListLoop) registerBenchmark(FlattenListFlatMap) registerBenchmark(FloatingPointParsing) registerBenchmark(FloatingPointPrinting) registerBenchmark(Hanoi) registerBenchmark(HashTest) registerBenchmark(Histogram) registerBenchmark(HTTP2StateMachine) registerBenchmark(InsertCharacter) registerBenchmark(IntegerParsing) registerBenchmark(IntegrateTest) registerBenchmark(IterateData) registerBenchmark(Join) registerBenchmark(LazyFilter) registerBenchmark(LinkedList) registerBenchmark(LuhnAlgoEager) registerBenchmark(LuhnAlgoLazy) registerBenchmark(MapReduce) registerBenchmark(Memset) registerBenchmark(MirrorDefault) registerBenchmark(MonteCarloE) registerBenchmark(MonteCarloPi) registerBenchmark(NSDictionaryCastToSwift) registerBenchmark(NSErrorTest) #if os(macOS) || os(iOS) || os(watchOS) || os(tvOS) registerBenchmark(NSStringConversion) #endif registerBenchmark(NibbleSort) registerBenchmark(NIOChannelPipeline) registerBenchmark(NopDeinit) registerBenchmark(ObjectAllocation) #if os(macOS) || os(iOS) || os(watchOS) || os(tvOS) registerBenchmark(ObjectiveCBridging) registerBenchmark(ObjectiveCBridgingStubs) #if !(SWIFT_PACKAGE || Xcode) registerBenchmark(ObjectiveCNoBridgingStubs) #endif #endif registerBenchmark(ObserverClosure) registerBenchmark(ObserverForwarderStruct) registerBenchmark(ObserverPartiallyAppliedMethod) registerBenchmark(ObserverUnappliedMethod) registerBenchmark(OpaqueConsumingUsers) registerBenchmark(OpenClose) registerBenchmark(Phonebook) registerBenchmark(PointerArithmetics) registerBenchmark(PolymorphicCalls) registerBenchmark(PopFront) registerBenchmark(PopFrontArrayGeneric) registerBenchmark(Prefix) registerBenchmark(PrefixWhile) registerBenchmark(Prims) registerBenchmark(PrimsNonStrongRef) registerBenchmark(PrimsSplit) registerBenchmark(ProtocolDispatch) registerBenchmark(ProtocolDispatch2) registerBenchmark(QueueGeneric) registerBenchmark(QueueConcrete) registerBenchmark(RC4Test) registerBenchmark(RGBHistogram) registerBenchmark(Radix2CooleyTukey) registerBenchmark(RandomShuffle) registerBenchmark(RandomTree) registerBenchmark(RandomValues) registerBenchmark(RangeAssignment) registerBenchmark(RangeIteration) registerBenchmark(RangeOverlaps) registerBenchmark(RangeReplaceableCollectionPlusDefault) registerBenchmark(RecursiveOwnedParameter) registerBenchmark(ReduceInto) registerBenchmark(RemoveWhere) registerBenchmark(ReversedCollections) registerBenchmark(RomanNumbers) registerBenchmark(SequenceAlgos) registerBenchmark(SetTests) registerBenchmark(SevenBoom) registerBenchmark(Sim2DArray) registerBenchmark(SortArrayInClass) registerBenchmark(SortIntPyramids) registerBenchmark(SortLargeExistentials) registerBenchmark(SortLettersInPlace) registerBenchmark(SortStrings) registerBenchmark(StackPromo) registerBenchmark(StaticArrayTest) registerBenchmark(StrComplexWalk) registerBenchmark(StrToInt) registerBenchmark(StringBuilder) registerBenchmark(StringComparison) registerBenchmark(StringEdits) registerBenchmark(StringEnum) registerBenchmark(StringHashing) registerBenchmark(StringInterpolation) registerBenchmark(StringInterpolationSmall) registerBenchmark(StringInterpolationManySmallSegments) registerBenchmark(StringMatch) registerBenchmark(StringNormalization) registerBenchmark(StringRemoveDupes) registerBenchmark(StringReplaceSubrange) registerBenchmark(StringTests) registerBenchmark(StringWalk) registerBenchmark(SubstringTest) registerBenchmark(Suffix) registerBenchmark(SuperChars) registerBenchmark(TwoSum) registerBenchmark(TypeFlood) registerBenchmark(TypeName) registerBenchmark(UTF8Decode) registerBenchmark(Walsh) registerBenchmark(WordCount) registerBenchmark(XorLoop) main()
apache-2.0
944bd2238c86956c087dfee89b06378b
27.458886
80
0.878833
5.413219
false
false
false
false
kenny2006cen/GYXMPP
HMModules/HMBaseKit/HMBaseKit/Classes/HMExtension/UIColor+Extension.swift
1
2680
// // UIColor+Extension.swift // HMBaseKit // // Created by Ko Lee on 2019/8/21. // import UIKit public extension UIColor { convenience init(_ hex: UInt) { self.init( red: CGFloat((hex & 0xFF0000) >> 16) / 255.0, green: CGFloat((hex & 0x00FF00) >> 8) / 255.0, blue: CGFloat(hex & 0x0000FF) / 255.0, alpha: CGFloat(1.0) ) } ///十六进制字符串形式颜色值 class func hm_color(_ hex: String) -> UIColor { return hm_basekit_hexColor(hex) } static var hm_randomColor: UIColor { let red = CGFloat(arc4random()%256)/255.0 let green = CGFloat(arc4random()%256)/255.0 let blue = CGFloat(arc4random()%256)/255.0 return UIColor(red: red, green: green, blue: blue, alpha: 1.0) } ///适配暗黑模式设置颜色 dark -- 暗黑模式下的颜色 light -- 其他模式下的颜色 class func hm_traitColor(_ dark:UIColor = .white, _ light:UIColor) -> UIColor { if #available(iOS 13.0, *) { let color = UIColor{ (traitCollection) -> UIColor in if traitCollection.userInterfaceStyle == .dark { return dark } else { return light } } return color } else { return light } } } /// 定义16进制值颜色 fileprivate extension UIColor { private class func hm_basekit_hexColor(_ hex: String) -> UIColor { var cstr = hex.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines).uppercased() as NSString; if(cstr.length < 6){ return UIColor.clear; } if(cstr.hasPrefix("0X")){ cstr = cstr.substring(from: 2) as NSString } if(cstr.hasPrefix("#")){ cstr = cstr.substring(from: 1) as NSString } if(cstr.length != 6){ return UIColor.clear; } var range = NSRange.init() range.location = 0 range.length = 2 //r let rStr = cstr.substring(with: range); //g range.location = 2; let gStr = cstr.substring(with: range) //b range.location = 4; let bStr = cstr.substring(with: range) var r :UInt32 = 0x0; var g :UInt32 = 0x0; var b :UInt32 = 0x0; Scanner.init(string: rStr).scanHexInt32(&r); Scanner.init(string: gStr).scanHexInt32(&g); Scanner.init(string: bStr).scanHexInt32(&b); return UIColor.init(red: CGFloat(r) / 255.0, green: CGFloat(g) / 255.0, blue: CGFloat(b) / 255.0, alpha: 1.0); } }
mit
d342bf30b0a28860094f877de74a8528
28.431818
115
0.535521
3.748191
false
false
false
false
anzfactory/QiitaCollection
QiitaCollection/UserEntity.swift
1
3280
// // UserEntity.swift // QiitaCollection // // Created by ANZ on 2015/02/07. // Copyright (c) 2015年 anz. All rights reserved. // import UIKit import SwiftyJSON struct UserEntity: EntityProtocol { let id: String let name: String var displayName: String { get { return "@" + id } } let introduction: String let organization: String let web: String let github: String let twitter: String let facebook: String let linkedin: String let location: String let profImage: String var profUrl: NSURL { get { return NSURL(string: profImage)! } } let itemCount: Int let followersCount: Int let followeesCount: Int init (data: [String : JSON]) { id = data["id"]!.string! name = data["name"]!.string! introduction = data["description"]?.string ?? "" organization = data["organization"]?.string ?? "" web = data["website_url"]?.string ?? "" github = data["github_login_name"]?.string ?? "" twitter = data["twitter_screen_name"]?.string ?? "" facebook = data["facebook_id"]?.string ?? "" linkedin = data["linkedin_id"]?.string ?? "" location = data["location"]?.string ?? "" profImage = data["profile_image_url"]?.string ?? "" itemCount = data["items_count"]?.intValue ?? 0 followersCount = data["followers_count"]?.intValue ?? 0 followeesCount = data["followees_count"]?.intValue ?? 0 } init (data: JSON) { id = data["id"].string! name = data["name"].string! introduction = data["description"].string ?? "" organization = data["organization"].string ?? "" web = data["website_url"].string ?? "" github = data["github_login_name"].string ?? "" twitter = data["twitter_screen_name"].string ?? "" facebook = data["facebook_id"].string ?? "" linkedin = data["linkedin_id"].string ?? "" location = data["location"].string ?? "" profImage = data["profile_image_url"].string ?? "" itemCount = data["items_count"].intValue ?? 0 followersCount = data["followers_count"].intValue ?? 0 followeesCount = data["followees_count"].intValue ?? 0 } func loadThumb(imageView: UIImageView) { if self.profImage.isEmpty { imageView.image = UIImage(named: "default"); return } imageView.sd_setImageWithURL(self.profUrl, completed: { (image, error, cacheType, url) -> Void in if error != nil { imageView.image = UIImage(named: "default") println("error..." + error.localizedDescription) } }) } func loadThumb(button: UIButton) { if self.profImage.isEmpty { button.setImage(nil, forState: UIControlState.Normal) return } button.sd_setImageWithURL(self.profUrl, forState: UIControlState.Normal, completed: { (image, error, cacheType, url) -> Void in if error != nil { button.setImage(UIImage(named: "default"), forState: UIControlState.Normal) println("error..." + error.localizedDescription) } }) } }
mit
7cf6ff667fa2195959b37ac5923a7987
33.505263
135
0.570775
4.484268
false
false
false
false
Darkhorse-Fraternity/EasyIOS-Swift
Pod/Classes/Extend/EUI/EUI+ButtonProperty.swift
1
4468
// // EUI+ButtonProperty.swift // medical // // Created by zhuchao on 15/5/1. // Copyright (c) 2015年 zhuchao. All rights reserved. // import Foundation class ButtonProperty:ViewProperty{ var highlightedStyle = "" var disabledStyle = "" var selectedStyle = "" var applicationStyle = "" var reservedStyle = "" var highlightedText:String? var disabledText:String? var selectedText:String? var applicationText:String? var reservedText:String? var onEvent:SelectorAction? override func view() -> UIButton{ var view = UIButton() view.tagProperty = self if self.style != "" { view.setAttributedTitle(NSAttributedString(fromHTMLData: self.contentText?.toData(), attributes: ["html":self.style]), forState: UIControlState.Normal) } if self.highlightedText != nil { view.setAttributedTitle(NSAttributedString(fromHTMLData: self.highlightedText?.toData(), attributes: ["html":self.highlightedStyle]), forState: UIControlState.Highlighted) } if self.disabledText != nil { view.setAttributedTitle(NSAttributedString(fromHTMLData: self.disabledText?.toData(), attributes: ["html":self.disabledStyle]), forState: UIControlState.Disabled) } if self.selectedText != nil { view.setAttributedTitle(NSAttributedString(fromHTMLData: self.selectedText?.toData(), attributes: ["html":self.selectedStyle]), forState: UIControlState.Selected) } if self.applicationText != nil { view.setAttributedTitle(NSAttributedString(fromHTMLData: self.applicationText?.toData(), attributes: ["html":self.applicationStyle]), forState: UIControlState.Application) } if self.reservedText != nil { view.setAttributedTitle(NSAttributedString(fromHTMLData: self.reservedText?.toData(), attributes: ["html":self.reservedStyle]), forState: UIControlState.Reserved) } self.renderViewStyle(view) return view } override func renderTag(pelement: OGElement) { self.tagOut += ["highlighted","disabled","selected","application","reserved","disabled-text", "selected-text","application-text","reserved-text","highlighted-text","onevent"] super.renderTag(pelement) if let highlightedStyle = EUIParse.string(pelement,key: "highlighted") { self.highlightedStyle = "html{" + highlightedStyle + "}" } if let disabledStyle = EUIParse.string(pelement,key: "disabled") { self.disabledStyle = "html{" + disabledStyle + "}" } if let selectedStyle = EUIParse.string(pelement,key: "selected") { self.selectedStyle = "html{" + selectedStyle + "}" } if let applicationStyle = EUIParse.string(pelement,key: "application") { self.applicationStyle = "html{" + applicationStyle + "}" } if let reservedStyle = EUIParse.string(pelement,key: "reserved") { self.reservedStyle = "html{" + reservedStyle + "}" } self.disabledText = EUIParse.string(pelement,key: "disabled-text") self.selectedText = EUIParse.string(pelement,key: "selected-text") self.applicationText = EUIParse.string(pelement,key: "application-text") self.reservedText = EUIParse.string(pelement,key: "reserved-text") self.highlightedText = EUIParse.string(pelement,key: "highlighted-text") if let theSelector = EUIParse.string(pelement, key: "onevent") { var values = theSelector.trimArrayBy(":") if values.count == 2 { var event = values[0] var secondArray = values[1].trimArray if secondArray.count == 1 { self.onEvent = SelectorAction(selector: secondArray[0], event: event) }else if values.count >= 2 { self.onEvent = SelectorAction(selector: secondArray[0], event: event, target: secondArray[1]) } } } var html = "" for child in pelement.children { html += child.html().trim } if let newHtml = self.bindTheKeyPath(html, key: "text") { html = newHtml } self.contentText = html } }
mit
ad86fcfa72bb15092233a40e7afc0931
37.17094
183
0.610614
4.756124
false
false
false
false
alreadyRight/Swift-algorithm
自定义cell编辑状态/Pods/SnapKit/Source/Typealiases.swift
51
1599
// // SnapKit // // Copyright (c) 2011-Present SnapKit Team - https://github.com/SnapKit // // 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 #if os(iOS) || os(tvOS) import UIKit typealias LayoutRelation = NSLayoutRelation typealias LayoutAttribute = NSLayoutAttribute typealias LayoutPriority = UILayoutPriority #else import AppKit typealias LayoutRelation = NSLayoutConstraint.Relation typealias LayoutAttribute = NSLayoutConstraint.Attribute typealias LayoutPriority = NSLayoutConstraint.Priority #endif
mit
c040af257b160b5289e4ea5b9bbd0d6f
42.216216
81
0.75985
4.744807
false
false
false
false
StupidTortoise/personal
iOS/Swift/IndexTable/IndexTable/ViewController.swift
1
2803
// // ViewController.swift // IndexTable // // Created by tortoise on 7/19/15. // Copyright (c) 2015 703. All rights reserved. // import UIKit class ViewController: UITableViewController, UISearchBarDelegate { var dictData: NSDictionary? var listGroupName: NSArray? override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. let bundle = NSBundle.mainBundle() let path = bundle.pathForResource("team_dictionary", ofType: "plist") self.dictData = NSDictionary(contentsOfFile: path!) let tempArray = self.dictData!.allKeys as NSArray self.listGroupName = tempArray.sortedArrayUsingSelector("compare:") } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return self.listGroupName!.count } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { let groupName = self.listGroupName?.objectAtIndex(section) as? String let listTeams = self.dictData!.objectForKey(groupName!) as? NSArray return listTeams!.count } override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? { let groupName = self.listGroupName!.objectAtIndex(section) as? String return groupName! } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cellIdentifier = "Cell" var cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier) as? UITableViewCell if cell == nil { cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: cellIdentifier) } let section = indexPath.section let row = indexPath.row let groupName = self.listGroupName!.objectAtIndex(section) as? String let listTeams = self.dictData!.objectForKey(groupName!) as? NSArray cell?.textLabel?.text = listTeams?.objectAtIndex(row) as? String return cell! } override func sectionIndexTitlesForTableView(tableView: UITableView) -> [AnyObject]! { let listTitles = NSMutableArray(capacity: self.listGroupName!.count) for item in self.listGroupName! { let groupName = item as? NSString let title = groupName!.substringToIndex(1) listTitles.addObject(title) } return listTitles as [AnyObject] } }
gpl-2.0
49deacb17f312ecde6aad1f3a8910b8d
32.771084
118
0.654299
5.369732
false
false
false
false
duycao2506/SASCoffeeIOS
Pods/SwiftPullToRefresh/SwiftPullToRefresh/TextItem.swift
1
934
// // TextItem.swift // SwiftPullToRefresh // // Created by Leo Zhou on 2017/5/1. // Copyright © 2017年 Leo Zhou. All rights reserved. // import UIKit final class TextItem { private let loadingText: String private let pullingText: String private let releaseText: String let label = UILabel() init(loadingText: String, pullingText: String = "", releaseText: String = "") { self.loadingText = loadingText self.pullingText = pullingText self.releaseText = releaseText label.font = UIFont.systemFont(ofSize: 14) label.textColor = UIColor.black.withAlphaComponent(0.8) } func didUpdateState(_ isRefreshing: Bool) { label.text = isRefreshing ? loadingText : pullingText label.sizeToFit() } func didUpdateProgress(_ progress: CGFloat) { label.text = progress == 1 ? releaseText : pullingText label.sizeToFit() } }
gpl-3.0
7af6625076baa338c8d4bff70c050028
23.5
83
0.656284
4.519417
false
false
false
false
blg-andreasbraun/ProcedureKit
Sources/Mobile/UI.swift
2
3444
// // ProcedureKit // // Copyright © 2016 ProcedureKit. All rights reserved. // import Foundation import UIKit public protocol PresentingViewController: class { func present(_ viewControllerToPresent: UIViewController, animated flag: Bool, completion: (() -> Void)?) func show(_ viewControllerToShow: UIViewController, sender: Any?) func showDetailViewController(_ viewControllerToShow: UIViewController, sender: Any?) } extension UIViewController: PresentingViewController { } public protocol DismissingViewController: class { var didDismissViewControllerBlock: () -> Void { get set } } public enum PresentationStyle { case show, showDetail, present } open class UIProcedure: Procedure { public let presented: UIViewController public let presenting: PresentingViewController public let style: PresentationStyle public let wrapInNavigationController: Bool public let sender: Any? public let finishAfterPresentating: Bool internal var shouldWaitUntilDismissal: Bool { return !finishAfterPresentating } public init<T: UIViewController>(present: T, from: PresentingViewController, withStyle style: PresentationStyle, inNavigationController: Bool = true, sender: Any? = nil, finishAfterPresenting: Bool = true) { self.presented = present self.presenting = from self.style = style self.wrapInNavigationController = inNavigationController self.sender = sender self.finishAfterPresentating = finishAfterPresenting super.init() } public convenience init<T: UIViewController>(present: T, from: PresentingViewController, withStyle style: PresentationStyle, inNavigationController: Bool = true, sender: Any? = nil, waitForDismissal: Bool) where T: DismissingViewController { self.init(present: present, from: from, withStyle: style, inNavigationController: inNavigationController, sender: sender, finishAfterPresenting: !waitForDismissal) if waitForDismissal { present.didDismissViewControllerBlock = { [weak self] in guard let strongSelf = self else { return } if !strongSelf.finishAfterPresentating && strongSelf.isExecuting { strongSelf.finish() } } } } open override func execute() { DispatchQueue.main.async { [weak self] in guard let strongSelf = self else { return } switch strongSelf.style { case .present: let viewControllerToPresent: UIViewController if strongSelf.presented is UIAlertController || !strongSelf.wrapInNavigationController { viewControllerToPresent = strongSelf.presented } else { viewControllerToPresent = UINavigationController(rootViewController: strongSelf.presented) } strongSelf.presenting.present(viewControllerToPresent, animated: true, completion: nil) case .show: strongSelf.presenting.show(strongSelf.presented, sender: strongSelf.sender) case .showDetail: strongSelf.presenting.showDetailViewController(strongSelf.presented, sender: strongSelf.sender) } if strongSelf.finishAfterPresentating { strongSelf.finish() return } } } }
mit
f6cdf146cec020534ef6b67cfb13330d
36.423913
245
0.675864
5.625817
false
false
false
false
borland/MTGLifeCounter2
MTGLifeCounter2/Utility.swift
1
3491
// // Utility.swift // MTGLifeCounter2 // // Created by Orion Edwards on 4/09/14. // Copyright (c) 2014 Orion Edwards. All rights reserved. // import Foundation import UIKit public let GlobalTintColor = UIColor(red: 0.302, green: 0.102, blue: 0.702, alpha: 1) // swift 2.2 compiler +'ing more than 3 arrays together takes minutes to COMPILE, so we don't + them func concat<T>(_ arrays: [[T]]) -> [T] { var result = [T]() for array in arrays { result.append(contentsOf: array) } return result } extension UIView { func addConstraints(_ format:String, views:[String:UIView], metrics:[String:CGFloat]? = nil, options:NSLayoutConstraint.FormatOptions=NSLayoutConstraint.FormatOptions(rawValue: 0)) { let constraints = NSLayoutConstraint.constraints( withVisualFormat: format, options: options, metrics: metrics, views: views) self.addConstraints(constraints) } func addAllConstraints(_ constraints: [NSLayoutConstraint]...) { addConstraints(concat(constraints)) } func removeAllConstraints(_ constraints: [NSLayoutConstraint]...) { removeConstraints(concat(constraints)) } } extension Sequence where Iterator.Element == NSLayoutConstraint { func affectingView(_ view: UIView) -> [NSLayoutConstraint] { return filter { if let first = $0.firstItem as? UIView, first == view { return true } if let second = $0.secondItem as? UIView, second == view { return true } return false } } } //! The UInt is the number rolled on the dice face, the Bool is true if this is the "winning" value func randomUntiedDiceRolls(_ numDice:Int, diceFaceCount:UInt) -> [(UInt, Bool)] { var values = Array(repeating: UInt(1), count: numDice) // find the indexes of values that have the highest value, and replace those values with randoms. Repeat until no ties while true { let maxVal = values.max()! // we only care if the highest dice rolls are tied (e.g. if there are 3 people and the dice go 7,2,2 that's fine) let tiedValueIndexes = findIndexes(values, value: maxVal) if tiedValueIndexes.count < 2 { break } for ix in tiedValueIndexes { values[ix] = UInt(arc4random_uniform(UInt32(diceFaceCount)) + 1) } } let maxVal = values.max()! return values.map{ x in (x, x == maxVal) } } func delay(_ seconds: TimeInterval, block: @escaping ()->()) -> () -> () { var canceled = false // volatile? lock? let dt = DispatchTime.now() + Double(Int64(seconds * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC) DispatchQueue.main.asyncAfter(deadline: dt) { if !canceled { block() } } return { canceled = true } } func findIndexes<T : Equatable>(_ domain:[T], value:T) -> [Int] { return domain .enumerated() .filter{ (ix, obj) in obj == value } .map{ (ix, obj) in ix } } enum ContainerOrientation { case portrait, landscape } extension UIView { /** returns the "orientation" of the VIEW ITSELF, not neccessarily the screen */ // var orientation : ScreenOrientation { // return bounds.size.orientation // } } extension CGSize { var orientation : ContainerOrientation { return (width > height) ? .landscape : .portrait } }
mit
a054cb8e320c7de5a6eaeefc22b55bbc
29.893805
186
0.618734
4.151011
false
false
false
false
jorgetemp/maps-sdk-for-ios-samples
tutorials/current-place-on-map/current-place-on-map/PlacesViewController.swift
1
3050
/* * Copyright 2017 Google Inc. All rights reserved. * * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this * file except in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF * ANY KIND, either express or implied. See the License for the specific language governing * permissions and limitations under the License. */ import UIKit import GooglePlaces class PlacesViewController: UIViewController { @IBOutlet weak var tableView: UITableView! // An array to hold the list of possible locations. var likelyPlaces: [GMSPlace] = [] var selectedPlace: GMSPlace? // Cell reuse id (cells that scroll out of view can be reused). let cellReuseIdentifier = "cell" override func viewDidLoad() { super.viewDidLoad() // Register the table view cell class and its reuse id. tableView.register(UITableViewCell.self, forCellReuseIdentifier: cellReuseIdentifier) // This view controller provides delegate methods and row data for the table view. tableView.delegate = self tableView.dataSource = self tableView.reloadData() } // Pass the selected place to the new view controller. override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "unwindToMain" { if let nextViewController = segue.destination as? MapViewController { nextViewController.selectedPlace = selectedPlace } } } } // Respond when a user selects a place. extension PlacesViewController: UITableViewDelegate { func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { selectedPlace = likelyPlaces[indexPath.row] performSegue(withIdentifier: "unwindToMain", sender: self) } } // Populate the table with the list of most likely places. extension PlacesViewController: UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return likelyPlaces.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: cellReuseIdentifier, for: indexPath) let collectionItem = likelyPlaces[indexPath.row] cell.textLabel?.text = collectionItem.name return cell } // Adjust cell height to only show the first five items in the table // (scrolling is disabled in IB). func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return self.tableView.frame.size.height/5 } // Make table rows display at proper height if there are less than 5 items. func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { if (section == tableView.numberOfSections - 1) { return 1 } return 0 } }
apache-2.0
4a5069b129fdd5e640c853aa5aaab2c1
33.269663
98
0.738033
4.780564
false
false
false
false
ShinCurry/Maria
Maria/MariaNotification.swift
1
1006
// // Aria2Notification.swift // Aria2 // // Created by ShinCurry on 16/4/14. // Copyright © 2016年 ShinCurry. All rights reserved. // import Foundation open class MariaNotification { static public func notification(title: String, details: String) { let notification = NSUserNotification() notification.title = title notification.informativeText = details NSUserNotificationCenter.default.deliver(notification) } static public func actionNotification(identifier: String, title: String, details: String, userInfo: [String: AnyObject]?) { let notification = NSUserNotification() notification.title = title notification.informativeText = details notification.identifier = identifier notification.userInfo = userInfo NSUserNotificationCenter.default.deliver(notification) } static public func removeAllNotification() { NSUserNotificationCenter.default.removeAllDeliveredNotifications() } }
gpl-3.0
2b5df34990527b1177f08e7745688760
33.586207
127
0.717846
5.278947
false
false
false
false
poetmountain/MotionMachine
Sources/MotionSequence.swift
1
38649
// // MotionSequence.swift // MotionMachine // // Created by Brett Walker on 5/11/16. // Copyright © 2016-2018 Poet & Mountain, LLC. 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 Foundation public typealias SequenceUpdateClosure = (_ sequence: MotionSequence) -> Void /** * This notification closure should be called when the `start` method starts a motion operation. If a delay has been specified, this closure is called after the delay is complete. * * - seealso: start */ public typealias SequenceStarted = SequenceUpdateClosure /** * This notification closure should be called when the `stop` method starts a motion operation. * * - seealso: stop */ public typealias SequenceStopped = SequenceUpdateClosure /** * This notification closure should be called when the `update` method is called while a Moveable object is currently moving. * * - seealso: update */ public typealias SequenceUpdated = SequenceUpdateClosure /** * This notification closure should be called when a motion operation reverses its movement direction. * */ public typealias SequenceReversed = SequenceUpdateClosure /** * This notification closure should be called when a motion has started a new repeat cycle. * */ public typealias SequenceRepeated = SequenceUpdateClosure /** * This notification closure should be called when calling the `pause` method pauses a motion operation. * */ public typealias SequencePaused = SequenceUpdateClosure /** * This notification closure should be called when calling the `resume` method resumes a motion operation. * */ public typealias SequenceResumed = SequenceUpdateClosure /** * This notification closure should be called when a motion operation has fully completed. * * - remark: This closure should only be executed when all activity related to the motion has ceased. For instance, if a Moveable class allows a motion to be repeated multiple times, this closure should be called when all repetitions have finished. * */ public typealias SequenceCompleted = SequenceUpdateClosure /** * This notification closure should be called when a sequence's movement has advanced to its next sequence step. * */ public typealias SequenceStepped = SequenceUpdateClosure /** * MotionSequence moves a collection of objects conforming to the `Moveable` protocol in sequential order. MotionSequence provides a powerful and easy way of chaining together individual motions to create complex animations. */ public class MotionSequence: Moveable, MoveableCollection, TempoDriven, MotionUpdateDelegate { // MARK: - Public Properties ///------------------------------------- /// Setting Up a MotionSequence ///------------------------------------- /** * The delay, in seconds, before the sequence begins. * * - warning: Setting this parameter after a sequence has begun has no effect. */ public var delay: TimeInterval = 0.0 /** * A Boolean which determines whether the sequence should repeat. When set to `true`, the sequence repeats for the number of times specified by the `repeatCycles` property. The default value is `false`. * * - note: By design, setting this value to `true` without changing the `repeatCycles` property from its default value (0) will cause the sequence to repeat infinitely. * - seealso: repeatCycles */ public var repeating: Bool = false /** * The number of complete sequence cycle operations to repeat. * * - remark: This property is only used when `repeating` is set to `true`. Assigning `REPEAT_INFINITE` to this property signals an infinite amount of motion cycle repetitions. The default value is `REPEAT_INFINITE`. * * - seealso: repeating */ public var repeatCycles: UInt = REPEAT_INFINITE // MOTION STATE /** * An array of `Moveable` objects controlled by this MotionSequence object, determining each step of the sequence. (read-only) * * - remark: The order of objects in this array represents the sequence order in which each will be moved. */ private(set) public var steps: [Moveable] = [] /// A `MotionDirection` enum which represents the current direction of the motion operation. (read-only) private(set) public var motionDirection: MotionDirection /** * A value between 0.0 and 1.0, which represents the current progress of a movement between two value destinations. (read-only) * * - remark: Be aware that if this motion is `reversing` or `repeating`, this value will only represent one movement. For instance, if a Motion has been set to repeat once, this value will move from 0.0 to 1.0, then reset to 0.0 again as the new repeat cycle starts. Similarly, if a Motion is set to reverse, this progress will represent each movement; first in the forward direction, then again when reversing back to the starting values. */ private(set) public var motionProgress: Double { get { return _motionProgress } set(newValue) { _motionProgress = newValue // sync cycleProgress with motionProgress so that cycleProgress always represents total cycle progress if (reversing && motionDirection == .forward) { _cycleProgress = _motionProgress * 0.5 } else if (reversing && motionDirection == .reverse) { _cycleProgress = (_motionProgress * 0.5) + 0.5 } else { _cycleProgress = _motionProgress } } } private var _motionProgress: Double = 0.0 /** * A value between 0.0 and 1.0, which represents the current progress of a motion cycle. (read-only) * * - remark: A cycle represents the total length of a one motion operation. If `reversing` is set to `true`, a cycle comprises two separate movements (the forward movement, which at completion will have a value of 0.5, and the movement in reverse which at completion will have a value of 1.0); otherwise a cycle is the length of one movement. Note that if `repeating`, each repetition will be a new cycle and thus the progress will reset to 0.0 for each repeat. */ private(set) public var cycleProgress: Double { get { return _cycleProgress } set(newValue) { _cycleProgress = newValue // sync motionProgress with cycleProgress, so we modify the ivar directly (otherwise we'd enter a recursive loop as each setter is called) if (reversing) { var new_progress = _cycleProgress * 2 if (_cycleProgress >= 0.5) { new_progress -= 1 } _motionProgress = new_progress } else { _motionProgress = _cycleProgress } } } private var _cycleProgress: Double = 0.0 /** * The amount of completed motion cycles. (read-only) * * - remark: A cycle represents the total length of a one motion operation. If `reversing` is set to `true`, a cycle comprises two separate movements (the forward movement and the movement in reverse); otherwise a cycle is the length of one movement. Note that if `repeating`, each repetition will be a new cycle. */ private(set) public var cyclesCompletedCount: UInt = 0 /** * A value between 0.0 and 1.0, which represents the current overall progress of the sequence. This value should include all reversing and repeat motion cycles. (read-only) * * - remark: If a sequence is not repeating, this value will be equivalent to the value of `cycleProgress`. * - seealso: cycleProgress * */ public var totalProgress: Double { get { // sync totalProgress with cycleProgress if (repeating && repeatCycles > 0 && cyclesCompletedCount < (repeatCycles+1)) { return (_cycleProgress + Double(cyclesCompletedCount)) / Double(repeatCycles+1) } else { return _cycleProgress } } } // MARK: Moveable protocol properties /** * Specifies that the MotionSequence's child motions should reverse their movements back to their starting values after completing their forward movements. When each child motion should reverse is determined by the MotionSequence's `reversingMode`. * * - important: The previous state of `reversing` on any of this sequence's `Moveable` objects will be overridden with the value you assign to this property! */ public var reversing: Bool { get { return _reversing } set(newValue) { _reversing = newValue // change the `reversing` property on each `Moveable` object sequence step to reflect the sequence's new state if (reversingMode == .contiguous) { for step in steps { step.reversing = _reversing } } motionsReversedCount = 0 } } private var _reversing: Bool = false /// A `MotionState` enum which represents the current movement state of the motion operation. (read-only) private(set) public var motionState: MotionState /// Provides a delegate for updates to a Moveable object's status, used by Moveable collections. public weak var updateDelegate: MotionUpdateDelegate? // MARK: MoveableCollection protocol properties /** * A `CollectionReversingMode` enum which defines the behavior of a `Moveable` class when its `reversing` property is set to `true`. In the standard MotionMachine classes only `MotionSequence` currently uses this property to alter its behavior. * * - note: While including this property in custom classes which implement the `MoveableCollection` protocol is required, implementation of behavior based on the property's value is optional. * - remark: The default value is `Sequential`. Please see the documentation for `CollectionReversingMode` for more information on these modes. */ public var reversingMode: CollectionReversingMode = .sequential { didSet { if (reversingMode == .contiguous && reversing) { for step in steps { step.reversing = true if var collection = step as? MoveableCollection { // by default, setting a .Contiguous reversingMode will cascade down to sub-collections // since usually a user would expect a contiguous movement from each sub-motion when setting this value collection.reversingMode = .contiguous } } } else if (reversingMode == .sequential && reversing) { for step in steps { step.reversing = false } } } } // MARK: TempoBeating protocol properties /** * A concrete `Tempo` subclass that provides an update "beat" while a motion operation occurs. * * - remark: By default, Motion will assign an instance of `CATempo` to this property, which uses CADisplayLink for interval updates. */ public var tempo: Tempo? { get { return _tempo } set(newValue) { if _tempo != nil { _tempo?.delegate = nil _tempo = nil } _tempo = newValue _tempo?.delegate = self // tell sequence steps conforming to the `TempoDriven` protocol that don't want their tempo used to stop their tempo updates for (index, step) in steps.enumerated() { if let driven = step as? TempoDriven { if (index < tempoOverrides.count) { let should_override = tempoOverrides[index] if should_override { driven.stopTempoUpdates() } } } } } } lazy private var _tempo: Tempo? = { return CATempo.init() }() // MARK: - Notification closures /** * This closure is called when a motion operation starts. * * - seealso: start */ @discardableResult public func started(_ closure: @escaping SequenceStarted) -> Self { _started = closure return self } private var _started: SequenceStarted? /** * This closure is called when a motion operation is stopped by calling the `stop` method. * * - seealso: stop */ @discardableResult public func stopped(_ closure: @escaping SequenceStopped) -> Self { _stopped = closure return self } private var _stopped: SequenceStopped? /** * This closure is called when a motion operation update occurs and this instance's `motionState` is `.Moving`. * * - seealso: update(withTimeInterval:) */ @discardableResult public func updated(_ closure: @escaping SequenceUpdated) -> Self { _updated = closure return self } private var _updated: SequenceUpdated? /** * This closure is called when a motion cycle has completed. * * - seealso: repeating, cyclesCompletedCount */ @discardableResult public func cycleRepeated(_ closure: @escaping SequenceRepeated) -> Self { _cycleRepeated = closure return self } private var _cycleRepeated: SequenceRepeated? /** * This closure is called when the `motionDirection` property changes to `.Reversing`. * * - seealso: motionDirection, reversing */ @discardableResult public func reversed(_ closure: @escaping SequenceReversed) -> Self { _reversed = closure return self } private var _reversed: SequenceReversed? /** * This closure is called when calling the `pause` method on this instance causes a motion operation to pause. * * - seealso: pause */ @discardableResult public func paused(_ closure: @escaping SequencePaused) -> Self { _paused = closure return self } private var _paused: SequencePaused? /** * This closure is called when calling the `resume` method on this instance causes a motion operation to resume. * * - seealso: resume */ @discardableResult public func resumed(_ closure: @escaping SequenceResumed) -> Self { _resumed = closure return self } private var _resumed: SequenceResumed? /** * This closure is called when a motion operation has completed (or when all motion cycles have completed, if `repeating` is set to `true`). * */ @discardableResult public func completed(_ closure: @escaping SequenceCompleted) -> Self { _completed = closure return self } private var _completed: SequenceCompleted? /** * This notification closure is called when the sequence's movement has advanced to its next sequence step. * */ @discardableResult public func stepCompleted(_ closure: @escaping SequenceStepped) -> Self { _stepCompleted = closure return self } private var _stepCompleted: SequenceStepped? // MARK: - Private Properties /// The starting time of the current sequence's delay. A value of 0 means that no motion is currently in progress. private var startTime: TimeInterval = 0.0 /// The most recent update timestamp, as sent by the `update` method. private var currentTime: TimeInterval = 0.0 /// The ending time of the delay, which is determined by adding the delay to the starting time. private var endTime: TimeInterval = 0.0 /// Timestamp when the `pause` method is called, to track amount of time paused. private var pauseTimestamp: TimeInterval = 0.0 /** * An array of Boolean values representing whether a `Moveable` object should 'override' the MotionSequence's `Tempo` object and use its own instead. The positions of the array correspond to the positions of the `Moveable` objects in the `steps` array. */ private var tempoOverrides: [Bool] = [] /// An integer representing the position of the current sequence step. private var currentSequenceIndex: Int = 0 /// The number of `Moveable` objects which have completed their motion operations. private var motionsCompletedCount: Int = 0 /** * The number of `Moveable` objects which have finished one direction of a movement cycle and are now moving in a reverse direction. This property is used to sync motion operations when `reversing` and `syncMotionsWhenReversing` are both set to `true`. */ private var motionsReversedCount: Int = 0 // MARK: - Initialization /** * Initializer. * * - parameters: * - steps: An array of `Moveable` objects the MotionSequence should control. The positions of the objects in the Array will determine the order in which the child motions should move. * - options: An optional set of `MotionsOptions`. */ public init(steps: [Moveable] = [], options: MotionOptions? = MotionOptions.none) { // unpack options values if let unwrappedOptions = options { repeating = unwrappedOptions.contains(.repeats) _reversing = unwrappedOptions.contains(.reverses) } motionState = .stopped motionDirection = .forward for step: Moveable in steps { add(step) } _tempo?.delegate = self } deinit { tempo?.delegate = nil for index in 0 ..< steps.count { steps[index].updateDelegate = nil } } // MARK: - Public methods /** * Adds a sequence step to the end of the current sequence. * * - parameters: * - sequenceStep: An object which adopts the `Moveable` protocol. * - useChildTempo: When `true`, the child object should use its own tempo to update its motion progress, and thus the `update` method will not be called on the object by the MotionSequence instance. The default is `false`, meaning that the MotionSequence will use its own `Tempo` object to send updates to this child motion. This setting has no effect if the motion object does not conform to the `TempoDriven` protocol. * * * - warning: * - A NSInternalInconsistencyException will be raised if the provided object does not adopt the `Moveable` protocol. * - This method should not be called after a MotionSequence has started moving. */ @discardableResult public func add(_ sequenceStep: Moveable, useChildTempo: Bool = false) -> Self { if (reversing && reversingMode == .contiguous) { sequenceStep.reversing = true } if let tempo_beating = (sequenceStep as? TempoDriven) { if (!useChildTempo) { tempo_beating.stopTempoUpdates() } } steps.append(sequenceStep) tempoOverrides.append(!useChildTempo) // use the opposite Boolean value in order to represent which tempos should be overriden by the sequence // subscribe to this motion's status updates sequenceStep.updateDelegate = self return self } /** * Adds an array of sequence steps to the current sequence. * * - parameter steps: An array of 'Moveable` objects. * * - note: All objects added via this method which subscribe to the `TempoDriven` protocol will have their Tempo updates overriden. The MotionSequence will call the `update` method directly on all of them. * * - warning: * - A NSInternalInconsistencyException will be raised if the provided object does not adopt the `Moveable` protocol. * - This method should not be called after a MotionGroup has started moving. * */ @discardableResult public func add(_ steps: [Moveable]) -> Self { for step in steps { _ = add(step) } return self } /** * Removes the specified motion object from the sequence. * * - parameter sequenceStep: The sequence step to remove. */ public func remove(_ sequenceStep: Moveable) { // first grab the index of the object in the motions array so we can remove the corresponding tempoOverrides value let index = steps.firstIndex { $0 == sequenceStep } if let motion_index = index { sequenceStep.updateDelegate = nil steps.remove(at: motion_index) tempoOverrides.remove(at: motion_index) } } /** * Adds a delay before the motion operation will begin. * * - parameter amount: The number of seconds to wait. * - returns: A reference to this MotionSequence instance, for the purpose of chaining multiple calls to this method. */ @discardableResult public func afterDelay(_ amount: TimeInterval) -> MotionSequence { delay = amount return self } /** * Specifies that a motion cycle should repeat and the number of times it should do so. When no value is provided, the motion will repeat infinitely. * * - remark: When this method is used there is no need to specify `.Repeat` in the `options` parameter of the init method. * * - parameter numberOfCycles: The number of motion cycles to repeat. The default value is `REPEAT_INFINITE`. * - returns: A reference to this MotionSequence instance, for the purpose of chaining multiple calls to this method. * - seealso: repeatCycles, repeating */ @discardableResult public func repeats(_ numberOfCycles: UInt = REPEAT_INFINITE) -> MotionSequence { repeatCycles = numberOfCycles repeating = true return self } /** * Specifies that the MotionSequence's child motions should reverse their movements back to their starting values after completing their forward movements. * * - remark: When this method is used there is no need to specify `.Reverse` in the `options` parameter of the init method. * * - parameter mode: Defines the `CollectionReversingMode` used when reversing. * - returns: A reference to this MotionSequence instance, for the purpose of chaining multiple calls to this method. * - seealso: reversing, reversingMode */ @discardableResult public func reverses(_ mode: CollectionReversingMode = .sequential) -> MotionSequence { reversing = true reversingMode = mode return self } /** * Either the sequence step which is currently moving, or the first sequence step if this instance's `motionState` is currently `Stopped`. * * - returns: The current sequence step. */ public func currentStep() -> Moveable? { var sequence_step: Moveable? if (currentSequenceIndex < steps.count && currentSequenceIndex >= 0) { sequence_step = steps[currentSequenceIndex] } return sequence_step } // MARK: Private methods /// Starts the sequence's next repeat cycle, if there is one. private func nextRepeatCycle() { cyclesCompletedCount += 1 if (repeatCycles == 0 || cyclesCompletedCount - 1 < repeatCycles) { // reset sequence for another cycle currentSequenceIndex = 0 _motionProgress = 0.0 _cycleProgress = 0.0 // reset all sequence steps for step in steps { step.reset() } // call cycle closure weak var weak_self = self _cycleRepeated?(weak_self!) if (reversing) { if (motionDirection == .forward) { motionDirection = .reverse } else if (motionDirection == .reverse) { motionDirection = .forward } motionsReversedCount = 0 } // send repeat status update sendStatusUpdate(.repeated) if (reversing && reversingMode == .sequential) { currentSequenceIndex += 1 } // start first sequence step if let step = currentStep() { if (step.motionState == .paused) { step.resume() } _ = step.start() } } else { sequenceCompleted() } } /// Starts the next sequence step if the sequence is not yet complete. private func nextSequenceStep() { if ( (!reversing && currentSequenceIndex + 1 < steps.count) || (reversing && (motionDirection == .forward && currentSequenceIndex + 1 < steps.count)) || (reversing && (motionDirection == .reverse && currentSequenceIndex - 1 >= 0)) ) { if (!reversing || (reversing && motionDirection == .forward)) { currentSequenceIndex += 1 } else if (reversing && motionDirection == .reverse) { currentSequenceIndex -= 1 } // call step closure weak var weak_self = self _stepCompleted?(weak_self!) // send step status update sendStatusUpdate(.stepped) // start the next sequence step if let next_step = currentStep() { if (!reversing || (reversing && reversingMode == .contiguous && motionDirection == .forward) || (reversing && reversingMode == .sequential)) { _ = next_step.start() } else { if (next_step.motionState == .paused) { next_step.resume() } } } } } /// Reverses the direction of the sequence. private func reverseMotionDirection() { if (motionDirection == .forward) { motionDirection = .reverse } else if (motionDirection == .reverse) { motionDirection = .forward } motionsReversedCount = 0 // call reverse closure weak var weak_self = self _reversed?(weak_self!) let half_complete = round(Double(repeatCycles) * 0.5) if (motionDirection == .reverse && (Double(cyclesCompletedCount) ≈≈ half_complete)) { sendStatusUpdate(.halfCompleted) } else { sendStatusUpdate(.reversed) } } /// Called when the sequence has completed its movement. private func sequenceCompleted() { motionState = .stopped motionProgress = 1.0 _cycleProgress = 1.0 if (!repeating) { cyclesCompletedCount += 1 } // call update closure weak var weak_self = self _updated?(weak_self!) // call complete closure _completed?(weak_self!) // send completion status update sendStatusUpdate(.completed) } /** * Dispatches a status update to the `MotionUpdateDelegate` delegate assigned to the object, if there is one. * * - parameter status: The `MoveableStatus` enum value to send to the delegate. */ private func sendStatusUpdate(_ status: MoveableStatus) { weak var weak_self = self updateDelegate?.motionStatusUpdated(forMotion: weak_self!, updateType: status) } /** * Calculates the current progress of the sequence. * */ private func calculateProgress() { // add up all the totalProgress values for each child motion, then clamp it to 1.0 var children_progress = 0.0 for step in steps { children_progress += step.totalProgress } children_progress /= Double(steps.count) if (reversing && reversingMode == .sequential) { children_progress *= 0.5 if (motionDirection == .reverse) { children_progress += 0.5 } } children_progress = min(children_progress, 1.0) cycleProgress = children_progress } // MARK: Moveable methods public func update(withTimeInterval currentTime: TimeInterval) { self.currentTime = currentTime if (motionState == .moving) { if (startTime == 0.0 && cyclesCompletedCount == 0) { startTime = currentTime } if (currentSequenceIndex < tempoOverrides.count) { if let step = currentStep() { let should_send_tempo = tempoOverrides[currentSequenceIndex] if should_send_tempo { step.update(withTimeInterval: currentTime) } } } // update progress calculateProgress() // call update closure, but only if this sequence is still moving if (motionState == .moving) { weak var weak_self = self as MotionSequence _updated?(weak_self!) } } else if (motionState == .delayed) { if (startTime == 0.0) { // a start time of 0.0 means we need to initialize the motion times startTime = currentTime endTime = startTime + delay } if (currentTime >= endTime) { // delay is done, time to move motionState = .moving if let step = currentStep() { _ = step.start() } // call start closure weak var weak_self = self as MotionSequence _started?(weak_self!) // send start status update sendStatusUpdate(.started) } } } @discardableResult public func start() -> Self { if (motionState == .stopped) { reset() if (delay == 0.0) { motionState = .moving if let sequence_step = currentStep() { _ = sequence_step.start() } // call start closure weak var weak_self = self as MotionSequence _started?(weak_self!) // send start status update sendStatusUpdate(.started) } else { motionState = .delayed } } return self } public func stop() { if (motionState == .moving || motionState == .paused || motionState == .delayed) { motionState = .stopped _motionProgress = 0.0 _cycleProgress = 0.0 if let sequence_step = currentStep() { sequence_step.stop() } // call stop closure weak var weak_self = self as MotionSequence _stopped?(weak_self!) // send stop status update sendStatusUpdate(.stopped) } } public func pause() { if (motionState == .moving) { motionState = .paused if let sequence_step = currentStep() { sequence_step.pause() } // call pause closure weak var weak_self = self as MotionSequence _paused?(weak_self!) // send pause status update sendStatusUpdate(.paused) } } public func resume() { if (motionState == .paused) { motionState = .moving if let sequence_step = currentStep() { sequence_step.resume() } // call resume closure weak var weak_self = self as MotionSequence _resumed?(weak_self!) // send resume status update sendStatusUpdate(.resumed) } } /// Resets the sequence and all child motions to its initial state. public func reset() { motionState = .stopped currentSequenceIndex = 0 motionsCompletedCount = 0 cyclesCompletedCount = 0 motionDirection = .forward motionsReversedCount = 0 _motionProgress = 0.0 _cycleProgress = 0.0 startTime = 0.0 // reset all sequence steps for step in steps { step.reset() } } // MARK: - MotionUpdateDelegate methods public func motionStatusUpdated(forMotion motion: Moveable, updateType status: MoveableStatus) { calculateProgress() switch status { case .halfCompleted: if (reversing && reversingMode == .contiguous && motionDirection == .forward) { motionsReversedCount += 1 if (motionsReversedCount >= steps.count) { // the last sequence step has reversed, so we need to unpause each step backwards in sequence reverseMotionDirection() } else { // pause this motion step until we're ready for it to complete the back half of its motion cycle motion.pause() nextSequenceStep() } } case .completed: if ((motionDirection == .reverse && currentSequenceIndex - 1 >= 0) || (motionDirection == .forward && currentSequenceIndex + 1 < steps.count) ) { // if there is another sequence step in the direction of movement, then move to the next step nextSequenceStep() } else { if (reversing && reversingMode == .sequential && ((motionDirection == .forward && currentSequenceIndex + 1 >= steps.count) || (motionDirection == .reverse && currentSequenceIndex - 1 == 0))) { // if the sequence is set to reverse its motion and mode is noncontiguous // + if the sequence has no more steps left // then flip the motion direction and play the sequence again if (steps.count > 1) { reverseMotionDirection() // reset all step progress so totalProgress and cycleProgress remain accurate for step in steps { step.reset() } // start the same clip again if (!reversing || (reversing && motionDirection == .forward)) { currentSequenceIndex -= 1 } else if (reversing && motionDirection == .reverse) { currentSequenceIndex += 1 } nextSequenceStep() } else { // if there's only one step, just end the sequence sequenceCompleted() } } else if (repeating) { nextRepeatCycle() } else { sequenceCompleted() } } default: break } } // MARK: - TempoDriven methods public func stopTempoUpdates() { tempo?.delegate = nil tempo = nil } // MARK: - TempoDelegate methods public func tempoBeatUpdate(_ timestamp: TimeInterval) { update(withTimeInterval: timestamp) } }
mit
9adc836bd7430393a841d9135f4e2993
33.908762
466
0.574112
5.234187
false
false
false
false
andrea-prearo/SwiftExamples
RegionMonitor/RegionMonitor/RegionAnnotationsStore.swift
1
875
// // RegionAnnotationsStore.swift // RegionMonitor // // Created by Andrea Prearo on 5/24/15. // Copyright (c) 2015 Andrea Prearo. All rights reserved. // import Foundation let RegionAnnotationItemsKey = "RegionAnnotationItems" let RegionAnnotationItemsDidChangeNotification = "RegionAnnotationItemsDidChangeNotification" class RegionAnnotationsStore { // MARK: Singleton static let sharedInstance = GenericStore<RegionAnnotation>(storeItemsKey: RegionAnnotationItemsKey, storeItemsDidChangeNotification: RegionAnnotationItemsDidChangeNotification) class func annotationForRegionIdentifier(_ identifier: String) -> RegionAnnotation? { for annotation in RegionAnnotationsStore.sharedInstance.storedItems { if annotation.identifier == identifier { return annotation } } return nil } }
mit
1a7471b73bab5e9bdc2af5ac2d28bd3c
29.172414
180
0.745143
5.116959
false
false
false
false
apple/swift-log
Tests/LoggingTests/SubDirectoryOfLoggingTests/EmitALogFromSubDirectory.swift
1
802
//===----------------------------------------------------------------------===// // // This source file is part of the Swift Logging API open source project // // Copyright (c) 2021 Apple Inc. and the Swift Logging API project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of Swift Logging API project authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// import Logging internal func emitLogMessage(_ message: Logger.Message, to logger: Logger) { logger.trace(message) logger.debug(message) logger.info(message) logger.notice(message) logger.warning(message) logger.error(message) logger.critical(message) }
apache-2.0
0b1c05d328ff5471d2eacfb02ae52b5a
31.08
80
0.584788
4.802395
false
false
false
false
hhsolar/MemoryMaster-iOS
MemoryMaster/Controller/ImagePickerViewController.swift
1
4558
// // ImagePickerViewController.swift // MemoryMaster // // Created by apple on 8/10/2017. // Copyright © 2017 greatwall. All rights reserved. // import UIKit import Photos private let oneTimeLoadPhotos: Int = 45 class ImagePickerViewController: BaseTopViewController, UICollectionViewDelegateFlowLayout { // public api var noteController: EditNoteViewController? var personController: PersonEditTableViewController? var smallPhotoArray = [UIImage]() var photoAsset = [PHAsset]() var loadImageIndex: Int? var unloadImageNumber: Int { return photoAsset.count - smallPhotoArray.count } let refreshControl = UIRefreshControl() @IBOutlet weak var photoCollectionView: UICollectionView! override func viewDidLoad() { super.viewDidLoad() setupUI() getPhotoData() } override func setupUI() { super.setupUI() super.titleLabel.text = "All Photos" let nib = UINib(nibName: "ImagePickerCollectionViewCell", bundle: Bundle.main) photoCollectionView.register(nib, forCellWithReuseIdentifier: "ImagePickerCollectionViewCell") let layout = UICollectionViewFlowLayout.init() layout.itemSize = CGSize(width: (UIScreen.main.bounds.width - 20) / 3, height: (UIScreen.main.bounds.width - 20) / 3) layout.minimumLineSpacing = 5 layout.minimumInteritemSpacing = 0 photoCollectionView.collectionViewLayout = layout photoCollectionView.backgroundColor = UIColor.white photoCollectionView.delegate = self photoCollectionView.dataSource = self refreshControl.addTarget(self, action: #selector(self.loadMorePhoto), for: .valueChanged) photoCollectionView.addSubview(refreshControl) } @objc func loadMorePhoto() { var upperIndex = 0 var scrollIndex = loadImageIndex! if loadImageIndex! - (oneTimeLoadPhotos - 1) >= 0 { upperIndex = loadImageIndex! - (oneTimeLoadPhotos - 1) scrollIndex = oneTimeLoadPhotos - 1 } let subAsset = Array(photoAsset[upperIndex...loadImageIndex!]) UIImage.async_getLibraryThumbnails(assets: subAsset) { [weak self] (allSmallImageArray) in self?.smallPhotoArray.insert(contentsOf: allSmallImageArray, at: 0) DispatchQueue.main.async { self?.photoCollectionView.reloadData() self?.photoCollectionView.scrollToItem(at: IndexPath(item: scrollIndex, section: 0), at: .top, animated: false) self?.refreshControl.endRefreshing() } } loadImageIndex = upperIndex - 1 } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets { return UIEdgeInsetsMake(5, 5, 5, 5) } private func getPhotoData() { photoAsset = UIImage.getPhotoAssets() loadImageIndex = photoAsset.count - 1 loadMorePhoto() } } extension ImagePickerViewController: UICollectionViewDelegate, UICollectionViewDataSource { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return smallPhotoArray.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ImagePickerCollectionViewCell", for: indexPath) as! ImagePickerCollectionViewCell cell.photoImageView.image = smallPhotoArray[indexPath.row] return cell } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { let image = UIImage.getOriginalPhoto(asset: photoAsset[unloadImageNumber + indexPath.row]) if noteController != nil { let controller = TOCropViewController.init(image: image) controller.delegate = self.noteController dismiss(animated: true) { self.noteController?.present(controller, animated: true, completion: nil) } } else if personController != nil { let controller = TOCropViewController.init(croppingStyle: .circular, image: image) controller.delegate = self.personController dismiss(animated: true) { self.personController?.present(controller, animated: true, completion: nil) } } } }
mit
d8d385dace9295267ac64d0ad4c0788a
38.973684
162
0.680711
5.329825
false
false
false
false
ninjaprox/NVActivityIndicatorView
Sources/Base/Animations/NVActivityIndicatorAnimationBallPulseSync.swift
2
2959
// // NVActivityIndicatorAnimationBallPulseSync.swift // NVActivityIndicatorView // // The MIT License (MIT) // Copyright (c) 2016 Vinh Nguyen // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // #if canImport(UIKit) import UIKit class NVActivityIndicatorAnimationBallPulseSync: NVActivityIndicatorAnimationDelegate { func setUpAnimation(in layer: CALayer, size: CGSize, color: UIColor) { let circleSpacing: CGFloat = 2 let circleSize = (size.width - circleSpacing * 2) / 3 let x = (layer.bounds.size.width - size.width) / 2 let y = (layer.bounds.size.height - circleSize) / 2 let deltaY = (size.height / 2 - circleSize / 2) / 2 let duration: CFTimeInterval = 0.6 let beginTime = CACurrentMediaTime() let beginTimes: [CFTimeInterval] = [0.07, 0.14, 0.21] let timingFunciton = CAMediaTimingFunction(name: .easeInEaseOut) // Animation let animation = CAKeyframeAnimation(keyPath: "transform.translation.y") animation.keyTimes = [0, 0.33, 0.66, 1] animation.timingFunctions = [timingFunciton, timingFunciton, timingFunciton] animation.values = [0, deltaY, -deltaY, 0] animation.duration = duration animation.repeatCount = HUGE animation.isRemovedOnCompletion = false // Draw circles for i in 0 ..< 3 { let circle = NVActivityIndicatorShape.circle.layerWith(size: CGSize(width: circleSize, height: circleSize), color: color) let frame = CGRect(x: x + circleSize * CGFloat(i) + circleSpacing * CGFloat(i), y: y, width: circleSize, height: circleSize) animation.beginTime = beginTime + beginTimes[i] circle.frame = frame circle.add(animation, forKey: "animation") layer.addSublayer(circle) } } } #endif
mit
e4644ed3241a71f40c85bcf0bdedd387
41.884058
133
0.676242
4.681962
false
false
false
false
practicalswift/swift
test/SourceKit/CursorInfo/cursor_info_param.swift
7
2095
func simpleParams(a: Int, b theB: Int) {} struct AccessorTest { subscript(a: Int, b theB: Int) -> Int { return a } var prop: Int { get { return 0 } set(v) {} } } #sourceLocation(file: "custom.swuft", line: 2000) func customSourceLocation(a: Int) {} #sourceLocation() // RUN: %sourcekitd-test -req=cursor -pos=1:19 %s -- %s | %FileCheck -check-prefix=CHECK-FUNC-A %s // CHECK-FUNC-A: s:17cursor_info_param12simpleParams1a1bySi_SitFACL_Sivp // CHECK-FUNC-A: PARENT OFFSET: 5 // RUN: %sourcekitd-test -req=cursor -pos=1:27 %s -- %s | %FileCheck -check-prefix=CHECK-FUNC-B %s // CHECK-FUNC-B: s:17cursor_info_param12simpleParams1a1bySi_SitF{{$}} // RUN: %sourcekitd-test -req=cursor -pos=1:29 %s -- %s | %FileCheck -check-prefix=CHECK-FUNC-THEB %s // CHECK-FUNC-THEB: s:17cursor_info_param12simpleParams1a1bySi_SitF4theBL_Sivp // CHECK-FUNC-THEB-NOT: PARENT OFFSET // RUN: %sourcekitd-test -req=cursor -pos=4:13 %s -- %s | %FileCheck -check-prefix=CHECK-SUBSCRIPT-A %s // FIXME: This USR is wrong; see https://bugs.swift.org/browse/SR-8660. // CHECK-SUBSCRIPT-A: s:17cursor_info_param12AccessorTestV1aL_Sivp // CHECK-SUBSCRIPT-A: PARENT OFFSET: 67 // RUN: %sourcekitd-test -req=cursor -pos=4:21 %s -- %s | %FileCheck -check-prefix=CHECK-SUBSCRIPT-B %s // CHECK-SUBSCRIPT-B: s:17cursor_info_param12AccessorTestV // RUN: %sourcekitd-test -req=cursor -pos=4:23 %s -- %s | %FileCheck -check-prefix=CHECK-SUBSCRIPT-THEB %s // FIXME: This USR is wrong; see https://bugs.swift.org/browse/SR-8660. // CHECK-SUBSCRIPT-THEB: s:17cursor_info_param12AccessorTestV4theBL_Sivp // CHECK-SUBSCRIPT-THEB-NOT: PARENT OFFSET // RUN: %sourcekitd-test -req=cursor -pos=7:9 %s -- %s | %FileCheck -check-prefix=CHECK-SETTER-V %s // CHECK-SETTER-V: s:17cursor_info_param12AccessorTestV4propSivs1vL_Sivp // CHECK-SETTER-V: PARENT OFFSET: 161 // RUN: %sourcekitd-test -req=cursor -pos=12:27 %s -- %s | %FileCheck -check-prefix=CHECK-CUSTOM-SOURCELOCATION %s // CHECK-CUSTOM-SOURCELOCATION: s:17cursor_info_param20customSourceLocation1aySi_tFACL_Sivp // CHECK-CUSTOM-SOURCELOCATION: PARENT OFFSET: 233
apache-2.0
f8cc1d78114a7dfca4b7a11a4c4a58b6
45.555556
114
0.717422
2.74574
false
true
false
false
jopamer/swift
validation-test/stdlib/Dictionary.swift
1
140571
// RUN: %empty-directory(%t) // // RUN: %gyb %s -o %t/main.swift // RUN: if [ %target-runtime == "objc" ]; then \ // RUN: %target-clang -fobjc-arc %S/Inputs/SlurpFastEnumeration/SlurpFastEnumeration.m -c -o %t/SlurpFastEnumeration.o; \ // RUN: %line-directive %t/main.swift -- %target-build-swift %S/Inputs/DictionaryKeyValueTypes.swift %S/Inputs/DictionaryKeyValueTypesObjC.swift %t/main.swift -I %S/Inputs/SlurpFastEnumeration/ -Xlinker %t/SlurpFastEnumeration.o -o %t/Dictionary -Xfrontend -disable-access-control; \ // RUN: else \ // RUN: %line-directive %t/main.swift -- %target-build-swift %S/Inputs/DictionaryKeyValueTypes.swift %t/main.swift -o %t/Dictionary -Xfrontend -disable-access-control; \ // RUN: fi // // RUN: %line-directive %t/main.swift -- %target-run %t/Dictionary // REQUIRES: executable_test import StdlibUnittest import StdlibCollectionUnittest #if _runtime(_ObjC) import Foundation import StdlibUnittestFoundationExtras #endif extension Dictionary { func _rawIdentifier() -> Int { return unsafeBitCast(self, to: Int.self) } } // Check that the generic parameters are called 'Key' and 'Value'. protocol TestProtocol1 {} extension Dictionary where Key : TestProtocol1, Value : TestProtocol1 { var _keyValueAreTestProtocol1: Bool { fatalError("not implemented") } } extension DictionaryIndex where Key : TestProtocol1, Value : TestProtocol1 { var _keyValueAreTestProtocol1: Bool { fatalError("not implemented") } } extension DictionaryIterator where Key : TestProtocol1, Value : TestProtocol1 { var _keyValueAreTestProtocol1: Bool { fatalError("not implemented") } } var DictionaryTestSuite = TestSuite("Dictionary") DictionaryTestSuite.test("AssociatedTypes") { typealias Collection = Dictionary<MinimalHashableValue, OpaqueValue<Int>> expectCollectionAssociatedTypes( collectionType: Collection.self, iteratorType: DictionaryIterator<MinimalHashableValue, OpaqueValue<Int>>.self, subSequenceType: Slice<Collection>.self, indexType: DictionaryIndex<MinimalHashableValue, OpaqueValue<Int>>.self, indicesType: DefaultIndices<Collection>.self) } DictionaryTestSuite.test("sizeof") { var dict = [1: "meow", 2: "meow"] #if arch(i386) || arch(arm) expectEqual(4, MemoryLayout.size(ofValue: dict)) #else expectEqual(8, MemoryLayout.size(ofValue: dict)) #endif } DictionaryTestSuite.test("Index.Hashable") { let d = [1: "meow", 2: "meow", 3: "meow"] let e = Dictionary(uniqueKeysWithValues: zip(d.indices, d)) expectEqual(d.count, e.count) expectNotNil(e[d.startIndex]) } DictionaryTestSuite.test("valueDestruction") { var d1 = Dictionary<Int, TestValueTy>() for i in 100...110 { d1[i] = TestValueTy(i) } var d2 = Dictionary<TestKeyTy, TestValueTy>() for i in 100...110 { d2[TestKeyTy(i)] = TestValueTy(i) } } DictionaryTestSuite.test("COW.Smoke") { var d1 = Dictionary<TestKeyTy, TestValueTy>(minimumCapacity: 10) let identity1 = d1._rawIdentifier() d1[TestKeyTy(10)] = TestValueTy(1010) d1[TestKeyTy(20)] = TestValueTy(1020) d1[TestKeyTy(30)] = TestValueTy(1030) var d2 = d1 _fixLifetime(d2) assert(identity1 == d2._rawIdentifier()) d2[TestKeyTy(40)] = TestValueTy(2040) assert(identity1 != d2._rawIdentifier()) d1[TestKeyTy(50)] = TestValueTy(1050) assert(identity1 == d1._rawIdentifier()) // Keep variables alive. _fixLifetime(d1) _fixLifetime(d2) } func getCOWFastDictionary() -> Dictionary<Int, Int> { var d = Dictionary<Int, Int>(minimumCapacity: 10) d[10] = 1010 d[20] = 1020 d[30] = 1030 return d } func getCOWFastDictionaryWithCOWValues() -> Dictionary<Int, TestValueCOWTy> { var d = Dictionary<Int, TestValueCOWTy>(minimumCapacity: 10) d[10] = TestValueCOWTy(1010) d[20] = TestValueCOWTy(1020) d[30] = TestValueCOWTy(1030) return d } func getCOWSlowDictionary() -> Dictionary<TestKeyTy, TestValueTy> { var d = Dictionary<TestKeyTy, TestValueTy>(minimumCapacity: 10) d[TestKeyTy(10)] = TestValueTy(1010) d[TestKeyTy(20)] = TestValueTy(1020) d[TestKeyTy(30)] = TestValueTy(1030) return d } func getCOWSlowEquatableDictionary() -> Dictionary<TestKeyTy, TestEquatableValueTy> { var d = Dictionary<TestKeyTy, TestEquatableValueTy>(minimumCapacity: 10) d[TestKeyTy(10)] = TestEquatableValueTy(1010) d[TestKeyTy(20)] = TestEquatableValueTy(1020) d[TestKeyTy(30)] = TestEquatableValueTy(1030) return d } DictionaryTestSuite.test("COW.Fast.IndexesDontAffectUniquenessCheck") { var d = getCOWFastDictionary() let identity1 = d._rawIdentifier() let startIndex = d.startIndex let endIndex = d.endIndex assert(startIndex != endIndex) assert(startIndex < endIndex) assert(startIndex <= endIndex) assert(!(startIndex >= endIndex)) assert(!(startIndex > endIndex)) assert(identity1 == d._rawIdentifier()) d[40] = 2040 assert(identity1 == d._rawIdentifier()) // Keep indexes alive during the calls above. _fixLifetime(startIndex) _fixLifetime(endIndex) } DictionaryTestSuite.test("COW.Slow.IndexesDontAffectUniquenessCheck") { var d = getCOWSlowDictionary() let identity1 = d._rawIdentifier() let startIndex = d.startIndex let endIndex = d.endIndex assert(startIndex != endIndex) assert(startIndex < endIndex) assert(startIndex <= endIndex) assert(!(startIndex >= endIndex)) assert(!(startIndex > endIndex)) assert(identity1 == d._rawIdentifier()) d[TestKeyTy(40)] = TestValueTy(2040) assert(identity1 == d._rawIdentifier()) // Keep indexes alive during the calls above. _fixLifetime(startIndex) _fixLifetime(endIndex) } DictionaryTestSuite.test("COW.Fast.SubscriptWithIndexDoesNotReallocate") { let d = getCOWFastDictionary() let identity1 = d._rawIdentifier() let startIndex = d.startIndex let empty = startIndex == d.endIndex assert((d.startIndex < d.endIndex) == !empty) assert(d.startIndex <= d.endIndex) assert((d.startIndex >= d.endIndex) == empty) assert(!(d.startIndex > d.endIndex)) assert(identity1 == d._rawIdentifier()) assert(d[startIndex].1 != 0) assert(identity1 == d._rawIdentifier()) } DictionaryTestSuite.test("COW.Slow.SubscriptWithIndexDoesNotReallocate") { let d = getCOWSlowDictionary() let identity1 = d._rawIdentifier() let startIndex = d.startIndex let empty = startIndex == d.endIndex assert((d.startIndex < d.endIndex) == !empty) assert(d.startIndex <= d.endIndex) assert((d.startIndex >= d.endIndex) == empty) assert(!(d.startIndex > d.endIndex)) assert(identity1 == d._rawIdentifier()) assert(d[startIndex].1.value != 0) assert(identity1 == d._rawIdentifier()) } DictionaryTestSuite.test("COW.Fast.SubscriptWithKeyDoesNotReallocate") .code { var d = getCOWFastDictionary() let identity1 = d._rawIdentifier() assert(d[10]! == 1010) assert(identity1 == d._rawIdentifier()) // Insert a new key-value pair. d[40] = 2040 assert(identity1 == d._rawIdentifier()) assert(d.count == 4) assert(d[10]! == 1010) assert(d[20]! == 1020) assert(d[30]! == 1030) assert(d[40]! == 2040) // Overwrite a value in existing binding. d[10] = 2010 assert(identity1 == d._rawIdentifier()) assert(d.count == 4) assert(d[10]! == 2010) assert(d[20]! == 1020) assert(d[30]! == 1030) assert(d[40]! == 2040) // Delete an existing key. d[10] = nil assert(identity1 == d._rawIdentifier()) assert(d.count == 3) assert(d[20]! == 1020) assert(d[30]! == 1030) assert(d[40]! == 2040) // Try to delete a key that does not exist. d[42] = nil assert(identity1 == d._rawIdentifier()) assert(d.count == 3) assert(d[20]! == 1020) assert(d[30]! == 1030) assert(d[40]! == 2040) do { var d2: [MinimalHashableValue : OpaqueValue<Int>] = [:] MinimalHashableValue.timesEqualEqualWasCalled = 0 MinimalHashableValue.timesHashIntoWasCalled = 0 expectNil(d2[MinimalHashableValue(42)]) // If the dictionary is empty, we shouldn't be computing the hash value of // the provided key. expectEqual(0, MinimalHashableValue.timesEqualEqualWasCalled) expectEqual(0, MinimalHashableValue.timesHashIntoWasCalled) } } DictionaryTestSuite.test("COW.Slow.SubscriptWithKeyDoesNotReallocate") .code { var d = getCOWSlowDictionary() let identity1 = d._rawIdentifier() assert(d[TestKeyTy(10)]!.value == 1010) assert(identity1 == d._rawIdentifier()) // Insert a new key-value pair. d[TestKeyTy(40)] = TestValueTy(2040) assert(identity1 == d._rawIdentifier()) assert(d.count == 4) assert(d[TestKeyTy(10)]!.value == 1010) assert(d[TestKeyTy(20)]!.value == 1020) assert(d[TestKeyTy(30)]!.value == 1030) assert(d[TestKeyTy(40)]!.value == 2040) // Overwrite a value in existing binding. d[TestKeyTy(10)] = TestValueTy(2010) assert(identity1 == d._rawIdentifier()) assert(d.count == 4) assert(d[TestKeyTy(10)]!.value == 2010) assert(d[TestKeyTy(20)]!.value == 1020) assert(d[TestKeyTy(30)]!.value == 1030) assert(d[TestKeyTy(40)]!.value == 2040) // Delete an existing key. d[TestKeyTy(10)] = nil assert(identity1 == d._rawIdentifier()) assert(d.count == 3) assert(d[TestKeyTy(20)]!.value == 1020) assert(d[TestKeyTy(30)]!.value == 1030) assert(d[TestKeyTy(40)]!.value == 2040) // Try to delete a key that does not exist. d[TestKeyTy(42)] = nil assert(identity1 == d._rawIdentifier()) assert(d.count == 3) assert(d[TestKeyTy(20)]!.value == 1020) assert(d[TestKeyTy(30)]!.value == 1030) assert(d[TestKeyTy(40)]!.value == 2040) do { var d2: [MinimalHashableClass : OpaqueValue<Int>] = [:] MinimalHashableClass.timesEqualEqualWasCalled = 0 MinimalHashableClass.timesHashIntoWasCalled = 0 expectNil(d2[MinimalHashableClass(42)]) // If the dictionary is empty, we shouldn't be computing the hash value of // the provided key. expectEqual(0, MinimalHashableClass.timesEqualEqualWasCalled) expectEqual(0, MinimalHashableClass.timesHashIntoWasCalled) } } DictionaryTestSuite.test("COW.Fast.UpdateValueForKeyDoesNotReallocate") { do { var d1 = getCOWFastDictionary() let identity1 = d1._rawIdentifier() // Insert a new key-value pair. assert(d1.updateValue(2040, forKey: 40) == .none) assert(identity1 == d1._rawIdentifier()) assert(d1[40]! == 2040) // Overwrite a value in existing binding. assert(d1.updateValue(2010, forKey: 10)! == 1010) assert(identity1 == d1._rawIdentifier()) assert(d1[10]! == 2010) } do { var d1 = getCOWFastDictionary() let identity1 = d1._rawIdentifier() var d2 = d1 assert(identity1 == d1._rawIdentifier()) assert(identity1 == d2._rawIdentifier()) // Insert a new key-value pair. d2.updateValue(2040, forKey: 40) assert(identity1 == d1._rawIdentifier()) assert(identity1 != d2._rawIdentifier()) assert(d1.count == 3) assert(d1[10]! == 1010) assert(d1[20]! == 1020) assert(d1[30]! == 1030) assert(d1[40] == .none) assert(d2.count == 4) assert(d2[10]! == 1010) assert(d2[20]! == 1020) assert(d2[30]! == 1030) assert(d2[40]! == 2040) // Keep variables alive. _fixLifetime(d1) _fixLifetime(d2) } do { var d1 = getCOWFastDictionary() let identity1 = d1._rawIdentifier() var d2 = d1 assert(identity1 == d1._rawIdentifier()) assert(identity1 == d2._rawIdentifier()) // Overwrite a value in existing binding. d2.updateValue(2010, forKey: 10) assert(identity1 == d1._rawIdentifier()) assert(identity1 != d2._rawIdentifier()) assert(d1.count == 3) assert(d1[10]! == 1010) assert(d1[20]! == 1020) assert(d1[30]! == 1030) assert(d2.count == 3) assert(d2[10]! == 2010) assert(d2[20]! == 1020) assert(d2[30]! == 1030) // Keep variables alive. _fixLifetime(d1) _fixLifetime(d2) } } DictionaryTestSuite.test("COW.Slow.AddDoesNotReallocate") { do { var d1 = getCOWSlowDictionary() let identity1 = d1._rawIdentifier() // Insert a new key-value pair. assert(d1.updateValue(TestValueTy(2040), forKey: TestKeyTy(40)) == nil) assert(identity1 == d1._rawIdentifier()) assert(d1.count == 4) assert(d1[TestKeyTy(40)]!.value == 2040) // Overwrite a value in existing binding. assert(d1.updateValue(TestValueTy(2010), forKey: TestKeyTy(10))!.value == 1010) assert(identity1 == d1._rawIdentifier()) assert(d1.count == 4) assert(d1[TestKeyTy(10)]!.value == 2010) } do { var d1 = getCOWSlowDictionary() let identity1 = d1._rawIdentifier() var d2 = d1 assert(identity1 == d1._rawIdentifier()) assert(identity1 == d2._rawIdentifier()) // Insert a new key-value pair. d2.updateValue(TestValueTy(2040), forKey: TestKeyTy(40)) assert(identity1 == d1._rawIdentifier()) assert(identity1 != d2._rawIdentifier()) assert(d1.count == 3) assert(d1[TestKeyTy(10)]!.value == 1010) assert(d1[TestKeyTy(20)]!.value == 1020) assert(d1[TestKeyTy(30)]!.value == 1030) assert(d1[TestKeyTy(40)] == nil) assert(d2.count == 4) assert(d2[TestKeyTy(10)]!.value == 1010) assert(d2[TestKeyTy(20)]!.value == 1020) assert(d2[TestKeyTy(30)]!.value == 1030) assert(d2[TestKeyTy(40)]!.value == 2040) // Keep variables alive. _fixLifetime(d1) _fixLifetime(d2) } do { var d1 = getCOWSlowDictionary() let identity1 = d1._rawIdentifier() var d2 = d1 assert(identity1 == d1._rawIdentifier()) assert(identity1 == d2._rawIdentifier()) // Overwrite a value in existing binding. d2.updateValue(TestValueTy(2010), forKey: TestKeyTy(10)) assert(identity1 == d1._rawIdentifier()) assert(identity1 != d2._rawIdentifier()) assert(d1.count == 3) assert(d1[TestKeyTy(10)]!.value == 1010) assert(d1[TestKeyTy(20)]!.value == 1020) assert(d1[TestKeyTy(30)]!.value == 1030) assert(d2.count == 3) assert(d2[TestKeyTy(10)]!.value == 2010) assert(d2[TestKeyTy(20)]!.value == 1020) assert(d2[TestKeyTy(30)]!.value == 1030) // Keep variables alive. _fixLifetime(d1) _fixLifetime(d2) } } DictionaryTestSuite.test("COW.Fast.MergeSequenceDoesNotReallocate") .code { do { var d1 = getCOWFastDictionary() let identity1 = d1._rawIdentifier() // Merge some new values. d1.merge([(40, 2040), (50, 2050)]) { _, y in y } assert(identity1 == d1._rawIdentifier()) assert(d1.count == 5) assert(d1[50]! == 2050) // Merge and overwrite some existing values. d1.merge([(10, 2010), (60, 2060)]) { _, y in y } assert(identity1 == d1._rawIdentifier()) assert(d1.count == 6) assert(d1[10]! == 2010) assert(d1[60]! == 2060) // Merge, keeping existing values. d1.merge([(30, 2030), (70, 2070)]) { x, _ in x } assert(identity1 == d1._rawIdentifier()) assert(d1.count == 7) assert(d1[30]! == 1030) assert(d1[70]! == 2070) let d2 = d1.merging([(40, 3040), (80, 3080)]) { _, y in y } assert(identity1 == d1._rawIdentifier()) assert(identity1 != d2._rawIdentifier()) assert(d2.count == 8) assert(d2[40]! == 3040) assert(d2[80]! == 3080) } do { var d1 = getCOWFastDictionary() let identity1 = d1._rawIdentifier() var d2 = d1 assert(identity1 == d1._rawIdentifier()) assert(identity1 == d2._rawIdentifier()) // Merge some new values. d2.merge([(40, 2040), (50, 2050)]) { _, y in y } assert(identity1 == d1._rawIdentifier()) assert(identity1 != d2._rawIdentifier()) assert(d1.count == 3) assert(d1[10]! == 1010) assert(d1[20]! == 1020) assert(d1[30]! == 1030) assert(d1[40] == nil) assert(d2.count == 5) assert(d2[10]! == 1010) assert(d2[20]! == 1020) assert(d2[30]! == 1030) assert(d2[40]! == 2040) assert(d2[50]! == 2050) // Keep variables alive. _fixLifetime(d1) _fixLifetime(d2) } do { var d1 = getCOWFastDictionary() let identity1 = d1._rawIdentifier() var d2 = d1 assert(identity1 == d1._rawIdentifier()) assert(identity1 == d2._rawIdentifier()) // Merge and overwrite some existing values. d2.merge([(10, 2010)]) { _, y in y } assert(identity1 == d1._rawIdentifier()) assert(identity1 != d2._rawIdentifier()) assert(d1.count == 3) assert(d1[10]! == 1010) assert(d1[20]! == 1020) assert(d1[30]! == 1030) assert(d2.count == 3) assert(d2[10]! == 2010) assert(d2[20]! == 1020) assert(d2[30]! == 1030) // Keep variables alive. _fixLifetime(d1) _fixLifetime(d2) } do { var d1 = getCOWFastDictionary() let identity1 = d1._rawIdentifier() var d2 = d1 assert(identity1 == d1._rawIdentifier()) assert(identity1 == d2._rawIdentifier()) // Merge, keeping existing values. d2.merge([(10, 2010)]) { x, _ in x } assert(identity1 == d1._rawIdentifier()) assert(identity1 != d2._rawIdentifier()) assert(d1.count == 3) assert(d1[10]! == 1010) assert(d1[20]! == 1020) assert(d1[30]! == 1030) assert(d2.count == 3) assert(d2[10]! == 1010) assert(d2[20]! == 1020) assert(d2[30]! == 1030) // Keep variables alive. _fixLifetime(d1) _fixLifetime(d2) } } DictionaryTestSuite.test("COW.Fast.MergeDictionaryDoesNotReallocate") .code { do { var d1 = getCOWFastDictionary() let identity1 = d1._rawIdentifier() // Merge some new values. d1.merge([40: 2040, 50: 2050]) { _, y in y } assert(identity1 == d1._rawIdentifier()) assert(d1.count == 5) assert(d1[50]! == 2050) // Merge and overwrite some existing values. d1.merge([10: 2010, 60: 2060]) { _, y in y } assert(identity1 == d1._rawIdentifier()) assert(d1.count == 6) assert(d1[10]! == 2010) assert(d1[60]! == 2060) // Merge, keeping existing values. d1.merge([30: 2030, 70: 2070]) { x, _ in x } assert(identity1 == d1._rawIdentifier()) assert(d1.count == 7) assert(d1[30]! == 1030) assert(d1[70]! == 2070) let d2 = d1.merging([40: 3040, 80: 3080]) { _, y in y } assert(identity1 == d1._rawIdentifier()) assert(identity1 != d2._rawIdentifier()) assert(d2.count == 8) assert(d2[40]! == 3040) assert(d2[80]! == 3080) } do { var d1 = getCOWFastDictionary() let identity1 = d1._rawIdentifier() var d2 = d1 assert(identity1 == d1._rawIdentifier()) assert(identity1 == d2._rawIdentifier()) // Merge some new values. d2.merge([40: 2040, 50: 2050]) { _, y in y } assert(identity1 == d1._rawIdentifier()) assert(identity1 != d2._rawIdentifier()) assert(d1.count == 3) assert(d1[10]! == 1010) assert(d1[20]! == 1020) assert(d1[30]! == 1030) assert(d1[40] == nil) assert(d2.count == 5) assert(d2[10]! == 1010) assert(d2[20]! == 1020) assert(d2[30]! == 1030) assert(d2[40]! == 2040) assert(d2[50]! == 2050) // Keep variables alive. _fixLifetime(d1) _fixLifetime(d2) } do { var d1 = getCOWFastDictionary() let identity1 = d1._rawIdentifier() var d2 = d1 assert(identity1 == d1._rawIdentifier()) assert(identity1 == d2._rawIdentifier()) // Merge and overwrite some existing values. d2.merge([10: 2010]) { _, y in y } assert(identity1 == d1._rawIdentifier()) assert(identity1 != d2._rawIdentifier()) assert(d1.count == 3) assert(d1[10]! == 1010) assert(d1[20]! == 1020) assert(d1[30]! == 1030) assert(d2.count == 3) assert(d2[10]! == 2010) assert(d2[20]! == 1020) assert(d2[30]! == 1030) // Keep variables alive. _fixLifetime(d1) _fixLifetime(d2) } do { var d1 = getCOWFastDictionary() let identity1 = d1._rawIdentifier() var d2 = d1 assert(identity1 == d1._rawIdentifier()) assert(identity1 == d2._rawIdentifier()) // Merge, keeping existing values. d2.merge([10: 2010]) { x, _ in x } assert(identity1 == d1._rawIdentifier()) assert(identity1 != d2._rawIdentifier()) assert(d1.count == 3) assert(d1[10]! == 1010) assert(d1[20]! == 1020) assert(d1[30]! == 1030) assert(d2.count == 3) assert(d2[10]! == 1010) assert(d2[20]! == 1020) assert(d2[30]! == 1030) // Keep variables alive. _fixLifetime(d1) _fixLifetime(d2) } } DictionaryTestSuite.test("COW.Fast.DefaultedSubscriptDoesNotReallocate") { do { var d1 = getCOWFastDictionary() let identity1 = d1._rawIdentifier() // No mutation on access. assert(d1[10, default: 0] + 1 == 1011) assert(d1[40, default: 0] + 1 == 1) assert(identity1 == d1._rawIdentifier()) assert(d1[10]! == 1010) // Increment existing in place. d1[10, default: 0] += 1 assert(identity1 == d1._rawIdentifier()) assert(d1[10]! == 1011) // Add incremented default value. d1[40, default: 0] += 1 assert(identity1 == d1._rawIdentifier()) assert(d1[40]! == 1) } do { var d1 = getCOWFastDictionary() let identity1 = d1._rawIdentifier() var d2 = d1 assert(identity1 == d1._rawIdentifier()) assert(identity1 == d2._rawIdentifier()) // No mutation on access. assert(d2[10, default: 0] + 1 == 1011) assert(d2[40, default: 0] + 1 == 1) assert(identity1 == d1._rawIdentifier()) assert(identity1 == d2._rawIdentifier()) // Increment existing in place. d2[10, default: 0] += 1 assert(identity1 == d1._rawIdentifier()) assert(identity1 != d2._rawIdentifier()) assert(d1[10]! == 1010) assert(d2[10]! == 1011) // Keep variables alive. _fixLifetime(d1) _fixLifetime(d2) } do { var d1 = getCOWFastDictionary() let identity1 = d1._rawIdentifier() var d2 = d1 assert(identity1 == d1._rawIdentifier()) assert(identity1 == d2._rawIdentifier()) // Add incremented default value. d2[40, default: 0] += 1 assert(identity1 == d1._rawIdentifier()) assert(identity1 != d2._rawIdentifier()) assert(d1[40] == nil) assert(d2[40]! == 1) // Keep variables alive. _fixLifetime(d1) _fixLifetime(d2) } } DictionaryTestSuite.test("COW.Fast.DefaultedSubscriptDoesNotCopyValue") { do { var d = getCOWFastDictionaryWithCOWValues() let identityValue30 = d[30]!.baseAddress // Increment the value without having to reallocate the underlying Base // instance, as uniquely referenced. d[30, default: TestValueCOWTy()].value += 1 assert(identityValue30 == d[30]!.baseAddress) assert(d[30]!.value == 1031) let value40 = TestValueCOWTy() let identityValue40 = value40.baseAddress // Increment the value, reallocating the underlying Base, as not uniquely // referenced. d[40, default: value40].value += 1 assert(identityValue40 != d[40]!.baseAddress) assert(d[40]!.value == 1) // Keep variables alive. _fixLifetime(d) _fixLifetime(value40) } } DictionaryTestSuite.test("COW.Fast.IndexForKeyDoesNotReallocate") { let d = getCOWFastDictionary() let identity1 = d._rawIdentifier() // Find an existing key. do { let foundIndex1 = d.index(forKey: 10)! assert(identity1 == d._rawIdentifier()) let foundIndex2 = d.index(forKey: 10)! assert(foundIndex1 == foundIndex2) assert(d[foundIndex1].0 == 10) assert(d[foundIndex1].1 == 1010) assert(identity1 == d._rawIdentifier()) } // Try to find a key that is not present. do { let foundIndex1 = d.index(forKey: 1111) assert(foundIndex1 == nil) assert(identity1 == d._rawIdentifier()) } do { let d2: [MinimalHashableValue : OpaqueValue<Int>] = [:] MinimalHashableValue.timesEqualEqualWasCalled = 0 MinimalHashableValue.timesHashIntoWasCalled = 0 expectNil(d2.index(forKey: MinimalHashableValue(42))) // If the dictionary is empty, we shouldn't be computing the hash value of // the provided key. expectEqual(0, MinimalHashableValue.timesEqualEqualWasCalled) expectEqual(0, MinimalHashableValue.timesHashIntoWasCalled) } } DictionaryTestSuite.test("COW.Slow.IndexForKeyDoesNotReallocate") { let d = getCOWSlowDictionary() let identity1 = d._rawIdentifier() // Find an existing key. do { let foundIndex1 = d.index(forKey: TestKeyTy(10))! assert(identity1 == d._rawIdentifier()) let foundIndex2 = d.index(forKey: TestKeyTy(10))! assert(foundIndex1 == foundIndex2) assert(d[foundIndex1].0 == TestKeyTy(10)) assert(d[foundIndex1].1.value == 1010) assert(identity1 == d._rawIdentifier()) } // Try to find a key that is not present. do { let foundIndex1 = d.index(forKey: TestKeyTy(1111)) assert(foundIndex1 == nil) assert(identity1 == d._rawIdentifier()) } do { let d2: [MinimalHashableClass : OpaqueValue<Int>] = [:] MinimalHashableClass.timesEqualEqualWasCalled = 0 MinimalHashableClass.timesHashIntoWasCalled = 0 expectNil(d2.index(forKey: MinimalHashableClass(42))) // If the dictionary is empty, we shouldn't be computing the hash value of // the provided key. expectEqual(0, MinimalHashableClass.timesEqualEqualWasCalled) expectEqual(0, MinimalHashableClass.timesHashIntoWasCalled) } } DictionaryTestSuite.test("COW.Fast.RemoveAtDoesNotReallocate") .code { do { var d = getCOWFastDictionary() let identity1 = d._rawIdentifier() let foundIndex1 = d.index(forKey: 10)! assert(identity1 == d._rawIdentifier()) assert(d[foundIndex1].0 == 10) assert(d[foundIndex1].1 == 1010) let removed = d.remove(at: foundIndex1) assert(removed.0 == 10) assert(removed.1 == 1010) assert(identity1 == d._rawIdentifier()) assert(d.index(forKey: 10) == nil) } do { let d1 = getCOWFastDictionary() let identity1 = d1._rawIdentifier() var d2 = d1 assert(identity1 == d1._rawIdentifier()) assert(identity1 == d2._rawIdentifier()) let foundIndex1 = d2.index(forKey: 10)! assert(d2[foundIndex1].0 == 10) assert(d2[foundIndex1].1 == 1010) assert(identity1 == d1._rawIdentifier()) assert(identity1 == d2._rawIdentifier()) let removed = d2.remove(at: foundIndex1) assert(removed.0 == 10) assert(removed.1 == 1010) assert(identity1 == d1._rawIdentifier()) assert(identity1 != d2._rawIdentifier()) assert(d2.index(forKey: 10) == nil) } } DictionaryTestSuite.test("COW.Slow.RemoveAtDoesNotReallocate") .code { do { var d = getCOWSlowDictionary() let identity1 = d._rawIdentifier() let foundIndex1 = d.index(forKey: TestKeyTy(10))! assert(identity1 == d._rawIdentifier()) assert(d[foundIndex1].0 == TestKeyTy(10)) assert(d[foundIndex1].1.value == 1010) let removed = d.remove(at: foundIndex1) assert(removed.0 == TestKeyTy(10)) assert(removed.1.value == 1010) assert(identity1 == d._rawIdentifier()) assert(d.index(forKey: TestKeyTy(10)) == nil) } do { let d1 = getCOWSlowDictionary() let identity1 = d1._rawIdentifier() var d2 = d1 assert(identity1 == d1._rawIdentifier()) assert(identity1 == d2._rawIdentifier()) let foundIndex1 = d2.index(forKey: TestKeyTy(10))! assert(d2[foundIndex1].0 == TestKeyTy(10)) assert(d2[foundIndex1].1.value == 1010) let removed = d2.remove(at: foundIndex1) assert(removed.0 == TestKeyTy(10)) assert(removed.1.value == 1010) assert(identity1 == d1._rawIdentifier()) assert(identity1 != d2._rawIdentifier()) assert(d2.index(forKey: TestKeyTy(10)) == nil) } } DictionaryTestSuite.test("COW.Fast.RemoveValueForKeyDoesNotReallocate") .code { do { var d1 = getCOWFastDictionary() let identity1 = d1._rawIdentifier() var deleted = d1.removeValue(forKey: 0) assert(deleted == nil) assert(identity1 == d1._rawIdentifier()) deleted = d1.removeValue(forKey: 10) assert(deleted! == 1010) assert(identity1 == d1._rawIdentifier()) // Keep variables alive. _fixLifetime(d1) } do { let d1 = getCOWFastDictionary() let identity1 = d1._rawIdentifier() var d2 = d1 var deleted = d2.removeValue(forKey: 0) assert(deleted == nil) assert(identity1 == d1._rawIdentifier()) assert(identity1 == d2._rawIdentifier()) deleted = d2.removeValue(forKey: 10) assert(deleted! == 1010) assert(identity1 == d1._rawIdentifier()) assert(identity1 != d2._rawIdentifier()) // Keep variables alive. _fixLifetime(d1) _fixLifetime(d2) } } DictionaryTestSuite.test("COW.Slow.RemoveValueForKeyDoesNotReallocate") .code { do { var d1 = getCOWSlowDictionary() let identity1 = d1._rawIdentifier() var deleted = d1.removeValue(forKey: TestKeyTy(0)) assert(deleted == nil) assert(identity1 == d1._rawIdentifier()) deleted = d1.removeValue(forKey: TestKeyTy(10)) assert(deleted!.value == 1010) assert(identity1 == d1._rawIdentifier()) // Keep variables alive. _fixLifetime(d1) } do { let d1 = getCOWSlowDictionary() let identity1 = d1._rawIdentifier() var d2 = d1 var deleted = d2.removeValue(forKey: TestKeyTy(0)) assert(deleted == nil) assert(identity1 == d1._rawIdentifier()) assert(identity1 == d2._rawIdentifier()) deleted = d2.removeValue(forKey: TestKeyTy(10)) assert(deleted!.value == 1010) assert(identity1 == d1._rawIdentifier()) assert(identity1 != d2._rawIdentifier()) // Keep variables alive. _fixLifetime(d1) _fixLifetime(d2) } } DictionaryTestSuite.test("COW.Fast.RemoveAllDoesNotReallocate") { do { var d = getCOWFastDictionary() let originalCapacity = d.capacity assert(d.count == 3) assert(d[10]! == 1010) d.removeAll() // We cannot assert that identity changed, since the new buffer of smaller // size can be allocated at the same address as the old one. let identity1 = d._rawIdentifier() assert(d.capacity < originalCapacity) assert(d.count == 0) assert(d[10] == nil) d.removeAll() assert(identity1 == d._rawIdentifier()) assert(d.count == 0) assert(d[10] == nil) } do { var d = getCOWFastDictionary() let identity1 = d._rawIdentifier() let originalCapacity = d.capacity assert(d.count == 3) assert(d[10]! == 1010) d.removeAll(keepingCapacity: true) assert(identity1 == d._rawIdentifier()) assert(d.capacity == originalCapacity) assert(d.count == 0) assert(d[10] == nil) d.removeAll(keepingCapacity: true) assert(identity1 == d._rawIdentifier()) assert(d.capacity == originalCapacity) assert(d.count == 0) assert(d[10] == nil) } do { var d1 = getCOWFastDictionary() let identity1 = d1._rawIdentifier() assert(d1.count == 3) assert(d1[10]! == 1010) var d2 = d1 d2.removeAll() let identity2 = d2._rawIdentifier() assert(identity1 == d1._rawIdentifier()) assert(identity2 != identity1) assert(d1.count == 3) assert(d1[10]! == 1010) assert(d2.count == 0) assert(d2[10] == nil) // Keep variables alive. _fixLifetime(d1) _fixLifetime(d2) } do { var d1 = getCOWFastDictionary() let identity1 = d1._rawIdentifier() let originalCapacity = d1.capacity assert(d1.count == 3) assert(d1[10] == 1010) var d2 = d1 d2.removeAll(keepingCapacity: true) let identity2 = d2._rawIdentifier() assert(identity1 == d1._rawIdentifier()) assert(identity2 != identity1) assert(d1.count == 3) assert(d1[10]! == 1010) assert(d2.capacity == originalCapacity) assert(d2.count == 0) assert(d2[10] == nil) // Keep variables alive. _fixLifetime(d1) _fixLifetime(d2) } } DictionaryTestSuite.test("COW.Slow.RemoveAllDoesNotReallocate") { do { var d = getCOWSlowDictionary() let originalCapacity = d.capacity assert(d.count == 3) assert(d[TestKeyTy(10)]!.value == 1010) d.removeAll() // We cannot assert that identity changed, since the new buffer of smaller // size can be allocated at the same address as the old one. let identity1 = d._rawIdentifier() assert(d.capacity < originalCapacity) assert(d.count == 0) assert(d[TestKeyTy(10)] == nil) d.removeAll() assert(identity1 == d._rawIdentifier()) assert(d.count == 0) assert(d[TestKeyTy(10)] == nil) } do { var d = getCOWSlowDictionary() let identity1 = d._rawIdentifier() let originalCapacity = d.capacity assert(d.count == 3) assert(d[TestKeyTy(10)]!.value == 1010) d.removeAll(keepingCapacity: true) assert(identity1 == d._rawIdentifier()) assert(d.capacity == originalCapacity) assert(d.count == 0) assert(d[TestKeyTy(10)] == nil) d.removeAll(keepingCapacity: true) assert(identity1 == d._rawIdentifier()) assert(d.capacity == originalCapacity) assert(d.count == 0) assert(d[TestKeyTy(10)] == nil) } do { var d1 = getCOWSlowDictionary() let identity1 = d1._rawIdentifier() assert(d1.count == 3) assert(d1[TestKeyTy(10)]!.value == 1010) var d2 = d1 d2.removeAll() let identity2 = d2._rawIdentifier() assert(identity1 == d1._rawIdentifier()) assert(identity2 != identity1) assert(d1.count == 3) assert(d1[TestKeyTy(10)]!.value == 1010) assert(d2.count == 0) assert(d2[TestKeyTy(10)] == nil) // Keep variables alive. _fixLifetime(d1) _fixLifetime(d2) } do { var d1 = getCOWSlowDictionary() let identity1 = d1._rawIdentifier() let originalCapacity = d1.capacity assert(d1.count == 3) assert(d1[TestKeyTy(10)]!.value == 1010) var d2 = d1 d2.removeAll(keepingCapacity: true) let identity2 = d2._rawIdentifier() assert(identity1 == d1._rawIdentifier()) assert(identity2 != identity1) assert(d1.count == 3) assert(d1[TestKeyTy(10)]!.value == 1010) assert(d2.capacity == originalCapacity) assert(d2.count == 0) assert(d2[TestKeyTy(10)] == nil) // Keep variables alive. _fixLifetime(d1) _fixLifetime(d2) } } DictionaryTestSuite.test("COW.Fast.CountDoesNotReallocate") { let d = getCOWFastDictionary() let identity1 = d._rawIdentifier() assert(d.count == 3) assert(identity1 == d._rawIdentifier()) } DictionaryTestSuite.test("COW.Slow.CountDoesNotReallocate") { let d = getCOWSlowDictionary() let identity1 = d._rawIdentifier() assert(d.count == 3) assert(identity1 == d._rawIdentifier()) } DictionaryTestSuite.test("COW.Fast.GenerateDoesNotReallocate") { let d = getCOWFastDictionary() let identity1 = d._rawIdentifier() var iter = d.makeIterator() var pairs = Array<(Int, Int)>() while let (key, value) = iter.next() { pairs += [(key, value)] } assert(equalsUnordered(pairs, [ (10, 1010), (20, 1020), (30, 1030) ])) assert(identity1 == d._rawIdentifier()) } DictionaryTestSuite.test("COW.Slow.GenerateDoesNotReallocate") { let d = getCOWSlowDictionary() let identity1 = d._rawIdentifier() var iter = d.makeIterator() var pairs = Array<(Int, Int)>() while let (key, value) = iter.next() { pairs += [(key.value, value.value)] } assert(equalsUnordered(pairs, [ (10, 1010), (20, 1020), (30, 1030) ])) assert(identity1 == d._rawIdentifier()) } DictionaryTestSuite.test("COW.Fast.EqualityTestDoesNotReallocate") { let d1 = getCOWFastDictionary() let identity1 = d1._rawIdentifier() var d2 = getCOWFastDictionary() let identity2 = d2._rawIdentifier() assert(d1 == d2) assert(identity1 == d1._rawIdentifier()) assert(identity2 == d2._rawIdentifier()) d2[40] = 2040 assert(d1 != d2) assert(identity1 == d1._rawIdentifier()) assert(identity2 == d2._rawIdentifier()) } DictionaryTestSuite.test("COW.Slow.EqualityTestDoesNotReallocate") { let d1 = getCOWSlowEquatableDictionary() let identity1 = d1._rawIdentifier() var d2 = getCOWSlowEquatableDictionary() let identity2 = d2._rawIdentifier() assert(d1 == d2) assert(identity1 == d1._rawIdentifier()) assert(identity2 == d2._rawIdentifier()) d2[TestKeyTy(40)] = TestEquatableValueTy(2040) assert(d1 != d2) assert(identity1 == d1._rawIdentifier()) assert(identity2 == d2._rawIdentifier()) } //===--- // Keys and Values collection tests. //===--- DictionaryTestSuite.test("COW.Fast.ValuesAccessDoesNotReallocate") { var d1 = getCOWFastDictionary() let identity1 = d1._rawIdentifier() assert([1010, 1020, 1030] == d1.values.sorted()) assert(identity1 == d1._rawIdentifier()) var d2 = d1 assert(identity1 == d2._rawIdentifier()) let i = d2.index(forKey: 10)! assert(d1.values[i] == 1010) assert(d1[i] == (10, 1010)) d2.values[i] += 1 assert(d2.values[i] == 1011) assert(d2[10]! == 1011) assert(identity1 != d2._rawIdentifier()) assert(d1[10]! == 1010) assert(identity1 == d1._rawIdentifier()) checkCollection( Array(d1.values), d1.values, stackTrace: SourceLocStack()) { $0 == $1 } } DictionaryTestSuite.test("COW.Fast.KeysAccessDoesNotReallocate") { let d1 = getCOWFastDictionary() let identity1 = d1._rawIdentifier() assert([10, 20, 30] == d1.keys.sorted()) let i = d1.index(forKey: 10)! assert(d1.keys[i] == 10) assert(d1[i] == (10, 1010)) assert(identity1 == d1._rawIdentifier()) checkCollection( Array(d1.keys), d1.keys, stackTrace: SourceLocStack()) { $0 == $1 } do { let d2: [MinimalHashableValue : Int] = [ MinimalHashableValue(10): 1010, MinimalHashableValue(20): 1020, MinimalHashableValue(30): 1030, MinimalHashableValue(40): 1040, MinimalHashableValue(50): 1050, MinimalHashableValue(60): 1060, MinimalHashableValue(70): 1070, MinimalHashableValue(80): 1080, MinimalHashableValue(90): 1090, ] // Find the last key in the dictionary var lastKey: MinimalHashableValue = d2.first!.key for i in d2.indices { lastKey = d2[i].key } // firstIndex(where:) - linear search MinimalHashableValue.timesEqualEqualWasCalled = 0 let j = d2.firstIndex(where: { (k, _) in k == lastKey })! expectGE(MinimalHashableValue.timesEqualEqualWasCalled, 8) // index(forKey:) - O(1) bucket + linear search MinimalHashableValue.timesEqualEqualWasCalled = 0 let k = d2.index(forKey: lastKey)! expectLE(MinimalHashableValue.timesEqualEqualWasCalled, 4) // keys.firstIndex(of:) - O(1) bucket + linear search MinimalHashableValue.timesEqualEqualWasCalled = 0 let l = d2.keys.firstIndex(of: lastKey)! expectLE(MinimalHashableValue.timesEqualEqualWasCalled, 4) expectEqual(j, k) expectEqual(k, l) } } //===--- // Native dictionary tests. //===--- func helperDeleteThree(_ k1: TestKeyTy, _ k2: TestKeyTy, _ k3: TestKeyTy) { var d1 = Dictionary<TestKeyTy, TestValueTy>(minimumCapacity: 10) d1[k1] = TestValueTy(1010) d1[k2] = TestValueTy(1020) d1[k3] = TestValueTy(1030) assert(d1[k1]!.value == 1010) assert(d1[k2]!.value == 1020) assert(d1[k3]!.value == 1030) d1[k1] = nil assert(d1[k2]!.value == 1020) assert(d1[k3]!.value == 1030) d1[k2] = nil assert(d1[k3]!.value == 1030) d1[k3] = nil assert(d1.count == 0) } DictionaryTestSuite.test("deleteChainCollision") { let k1 = TestKeyTy(value: 10, hashValue: 0) let k2 = TestKeyTy(value: 20, hashValue: 0) let k3 = TestKeyTy(value: 30, hashValue: 0) helperDeleteThree(k1, k2, k3) } DictionaryTestSuite.test("deleteChainNoCollision") { let k1 = TestKeyTy(value: 10, hashValue: 0) let k2 = TestKeyTy(value: 20, hashValue: 1) let k3 = TestKeyTy(value: 30, hashValue: 2) helperDeleteThree(k1, k2, k3) } DictionaryTestSuite.test("deleteChainCollision2") { let k1_0 = TestKeyTy(value: 10, hashValue: 0) let k2_0 = TestKeyTy(value: 20, hashValue: 0) let k3_2 = TestKeyTy(value: 30, hashValue: 2) let k4_0 = TestKeyTy(value: 40, hashValue: 0) let k5_2 = TestKeyTy(value: 50, hashValue: 2) let k6_0 = TestKeyTy(value: 60, hashValue: 0) var d = Dictionary<TestKeyTy, TestValueTy>(minimumCapacity: 10) d[k1_0] = TestValueTy(1010) // in bucket 0 d[k2_0] = TestValueTy(1020) // in bucket 1 d[k3_2] = TestValueTy(1030) // in bucket 2 d[k4_0] = TestValueTy(1040) // in bucket 3 d[k5_2] = TestValueTy(1050) // in bucket 4 d[k6_0] = TestValueTy(1060) // in bucket 5 d[k3_2] = nil assert(d[k1_0]!.value == 1010) assert(d[k2_0]!.value == 1020) assert(d[k3_2] == nil) assert(d[k4_0]!.value == 1040) assert(d[k5_2]!.value == 1050) assert(d[k6_0]!.value == 1060) } DictionaryTestSuite.test("deleteChainCollisionRandomized") { let seed = UInt64.random(in: .min ... .max) var generator = LinearCongruentialGenerator(seed: seed) print("using LinearCongruentialGenerator(seed: \(seed))") func check(_ d: Dictionary<TestKeyTy, TestValueTy>) { let keys = Array(d.keys) for i in 0..<keys.count { for j in 0..<i { expectNotEqual(keys[i], keys[j]) } } for k in keys { expectNotNil(d[k]) } } let collisionChains = Int.random(in: 1...8, using: &generator) let chainOverlap = Int.random(in: 0...5, using: &generator) let chainLength = 7 var knownKeys: [TestKeyTy] = [] func getKey(_ value: Int) -> TestKeyTy { for k in knownKeys { if k.value == value { return k } } let hashValue = Int.random(in: 0 ..< (chainLength - chainOverlap), using: &generator) * collisionChains let k = TestKeyTy(value: value, hashValue: hashValue) knownKeys += [k] return k } var d = Dictionary<TestKeyTy, TestValueTy>(minimumCapacity: 30) for _ in 1..<300 { let key = getKey(Int.random(in: 0 ..< (collisionChains * chainLength), using: &generator)) if Int.random(in: 0 ..< (chainLength * 2), using: &generator) == 0 { d[key] = nil } else { d[key] = TestValueTy(key.value * 10) } check(d) } } DictionaryTestSuite.test("init(dictionaryLiteral:)") { do { var empty = Dictionary<Int, Int>() assert(empty.count == 0) assert(empty[1111] == nil) } do { var d = Dictionary(dictionaryLiteral: (10, 1010)) assert(d.count == 1) assert(d[10]! == 1010) assert(d[1111] == nil) } do { var d = Dictionary(dictionaryLiteral: (10, 1010), (20, 1020)) assert(d.count == 2) assert(d[10]! == 1010) assert(d[20]! == 1020) assert(d[1111] == nil) } do { var d = Dictionary(dictionaryLiteral: (10, 1010), (20, 1020), (30, 1030)) assert(d.count == 3) assert(d[10]! == 1010) assert(d[20]! == 1020) assert(d[30]! == 1030) assert(d[1111] == nil) } do { var d = Dictionary(dictionaryLiteral: (10, 1010), (20, 1020), (30, 1030), (40, 1040)) assert(d.count == 4) assert(d[10]! == 1010) assert(d[20]! == 1020) assert(d[30]! == 1030) assert(d[40]! == 1040) assert(d[1111] == nil) } do { var d: Dictionary<Int, Int> = [ 10: 1010, 20: 1020, 30: 1030 ] assert(d.count == 3) assert(d[10]! == 1010) assert(d[20]! == 1020) assert(d[30]! == 1030) } } DictionaryTestSuite.test("init(uniqueKeysWithValues:)") { do { var d = Dictionary(uniqueKeysWithValues: [(10, 1010), (20, 1020), (30, 1030)]) expectEqual(d.count, 3) expectEqual(d[10]!, 1010) expectEqual(d[20]!, 1020) expectEqual(d[30]!, 1030) expectNil(d[1111]) } do { var d = Dictionary<Int, Int>(uniqueKeysWithValues: EmptyCollection<(Int, Int)>()) expectEqual(d.count, 0) expectNil(d[1111]) } do { expectCrashLater() _ = Dictionary(uniqueKeysWithValues: [(10, 1010), (20, 1020), (10, 2010)]) } } DictionaryTestSuite.test("init(_:uniquingKeysWith:)") { do { let d = Dictionary( [(10, 1010), (20, 1020), (30, 1030), (10, 2010)], uniquingKeysWith: min) expectEqual(d.count, 3) expectEqual(d[10]!, 1010) expectEqual(d[20]!, 1020) expectEqual(d[30]!, 1030) expectNil(d[1111]) } do { let d = Dictionary( [(10, 1010), (20, 1020), (30, 1030), (10, 2010)] as [(Int, Int)], uniquingKeysWith: +) expectEqual(d.count, 3) expectEqual(d[10]!, 3020) expectEqual(d[20]!, 1020) expectEqual(d[30]!, 1030) expectNil(d[1111]) } do { let d = Dictionary([(10, 1010), (20, 1020), (30, 1030), (10, 2010)]) { (a, b) in Int("\(a)\(b)")! } expectEqual(d.count, 3) expectEqual(d[10]!, 10102010) expectEqual(d[20]!, 1020) expectEqual(d[30]!, 1030) expectNil(d[1111]) } do { let d = Dictionary([(10, 1010), (10, 2010), (10, 3010), (10, 4010)]) { $1 } expectEqual(d.count, 1) expectEqual(d[10]!, 4010) expectNil(d[1111]) } do { let d = Dictionary(EmptyCollection<(Int, Int)>(), uniquingKeysWith: min) expectEqual(d.count, 0) expectNil(d[1111]) } struct TE: Error {} do { // No duplicate keys, so no error thrown. let d1 = try Dictionary([(10, 1), (20, 2), (30, 3)]) { (_,_) in throw TE() } expectEqual(d1.count, 3) // Duplicate keys, should throw error. _ = try Dictionary([(10, 1), (10, 2)]) { (_,_) in throw TE() } _ = assertionFailure() } catch { assert(error is TE) } } DictionaryTestSuite.test("init(grouping:by:)") { let r = 0..<10 let d1 = Dictionary(grouping: r, by: { $0 % 3 }) expectEqual(3, d1.count) expectEqual([0, 3, 6, 9], d1[0]!) expectEqual([1, 4, 7], d1[1]!) expectEqual([2, 5, 8], d1[2]!) let d2 = Dictionary(grouping: r, by: { $0 }) expectEqual(10, d2.count) let d3 = Dictionary(grouping: 0..<0, by: { $0 }) expectEqual(0, d3.count) } DictionaryTestSuite.test("mapValues(_:)") { let d1 = [10: 1010, 20: 1020, 30: 1030] let d2 = d1.mapValues(String.init) expectEqual(d1.count, d2.count) expectEqual(d1.keys.first, d2.keys.first) for (key, _) in d1 { expectEqual(String(d1[key]!), d2[key]!) } do { let d3: [MinimalHashableValue : Int] = Dictionary( uniqueKeysWithValues: d1.lazy.map { (MinimalHashableValue($0), $1) }) expectEqual(d3.count, 3) MinimalHashableValue.timesEqualEqualWasCalled = 0 MinimalHashableValue.timesHashIntoWasCalled = 0 // Calling mapValues shouldn't ever recalculate any hashes. let d4 = d3.mapValues(String.init) expectEqual(d4.count, d3.count) expectEqual(0, MinimalHashableValue.timesEqualEqualWasCalled) expectEqual(0, MinimalHashableValue.timesHashIntoWasCalled) } } DictionaryTestSuite.test("capacity/init(minimumCapacity:)") { let d0 = Dictionary<String, Int>(minimumCapacity: 0) expectGE(d0.capacity, 0) let d1 = Dictionary<String, Int>(minimumCapacity: 1) expectGE(d1.capacity, 1) let d3 = Dictionary<String, Int>(minimumCapacity: 3) expectGE(d3.capacity, 3) let d4 = Dictionary<String, Int>(minimumCapacity: 4) expectGE(d4.capacity, 4) let d10 = Dictionary<String, Int>(minimumCapacity: 10) expectGE(d10.capacity, 10) let d100 = Dictionary<String, Int>(minimumCapacity: 100) expectGE(d100.capacity, 100) let d1024 = Dictionary<String, Int>(minimumCapacity: 1024) expectGE(d1024.capacity, 1024) } DictionaryTestSuite.test("capacity/reserveCapacity(_:)") { var d1 = [10: 1010, 20: 1020, 30: 1030] expectEqual(3, d1.capacity) d1[40] = 1040 expectEqual(6, d1.capacity) // Reserving new capacity jumps up to next limit. d1.reserveCapacity(7) expectEqual(12, d1.capacity) // Can reserve right up to a limit. d1.reserveCapacity(24) expectEqual(24, d1.capacity) // Fill up to the limit, no reallocation. d1.merge(stride(from: 50, through: 240, by: 10).lazy.map { ($0, 1000 + $0) }, uniquingKeysWith: { (_,_) in fatalError() }) expectEqual(24, d1.count) expectEqual(24, d1.capacity) d1[250] = 1250 expectEqual(48, d1.capacity) } #if _runtime(_ObjC) //===--- // NSDictionary -> Dictionary bridging tests. //===--- func getAsNSDictionary(_ d: Dictionary<Int, Int>) -> NSDictionary { let keys = Array(d.keys.map { TestObjCKeyTy($0) }) let values = Array(d.values.map { TestObjCValueTy($0) }) // Return an `NSMutableDictionary` to make sure that it has a unique // pointer identity. return NSMutableDictionary(objects: values, forKeys: keys) } func getAsEquatableNSDictionary(_ d: Dictionary<Int, Int>) -> NSDictionary { let keys = Array(d.keys.map { TestObjCKeyTy($0) }) let values = Array(d.values.map { TestObjCEquatableValueTy($0) }) // Return an `NSMutableDictionary` to make sure that it has a unique // pointer identity. return NSMutableDictionary(objects: values, forKeys: keys) } func getAsNSMutableDictionary(_ d: Dictionary<Int, Int>) -> NSMutableDictionary { let keys = Array(d.keys.map { TestObjCKeyTy($0) }) let values = Array(d.values.map { TestObjCValueTy($0) }) return NSMutableDictionary(objects: values, forKeys: keys) } func getBridgedVerbatimDictionary() -> Dictionary<NSObject, AnyObject> { let nsd = getAsNSDictionary([10: 1010, 20: 1020, 30: 1030]) return convertNSDictionaryToDictionary(nsd) } func getBridgedVerbatimDictionary(_ d: Dictionary<Int, Int>) -> Dictionary<NSObject, AnyObject> { let nsd = getAsNSDictionary(d) return convertNSDictionaryToDictionary(nsd) } func getBridgedVerbatimDictionaryAndNSMutableDictionary() -> (Dictionary<NSObject, AnyObject>, NSMutableDictionary) { let nsd = getAsNSMutableDictionary([10: 1010, 20: 1020, 30: 1030]) return (convertNSDictionaryToDictionary(nsd), nsd) } func getBridgedNonverbatimDictionary() -> Dictionary<TestBridgedKeyTy, TestBridgedValueTy> { let nsd = getAsNSDictionary([10: 1010, 20: 1020, 30: 1030 ]) return Swift._forceBridgeFromObjectiveC(nsd, Dictionary.self) } func getBridgedNonverbatimDictionary(_ d: Dictionary<Int, Int>) -> Dictionary<TestBridgedKeyTy, TestBridgedValueTy> { let nsd = getAsNSDictionary(d) return Swift._forceBridgeFromObjectiveC(nsd, Dictionary.self) } func getBridgedNonverbatimDictionaryAndNSMutableDictionary() -> (Dictionary<TestBridgedKeyTy, TestBridgedValueTy>, NSMutableDictionary) { let nsd = getAsNSMutableDictionary([10: 1010, 20: 1020, 30: 1030]) return (Swift._forceBridgeFromObjectiveC(nsd, Dictionary.self), nsd) } func getBridgedVerbatimEquatableDictionary(_ d: Dictionary<Int, Int>) -> Dictionary<NSObject, TestObjCEquatableValueTy> { let nsd = getAsEquatableNSDictionary(d) return convertNSDictionaryToDictionary(nsd) } func getBridgedNonverbatimEquatableDictionary(_ d: Dictionary<Int, Int>) -> Dictionary<TestBridgedKeyTy, TestBridgedEquatableValueTy> { let nsd = getAsEquatableNSDictionary(d) return Swift._forceBridgeFromObjectiveC(nsd, Dictionary.self) } func getHugeBridgedVerbatimDictionaryHelper() -> NSDictionary { let keys = (1...32).map { TestObjCKeyTy($0) } let values = (1...32).map { TestObjCValueTy(1000 + $0) } return NSMutableDictionary(objects: values, forKeys: keys) } func getHugeBridgedVerbatimDictionary() -> Dictionary<NSObject, AnyObject> { let nsd = getHugeBridgedVerbatimDictionaryHelper() return convertNSDictionaryToDictionary(nsd) } func getHugeBridgedNonverbatimDictionary() -> Dictionary<TestBridgedKeyTy, TestBridgedValueTy> { let nsd = getHugeBridgedVerbatimDictionaryHelper() return Swift._forceBridgeFromObjectiveC(nsd, Dictionary.self) } /// A mock dictionary that stores its keys and values in parallel arrays, which /// allows it to return inner pointers to the keys array in fast enumeration. @objc class ParallelArrayDictionary : NSDictionary { struct Keys { var key0: AnyObject = TestObjCKeyTy(10) var key1: AnyObject = TestObjCKeyTy(20) var key2: AnyObject = TestObjCKeyTy(30) var key3: AnyObject = TestObjCKeyTy(40) } var keys = [ Keys() ] var value: AnyObject = TestObjCValueTy(1111) override init() { super.init() } override init( objects: UnsafePointer<AnyObject>?, forKeys keys: UnsafePointer<NSCopying>?, count: Int) { super.init(objects: objects, forKeys: keys, count: count) } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) not implemented by ParallelArrayDictionary") } @objc(copyWithZone:) override func copy(with zone: NSZone?) -> Any { // Ensure that copying this dictionary does not produce a CoreFoundation // object. return self } override func countByEnumerating( with state: UnsafeMutablePointer<NSFastEnumerationState>, objects: AutoreleasingUnsafeMutablePointer<AnyObject?>, count: Int ) -> Int { var theState = state.pointee if theState.state == 0 { theState.state = 1 theState.itemsPtr = AutoreleasingUnsafeMutablePointer(keys._baseAddressIfContiguous) theState.mutationsPtr = _fastEnumerationStorageMutationsPtr state.pointee = theState return 4 } return 0 } override func object(forKey aKey: Any) -> Any? { return value } override var count: Int { return 4 } } func getParallelArrayBridgedVerbatimDictionary() -> Dictionary<NSObject, AnyObject> { let nsd: NSDictionary = ParallelArrayDictionary() return convertNSDictionaryToDictionary(nsd) } func getParallelArrayBridgedNonverbatimDictionary() -> Dictionary<TestBridgedKeyTy, TestBridgedValueTy> { let nsd: NSDictionary = ParallelArrayDictionary() return Swift._forceBridgeFromObjectiveC(nsd, Dictionary.self) } @objc class CustomImmutableNSDictionary : NSDictionary { init(_privateInit: ()) { super.init() } override init() { expectUnreachable() super.init() } override init( objects: UnsafePointer<AnyObject>?, forKeys keys: UnsafePointer<NSCopying>?, count: Int) { expectUnreachable() super.init(objects: objects, forKeys: keys, count: count) } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) not implemented by CustomImmutableNSDictionary") } @objc(copyWithZone:) override func copy(with zone: NSZone?) -> Any { CustomImmutableNSDictionary.timesCopyWithZoneWasCalled += 1 return self } override func object(forKey aKey: Any) -> Any? { CustomImmutableNSDictionary.timesObjectForKeyWasCalled += 1 return getAsNSDictionary([10: 1010, 20: 1020, 30: 1030]).object(forKey: aKey) } override func keyEnumerator() -> NSEnumerator { CustomImmutableNSDictionary.timesKeyEnumeratorWasCalled += 1 return getAsNSDictionary([10: 1010, 20: 1020, 30: 1030]).keyEnumerator() } override var count: Int { CustomImmutableNSDictionary.timesCountWasCalled += 1 return 3 } static var timesCopyWithZoneWasCalled = 0 static var timesObjectForKeyWasCalled = 0 static var timesKeyEnumeratorWasCalled = 0 static var timesCountWasCalled = 0 } DictionaryTestSuite.test("BridgedFromObjC.Verbatim.DictionaryIsCopied") { let (d, nsd) = getBridgedVerbatimDictionaryAndNSMutableDictionary() assert(isCocoaDictionary(d)) // Find an existing key. do { let kv = d[d.index(forKey: TestObjCKeyTy(10))!] assert(kv.0 == TestObjCKeyTy(10)) assert((kv.1 as! TestObjCValueTy).value == 1010) } // Delete the key from the NSMutableDictionary. assert(nsd[TestObjCKeyTy(10)] != nil) nsd.removeObject(forKey: TestObjCKeyTy(10)) assert(nsd[TestObjCKeyTy(10)] == nil) // Find an existing key, again. do { let kv = d[d.index(forKey: TestObjCKeyTy(10))!] assert(kv.0 == TestObjCKeyTy(10)) assert((kv.1 as! TestObjCValueTy).value == 1010) } } DictionaryTestSuite.test("BridgedFromObjC.Nonverbatim.DictionaryIsCopied") { let (d, nsd) = getBridgedNonverbatimDictionaryAndNSMutableDictionary() assert(isNativeDictionary(d)) // Find an existing key. do { let kv = d[d.index(forKey: TestBridgedKeyTy(10))!] assert(kv.0 == TestBridgedKeyTy(10)) assert(kv.1.value == 1010) } // Delete the key from the NSMutableDictionary. assert(nsd[TestBridgedKeyTy(10) as NSCopying] != nil) nsd.removeObject(forKey: TestBridgedKeyTy(10) as NSCopying) assert(nsd[TestBridgedKeyTy(10) as NSCopying] == nil) // Find an existing key, again. do { let kv = d[d.index(forKey: TestBridgedKeyTy(10))!] assert(kv.0 == TestBridgedKeyTy(10)) assert(kv.1.value == 1010) } } DictionaryTestSuite.test("BridgedFromObjC.Verbatim.NSDictionaryIsRetained") { let nsd: NSDictionary = NSDictionary(dictionary: getAsNSDictionary([10: 1010, 20: 1020, 30: 1030])) let d: [NSObject : AnyObject] = convertNSDictionaryToDictionary(nsd) let bridgedBack: NSDictionary = convertDictionaryToNSDictionary(d) expectEqual( unsafeBitCast(nsd, to: Int.self), unsafeBitCast(bridgedBack, to: Int.self)) _fixLifetime(nsd) _fixLifetime(d) _fixLifetime(bridgedBack) } DictionaryTestSuite.test("BridgedFromObjC.Nonverbatim.NSDictionaryIsCopied") { let nsd: NSDictionary = NSDictionary(dictionary: getAsNSDictionary([10: 1010, 20: 1020, 30: 1030])) let d: [TestBridgedKeyTy : TestBridgedValueTy] = convertNSDictionaryToDictionary(nsd) let bridgedBack: NSDictionary = convertDictionaryToNSDictionary(d) expectNotEqual( unsafeBitCast(nsd, to: Int.self), unsafeBitCast(bridgedBack, to: Int.self)) _fixLifetime(nsd) _fixLifetime(d) _fixLifetime(bridgedBack) } DictionaryTestSuite.test("BridgedFromObjC.Verbatim.ImmutableDictionaryIsRetained") { let nsd: NSDictionary = CustomImmutableNSDictionary(_privateInit: ()) CustomImmutableNSDictionary.timesCopyWithZoneWasCalled = 0 CustomImmutableNSDictionary.timesObjectForKeyWasCalled = 0 CustomImmutableNSDictionary.timesKeyEnumeratorWasCalled = 0 CustomImmutableNSDictionary.timesCountWasCalled = 0 let d: [NSObject : AnyObject] = convertNSDictionaryToDictionary(nsd) expectEqual(1, CustomImmutableNSDictionary.timesCopyWithZoneWasCalled) expectEqual(0, CustomImmutableNSDictionary.timesObjectForKeyWasCalled) expectEqual(0, CustomImmutableNSDictionary.timesKeyEnumeratorWasCalled) expectEqual(0, CustomImmutableNSDictionary.timesCountWasCalled) let bridgedBack: NSDictionary = convertDictionaryToNSDictionary(d) expectEqual( unsafeBitCast(nsd, to: Int.self), unsafeBitCast(bridgedBack, to: Int.self)) _fixLifetime(nsd) _fixLifetime(d) _fixLifetime(bridgedBack) } DictionaryTestSuite.test("BridgedFromObjC.Nonverbatim.ImmutableDictionaryIsCopied") { let nsd: NSDictionary = CustomImmutableNSDictionary(_privateInit: ()) CustomImmutableNSDictionary.timesCopyWithZoneWasCalled = 0 CustomImmutableNSDictionary.timesObjectForKeyWasCalled = 0 CustomImmutableNSDictionary.timesKeyEnumeratorWasCalled = 0 CustomImmutableNSDictionary.timesCountWasCalled = 0 TestBridgedValueTy.bridgeOperations = 0 let d: [TestBridgedKeyTy : TestBridgedValueTy] = convertNSDictionaryToDictionary(nsd) expectEqual(0, CustomImmutableNSDictionary.timesCopyWithZoneWasCalled) expectEqual(3, CustomImmutableNSDictionary.timesObjectForKeyWasCalled) expectEqual(1, CustomImmutableNSDictionary.timesKeyEnumeratorWasCalled) expectNotEqual(0, CustomImmutableNSDictionary.timesCountWasCalled) expectEqual(3, TestBridgedValueTy.bridgeOperations) let bridgedBack: NSDictionary = convertDictionaryToNSDictionary(d) expectNotEqual( unsafeBitCast(nsd, to: Int.self), unsafeBitCast(bridgedBack, to: Int.self)) _fixLifetime(nsd) _fixLifetime(d) _fixLifetime(bridgedBack) } DictionaryTestSuite.test("BridgedFromObjC.Verbatim.IndexForKey") { let d = getBridgedVerbatimDictionary() let identity1 = d._rawIdentifier() assert(isCocoaDictionary(d)) // Find an existing key. do { var kv = d[d.index(forKey: TestObjCKeyTy(10))!] assert(kv.0 == TestObjCKeyTy(10)) assert((kv.1 as! TestObjCValueTy).value == 1010) kv = d[d.index(forKey: TestObjCKeyTy(20))!] assert(kv.0 == TestObjCKeyTy(20)) assert((kv.1 as! TestObjCValueTy).value == 1020) kv = d[d.index(forKey: TestObjCKeyTy(30))!] assert(kv.0 == TestObjCKeyTy(30)) assert((kv.1 as! TestObjCValueTy).value == 1030) } // Try to find a key that does not exist. assert(d.index(forKey: TestObjCKeyTy(40)) == nil) assert(identity1 == d._rawIdentifier()) } DictionaryTestSuite.test("BridgedFromObjC.Nonverbatim.IndexForKey") { let d = getBridgedNonverbatimDictionary() let identity1 = d._rawIdentifier() assert(isNativeDictionary(d)) // Find an existing key. do { var kv = d[d.index(forKey: TestBridgedKeyTy(10))!] assert(kv.0 == TestBridgedKeyTy(10)) assert(kv.1.value == 1010) kv = d[d.index(forKey: TestBridgedKeyTy(20))!] assert(kv.0 == TestBridgedKeyTy(20)) assert(kv.1.value == 1020) kv = d[d.index(forKey: TestBridgedKeyTy(30))!] assert(kv.0 == TestBridgedKeyTy(30)) assert(kv.1.value == 1030) } // Try to find a key that does not exist. assert(d.index(forKey: TestBridgedKeyTy(40)) == nil) assert(identity1 == d._rawIdentifier()) } DictionaryTestSuite.test("BridgedFromObjC.Verbatim.SubscriptWithIndex") { let d = getBridgedVerbatimDictionary() let identity1 = d._rawIdentifier() assert(isCocoaDictionary(d)) let startIndex = d.startIndex let endIndex = d.endIndex assert(startIndex != endIndex) assert(startIndex < endIndex) assert(startIndex <= endIndex) assert(!(startIndex >= endIndex)) assert(!(startIndex > endIndex)) assert(identity1 == d._rawIdentifier()) var pairs = Array<(Int, Int)>() for i in d.indices { let (key, value) = d[i] let kv = ((key as! TestObjCKeyTy).value, (value as! TestObjCValueTy).value) pairs += [kv] } assert(equalsUnordered(pairs, [ (10, 1010), (20, 1020), (30, 1030) ])) assert(identity1 == d._rawIdentifier()) // Keep indexes alive during the calls above. _fixLifetime(startIndex) _fixLifetime(endIndex) } DictionaryTestSuite.test("BridgedFromObjC.Nonverbatim.SubscriptWithIndex") { let d = getBridgedNonverbatimDictionary() let identity1 = d._rawIdentifier() assert(isNativeDictionary(d)) let startIndex = d.startIndex let endIndex = d.endIndex assert(startIndex != endIndex) assert(startIndex < endIndex) assert(startIndex <= endIndex) assert(!(startIndex >= endIndex)) assert(!(startIndex > endIndex)) assert(identity1 == d._rawIdentifier()) var pairs = Array<(Int, Int)>() for i in d.indices { let (key, value) = d[i] let kv = (key.value, value.value) pairs += [kv] } assert(equalsUnordered(pairs, [ (10, 1010), (20, 1020), (30, 1030) ])) assert(identity1 == d._rawIdentifier()) // Keep indexes alive during the calls above. _fixLifetime(startIndex) _fixLifetime(endIndex) } DictionaryTestSuite.test("BridgedFromObjC.Verbatim.SubscriptWithIndex_Empty") { let d = getBridgedVerbatimDictionary([:]) let identity1 = d._rawIdentifier() assert(isCocoaDictionary(d)) let startIndex = d.startIndex let endIndex = d.endIndex assert(startIndex == endIndex) assert(!(startIndex < endIndex)) assert(startIndex <= endIndex) assert(startIndex >= endIndex) assert(!(startIndex > endIndex)) assert(identity1 == d._rawIdentifier()) // Keep indexes alive during the calls above. _fixLifetime(startIndex) _fixLifetime(endIndex) } DictionaryTestSuite.test("BridgedFromObjC.Nonverbatim.SubscriptWithIndex_Empty") { let d = getBridgedNonverbatimDictionary([:]) let identity1 = d._rawIdentifier() assert(isNativeDictionary(d)) let startIndex = d.startIndex let endIndex = d.endIndex assert(startIndex == endIndex) assert(!(startIndex < endIndex)) assert(startIndex <= endIndex) assert(startIndex >= endIndex) assert(!(startIndex > endIndex)) assert(identity1 == d._rawIdentifier()) // Keep indexes alive during the calls above. _fixLifetime(startIndex) _fixLifetime(endIndex) } DictionaryTestSuite.test("BridgedFromObjC.Verbatim.SubscriptWithKey") { var d = getBridgedVerbatimDictionary() let identity1 = d._rawIdentifier() assert(isCocoaDictionary(d)) // Read existing key-value pairs. var v = d[TestObjCKeyTy(10)] as! TestObjCValueTy assert(v.value == 1010) v = d[TestObjCKeyTy(20)] as! TestObjCValueTy assert(v.value == 1020) v = d[TestObjCKeyTy(30)] as! TestObjCValueTy assert(v.value == 1030) assert(identity1 == d._rawIdentifier()) // Insert a new key-value pair. d[TestObjCKeyTy(40)] = TestObjCValueTy(2040) let identity2 = d._rawIdentifier() assert(identity1 != identity2) assert(isNativeDictionary(d)) assert(d.count == 4) v = d[TestObjCKeyTy(10)] as! TestObjCValueTy assert(v.value == 1010) v = d[TestObjCKeyTy(20)] as! TestObjCValueTy assert(v.value == 1020) v = d[TestObjCKeyTy(30)] as! TestObjCValueTy assert(v.value == 1030) v = d[TestObjCKeyTy(40)] as! TestObjCValueTy assert(v.value == 2040) // Overwrite value in existing binding. d[TestObjCKeyTy(10)] = TestObjCValueTy(2010) assert(identity2 == d._rawIdentifier()) assert(isNativeDictionary(d)) assert(d.count == 4) v = d[TestObjCKeyTy(10)] as! TestObjCValueTy assert(v.value == 2010) v = d[TestObjCKeyTy(20)] as! TestObjCValueTy assert(v.value == 1020) v = d[TestObjCKeyTy(30)] as! TestObjCValueTy assert(v.value == 1030) v = d[TestObjCKeyTy(40)] as! TestObjCValueTy assert(v.value == 2040) } DictionaryTestSuite.test("BridgedFromObjC.Nonverbatim.SubscriptWithKey") { var d = getBridgedNonverbatimDictionary() let identity1 = d._rawIdentifier() assert(isNativeDictionary(d)) // Read existing key-value pairs. var v = d[TestBridgedKeyTy(10)] assert(v!.value == 1010) v = d[TestBridgedKeyTy(20)] assert(v!.value == 1020) v = d[TestBridgedKeyTy(30)] assert(v!.value == 1030) assert(identity1 == d._rawIdentifier()) // Insert a new key-value pair. d[TestBridgedKeyTy(40)] = TestBridgedValueTy(2040) let identity2 = d._rawIdentifier() // Storage identity may or may not change depending on allocation behavior. // (d is eagerly bridged to a regular uniquely referenced native Dictionary.) //assert(identity1 != identity2) assert(isNativeDictionary(d)) assert(d.count == 4) v = d[TestBridgedKeyTy(10)] assert(v!.value == 1010) v = d[TestBridgedKeyTy(20)] assert(v!.value == 1020) v = d[TestBridgedKeyTy(30)] assert(v!.value == 1030) v = d[TestBridgedKeyTy(40)] assert(v!.value == 2040) // Overwrite value in existing binding. d[TestBridgedKeyTy(10)] = TestBridgedValueTy(2010) assert(identity2 == d._rawIdentifier()) assert(isNativeDictionary(d)) assert(d.count == 4) v = d[TestBridgedKeyTy(10)] assert(v!.value == 2010) v = d[TestBridgedKeyTy(20)] assert(v!.value == 1020) v = d[TestBridgedKeyTy(30)] assert(v!.value == 1030) v = d[TestBridgedKeyTy(40)] assert(v!.value == 2040) } DictionaryTestSuite.test("BridgedFromObjC.Verbatim.UpdateValueForKey") { // Insert a new key-value pair. do { var d = getBridgedVerbatimDictionary() let identity1 = d._rawIdentifier() assert(isCocoaDictionary(d)) let oldValue: AnyObject? = d.updateValue(TestObjCValueTy(2040), forKey: TestObjCKeyTy(40)) assert(oldValue == nil) let identity2 = d._rawIdentifier() assert(identity1 != identity2) assert(isNativeDictionary(d)) assert(d.count == 4) assert((d[TestObjCKeyTy(10)] as! TestObjCValueTy).value == 1010) assert((d[TestObjCKeyTy(20)] as! TestObjCValueTy).value == 1020) assert((d[TestObjCKeyTy(30)] as! TestObjCValueTy).value == 1030) assert((d[TestObjCKeyTy(40)] as! TestObjCValueTy).value == 2040) } // Overwrite a value in existing binding. do { var d = getBridgedVerbatimDictionary() let identity1 = d._rawIdentifier() assert(isCocoaDictionary(d)) let oldValue: AnyObject? = d.updateValue(TestObjCValueTy(2010), forKey: TestObjCKeyTy(10)) assert((oldValue as! TestObjCValueTy).value == 1010) let identity2 = d._rawIdentifier() assert(identity1 != identity2) assert(isNativeDictionary(d)) assert(d.count == 3) assert((d[TestObjCKeyTy(10)] as! TestObjCValueTy).value == 2010) assert((d[TestObjCKeyTy(20)] as! TestObjCValueTy).value == 1020) assert((d[TestObjCKeyTy(30)] as! TestObjCValueTy).value == 1030) } } DictionaryTestSuite.test("BridgedFromObjC.Nonverbatim.UpdateValueForKey") { // Insert a new key-value pair. do { var d = getBridgedNonverbatimDictionary() // let identity1 = d._rawIdentifier() assert(isNativeDictionary(d)) let oldValue = d.updateValue(TestBridgedValueTy(2040), forKey: TestBridgedKeyTy(40)) assert(oldValue == nil) // let identity2 = d._rawIdentifier() // Storage identity may or may not change depending on allocation behavior. // (d is eagerly bridged to a regular uniquely referenced native Dictionary.) //assert(identity1 != identity2) assert(isNativeDictionary(d)) assert(d.count == 4) assert(d[TestBridgedKeyTy(10)]!.value == 1010) assert(d[TestBridgedKeyTy(20)]!.value == 1020) assert(d[TestBridgedKeyTy(30)]!.value == 1030) assert(d[TestBridgedKeyTy(40)]!.value == 2040) } // Overwrite a value in existing binding. do { var d = getBridgedNonverbatimDictionary() let identity1 = d._rawIdentifier() assert(isNativeDictionary(d)) let oldValue = d.updateValue(TestBridgedValueTy(2010), forKey: TestBridgedKeyTy(10))! assert(oldValue.value == 1010) let identity2 = d._rawIdentifier() assert(identity1 == identity2) assert(isNativeDictionary(d)) assert(d.count == 3) assert(d[TestBridgedKeyTy(10)]!.value == 2010) assert(d[TestBridgedKeyTy(20)]!.value == 1020) assert(d[TestBridgedKeyTy(30)]!.value == 1030) } } DictionaryTestSuite.test("BridgedFromObjC.Verbatim.RemoveAt") { var d = getBridgedVerbatimDictionary() let identity1 = d._rawIdentifier() assert(isCocoaDictionary(d)) let foundIndex1 = d.index(forKey: TestObjCKeyTy(10))! assert(d[foundIndex1].0 == TestObjCKeyTy(10)) assert((d[foundIndex1].1 as! TestObjCValueTy).value == 1010) assert(identity1 == d._rawIdentifier()) let removedElement = d.remove(at: foundIndex1) assert(identity1 != d._rawIdentifier()) assert(isNativeDictionary(d)) assert(removedElement.0 == TestObjCKeyTy(10)) assert((removedElement.1 as! TestObjCValueTy).value == 1010) assert(d.count == 2) assert(d.index(forKey: TestObjCKeyTy(10)) == nil) } DictionaryTestSuite.test("BridgedFromObjC.Nonverbatim.RemoveAt") .code { var d = getBridgedNonverbatimDictionary() let identity1 = d._rawIdentifier() assert(isNativeDictionary(d)) let foundIndex1 = d.index(forKey: TestBridgedKeyTy(10))! assert(d[foundIndex1].0 == TestBridgedKeyTy(10)) assert(d[foundIndex1].1.value == 1010) assert(identity1 == d._rawIdentifier()) let removedElement = d.remove(at: foundIndex1) assert(identity1 == d._rawIdentifier()) assert(isNativeDictionary(d)) assert(removedElement.0 == TestObjCKeyTy(10) as TestBridgedKeyTy) assert(removedElement.1.value == 1010) assert(d.count == 2) assert(d.index(forKey: TestBridgedKeyTy(10)) == nil) } DictionaryTestSuite.test("BridgedFromObjC.Verbatim.RemoveValueForKey") { do { var d = getBridgedVerbatimDictionary() let identity1 = d._rawIdentifier() assert(isCocoaDictionary(d)) var deleted: AnyObject? = d.removeValue(forKey: TestObjCKeyTy(0)) assert(deleted == nil) assert(identity1 == d._rawIdentifier()) assert(isCocoaDictionary(d)) deleted = d.removeValue(forKey: TestObjCKeyTy(10)) assert((deleted as! TestObjCValueTy).value == 1010) let identity2 = d._rawIdentifier() assert(identity1 != identity2) assert(isNativeDictionary(d)) assert(d.count == 2) assert(d[TestObjCKeyTy(10)] == nil) assert((d[TestObjCKeyTy(20)] as! TestObjCValueTy).value == 1020) assert((d[TestObjCKeyTy(30)] as! TestObjCValueTy).value == 1030) assert(identity2 == d._rawIdentifier()) } do { var d1 = getBridgedVerbatimDictionary() let identity1 = d1._rawIdentifier() var d2 = d1 assert(isCocoaDictionary(d1)) assert(isCocoaDictionary(d2)) var deleted: AnyObject? = d2.removeValue(forKey: TestObjCKeyTy(0)) assert(deleted == nil) assert(identity1 == d1._rawIdentifier()) assert(identity1 == d2._rawIdentifier()) assert(isCocoaDictionary(d1)) assert(isCocoaDictionary(d2)) deleted = d2.removeValue(forKey: TestObjCKeyTy(10)) assert((deleted as! TestObjCValueTy).value == 1010) let identity2 = d2._rawIdentifier() assert(identity1 != identity2) assert(isCocoaDictionary(d1)) assert(isNativeDictionary(d2)) assert(d2.count == 2) assert((d1[TestObjCKeyTy(10)] as! TestObjCValueTy).value == 1010) assert((d1[TestObjCKeyTy(20)] as! TestObjCValueTy).value == 1020) assert((d1[TestObjCKeyTy(30)] as! TestObjCValueTy).value == 1030) assert(identity1 == d1._rawIdentifier()) assert(d2[TestObjCKeyTy(10)] == nil) assert((d2[TestObjCKeyTy(20)] as! TestObjCValueTy).value == 1020) assert((d2[TestObjCKeyTy(30)] as! TestObjCValueTy).value == 1030) assert(identity2 == d2._rawIdentifier()) } } DictionaryTestSuite.test("BridgedFromObjC.Nonverbatim.RemoveValueForKey") .code { do { var d = getBridgedNonverbatimDictionary() let identity1 = d._rawIdentifier() assert(isNativeDictionary(d)) var deleted = d.removeValue(forKey: TestBridgedKeyTy(0)) assert(deleted == nil) assert(identity1 == d._rawIdentifier()) assert(isNativeDictionary(d)) deleted = d.removeValue(forKey: TestBridgedKeyTy(10)) assert(deleted!.value == 1010) let identity2 = d._rawIdentifier() assert(identity1 == identity2) assert(isNativeDictionary(d)) assert(d.count == 2) assert(d[TestBridgedKeyTy(10)] == nil) assert(d[TestBridgedKeyTy(20)]!.value == 1020) assert(d[TestBridgedKeyTy(30)]!.value == 1030) assert(identity2 == d._rawIdentifier()) } do { var d1 = getBridgedNonverbatimDictionary() let identity1 = d1._rawIdentifier() var d2 = d1 assert(isNativeDictionary(d1)) assert(isNativeDictionary(d2)) var deleted = d2.removeValue(forKey: TestBridgedKeyTy(0)) assert(deleted == nil) assert(identity1 == d1._rawIdentifier()) assert(identity1 == d2._rawIdentifier()) assert(isNativeDictionary(d1)) assert(isNativeDictionary(d2)) deleted = d2.removeValue(forKey: TestBridgedKeyTy(10)) assert(deleted!.value == 1010) let identity2 = d2._rawIdentifier() assert(identity1 != identity2) assert(isNativeDictionary(d1)) assert(isNativeDictionary(d2)) assert(d2.count == 2) assert(d1[TestBridgedKeyTy(10)]!.value == 1010) assert(d1[TestBridgedKeyTy(20)]!.value == 1020) assert(d1[TestBridgedKeyTy(30)]!.value == 1030) assert(identity1 == d1._rawIdentifier()) assert(d2[TestBridgedKeyTy(10)] == nil) assert(d2[TestBridgedKeyTy(20)]!.value == 1020) assert(d2[TestBridgedKeyTy(30)]!.value == 1030) assert(identity2 == d2._rawIdentifier()) } } DictionaryTestSuite.test("BridgedFromObjC.Verbatim.RemoveAll") { do { var d = getBridgedVerbatimDictionary([:]) let identity1 = d._rawIdentifier() assert(isCocoaDictionary(d)) assert(d.count == 0) d.removeAll() assert(identity1 == d._rawIdentifier()) assert(d.count == 0) } do { var d = getBridgedVerbatimDictionary() let identity1 = d._rawIdentifier() assert(isCocoaDictionary(d)) let originalCapacity = d.count assert(d.count == 3) assert((d[TestObjCKeyTy(10)] as! TestObjCValueTy).value == 1010) d.removeAll() assert(identity1 != d._rawIdentifier()) assert(d.capacity < originalCapacity) assert(d.count == 0) assert(d[TestObjCKeyTy(10)] == nil) } do { var d = getBridgedVerbatimDictionary() let identity1 = d._rawIdentifier() assert(isCocoaDictionary(d)) let originalCapacity = d.count assert(d.count == 3) assert((d[TestObjCKeyTy(10)] as! TestObjCValueTy).value == 1010) d.removeAll(keepingCapacity: true) assert(identity1 != d._rawIdentifier()) assert(d.capacity >= originalCapacity) assert(d.count == 0) assert(d[TestObjCKeyTy(10)] == nil) } do { var d1 = getBridgedVerbatimDictionary() let identity1 = d1._rawIdentifier() assert(isCocoaDictionary(d1)) let originalCapacity = d1.count assert(d1.count == 3) assert((d1[TestObjCKeyTy(10)] as! TestObjCValueTy).value == 1010) var d2 = d1 d2.removeAll() let identity2 = d2._rawIdentifier() assert(identity1 == d1._rawIdentifier()) assert(identity2 != identity1) assert(d1.count == 3) assert((d1[TestObjCKeyTy(10)] as! TestObjCValueTy).value == 1010) assert(d2.capacity < originalCapacity) assert(d2.count == 0) assert(d2[TestObjCKeyTy(10)] == nil) } do { var d1 = getBridgedVerbatimDictionary() let identity1 = d1._rawIdentifier() assert(isCocoaDictionary(d1)) let originalCapacity = d1.count assert(d1.count == 3) assert((d1[TestObjCKeyTy(10)] as! TestObjCValueTy).value == 1010) var d2 = d1 d2.removeAll(keepingCapacity: true) let identity2 = d2._rawIdentifier() assert(identity1 == d1._rawIdentifier()) assert(identity2 != identity1) assert(d1.count == 3) assert((d1[TestObjCKeyTy(10)] as! TestObjCValueTy).value == 1010) assert(d2.capacity >= originalCapacity) assert(d2.count == 0) assert(d2[TestObjCKeyTy(10)] == nil) } } DictionaryTestSuite.test("BridgedFromObjC.Nonverbatim.RemoveAll") { do { var d = getBridgedNonverbatimDictionary([:]) let identity1 = d._rawIdentifier() assert(isNativeDictionary(d)) assert(d.count == 0) d.removeAll() assert(identity1 == d._rawIdentifier()) assert(d.count == 0) } do { var d = getBridgedNonverbatimDictionary() let identity1 = d._rawIdentifier() assert(isNativeDictionary(d)) let originalCapacity = d.count assert(d.count == 3) assert(d[TestBridgedKeyTy(10)]!.value == 1010) d.removeAll() assert(identity1 != d._rawIdentifier()) assert(d.capacity < originalCapacity) assert(d.count == 0) assert(d[TestBridgedKeyTy(10)] == nil) } do { var d = getBridgedNonverbatimDictionary() let identity1 = d._rawIdentifier() assert(isNativeDictionary(d)) let originalCapacity = d.count assert(d.count == 3) assert(d[TestBridgedKeyTy(10)]!.value == 1010) d.removeAll(keepingCapacity: true) assert(identity1 == d._rawIdentifier()) assert(d.capacity >= originalCapacity) assert(d.count == 0) assert(d[TestBridgedKeyTy(10)] == nil) } do { let d1 = getBridgedNonverbatimDictionary() let identity1 = d1._rawIdentifier() assert(isNativeDictionary(d1)) let originalCapacity = d1.count assert(d1.count == 3) assert(d1[TestBridgedKeyTy(10)]!.value == 1010) var d2 = d1 d2.removeAll() let identity2 = d2._rawIdentifier() assert(identity1 == d1._rawIdentifier()) assert(identity2 != identity1) assert(d1.count == 3) assert(d1[TestBridgedKeyTy(10)]!.value == 1010) assert(d2.capacity < originalCapacity) assert(d2.count == 0) assert(d2[TestBridgedKeyTy(10)] == nil) } do { let d1 = getBridgedNonverbatimDictionary() let identity1 = d1._rawIdentifier() assert(isNativeDictionary(d1)) let originalCapacity = d1.count assert(d1.count == 3) assert(d1[TestBridgedKeyTy(10)]!.value == 1010) var d2 = d1 d2.removeAll(keepingCapacity: true) let identity2 = d2._rawIdentifier() assert(identity1 == d1._rawIdentifier()) assert(identity2 != identity1) assert(d1.count == 3) assert(d1[TestBridgedKeyTy(10)]!.value == 1010) assert(d2.capacity >= originalCapacity) assert(d2.count == 0) assert(d2[TestBridgedKeyTy(10)] == nil) } } DictionaryTestSuite.test("BridgedFromObjC.Verbatim.Count") { let d = getBridgedVerbatimDictionary() let identity1 = d._rawIdentifier() assert(isCocoaDictionary(d)) assert(d.count == 3) assert(identity1 == d._rawIdentifier()) } DictionaryTestSuite.test("BridgedFromObjC.Nonverbatim.Count") { let d = getBridgedNonverbatimDictionary() let identity1 = d._rawIdentifier() assert(isNativeDictionary(d)) assert(d.count == 3) assert(identity1 == d._rawIdentifier()) } DictionaryTestSuite.test("BridgedFromObjC.Verbatim.Generate") { let d = getBridgedVerbatimDictionary() let identity1 = d._rawIdentifier() assert(isCocoaDictionary(d)) var iter = d.makeIterator() var pairs = Array<(Int, Int)>() while let (key, value) = iter.next() { let kv = ((key as! TestObjCKeyTy).value, (value as! TestObjCValueTy).value) pairs.append(kv) } assert(equalsUnordered(pairs, [ (10, 1010), (20, 1020), (30, 1030) ])) assert(iter.next() == nil) assert(iter.next() == nil) assert(iter.next() == nil) assert(identity1 == d._rawIdentifier()) } DictionaryTestSuite.test("BridgedFromObjC.Nonverbatim.Generate") { let d = getBridgedNonverbatimDictionary() let identity1 = d._rawIdentifier() assert(isNativeDictionary(d)) var iter = d.makeIterator() var pairs = Array<(Int, Int)>() while let (key, value) = iter.next() { let kv = (key.value, value.value) pairs.append(kv) } assert(equalsUnordered(pairs, [ (10, 1010), (20, 1020), (30, 1030) ])) assert(iter.next() == nil) assert(iter.next() == nil) assert(iter.next() == nil) assert(identity1 == d._rawIdentifier()) } DictionaryTestSuite.test("BridgedFromObjC.Verbatim.Generate_Empty") { let d = getBridgedVerbatimDictionary([:]) let identity1 = d._rawIdentifier() assert(isCocoaDictionary(d)) var iter = d.makeIterator() // Cannot write code below because of // <rdar://problem/16811736> Optional tuples are broken as optionals regarding == comparison // assert(iter.next() == .none) assert(iter.next() == nil) assert(iter.next() == nil) assert(iter.next() == nil) assert(iter.next() == nil) assert(identity1 == d._rawIdentifier()) } DictionaryTestSuite.test("BridgedFromObjC.Nonverbatim.Generate_Empty") { let d = getBridgedNonverbatimDictionary([:]) let identity1 = d._rawIdentifier() assert(isNativeDictionary(d)) var iter = d.makeIterator() // Cannot write code below because of // <rdar://problem/16811736> Optional tuples are broken as optionals regarding == comparison // assert(iter.next() == .none) assert(iter.next() == nil) assert(iter.next() == nil) assert(iter.next() == nil) assert(iter.next() == nil) assert(identity1 == d._rawIdentifier()) } DictionaryTestSuite.test("BridgedFromObjC.Verbatim.Generate_Huge") { let d = getHugeBridgedVerbatimDictionary() let identity1 = d._rawIdentifier() assert(isCocoaDictionary(d)) var iter = d.makeIterator() var pairs = Array<(Int, Int)>() while let (key, value) = iter.next() { let kv = ((key as! TestObjCKeyTy).value, (value as! TestObjCValueTy).value) pairs.append(kv) } var expectedPairs = Array<(Int, Int)>() for i in 1...32 { expectedPairs += [(i, 1000 + i)] } assert(equalsUnordered(pairs, expectedPairs)) assert(iter.next() == nil) assert(iter.next() == nil) assert(iter.next() == nil) assert(identity1 == d._rawIdentifier()) } DictionaryTestSuite.test("BridgedFromObjC.Nonverbatim.Generate_Huge") { let d = getHugeBridgedNonverbatimDictionary() let identity1 = d._rawIdentifier() assert(isNativeDictionary(d)) var iter = d.makeIterator() var pairs = Array<(Int, Int)>() while let (key, value) = iter.next() { let kv = (key.value, value.value) pairs.append(kv) } var expectedPairs = Array<(Int, Int)>() for i in 1...32 { expectedPairs += [(i, 1000 + i)] } assert(equalsUnordered(pairs, expectedPairs)) assert(iter.next() == nil) assert(iter.next() == nil) assert(iter.next() == nil) assert(identity1 == d._rawIdentifier()) } DictionaryTestSuite.test("BridgedFromObjC.Verbatim.Generate_ParallelArray") { autoreleasepoolIfUnoptimizedReturnAutoreleased { // Add an autorelease pool because ParallelArrayDictionary autoreleases // values in objectForKey. let d = getParallelArrayBridgedVerbatimDictionary() let identity1 = d._rawIdentifier() assert(isCocoaDictionary(d)) var iter = d.makeIterator() var pairs = Array<(Int, Int)>() while let (key, value) = iter.next() { let kv = ((key as! TestObjCKeyTy).value, (value as! TestObjCValueTy).value) pairs.append(kv) } let expectedPairs = [ (10, 1111), (20, 1111), (30, 1111), (40, 1111) ] assert(equalsUnordered(pairs, expectedPairs)) assert(iter.next() == nil) assert(iter.next() == nil) assert(iter.next() == nil) assert(identity1 == d._rawIdentifier()) } } DictionaryTestSuite.test("BridgedFromObjC.Nonverbatim.Generate_ParallelArray") { autoreleasepoolIfUnoptimizedReturnAutoreleased { // Add an autorelease pool because ParallelArrayDictionary autoreleases // values in objectForKey. let d = getParallelArrayBridgedNonverbatimDictionary() let identity1 = d._rawIdentifier() assert(isNativeDictionary(d)) var iter = d.makeIterator() var pairs = Array<(Int, Int)>() while let (key, value) = iter.next() { let kv = (key.value, value.value) pairs.append(kv) } let expectedPairs = [ (10, 1111), (20, 1111), (30, 1111), (40, 1111) ] assert(equalsUnordered(pairs, expectedPairs)) assert(iter.next() == nil) assert(iter.next() == nil) assert(iter.next() == nil) assert(identity1 == d._rawIdentifier()) } } DictionaryTestSuite.test("BridgedFromObjC.Verbatim.EqualityTest_Empty") { let d1 = getBridgedVerbatimEquatableDictionary([:]) let identity1 = d1._rawIdentifier() assert(isCocoaDictionary(d1)) var d2 = getBridgedVerbatimEquatableDictionary([:]) var identity2 = d2._rawIdentifier() assert(isCocoaDictionary(d2)) // We can't check that `identity1 != identity2` because Foundation might be // returning the same singleton NSDictionary for empty dictionaries. assert(d1 == d2) assert(identity1 == d1._rawIdentifier()) assert(identity2 == d2._rawIdentifier()) d2[TestObjCKeyTy(10)] = TestObjCEquatableValueTy(2010) assert(isNativeDictionary(d2)) assert(identity2 != d2._rawIdentifier()) identity2 = d2._rawIdentifier() assert(d1 != d2) assert(identity1 == d1._rawIdentifier()) assert(identity2 == d2._rawIdentifier()) } DictionaryTestSuite.test("BridgedFromObjC.Nonverbatim.EqualityTest_Empty") { let d1 = getBridgedNonverbatimEquatableDictionary([:]) let identity1 = d1._rawIdentifier() assert(isNativeDictionary(d1)) var d2 = getBridgedNonverbatimEquatableDictionary([:]) let identity2 = d2._rawIdentifier() assert(isNativeDictionary(d2)) assert(identity1 != identity2) assert(d1 == d2) assert(identity1 == d1._rawIdentifier()) assert(identity2 == d2._rawIdentifier()) d2[TestBridgedKeyTy(10)] = TestBridgedEquatableValueTy(2010) assert(isNativeDictionary(d2)) assert(identity2 == d2._rawIdentifier()) assert(d1 != d2) assert(identity1 == d1._rawIdentifier()) assert(identity2 == d2._rawIdentifier()) } DictionaryTestSuite.test("BridgedFromObjC.Verbatim.EqualityTest_Small") { func helper(_ nd1: Dictionary<Int, Int>, _ nd2: Dictionary<Int, Int>, _ expectedEq: Bool) { let d1 = getBridgedVerbatimEquatableDictionary(nd1) let identity1 = d1._rawIdentifier() assert(isCocoaDictionary(d1)) var d2 = getBridgedVerbatimEquatableDictionary(nd2) var identity2 = d2._rawIdentifier() assert(isCocoaDictionary(d2)) do { let eq1 = (d1 == d2) assert(eq1 == expectedEq) let eq2 = (d2 == d1) assert(eq2 == expectedEq) let neq1 = (d1 != d2) assert(neq1 != expectedEq) let neq2 = (d2 != d1) assert(neq2 != expectedEq) } assert(identity1 == d1._rawIdentifier()) assert(identity2 == d2._rawIdentifier()) d2[TestObjCKeyTy(1111)] = TestObjCEquatableValueTy(1111) d2[TestObjCKeyTy(1111)] = nil assert(isNativeDictionary(d2)) assert(identity2 != d2._rawIdentifier()) identity2 = d2._rawIdentifier() do { let eq1 = (d1 == d2) assert(eq1 == expectedEq) let eq2 = (d2 == d1) assert(eq2 == expectedEq) let neq1 = (d1 != d2) assert(neq1 != expectedEq) let neq2 = (d2 != d1) assert(neq2 != expectedEq) } assert(identity1 == d1._rawIdentifier()) assert(identity2 == d2._rawIdentifier()) } helper([:], [:], true) helper([10: 1010], [10: 1010], true) helper([10: 1010, 20: 1020], [10: 1010, 20: 1020], true) helper([10: 1010, 20: 1020, 30: 1030], [10: 1010, 20: 1020, 30: 1030], true) helper([10: 1010, 20: 1020, 30: 1030], [10: 1010, 20: 1020, 1111: 1030], false) helper([10: 1010, 20: 1020, 30: 1030], [10: 1010, 20: 1020, 30: 1111], false) helper([10: 1010, 20: 1020, 30: 1030], [10: 1010, 20: 1020], false) helper([10: 1010, 20: 1020, 30: 1030], [10: 1010], false) helper([10: 1010, 20: 1020, 30: 1030], [:], false) helper([10: 1010, 20: 1020, 30: 1030], [10: 1010, 20: 1020, 30: 1030, 40: 1040], false) } DictionaryTestSuite.test("BridgedFromObjC.Verbatim.ArrayOfDictionaries") { let nsa = NSMutableArray() for i in 0..<3 { nsa.add( getAsNSDictionary([10: 1010 + i, 20: 1020 + i, 30: 1030 + i])) } var a = nsa as [AnyObject] as! [Dictionary<NSObject, AnyObject>] for i in 0..<3 { let d = a[i] var iter = d.makeIterator() var pairs = Array<(Int, Int)>() while let (key, value) = iter.next() { let kv = ((key as! TestObjCKeyTy).value, (value as! TestObjCValueTy).value) pairs.append(kv) } let expectedPairs = [ (10, 1010 + i), (20, 1020 + i), (30, 1030 + i) ] assert(equalsUnordered(pairs, expectedPairs)) } } DictionaryTestSuite.test("BridgedFromObjC.Nonverbatim.ArrayOfDictionaries") { let nsa = NSMutableArray() for i in 0..<3 { nsa.add( getAsNSDictionary([10: 1010 + i, 20: 1020 + i, 30: 1030 + i])) } var a = nsa as [AnyObject] as! [Dictionary<TestBridgedKeyTy, TestBridgedValueTy>] for i in 0..<3 { let d = a[i] var iter = d.makeIterator() var pairs = Array<(Int, Int)>() while let (key, value) = iter.next() { let kv = (key.value, value.value) pairs.append(kv) } let expectedPairs = [ (10, 1010 + i), (20, 1020 + i), (30, 1030 + i) ] assert(equalsUnordered(pairs, expectedPairs)) } } DictionaryTestSuite.test("BridgedFromObjC.Nonverbatim.StringEqualityMismatch") { // NSString's isEqual(_:) implementation is stricter than Swift's String, so // Dictionary values bridged over from Objective-C may have duplicate keys. // rdar://problem/35995647 let cafe1 = "Cafe\u{301}" as NSString let cafe2 = "Café" as NSString let nsd = NSMutableDictionary() nsd.setObject(42, forKey: cafe1) nsd.setObject(23, forKey: cafe2) expectEqual(2, nsd.count) expectTrue((42 as NSNumber).isEqual(nsd.object(forKey: cafe1))) expectTrue((23 as NSNumber).isEqual(nsd.object(forKey: cafe2))) let d = convertNSDictionaryToDictionary(nsd) as [String: Int] expectEqual(1, d.count) expectEqual(d["Cafe\u{301}"], d["Café"]) let v = d["Café"] expectTrue(v == 42 || v == 23) } //===--- // Dictionary -> NSDictionary bridging tests. // // Key and Value are bridged verbatim. //===--- DictionaryTestSuite.test("BridgedToObjC.Verbatim.Count") { let d = getBridgedNSDictionaryOfRefTypesBridgedVerbatim() assert(d.count == 3) } DictionaryTestSuite.test("BridgedToObjC.Verbatim.ObjectForKey") { let d = getBridgedNSDictionaryOfRefTypesBridgedVerbatim() var v: AnyObject? = d.object(forKey: TestObjCKeyTy(10)).map { $0 as AnyObject } expectEqual(1010, (v as! TestObjCValueTy).value) let idValue10 = unsafeBitCast(v, to: UInt.self) v = d.object(forKey: TestObjCKeyTy(20)).map { $0 as AnyObject } expectEqual(1020, (v as! TestObjCValueTy).value) let idValue20 = unsafeBitCast(v, to: UInt.self) v = d.object(forKey: TestObjCKeyTy(30)).map { $0 as AnyObject } expectEqual(1030, (v as! TestObjCValueTy).value) let idValue30 = unsafeBitCast(v, to: UInt.self) expectNil(d.object(forKey: TestObjCKeyTy(40))) // NSDictionary can store mixed key types. Swift's Dictionary is typed, but // when bridged to NSDictionary, it should behave like one, and allow queries // for mismatched key types. expectNil(d.object(forKey: TestObjCInvalidKeyTy())) for _ in 0..<3 { expectEqual(idValue10, unsafeBitCast( d.object(forKey: TestObjCKeyTy(10)).map { $0 as AnyObject }, to: UInt.self)) expectEqual(idValue20, unsafeBitCast( d.object(forKey: TestObjCKeyTy(20)).map { $0 as AnyObject }, to: UInt.self)) expectEqual(idValue30, unsafeBitCast( d.object(forKey: TestObjCKeyTy(30)).map { $0 as AnyObject }, to: UInt.self)) } expectAutoreleasedKeysAndValues(unopt: (0, 3)) } DictionaryTestSuite.test("BridgedToObjC.Verbatim.KeyEnumerator.NextObject") { let d = getBridgedNSDictionaryOfRefTypesBridgedVerbatim() var capturedIdentityPairs = Array<(UInt, UInt)>() for _ in 0..<3 { let enumerator = d.keyEnumerator() var dataPairs = Array<(Int, Int)>() var identityPairs = Array<(UInt, UInt)>() while let key = enumerator.nextObject() { let keyObj = key as AnyObject let value: AnyObject = d.object(forKey: keyObj)! as AnyObject let dataPair = ((keyObj as! TestObjCKeyTy).value, (value as! TestObjCValueTy).value) dataPairs.append(dataPair) let identityPair = (unsafeBitCast(keyObj, to: UInt.self), unsafeBitCast(value, to: UInt.self)) identityPairs.append(identityPair) } expectTrue( equalsUnordered(dataPairs, [ (10, 1010), (20, 1020), (30, 1030) ])) if capturedIdentityPairs.isEmpty { capturedIdentityPairs = identityPairs } else { expectTrue(equalsUnordered(capturedIdentityPairs, identityPairs)) } assert(enumerator.nextObject() == nil) assert(enumerator.nextObject() == nil) assert(enumerator.nextObject() == nil) } expectAutoreleasedKeysAndValues(unopt: (3, 3)) } DictionaryTestSuite.test("BridgedToObjC.Verbatim.KeyEnumerator.NextObject_Empty") { let d = getBridgedEmptyNSDictionary() let enumerator = d.keyEnumerator() assert(enumerator.nextObject() == nil) assert(enumerator.nextObject() == nil) assert(enumerator.nextObject() == nil) } DictionaryTestSuite.test("BridgedToObjC.Verbatim.KeyEnumerator.FastEnumeration.UseFromSwift") { let d = getBridgedNSDictionaryOfRefTypesBridgedVerbatim() checkDictionaryFastEnumerationFromSwift( [ (10, 1010), (20, 1020), (30, 1030) ], d, { d.keyEnumerator() }, { ($0 as! TestObjCKeyTy).value }, { ($0 as! TestObjCValueTy).value }) expectAutoreleasedKeysAndValues(unopt: (3, 3)) } DictionaryTestSuite.test("BridgedToObjC.Verbatim.KeyEnumerator.FastEnumeration.UseFromObjC") { let d = getBridgedNSDictionaryOfRefTypesBridgedVerbatim() checkDictionaryFastEnumerationFromObjC( [ (10, 1010), (20, 1020), (30, 1030) ], d, { d.keyEnumerator() }, { ($0 as! TestObjCKeyTy).value }, { ($0 as! TestObjCValueTy).value }) expectAutoreleasedKeysAndValues(unopt: (3, 3)) } DictionaryTestSuite.test("BridgedToObjC.Verbatim.KeyEnumerator.FastEnumeration_Empty") { let d = getBridgedEmptyNSDictionary() checkDictionaryFastEnumerationFromSwift( [], d, { d.keyEnumerator() }, { ($0 as! TestObjCKeyTy).value }, { ($0 as! TestObjCValueTy).value }) checkDictionaryFastEnumerationFromObjC( [], d, { d.keyEnumerator() }, { ($0 as! TestObjCKeyTy).value }, { ($0 as! TestObjCValueTy).value }) } DictionaryTestSuite.test("BridgedToObjC.Verbatim.FastEnumeration.UseFromSwift") { let d = getBridgedNSDictionaryOfRefTypesBridgedVerbatim() checkDictionaryFastEnumerationFromSwift( [ (10, 1010), (20, 1020), (30, 1030) ], d, { d }, { ($0 as! TestObjCKeyTy).value }, { ($0 as! TestObjCValueTy).value }) expectAutoreleasedKeysAndValues(unopt: (0, 3)) } DictionaryTestSuite.test("BridgedToObjC.Verbatim.FastEnumeration.UseFromObjC") { let d = getBridgedNSDictionaryOfRefTypesBridgedVerbatim() checkDictionaryFastEnumerationFromObjC( [ (10, 1010), (20, 1020), (30, 1030) ], d, { d }, { ($0 as! TestObjCKeyTy).value }, { ($0 as! TestObjCValueTy).value }) expectAutoreleasedKeysAndValues(unopt: (0, 3)) } DictionaryTestSuite.test("BridgedToObjC.Verbatim.FastEnumeration_Empty") { let d = getBridgedEmptyNSDictionary() checkDictionaryFastEnumerationFromSwift( [], d, { d }, { ($0 as! TestObjCKeyTy).value }, { ($0 as! TestObjCValueTy).value }) checkDictionaryFastEnumerationFromObjC( [], d, { d }, { ($0 as! TestObjCKeyTy).value }, { ($0 as! TestObjCValueTy).value }) } /// Check for buffer overruns/underruns in Swift's /// `-[NSDictionary getObjects:andKeys:count:]` implementations. func checkGetObjectsAndKeys( _ dictionary: NSDictionary, count: Int, file: String = #file, line: UInt = #line) { let canary = NSObject() let storageSize = 2 * max(count, dictionary.count) + 2 // Create buffers for storing keys and values at +0 refcounts, // then call getObjects:andKeys:count: via a shim in // StdlibUnittestFoundationExtras. typealias UnmanagedPointer = UnsafeMutablePointer<Unmanaged<AnyObject>> let keys = UnmanagedPointer.allocate(capacity: storageSize) keys.initialize(repeating: Unmanaged.passUnretained(canary), count: storageSize) let values = UnmanagedPointer.allocate(capacity: storageSize) values.initialize(repeating: Unmanaged.passUnretained(canary), count: storageSize) keys.withMemoryRebound(to: AnyObject.self, capacity: storageSize) { k in values.withMemoryRebound(to: AnyObject.self, capacity: storageSize) { v in dictionary.available_getObjects( AutoreleasingUnsafeMutablePointer(v), andKeys: AutoreleasingUnsafeMutablePointer(k), count: count) } } // Check results. for i in 0 ..< storageSize { let key = keys[i].takeUnretainedValue() let value = values[i].takeUnretainedValue() if i < min(count, dictionary.count) { expectTrue( key !== canary, """ Buffer underrun at offset \(i) with count \(count): keys[\(i)] was left unchanged """, file: file, line: line) expectTrue( value !== canary, """ Buffer underrun at offset \(i) with count \(count): values[\(i)] was left unchanged """, file: file, line: line) if key !== canary, value !== canary { autoreleasepoolIfUnoptimizedReturnAutoreleased { // We need an autorelease pool because objectForKey returns // autoreleased values. expectTrue( value === dictionary.object(forKey: key) as AnyObject, """ Inconsistency at offset \(i) with count \(count): values[\(i)] does not match value for keys[\(i)] """, file: file, line: line) } } } else { expectTrue( key === canary, """ Buffer overrun at offset \(i) with count \(count): keys[\(i)] was overwritten with value \(key) """, file: file, line: line) expectTrue( value === canary, """ Buffer overrun at offset \(i) with count \(count): values[\(i)] was overwritten with value \(key) """, file: file, line: line) } } keys.deinitialize(count: storageSize) // noop keys.deallocate() values.deinitialize(count: storageSize) // noop values.deallocate() withExtendedLifetime(canary) {} } DictionaryTestSuite.test("BridgedToObjC.Verbatim.getObjects:andKeys:count:") { let d = getBridgedNSDictionaryOfRefTypesBridgedVerbatim() for count in 0 ..< d.count + 2 { checkGetObjectsAndKeys(d, count: count) } } DictionaryTestSuite.test("BridgedToObjC.Verbatim.getObjects:andKeys:count:/InvalidCount") { expectCrashLater() let d = getBridgedNSDictionaryOfRefTypesBridgedVerbatim() checkGetObjectsAndKeys(d, count: -1) } //===--- // Dictionary -> NSDictionary bridging tests. // // Key type and value type are bridged non-verbatim. //===--- DictionaryTestSuite.test("BridgedToObjC.KeyValue_ValueTypesCustomBridged") { let d = getBridgedNSDictionaryOfKeyValue_ValueTypesCustomBridged() let enumerator = d.keyEnumerator() var pairs = Array<(Int, Int)>() while let key = enumerator.nextObject() { let value: AnyObject = d.object(forKey: key)! as AnyObject let kv = ((key as! TestObjCKeyTy).value, (value as! TestObjCValueTy).value) pairs.append(kv) } assert(equalsUnordered(pairs, [ (10, 1010), (20, 1020), (30, 1030) ])) expectAutoreleasedKeysAndValues(unopt: (3, 3)) } DictionaryTestSuite.test("BridgedToObjC.Custom.KeyEnumerator.FastEnumeration.UseFromSwift") { let d = getBridgedNSDictionaryOfKeyValue_ValueTypesCustomBridged() checkDictionaryFastEnumerationFromSwift( [ (10, 1010), (20, 1020), (30, 1030) ], d, { d.keyEnumerator() }, { ($0 as! TestObjCKeyTy).value }, { ($0 as! TestObjCValueTy).value }) expectAutoreleasedKeysAndValues(unopt: (3, 3)) } DictionaryTestSuite.test("BridgedToObjC.Custom.KeyEnumerator.FastEnumeration.UseFromSwift.Partial") { let d = getBridgedNSDictionaryOfKeyValue_ValueTypesCustomBridged( numElements: 9) checkDictionaryEnumeratorPartialFastEnumerationFromSwift( [ (10, 1010), (20, 1020), (30, 1030), (40, 1040), (50, 1050), (60, 1060), (70, 1070), (80, 1080), (90, 1090) ], d, maxFastEnumerationItems: 5, { ($0 as! TestObjCKeyTy).value }, { ($0 as! TestObjCValueTy).value }) expectAutoreleasedKeysAndValues(unopt: (9, 9)) } DictionaryTestSuite.test("BridgedToObjC.Custom.KeyEnumerator.FastEnumeration.UseFromObjC") { let d = getBridgedNSDictionaryOfKeyValue_ValueTypesCustomBridged() checkDictionaryFastEnumerationFromObjC( [ (10, 1010), (20, 1020), (30, 1030) ], d, { d.keyEnumerator() }, { ($0 as! TestObjCKeyTy).value }, { ($0 as! TestObjCValueTy).value }) expectAutoreleasedKeysAndValues(unopt: (3, 3)) } DictionaryTestSuite.test("BridgedToObjC.Custom.FastEnumeration.UseFromSwift") { let d = getBridgedNSDictionaryOfKeyValue_ValueTypesCustomBridged() checkDictionaryFastEnumerationFromSwift( [ (10, 1010), (20, 1020), (30, 1030) ], d, { d }, { ($0 as! TestObjCKeyTy).value }, { ($0 as! TestObjCValueTy).value }) expectAutoreleasedKeysAndValues(unopt: (0, 3)) } DictionaryTestSuite.test("BridgedToObjC.Custom.FastEnumeration.UseFromObjC") { let d = getBridgedNSDictionaryOfKeyValue_ValueTypesCustomBridged() checkDictionaryFastEnumerationFromObjC( [ (10, 1010), (20, 1020), (30, 1030) ], d, { d }, { ($0 as! TestObjCKeyTy).value }, { ($0 as! TestObjCValueTy).value }) expectAutoreleasedKeysAndValues(unopt: (0, 3)) } DictionaryTestSuite.test("BridgedToObjC.Custom.FastEnumeration_Empty") { let d = getBridgedNSDictionaryOfKeyValue_ValueTypesCustomBridged( numElements: 0) checkDictionaryFastEnumerationFromSwift( [], d, { d }, { ($0 as! TestObjCKeyTy).value }, { ($0 as! TestObjCValueTy).value }) checkDictionaryFastEnumerationFromObjC( [], d, { d }, { ($0 as! TestObjCKeyTy).value }, { ($0 as! TestObjCValueTy).value }) } DictionaryTestSuite.test("BridgedToObjC.Custom.getObjects:andKeys:count:") { let d = getBridgedNSDictionaryOfKeyValue_ValueTypesCustomBridged() for count in 0 ..< d.count + 2 { checkGetObjectsAndKeys(d, count: count) } } DictionaryTestSuite.test("BridgedToObjC.Custom.getObjects:andKeys:count:/InvalidCount") { expectCrashLater() let d = getBridgedNSDictionaryOfKeyValue_ValueTypesCustomBridged() checkGetObjectsAndKeys(d, count: -1) } func getBridgedNSDictionaryOfKey_ValueTypeCustomBridged() -> NSDictionary { assert(!_isBridgedVerbatimToObjectiveC(TestBridgedKeyTy.self)) assert(_isBridgedVerbatimToObjectiveC(TestObjCValueTy.self)) var d = Dictionary<TestBridgedKeyTy, TestObjCValueTy>() d[TestBridgedKeyTy(10)] = TestObjCValueTy(1010) d[TestBridgedKeyTy(20)] = TestObjCValueTy(1020) d[TestBridgedKeyTy(30)] = TestObjCValueTy(1030) let bridged = convertDictionaryToNSDictionary(d) assert(isNativeNSDictionary(bridged)) return bridged } DictionaryTestSuite.test("BridgedToObjC.Key_ValueTypeCustomBridged") { let d = getBridgedNSDictionaryOfKey_ValueTypeCustomBridged() let enumerator = d.keyEnumerator() var pairs = Array<(Int, Int)>() while let key = enumerator.nextObject() { let value: AnyObject = d.object(forKey: key)! as AnyObject let kv = ((key as! TestObjCKeyTy).value, (value as! TestObjCValueTy).value) pairs.append(kv) } assert(equalsUnordered(pairs, [ (10, 1010), (20, 1020), (30, 1030) ])) expectAutoreleasedKeysAndValues(unopt: (3, 3)) } func getBridgedNSDictionaryOfValue_ValueTypeCustomBridged() -> NSDictionary { assert(_isBridgedVerbatimToObjectiveC(TestObjCKeyTy.self)) assert(!_isBridgedVerbatimToObjectiveC(TestBridgedValueTy.self)) var d = Dictionary<TestObjCKeyTy, TestBridgedValueTy>() d[TestObjCKeyTy(10)] = TestBridgedValueTy(1010) d[TestObjCKeyTy(20)] = TestBridgedValueTy(1020) d[TestObjCKeyTy(30)] = TestBridgedValueTy(1030) let bridged = convertDictionaryToNSDictionary(d) assert(isNativeNSDictionary(bridged)) return bridged } DictionaryTestSuite.test("BridgedToObjC.Value_ValueTypeCustomBridged") { let d = getBridgedNSDictionaryOfValue_ValueTypeCustomBridged() let enumerator = d.keyEnumerator() var pairs = Array<(Int, Int)>() while let key = enumerator.nextObject() { let value: AnyObject = d.object(forKey: key)! as AnyObject let kv = ((key as! TestObjCKeyTy).value, (value as! TestObjCValueTy).value) pairs.append(kv) } assert(equalsUnordered(pairs, [ (10, 1010), (20, 1020), (30, 1030) ])) expectAutoreleasedKeysAndValues(unopt: (3, 3)) } //===--- // NSDictionary -> Dictionary -> NSDictionary bridging tests. //===--- func getRoundtripBridgedNSDictionary() -> NSDictionary { let keys = [ 10, 20, 30 ].map { TestObjCKeyTy($0) } let values = [ 1010, 1020, 1030 ].map { TestObjCValueTy($0) } let nsd = NSDictionary(objects: values, forKeys: keys) let d: Dictionary<NSObject, AnyObject> = convertNSDictionaryToDictionary(nsd) let bridgedBack = convertDictionaryToNSDictionary(d) assert(isCocoaNSDictionary(bridgedBack)) // FIXME: this should be true. //assert(unsafeBitCast(nsd, Int.self) == unsafeBitCast(bridgedBack, Int.self)) return bridgedBack } DictionaryTestSuite.test("BridgingRoundtrip") { let d = getRoundtripBridgedNSDictionary() let enumerator = d.keyEnumerator() var pairs = Array<(key: Int, value: Int)>() while let key = enumerator.nextObject() { let value: AnyObject = d.object(forKey: key)! as AnyObject let kv = ((key as! TestObjCKeyTy).value, (value as! TestObjCValueTy).value) pairs.append(kv) } expectEqualsUnordered([ (10, 1010), (20, 1020), (30, 1030) ], pairs) } //===--- // NSDictionary -> Dictionary implicit conversion. //===--- DictionaryTestSuite.test("NSDictionaryToDictionaryConversion") { let keys = [ 10, 20, 30 ].map { TestObjCKeyTy($0) } let values = [ 1010, 1020, 1030 ].map { TestObjCValueTy($0) } let nsd = NSDictionary(objects: values, forKeys: keys) let d: Dictionary = nsd as Dictionary var pairs = Array<(Int, Int)>() for (key, value) in d { let kv = ((key as! TestObjCKeyTy).value, (value as! TestObjCValueTy).value) pairs.append(kv) } assert(equalsUnordered(pairs, [ (10, 1010), (20, 1020), (30, 1030) ])) } DictionaryTestSuite.test("DictionaryToNSDictionaryConversion") { var d = Dictionary<TestObjCKeyTy, TestObjCValueTy>(minimumCapacity: 32) d[TestObjCKeyTy(10)] = TestObjCValueTy(1010) d[TestObjCKeyTy(20)] = TestObjCValueTy(1020) d[TestObjCKeyTy(30)] = TestObjCValueTy(1030) checkDictionaryFastEnumerationFromSwift( [ (10, 1010), (20, 1020), (30, 1030) ], d as NSDictionary, { d as NSDictionary }, { ($0 as! TestObjCKeyTy).value }, { ($0 as! TestObjCValueTy).value }) expectAutoreleasedKeysAndValues(unopt: (0, 3)) } //===--- // Dictionary upcasts //===--- DictionaryTestSuite.test("DictionaryUpcastEntryPoint") { var d = Dictionary<TestObjCKeyTy, TestObjCValueTy>(minimumCapacity: 32) d[TestObjCKeyTy(10)] = TestObjCValueTy(1010) d[TestObjCKeyTy(20)] = TestObjCValueTy(1020) d[TestObjCKeyTy(30)] = TestObjCValueTy(1030) var dAsAnyObject: Dictionary<NSObject, AnyObject> = _dictionaryUpCast(d) assert(dAsAnyObject.count == 3) var v: AnyObject? = dAsAnyObject[TestObjCKeyTy(10)] assert((v! as! TestObjCValueTy).value == 1010) v = dAsAnyObject[TestObjCKeyTy(20)] assert((v! as! TestObjCValueTy).value == 1020) v = dAsAnyObject[TestObjCKeyTy(30)] assert((v! as! TestObjCValueTy).value == 1030) } DictionaryTestSuite.test("DictionaryUpcast") { var d = Dictionary<TestObjCKeyTy, TestObjCValueTy>(minimumCapacity: 32) d[TestObjCKeyTy(10)] = TestObjCValueTy(1010) d[TestObjCKeyTy(20)] = TestObjCValueTy(1020) d[TestObjCKeyTy(30)] = TestObjCValueTy(1030) var dAsAnyObject: Dictionary<NSObject, AnyObject> = d assert(dAsAnyObject.count == 3) var v: AnyObject? = dAsAnyObject[TestObjCKeyTy(10)] assert((v! as! TestObjCValueTy).value == 1010) v = dAsAnyObject[TestObjCKeyTy(20)] assert((v! as! TestObjCValueTy).value == 1020) v = dAsAnyObject[TestObjCKeyTy(30)] assert((v! as! TestObjCValueTy).value == 1030) } DictionaryTestSuite.test("DictionaryUpcastBridgedEntryPoint") { var d = Dictionary<TestBridgedKeyTy, TestBridgedValueTy>(minimumCapacity: 32) d[TestBridgedKeyTy(10)] = TestBridgedValueTy(1010) d[TestBridgedKeyTy(20)] = TestBridgedValueTy(1020) d[TestBridgedKeyTy(30)] = TestBridgedValueTy(1030) do { var dOO: Dictionary<NSObject, AnyObject> = _dictionaryBridgeToObjectiveC(d) assert(dOO.count == 3) var v: AnyObject? = dOO[TestObjCKeyTy(10)] assert((v! as! TestBridgedValueTy).value == 1010) v = dOO[TestObjCKeyTy(20)] assert((v! as! TestBridgedValueTy).value == 1020) v = dOO[TestObjCKeyTy(30)] assert((v! as! TestBridgedValueTy).value == 1030) } do { var dOV: Dictionary<NSObject, TestBridgedValueTy> = _dictionaryBridgeToObjectiveC(d) assert(dOV.count == 3) var v = dOV[TestObjCKeyTy(10)] assert(v!.value == 1010) v = dOV[TestObjCKeyTy(20)] assert(v!.value == 1020) v = dOV[TestObjCKeyTy(30)] assert(v!.value == 1030) } do { var dVO: Dictionary<TestBridgedKeyTy, AnyObject> = _dictionaryBridgeToObjectiveC(d) assert(dVO.count == 3) var v: AnyObject? = dVO[TestBridgedKeyTy(10)] assert((v! as! TestBridgedValueTy).value == 1010) v = dVO[TestBridgedKeyTy(20)] assert((v! as! TestBridgedValueTy).value == 1020) v = dVO[TestBridgedKeyTy(30)] assert((v! as! TestBridgedValueTy).value == 1030) } } DictionaryTestSuite.test("DictionaryUpcastBridged") { var d = Dictionary<TestBridgedKeyTy, TestBridgedValueTy>(minimumCapacity: 32) d[TestBridgedKeyTy(10)] = TestBridgedValueTy(1010) d[TestBridgedKeyTy(20)] = TestBridgedValueTy(1020) d[TestBridgedKeyTy(30)] = TestBridgedValueTy(1030) do { var dOO = d as Dictionary<NSObject, AnyObject> assert(dOO.count == 3) var v: AnyObject? = dOO[TestObjCKeyTy(10)] assert((v! as! TestBridgedValueTy).value == 1010) v = dOO[TestObjCKeyTy(20)] assert((v! as! TestBridgedValueTy).value == 1020) v = dOO[TestObjCKeyTy(30)] assert((v! as! TestBridgedValueTy).value == 1030) } do { var dOV = d as Dictionary<NSObject, TestBridgedValueTy> assert(dOV.count == 3) var v = dOV[TestObjCKeyTy(10)] assert(v!.value == 1010) v = dOV[TestObjCKeyTy(20)] assert(v!.value == 1020) v = dOV[TestObjCKeyTy(30)] assert(v!.value == 1030) } do { var dVO = d as Dictionary<TestBridgedKeyTy, AnyObject> assert(dVO.count == 3) var v: AnyObject? = dVO[TestBridgedKeyTy(10)] assert((v! as! TestBridgedValueTy).value == 1010) v = dVO[TestBridgedKeyTy(20)] assert((v! as! TestBridgedValueTy).value == 1020) v = dVO[TestBridgedKeyTy(30)] assert((v! as! TestBridgedValueTy).value == 1030) } } //===--- // Dictionary downcasts //===--- DictionaryTestSuite.test("DictionaryDowncastEntryPoint") { var d = Dictionary<NSObject, AnyObject>(minimumCapacity: 32) d[TestObjCKeyTy(10)] = TestObjCValueTy(1010) d[TestObjCKeyTy(20)] = TestObjCValueTy(1020) d[TestObjCKeyTy(30)] = TestObjCValueTy(1030) // Successful downcast. let dCC: Dictionary<TestObjCKeyTy, TestObjCValueTy> = _dictionaryDownCast(d) assert(dCC.count == 3) var v = dCC[TestObjCKeyTy(10)] assert(v!.value == 1010) v = dCC[TestObjCKeyTy(20)] assert(v!.value == 1020) v = dCC[TestObjCKeyTy(30)] assert(v!.value == 1030) expectAutoreleasedKeysAndValues(unopt: (0, 3)) } DictionaryTestSuite.test("DictionaryDowncast") { var d = Dictionary<NSObject, AnyObject>(minimumCapacity: 32) d[TestObjCKeyTy(10)] = TestObjCValueTy(1010) d[TestObjCKeyTy(20)] = TestObjCValueTy(1020) d[TestObjCKeyTy(30)] = TestObjCValueTy(1030) // Successful downcast. let dCC = d as! Dictionary<TestObjCKeyTy, TestObjCValueTy> assert(dCC.count == 3) var v = dCC[TestObjCKeyTy(10)] assert(v!.value == 1010) v = dCC[TestObjCKeyTy(20)] assert(v!.value == 1020) v = dCC[TestObjCKeyTy(30)] assert(v!.value == 1030) expectAutoreleasedKeysAndValues(unopt: (0, 3)) } DictionaryTestSuite.test("DictionaryDowncastConditionalEntryPoint") { var d = Dictionary<NSObject, AnyObject>(minimumCapacity: 32) d[TestObjCKeyTy(10)] = TestObjCValueTy(1010) d[TestObjCKeyTy(20)] = TestObjCValueTy(1020) d[TestObjCKeyTy(30)] = TestObjCValueTy(1030) // Successful downcast. if let dCC = _dictionaryDownCastConditional(d) as Dictionary<TestObjCKeyTy, TestObjCValueTy>? { assert(dCC.count == 3) var v = dCC[TestObjCKeyTy(10)] assert(v!.value == 1010) v = dCC[TestObjCKeyTy(20)] assert(v!.value == 1020) v = dCC[TestObjCKeyTy(30)] assert(v!.value == 1030) } else { assert(false) } // Unsuccessful downcast d["hello" as NSString] = 17 as NSNumber if let _ = _dictionaryDownCastConditional(d) as Dictionary<TestObjCKeyTy, TestObjCValueTy>? { assert(false) } } DictionaryTestSuite.test("DictionaryDowncastConditional") { var d = Dictionary<NSObject, AnyObject>(minimumCapacity: 32) d[TestObjCKeyTy(10)] = TestObjCValueTy(1010) d[TestObjCKeyTy(20)] = TestObjCValueTy(1020) d[TestObjCKeyTy(30)] = TestObjCValueTy(1030) // Successful downcast. if let dCC = d as? Dictionary<TestObjCKeyTy, TestObjCValueTy> { assert(dCC.count == 3) var v = dCC[TestObjCKeyTy(10)] assert(v!.value == 1010) v = dCC[TestObjCKeyTy(20)] assert(v!.value == 1020) v = dCC[TestObjCKeyTy(30)] assert(v!.value == 1030) } else { assert(false) } // Unsuccessful downcast d["hello" as NSString] = 17 as NSNumber if d is Dictionary<TestObjCKeyTy, TestObjCValueTy> { assert(false) } } DictionaryTestSuite.test("DictionaryBridgeFromObjectiveCEntryPoint") { var d = Dictionary<NSObject, AnyObject>(minimumCapacity: 32) d[TestObjCKeyTy(10)] = TestObjCValueTy(1010) d[TestObjCKeyTy(20)] = TestObjCValueTy(1020) d[TestObjCKeyTy(30)] = TestObjCValueTy(1030) // Successful downcast. let dCV: Dictionary<TestObjCKeyTy, TestBridgedValueTy> = _dictionaryBridgeFromObjectiveC(d) do { assert(dCV.count == 3) var v = dCV[TestObjCKeyTy(10)] assert(v!.value == 1010) v = dCV[TestObjCKeyTy(20)] assert(v!.value == 1020) v = dCV[TestObjCKeyTy(30)] assert(v!.value == 1030) } // Successful downcast. let dVC: Dictionary<TestBridgedKeyTy, TestObjCValueTy> = _dictionaryBridgeFromObjectiveC(d) do { assert(dVC.count == 3) var v = dVC[TestBridgedKeyTy(10)] assert(v!.value == 1010) v = dVC[TestBridgedKeyTy(20)] assert(v!.value == 1020) v = dVC[TestBridgedKeyTy(30)] assert(v!.value == 1030) } // Successful downcast. let dVV: Dictionary<TestBridgedKeyTy, TestBridgedValueTy> = _dictionaryBridgeFromObjectiveC(d) do { assert(dVV.count == 3) var v = dVV[TestBridgedKeyTy(10)] assert(v!.value == 1010) v = dVV[TestBridgedKeyTy(20)] assert(v!.value == 1020) v = dVV[TestBridgedKeyTy(30)] assert(v!.value == 1030) } } DictionaryTestSuite.test("DictionaryBridgeFromObjectiveC") { var d = Dictionary<NSObject, AnyObject>(minimumCapacity: 32) d[TestObjCKeyTy(10)] = TestObjCValueTy(1010) d[TestObjCKeyTy(20)] = TestObjCValueTy(1020) d[TestObjCKeyTy(30)] = TestObjCValueTy(1030) // Successful downcast. let dCV = d as! Dictionary<TestObjCKeyTy, TestBridgedValueTy> do { assert(dCV.count == 3) var v = dCV[TestObjCKeyTy(10)] assert(v!.value == 1010) v = dCV[TestObjCKeyTy(20)] assert(v!.value == 1020) v = dCV[TestObjCKeyTy(30)] assert(v!.value == 1030) } // Successful downcast. let dVC = d as! Dictionary<TestBridgedKeyTy, TestObjCValueTy> do { assert(dVC.count == 3) var v = dVC[TestBridgedKeyTy(10)] assert(v!.value == 1010) v = dVC[TestBridgedKeyTy(20)] assert(v!.value == 1020) v = dVC[TestBridgedKeyTy(30)] assert(v!.value == 1030) } // Successful downcast. let dVV = d as! Dictionary<TestBridgedKeyTy, TestBridgedValueTy> do { assert(dVV.count == 3) var v = dVV[TestBridgedKeyTy(10)] assert(v!.value == 1010) v = dVV[TestBridgedKeyTy(20)] assert(v!.value == 1020) v = dVV[TestBridgedKeyTy(30)] assert(v!.value == 1030) } } DictionaryTestSuite.test("DictionaryBridgeFromObjectiveCConditionalEntryPoint") { var d = Dictionary<NSObject, AnyObject>(minimumCapacity: 32) d[TestObjCKeyTy(10)] = TestObjCValueTy(1010) d[TestObjCKeyTy(20)] = TestObjCValueTy(1020) d[TestObjCKeyTy(30)] = TestObjCValueTy(1030) // Successful downcast. if let dCV = _dictionaryBridgeFromObjectiveCConditional(d) as Dictionary<TestObjCKeyTy, TestBridgedValueTy>? { assert(dCV.count == 3) var v = dCV[TestObjCKeyTy(10)] assert(v!.value == 1010) v = dCV[TestObjCKeyTy(20)] assert(v!.value == 1020) v = dCV[TestObjCKeyTy(30)] assert(v!.value == 1030) } else { assert(false) } // Successful downcast. if let dVC = _dictionaryBridgeFromObjectiveCConditional(d) as Dictionary<TestBridgedKeyTy, TestObjCValueTy>? { assert(dVC.count == 3) var v = dVC[TestBridgedKeyTy(10)] assert(v!.value == 1010) v = dVC[TestBridgedKeyTy(20)] assert(v!.value == 1020) v = dVC[TestBridgedKeyTy(30)] assert(v!.value == 1030) } else { assert(false) } // Successful downcast. if let dVV = _dictionaryBridgeFromObjectiveCConditional(d) as Dictionary<TestBridgedKeyTy, TestBridgedValueTy>? { assert(dVV.count == 3) var v = dVV[TestBridgedKeyTy(10)] assert(v!.value == 1010) v = dVV[TestBridgedKeyTy(20)] assert(v!.value == 1020) v = dVV[TestBridgedKeyTy(30)] assert(v!.value == 1030) } else { assert(false) } // Unsuccessful downcasts d["hello" as NSString] = 17 as NSNumber if let _ = _dictionaryBridgeFromObjectiveCConditional(d) as Dictionary<TestObjCKeyTy, TestBridgedValueTy>?{ assert(false) } if let _ = _dictionaryBridgeFromObjectiveCConditional(d) as Dictionary<TestBridgedKeyTy, TestObjCValueTy>?{ assert(false) } if let _ = _dictionaryBridgeFromObjectiveCConditional(d) as Dictionary<TestBridgedKeyTy, TestBridgedValueTy>?{ assert(false) } } DictionaryTestSuite.test("DictionaryBridgeFromObjectiveCConditional") { var d = Dictionary<NSObject, AnyObject>(minimumCapacity: 32) d[TestObjCKeyTy(10)] = TestObjCValueTy(1010) d[TestObjCKeyTy(20)] = TestObjCValueTy(1020) d[TestObjCKeyTy(30)] = TestObjCValueTy(1030) // Successful downcast. if let dCV = d as? Dictionary<TestObjCKeyTy, TestBridgedValueTy> { assert(dCV.count == 3) var v = dCV[TestObjCKeyTy(10)] assert(v!.value == 1010) v = dCV[TestObjCKeyTy(20)] assert(v!.value == 1020) v = dCV[TestObjCKeyTy(30)] assert(v!.value == 1030) } else { assert(false) } // Successful downcast. if let dVC = d as? Dictionary<TestBridgedKeyTy, TestObjCValueTy> { assert(dVC.count == 3) var v = dVC[TestBridgedKeyTy(10)] assert(v!.value == 1010) v = dVC[TestBridgedKeyTy(20)] assert(v!.value == 1020) v = dVC[TestBridgedKeyTy(30)] assert(v!.value == 1030) } else { assert(false) } // Successful downcast. if let dVV = d as? Dictionary<TestBridgedKeyTy, TestBridgedValueTy> { assert(dVV.count == 3) var v = dVV[TestBridgedKeyTy(10)] assert(v!.value == 1010) v = dVV[TestBridgedKeyTy(20)] assert(v!.value == 1020) v = dVV[TestBridgedKeyTy(30)] assert(v!.value == 1030) } else { assert(false) } // Unsuccessful downcasts d["hello" as NSString] = 17 as NSNumber if d is Dictionary<TestObjCKeyTy, TestBridgedValueTy> { assert(false) } if d is Dictionary<TestBridgedKeyTy, TestObjCValueTy> { assert(false) } if d is Dictionary<TestBridgedKeyTy, TestBridgedValueTy> { assert(false) } } #endif // _runtime(_ObjC) //===--- // Tests for APIs implemented strictly based on public interface. We only need // to test them once, not for every storage type. //===--- func getDerivedAPIsDictionary() -> Dictionary<Int, Int> { var d = Dictionary<Int, Int>(minimumCapacity: 10) d[10] = 1010 d[20] = 1020 d[30] = 1030 return d } var DictionaryDerivedAPIs = TestSuite("DictionaryDerivedAPIs") DictionaryDerivedAPIs.test("isEmpty") { do { let empty = Dictionary<Int, Int>() expectTrue(empty.isEmpty) } do { let d = getDerivedAPIsDictionary() expectFalse(d.isEmpty) } } #if _runtime(_ObjC) @objc class MockDictionaryWithCustomCount : NSDictionary { init(count: Int) { self._count = count super.init() } override init() { expectUnreachable() super.init() } override init( objects: UnsafePointer<AnyObject>?, forKeys keys: UnsafePointer<NSCopying>?, count: Int) { expectUnreachable() super.init(objects: objects, forKeys: keys, count: count) } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) not implemented by MockDictionaryWithCustomCount") } @objc(copyWithZone:) override func copy(with zone: NSZone?) -> Any { // Ensure that copying this dictionary produces an object of the same // dynamic type. return self } override func object(forKey aKey: Any) -> Any? { expectUnreachable() return NSObject() } override var count: Int { MockDictionaryWithCustomCount.timesCountWasCalled += 1 return _count } var _count: Int = 0 static var timesCountWasCalled = 0 } func getMockDictionaryWithCustomCount(count: Int) -> Dictionary<NSObject, AnyObject> { return MockDictionaryWithCustomCount(count: count) as Dictionary } func callGenericIsEmpty<C : Collection>(_ collection: C) -> Bool { return collection.isEmpty } DictionaryDerivedAPIs.test("isEmpty/ImplementationIsCustomized") { do { let d = getMockDictionaryWithCustomCount(count: 0) MockDictionaryWithCustomCount.timesCountWasCalled = 0 expectTrue(d.isEmpty) expectEqual(1, MockDictionaryWithCustomCount.timesCountWasCalled) } do { let d = getMockDictionaryWithCustomCount(count: 0) MockDictionaryWithCustomCount.timesCountWasCalled = 0 expectTrue(callGenericIsEmpty(d)) expectEqual(1, MockDictionaryWithCustomCount.timesCountWasCalled) } do { let d = getMockDictionaryWithCustomCount(count: 4) MockDictionaryWithCustomCount.timesCountWasCalled = 0 expectFalse(d.isEmpty) expectEqual(1, MockDictionaryWithCustomCount.timesCountWasCalled) } do { let d = getMockDictionaryWithCustomCount(count: 4) MockDictionaryWithCustomCount.timesCountWasCalled = 0 expectFalse(callGenericIsEmpty(d)) expectEqual(1, MockDictionaryWithCustomCount.timesCountWasCalled) } } #endif // _runtime(_ObjC) DictionaryDerivedAPIs.test("keys") { do { let empty = Dictionary<Int, Int>() let keys = Array(empty.keys) expectTrue(equalsUnordered(keys, [])) } do { let d = getDerivedAPIsDictionary() let keys = Array(d.keys) expectTrue(equalsUnordered(keys, [ 10, 20, 30 ])) } } DictionaryDerivedAPIs.test("values") { do { let empty = Dictionary<Int, Int>() let values = Array(empty.values) expectTrue(equalsUnordered(values, [])) } do { var d = getDerivedAPIsDictionary() var values = Array(d.values) expectTrue(equalsUnordered(values, [ 1010, 1020, 1030 ])) d[11] = 1010 values = Array(d.values) expectTrue(equalsUnordered(values, [ 1010, 1010, 1020, 1030 ])) } } #if _runtime(_ObjC) var ObjCThunks = TestSuite("ObjCThunks") class ObjCThunksHelper : NSObject { @objc dynamic func acceptArrayBridgedVerbatim(_ array: [TestObjCValueTy]) { expectEqual(10, array[0].value) expectEqual(20, array[1].value) expectEqual(30, array[2].value) } @objc dynamic func acceptArrayBridgedNonverbatim(_ array: [TestBridgedValueTy]) { // Cannot check elements because doing so would bridge them. expectEqual(3, array.count) } @objc dynamic func returnArrayBridgedVerbatim() -> [TestObjCValueTy] { return [ TestObjCValueTy(10), TestObjCValueTy(20), TestObjCValueTy(30) ] } @objc dynamic func returnArrayBridgedNonverbatim() -> [TestBridgedValueTy] { return [ TestBridgedValueTy(10), TestBridgedValueTy(20), TestBridgedValueTy(30) ] } @objc dynamic func acceptDictionaryBridgedVerbatim( _ d: [TestObjCKeyTy : TestObjCValueTy]) { expectEqual(3, d.count) expectEqual(1010, d[TestObjCKeyTy(10)]!.value) expectEqual(1020, d[TestObjCKeyTy(20)]!.value) expectEqual(1030, d[TestObjCKeyTy(30)]!.value) } @objc dynamic func acceptDictionaryBridgedNonverbatim( _ d: [TestBridgedKeyTy : TestBridgedValueTy]) { expectEqual(3, d.count) // Cannot check elements because doing so would bridge them. } @objc dynamic func returnDictionaryBridgedVerbatim() -> [TestObjCKeyTy : TestObjCValueTy] { return [ TestObjCKeyTy(10): TestObjCValueTy(1010), TestObjCKeyTy(20): TestObjCValueTy(1020), TestObjCKeyTy(30): TestObjCValueTy(1030), ] } @objc dynamic func returnDictionaryBridgedNonverbatim() -> [TestBridgedKeyTy : TestBridgedValueTy] { return [ TestBridgedKeyTy(10): TestBridgedValueTy(1010), TestBridgedKeyTy(20): TestBridgedValueTy(1020), TestBridgedKeyTy(30): TestBridgedValueTy(1030), ] } } ObjCThunks.test("Array/Accept") { let helper = ObjCThunksHelper() do { helper.acceptArrayBridgedVerbatim( [ TestObjCValueTy(10), TestObjCValueTy(20), TestObjCValueTy(30) ]) } do { TestBridgedValueTy.bridgeOperations = 0 helper.acceptArrayBridgedNonverbatim( [ TestBridgedValueTy(10), TestBridgedValueTy(20), TestBridgedValueTy(30) ]) expectEqual(0, TestBridgedValueTy.bridgeOperations) } } ObjCThunks.test("Array/Return") { let helper = ObjCThunksHelper() do { let a = helper.returnArrayBridgedVerbatim() expectEqual(10, a[0].value) expectEqual(20, a[1].value) expectEqual(30, a[2].value) } do { TestBridgedValueTy.bridgeOperations = 0 let a = helper.returnArrayBridgedNonverbatim() expectEqual(0, TestBridgedValueTy.bridgeOperations) TestBridgedValueTy.bridgeOperations = 0 expectEqual(10, a[0].value) expectEqual(20, a[1].value) expectEqual(30, a[2].value) expectEqual(0, TestBridgedValueTy.bridgeOperations) } } ObjCThunks.test("Dictionary/Accept") { let helper = ObjCThunksHelper() do { helper.acceptDictionaryBridgedVerbatim( [ TestObjCKeyTy(10): TestObjCValueTy(1010), TestObjCKeyTy(20): TestObjCValueTy(1020), TestObjCKeyTy(30): TestObjCValueTy(1030) ]) } do { TestBridgedKeyTy.bridgeOperations = 0 TestBridgedValueTy.bridgeOperations = 0 helper.acceptDictionaryBridgedNonverbatim( [ TestBridgedKeyTy(10): TestBridgedValueTy(1010), TestBridgedKeyTy(20): TestBridgedValueTy(1020), TestBridgedKeyTy(30): TestBridgedValueTy(1030) ]) expectEqual(0, TestBridgedKeyTy.bridgeOperations) expectEqual(0, TestBridgedValueTy.bridgeOperations) } } ObjCThunks.test("Dictionary/Return") { let helper = ObjCThunksHelper() do { let d = helper.returnDictionaryBridgedVerbatim() expectEqual(3, d.count) expectEqual(1010, d[TestObjCKeyTy(10)]!.value) expectEqual(1020, d[TestObjCKeyTy(20)]!.value) expectEqual(1030, d[TestObjCKeyTy(30)]!.value) } do { TestBridgedKeyTy.bridgeOperations = 0 TestBridgedValueTy.bridgeOperations = 0 let d = helper.returnDictionaryBridgedNonverbatim() expectEqual(0, TestBridgedKeyTy.bridgeOperations) expectEqual(0, TestBridgedValueTy.bridgeOperations) TestBridgedKeyTy.bridgeOperations = 0 TestBridgedValueTy.bridgeOperations = 0 expectEqual(3, d.count) expectEqual(1010, d[TestBridgedKeyTy(10)]!.value) expectEqual(1020, d[TestBridgedKeyTy(20)]!.value) expectEqual(1030, d[TestBridgedKeyTy(30)]!.value) expectEqual(0, TestBridgedKeyTy.bridgeOperations) expectEqual(0, TestBridgedValueTy.bridgeOperations) } } #endif // _runtime(_ObjC) //===--- // Check that iterators traverse a snapshot of the collection. //===--- DictionaryTestSuite.test("mutationDoesNotAffectIterator/subscript/store") { var dict = getDerivedAPIsDictionary() let iter = dict.makeIterator() dict[10] = 1011 expectEqualsUnordered( [ (10, 1010), (20, 1020), (30, 1030) ], Array(IteratorSequence(iter))) } DictionaryTestSuite.test("mutationDoesNotAffectIterator/removeValueForKey,1") { var dict = getDerivedAPIsDictionary() let iter = dict.makeIterator() expectOptionalEqual(1010, dict.removeValue(forKey: 10)) expectEqualsUnordered( [ (10, 1010), (20, 1020), (30, 1030) ], Array(IteratorSequence(iter))) } DictionaryTestSuite.test("mutationDoesNotAffectIterator/removeValueForKey,all") { var dict = getDerivedAPIsDictionary() let iter = dict.makeIterator() expectOptionalEqual(1010, dict.removeValue(forKey: 10)) expectOptionalEqual(1020, dict.removeValue(forKey: 20)) expectOptionalEqual(1030, dict.removeValue(forKey: 30)) expectEqualsUnordered( [ (10, 1010), (20, 1020), (30, 1030) ], Array(IteratorSequence(iter))) } DictionaryTestSuite.test( "mutationDoesNotAffectIterator/removeAll,keepingCapacity=false") { var dict = getDerivedAPIsDictionary() let iter = dict.makeIterator() dict.removeAll(keepingCapacity: false) expectEqualsUnordered( [ (10, 1010), (20, 1020), (30, 1030) ], Array(IteratorSequence(iter))) } DictionaryTestSuite.test( "mutationDoesNotAffectIterator/removeAll,keepingCapacity=true") { var dict = getDerivedAPIsDictionary() let iter = dict.makeIterator() dict.removeAll(keepingCapacity: true) expectEqualsUnordered( [ (10, 1010), (20, 1020), (30, 1030) ], Array(IteratorSequence(iter))) } //===--- // Misc tests. //===--- DictionaryTestSuite.test("misc") { do { // Dictionary literal var dict = ["Hello": 1, "World": 2] // Insertion dict["Swift"] = 3 // Access expectOptionalEqual(1, dict["Hello"]) expectOptionalEqual(2, dict["World"]) expectOptionalEqual(3, dict["Swift"]) expectNil(dict["Universe"]) // Overwriting existing value dict["Hello"] = 0 expectOptionalEqual(0, dict["Hello"]) expectOptionalEqual(2, dict["World"]) expectOptionalEqual(3, dict["Swift"]) expectNil(dict["Universe"]) } do { // Dictionaries with other types var d = [ 1.2: 1, 2.6: 2 ] d[3.3] = 3 expectOptionalEqual(1, d[1.2]) expectOptionalEqual(2, d[2.6]) expectOptionalEqual(3, d[3.3]) } do { var d = Dictionary<String, Int>(minimumCapacity: 13) d["one"] = 1 d["two"] = 2 d["three"] = 3 d["four"] = 4 d["five"] = 5 expectOptionalEqual(1, d["one"]) expectOptionalEqual(2, d["two"]) expectOptionalEqual(3, d["three"]) expectOptionalEqual(4, d["four"]) expectOptionalEqual(5, d["five"]) // Iterate over (key, value) tuples as a silly copy var d3 = Dictionary<String,Int>(minimumCapacity: 13) for (k, v) in d { d3[k] = v } expectOptionalEqual(1, d3["one"]) expectOptionalEqual(2, d3["two"]) expectOptionalEqual(3, d3["three"]) expectOptionalEqual(4, d3["four"]) expectOptionalEqual(5, d3["five"]) expectEqual(3, d.values[d.keys.firstIndex(of: "three")!]) expectEqual(4, d.values[d.keys.firstIndex(of: "four")!]) expectEqual(3, d3.values[d3.keys.firstIndex(of: "three")!]) expectEqual(4, d3.values[d3.keys.firstIndex(of: "four")!]) } } #if _runtime(_ObjC) DictionaryTestSuite.test("dropsBridgedCache") { // rdar://problem/18544533 // Previously this code would segfault due to a double free in the Dictionary // implementation. // This test will only fail in address sanitizer. var dict = [0:10] do { let bridged: NSDictionary = dict as NSDictionary expectEqual(10, bridged[0 as NSNumber] as! Int) } dict[0] = 11 do { let bridged: NSDictionary = dict as NSDictionary expectEqual(11, bridged[0 as NSNumber] as! Int) } } DictionaryTestSuite.test("getObjects:andKeys:count:") { let native = [1: "one", 2: "two"] as Dictionary<Int, String> let d = native as NSDictionary let keys = UnsafeMutableBufferPointer( start: UnsafeMutablePointer<NSNumber>.allocate(capacity: 2), count: 2) let values = UnsafeMutableBufferPointer( start: UnsafeMutablePointer<NSString>.allocate(capacity: 2), count: 2) let kp = AutoreleasingUnsafeMutablePointer<AnyObject?>(keys.baseAddress!) let vp = AutoreleasingUnsafeMutablePointer<AnyObject?>(values.baseAddress!) let null: AutoreleasingUnsafeMutablePointer<AnyObject?>? = nil let expectedKeys: [NSNumber] let expectedValues: [NSString] if native.first?.key == 1 { expectedKeys = [1, 2] expectedValues = ["one", "two"] } else { expectedKeys = [2, 1] expectedValues = ["two", "one"] } d.available_getObjects(null, andKeys: null, count: 2) // don't segfault d.available_getObjects(null, andKeys: kp, count: 2) expectEqual(expectedKeys, Array(keys)) d.available_getObjects(vp, andKeys: null, count: 2) expectEqual(expectedValues, Array(values)) d.available_getObjects(vp, andKeys: kp, count: 2) expectEqual(expectedKeys, Array(keys)) expectEqual(expectedValues, Array(values)) } #endif DictionaryTestSuite.test("popFirst") { // Empty do { var d = [Int: Int]() let popped = d.popFirst() expectNil(popped) } do { var popped = [(Int, Int)]() var d: [Int: Int] = [ 1010: 1010, 2020: 2020, 3030: 3030, ] let expected = [(1010, 1010), (2020, 2020), (3030, 3030)] while let element = d.popFirst() { popped.append(element) } // Note that removing an element may reorder remaining items, so we // can't compare ordering here. popped.sort(by: { $0.0 < $1.0 }) expectEqualSequence(expected, popped) { (lhs: (Int, Int), rhs: (Int, Int)) -> Bool in lhs.0 == rhs.0 && lhs.1 == rhs.1 } expectTrue(d.isEmpty) } } DictionaryTestSuite.test("removeAt") { // Test removing from the startIndex, the middle, and the end of a dictionary. for i in 1...3 { var d: [Int: Int] = [ 10: 1010, 20: 2020, 30: 3030, ] let removed = d.remove(at: d.index(forKey: i*10)!) expectEqual(i*10, removed.0) expectEqual(i*1010, removed.1) expectEqual(2, d.count) expectNil(d.index(forKey: i)) let origKeys: [Int] = [10, 20, 30] expectEqual(origKeys.filter { $0 != (i*10) }, d.keys.sorted()) } } DictionaryTestSuite.test("localHashSeeds") { // With global hashing, copying elements in hash order between hash tables // can become quadratic. (See https://bugs.swift.org/browse/SR-3268) // // We defeat this by mixing the local storage capacity into the global hash // seed, thereby breaking the correlation between bucket indices across // hash tables with different sizes. // // Verify this works by copying a small sampling of elements near the // beginning of a large Dictionary into a smaller one. If the elements end up // in the same order in the smaller Dictionary, then that indicates we do not // use size-dependent seeding. let count = 100_000 // Set a large table size to reduce frequency/length of collision chains. var large = [Int: Int](minimumCapacity: 4 * count) for i in 1 ..< count { large[i] = 2 * i } let bunch = count / 100 // 1 percent's worth of elements // Copy two bunches of elements into another dictionary that's half the size // of the first. We start after the initial bunch because the hash table may // begin with collided elements wrapped over from the end, and these would be // sorted into irregular slots in the smaller table. let slice = large.prefix(3 * bunch).dropFirst(bunch) var small = [Int: Int](minimumCapacity: large.capacity / 2) expectLT(small.capacity, large.capacity) for (key, value) in slice { small[key] = value } // Compare the second halves of the new dictionary and the slice. Ignore the // first halves; the first few elements may not be in the correct order if we // happened to start copying from the middle of a collision chain. let smallKeys = small.dropFirst(bunch).map { $0.key } let sliceKeys = slice.dropFirst(bunch).map { $0.key } // If this test fails, there is a problem with local hash seeding. expectFalse(smallKeys.elementsEqual(sliceKeys)) } DictionaryTestSuite.test("Hashable") { let d1: [Dictionary<Int, String>] = [ [1: "meow", 2: "meow", 3: "meow"], [1: "meow", 2: "meow", 3: "mooo"], [1: "meow", 2: "meow", 4: "meow"], [1: "meow", 2: "meow", 4: "mooo"]] checkHashable(d1, equalityOracle: { $0 == $1 }) let d2: [Dictionary<Int, Dictionary<Int, String>>] = [ [1: [2: "meow"]], [2: [1: "meow"]], [2: [2: "meow"]], [1: [1: "meow"]], [2: [2: "mooo"]], [2: [:]], [:]] checkHashable(d2, equalityOracle: { $0 == $1 }) // Dictionary should hash itself in a way that ensures instances get correctly // delineated even when they are nested in other commutative collections. // These are different Sets, so they should produce different hashes: let remix: [Set<Dictionary<String, Int>>] = [ [["Blanche": 1, "Rose": 2], ["Dorothy": 3, "Sophia": 4]], [["Blanche": 1, "Dorothy": 3], ["Rose": 2, "Sophia": 4]], [["Blanche": 1, "Sophia": 4], ["Rose": 2, "Dorothy": 3]] ] checkHashable(remix, equalityOracle: { $0 == $1 }) // Dictionary ordering is not guaranteed to be consistent across equal // instances. In particular, ordering is highly sensitive to the size of the // allocated storage buffer. Generate a few copies of the same dictionary with // different capacities, and verify that they compare and hash the same. var variants: [Dictionary<String, Int>] = [] for i in 4 ..< 12 { var set: Dictionary<String, Int> = [ "one": 1, "two": 2, "three": 3, "four": 4, "five": 5, "six": 6] set.reserveCapacity(1 << i) variants.append(set) } checkHashable(variants, equalityOracle: { _, _ in true }) } DictionaryTestSuite.setUp { #if _runtime(_ObjC) // Exercise ARC's autoreleased return value optimization in Foundation. // // On some platforms, when a new process is started, the optimization is // expected to fail the first time it is used in each linked // dylib. StdlibUnittest takes care of warming up ARC for the stdlib // (libswiftCore.dylib), but for this particular test we also need to do it // for Foundation, or there will be spurious leaks reported for tests // immediately following a crash test. // // <rdar://problem/42069800> stdlib tests: expectCrashLater() interferes with // counting autoreleased live objects let d = NSDictionary(objects: [1 as NSNumber], forKeys: [1 as NSNumber]) _ = d.object(forKey: 1 as NSNumber) #endif resetLeaksOfDictionaryKeysValues() #if _runtime(_ObjC) resetLeaksOfObjCDictionaryKeysValues() #endif } DictionaryTestSuite.tearDown { expectNoLeaksOfDictionaryKeysValues() #if _runtime(_ObjC) expectNoLeaksOfObjCDictionaryKeysValues() #endif } runAllTests()
apache-2.0
44a4bbc5ecf69709d6d05c6fd9cdfef1
28.493915
285
0.675958
3.974553
false
true
false
false
zmian/xcore.swift
Sources/Xcore/Cocoa/Components/Currency/CurrencyFormatter/CurrencyFormatter+Format.swift
1
4820
// // Xcore // Copyright © 2017 Xcore // MIT license, see LICENSE file for details // import SwiftUI extension CurrencyFormatter { /// Returns a string representation of a given money formatted using money /// properties. /// /// - Parameters: /// - money: The money to format. /// - Returns: A string representation of the given money. public func string( from money: Money, fractionLength limits: ClosedRange<Int>, format: String? = nil ) -> String { let amountString = components( from: money.amount, fractionLength: limits, sign: money.sign ) .joined(style: money.style) guard let format = format else { return amountString } return String(format: format, amountString) } public func attributedString(from money: Money, format: String? = nil) -> NSMutableAttributedString { let formattedMoney = _attributedString(from: money) guard let format = format else { return formattedMoney } let range = (format as NSString).range(of: "%@") guard range.length > 0 else { return formattedMoney } let mainFormat = NSMutableAttributedString(string: format, attributes: majorUnitFont(money)) mainFormat.replaceCharacters(in: range, with: formattedMoney) return mainFormat } } extension CurrencyFormatter { private func _attributedString(from money: Money) -> NSMutableAttributedString { let attributedString = _attributedStringWithoutColor(from: money) guard let foregroundColor = money.foregroundColor else { return attributedString } return attributedString.foregroundColor(UIColor(foregroundColor)) } private func _attributedStringWithoutColor(from money: Money) -> NSMutableAttributedString { let amount = money.amount if amount == 0, !money.shouldDisplayZero { return NSMutableAttributedString(string: " " + money.zeroString) } let components = self.components(from: amount, fractionLength: money.fractionLength, sign: money.sign) let joinedAmount = components.joined(style: money.style) let attributedString = NSMutableAttributedString( string: joinedAmount, attributes: majorUnitFont(money) ) guard money.shouldSuperscriptMinorUnit else { return attributedString } if let minorUnitRange = components.range(style: money.style).minorUnit { attributedString.setAttributes(minorUnitFont(money), range: minorUnitRange) } return attributedString } } // MARK: - Helpers extension CurrencyFormatter { private func majorUnitFont(_ money: Money) -> [NSAttributedString.Key: Any] { [.font: money.font.majorUnit].compactMapValues { $0 } } private func minorUnitFont(_ money: Money) -> [NSAttributedString.Key: Any] { let attributes: [NSAttributedString.Key: Any?] = [ .font: money.font.minorUnit, .baselineOffset: money.font.minorUnitOffset ] return attributes.compactMapValues { $0 } } } extension Money { fileprivate var foregroundColor: SwiftUI.Color? { guard color != .none else { return nil } var foregroundColor: SwiftUI.Color if amount == 0 { foregroundColor = color.zero } else { foregroundColor = amount > 0 ? color.positive : color.negative } return foregroundColor } } // MARK: - SwiftUI Support extension Money: View { public var body: some View { if amount == 0, !shouldDisplayZero { Text(zeroString) } else { let components = formatter.components(from: amount, fractionLength: fractionLength, sign: sign) let joinedAmount = components.joined(style: style) Text(joinedAmount) .unwrap(font.majorUnit) { view, value in view.font(SwiftUI.Font(value)) } .unwrap(foregroundColor) { view, color in view.foregroundColor(color) } // .applyIf(shouldSuperscriptMinorUnit) { // EmptyView() // } } } } // TODO: Add support for "shouldSuperscriptMinorUnit" /* extension String { func rangeFromNSRange(nsRange : NSRange) -> Range<String.Index>? { Range(nsRange, in: self) } } let amount = money.amount if let minorUnitRange = components.range(style: money.style).minorUnit { attributedString.setAttributes(minorUnitFont(money), range: minorUnitRange) } return attributedString */
mit
d1240756ed5e8c83b1b817b19c653527
27.856287
110
0.619423
4.892386
false
false
false
false
biohazardlover/ROer
Roer/DatabaseRecordCell.swift
1
1213
import UIKit import SDWebImage class DatabaseRecordCell: UITableViewCell { @IBOutlet var stackView: UIStackView! @IBOutlet var recordImageView: UIImageView! @IBOutlet var recordNameLabel: UILabel! @IBOutlet var extraLabel: UILabel! var cellInfo: DatabaseRecordCellInfo? { didSet { if let imageURL = cellInfo?.databaseRecord.smallImageURL { layoutMargins = UIEdgeInsets(top: 0, left: 47, bottom: 0, right: 0) stackView.insertArrangedSubview(recordImageView, at: 0) recordImageView.sd_setImage(with: imageURL) } else { layoutMargins = UIEdgeInsets(top: 0, left: 15, bottom: 0, right: 0) stackView.removeArrangedSubview(recordImageView) recordImageView.removeFromSuperview() recordImageView.image = nil } recordNameLabel.text = cellInfo?.databaseRecord.displayName extraLabel.text = cellInfo?.extra } } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) layoutMargins = UIEdgeInsets(top: 0, left: 47, bottom: 0, right: 0) } }
mit
e0037378a306099bf8a58467b4d97003
33.657143
83
0.617477
5.012397
false
false
false
false
PodBuilder/SwiftDataHash
SwiftDataHashTests/SwiftDataHashTests.swift
1
5591
// // SwiftDataHashTests.swift // SwiftDataHashTests // // Created by William Kent on 1/6/15. // Copyright (c) 2015 William Kent. All rights reserved. // import Foundation import XCTest import SwiftDataHash class SwiftDataHashTests: XCTestCase { // The implicitly-unwrapped optionals here are required, else the compiler complains. private var inputData: NSData! private var keyData: NSData! private func hashDataToHexString(data: NSData) -> String { let hexstr = NSMutableString() let bytes = UnsafePointer<UInt8>(data.bytes) for i in 0..<data.length { hexstr.appendFormat("%02x", bytes[i]) } return hexstr } override func setUp() { let inputString = "test" if let input = inputString.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true) { inputData = input } else { XCTFail("Could not get UTF-8 data of \(inputString)") } let inputKey = "key" if let key = inputKey.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true) { keyData = key } else { XCTFail("Could not get UTF-8 data of \(inputKey)") } } func testMD5Algorithm() { let computedHash = inputData.computeHashUsingAlgorithm(.MD5) let expectedHash = "098f6bcd4621d373cade4e832627b4f6" XCTAssertEqual(hashDataToHexString(computedHash), expectedHash, "MD5 hash function returned incorrect value") } func testSHA1Algorithm() { let computedHash = inputData.computeHashUsingAlgorithm(.SHA1) let expectedHash = "a94a8fe5ccb19ba61c4c0873d391e987982fbbd3" XCTAssertEqual(hashDataToHexString(computedHash), expectedHash, "SHA1 hash function returned incorrect value") } func testSHA224Algorithm() { let computedHash = inputData.computeHashUsingAlgorithm(.SHA224) let expectedHash = "90a3ed9e32b2aaf4c61c410eb925426119e1a9dc53d4286ade99a809" XCTAssertEqual(hashDataToHexString(computedHash), expectedHash, "SHA224 hash function returned incorrect value") } func testSHA256Algorithm() { let computedHash = inputData.computeHashUsingAlgorithm(.SHA256) let expectedHash = "9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08" XCTAssertEqual(hashDataToHexString(computedHash), expectedHash, "SHA256 hash function returned incorrect value") } func testSHA384Algorithm() { let computedHash = inputData.computeHashUsingAlgorithm(.SHA384) let expectedHash = "768412320f7b0aa5812fce428dc4706b3cae50e02a64caa16a782249bfe8efc4b7ef1ccb126255d196047dfedf17a0a9" XCTAssertEqual(hashDataToHexString(computedHash), expectedHash, "SHA384 hash function returned incorrect value") } func testSHA512Algorithm() { let computedHash = inputData.computeHashUsingAlgorithm(.SHA512) let expectedHash = "ee26b0dd4af7e749aa1a8ee3c10ae9923f618980772e473f8819a5d4940e0db27ac185f8a0e1d5f84f88bc887fd67b143732c304cc5fa9ad8e6f57f50028a8ff" XCTAssertEqual(hashDataToHexString(computedHash), expectedHash, "SHA512 hash function returned incorrect value") } func testSignedMD5Algorithm() { let computedHash = inputData.computeSignedHashUsingAlgorithm(.MD5, HMACKey: keyData) let expectedHash = "1d4a2743c056e467ff3f09c9af31de7e" XCTAssertEqual(hashDataToHexString(computedHash), expectedHash, "MD5 HMAC hash function returned incorrect value") } func testSignedSHA1Algorithm() { let computedHash = inputData.computeSignedHashUsingAlgorithm(.SHA1, HMACKey: keyData) let expectedHash = "671f54ce0c540f78ffe1e26dcf9c2a047aea4fda" XCTAssertEqual(hashDataToHexString(computedHash), expectedHash, "SHA1 HMAC hash function returned incorrect value") } func testSignedSHA224Algorithm() { let computedHash = inputData.computeSignedHashUsingAlgorithm(.SHA224, HMACKey: keyData) let expectedHash = "76b34b643e71d7d92afd4c689c0949cbe0c5445feae907aac532a5a1" XCTAssertEqual(hashDataToHexString(computedHash), expectedHash, "SHA224 HMAC hash function returned incorrect value") } func testSignedSHA256Algorithm() { let computedHash = inputData.computeSignedHashUsingAlgorithm(.SHA256, HMACKey: keyData) let expectedHash = "02afb56304902c656fcb737cdd03de6205bb6d401da2812efd9b2d36a08af159" XCTAssertEqual(hashDataToHexString(computedHash), expectedHash, "SHA256 HMAC hash function returned incorrect value") } func testSignedSHA384Algorithm() { let computedHash = inputData.computeSignedHashUsingAlgorithm(.SHA384, HMACKey: keyData) let expectedHash = "160a099ad9d6dadb46311cb4e6dfe98aca9ca519c2e0fedc8dc45da419b1173039cc131f0b5f68b2bbc2b635109b57a8" XCTAssertEqual(hashDataToHexString(computedHash), expectedHash, "SHA384 HMAC hash function returned incorrect value") } func testSignedSHA512Algorithm() { let computedHash = inputData.computeSignedHashUsingAlgorithm(.SHA512, HMACKey: keyData) let expectedHash = "287a0fb89a7fbdfa5b5538636918e537a5b83065e4ff331268b7aaa115dde047a9b0f4fb5b828608fc0b6327f10055f7637b058e9e0dbb9e698901a3e6dd461c" XCTAssertEqual(hashDataToHexString(computedHash), expectedHash, "SHA512 HMAC hash function returned incorrect value") } }
mit
c42b6e43f0abda34221ebdb7298447f4
42.679688
157
0.723484
3.853205
false
true
false
false
vapor/vapor
Sources/Vapor/HTTP/Server/HTTPServerResponseEncoder.swift
1
5782
import NIO import NIOHTTP1 final class HTTPServerResponseEncoder: ChannelOutboundHandler, RemovableChannelHandler { typealias OutboundIn = Response typealias OutboundOut = HTTPServerResponsePart /// Optional server header. private let serverHeader: String? private let dateCache: RFC1123DateCache struct ResponseEndSentEvent { } init(serverHeader: String?, dateCache: RFC1123DateCache) { self.serverHeader = serverHeader self.dateCache = dateCache } func write(context: ChannelHandlerContext, data: NIOAny, promise: EventLoopPromise<Void>?) { let response = self.unwrapOutboundIn(data) // add a RFC1123 timestamp to the Date header to make this // a valid request response.headers.add(name: "date", value: self.dateCache.currentTimestamp()) if let server = self.serverHeader { response.headers.add(name: "server", value: server) } // begin serializing context.write(wrapOutboundOut(.head(.init( version: response.version, status: response.status, headers: response.headers ))), promise: nil) if response.status == .noContent || response.forHeadRequest { // don't send bodies for 204 (no content) responses // or HEAD requests context.fireUserInboundEventTriggered(ResponseEndSentEvent()) context.writeAndFlush(self.wrapOutboundOut(.end(nil)), promise: promise) } else { switch response.body.storage { case .none: context.fireUserInboundEventTriggered(ResponseEndSentEvent()) context.writeAndFlush(wrapOutboundOut(.end(nil)), promise: promise) case .buffer(let buffer): self.writeAndflush(buffer: buffer, context: context, promise: promise) case .string(let string): let buffer = context.channel.allocator.buffer(string: string) self.writeAndflush(buffer: buffer, context: context, promise: promise) case .staticString(let string): let buffer = context.channel.allocator.buffer(staticString: string) self.writeAndflush(buffer: buffer, context: context, promise: promise) case .data(let data): let buffer = context.channel.allocator.buffer(bytes: data) self.writeAndflush(buffer: buffer, context: context, promise: promise) case .dispatchData(let data): let buffer = context.channel.allocator.buffer(dispatchData: data) self.writeAndflush(buffer: buffer, context: context, promise: promise) case .stream(let stream): let channelStream = ChannelResponseBodyStream( context: context, handler: self, promise: promise, count: stream.count == -1 ? nil : stream.count ) stream.callback(channelStream) } } } /// Writes a `ByteBuffer` to the context. private func writeAndflush(buffer: ByteBuffer, context: ChannelHandlerContext, promise: EventLoopPromise<Void>?) { if buffer.readableBytes > 0 { context.write(wrapOutboundOut(.body(.byteBuffer(buffer))), promise: nil) } context.fireUserInboundEventTriggered(ResponseEndSentEvent()) context.writeAndFlush(wrapOutboundOut(.end(nil)), promise: promise) } } private final class ChannelResponseBodyStream: BodyStreamWriter { let context: ChannelHandlerContext let handler: HTTPServerResponseEncoder let promise: EventLoopPromise<Void>? let count: Int? var currentCount: Int var isComplete: Bool var eventLoop: EventLoop { return self.context.eventLoop } enum Error: Swift.Error { case tooManyBytes case notEnoughBytes } init( context: ChannelHandlerContext, handler: HTTPServerResponseEncoder, promise: EventLoopPromise<Void>?, count: Int? ) { self.context = context self.handler = handler self.promise = promise self.count = count self.currentCount = 0 self.isComplete = false } func write(_ result: BodyStreamResult, promise: EventLoopPromise<Void>?) { switch result { case .buffer(let buffer): self.context.writeAndFlush(self.handler.wrapOutboundOut(.body(.byteBuffer(buffer))), promise: promise) self.currentCount += buffer.readableBytes if let count = self.count, self.currentCount > count { self.promise?.fail(Error.tooManyBytes) promise?.fail(Error.notEnoughBytes) } case .end: self.isComplete = true if let count = self.count, self.currentCount != count { self.promise?.fail(Error.notEnoughBytes) promise?.fail(Error.notEnoughBytes) } self.context.fireUserInboundEventTriggered(HTTPServerResponseEncoder.ResponseEndSentEvent()) self.context.writeAndFlush(self.handler.wrapOutboundOut(.end(nil)), promise: promise) self.promise?.succeed(()) case .error(let error): self.isComplete = true self.context.fireUserInboundEventTriggered(HTTPServerResponseEncoder.ResponseEndSentEvent()) self.context.writeAndFlush(self.handler.wrapOutboundOut(.end(nil)), promise: promise) self.promise?.fail(error) } } deinit { assert(self.isComplete, "Response body stream writer deinitialized before .end or .error was sent.") } }
mit
ad27ef81d2ac578a43aba510c35e1d58
39.433566
118
0.628329
5.11229
false
false
false
false
realtime-framework/realtime-news-swift
Realtime/Realtime/OptionsViewController.swift
1
6941
// // OptionsViewController.swift // RealtimeNews // // Created by Joao Caixinha on 24/02/15. // Copyright (c) 2015 Realtime. All rights reserved. // import UIKit protocol OptionsViewProtocol { func didTap(option:NSString, onSection:NSString) } class OptionsViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, SMProtocol { struct Static { static var onceToken: dispatch_once_t = 0 } var isFiltred:Bool var filter:String var isVisible:Bool? var isAnimating:Bool? var isConnected:Bool? var menuData:NSMutableDictionary? var settings:NSArray? var delegate:OptionsViewProtocol? @IBOutlet weak var table_Options: UITableView! @IBOutlet weak var labelVersion: UILabel! required override init(nibName: String?, bundle: NSBundle?) { self.isFiltred = false self.filter = "" super.init(nibName: nibName, bundle: bundle) } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() self.view.layer.borderColor = UIColor.lightGrayColor().CGColor self.view.layer.borderWidth = 1.0 self.settings = ["Logout"] self.table_Options.dataSource = self self.table_Options.delegate = self let version:String = NSBundle.mainBundle().objectForInfoDictionaryKey("CFBundleShortVersionString") as! String let built:String = NSBundle.mainBundle().objectForInfoDictionaryKey("CFBundleVersion") as! String self.labelVersion.text = " Version: \(version) (\(built))" NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("reAuthenticate"), name: "reAuthenticate", object: nil) } func reAuthenticate() { storage?.tagsTableRef?.getMenu() } func onReconnected() { storage?.tagsTableRef?.getMenu() } func onReconnecting() { storage?.tagsTableRef?.getMenu() } func didReceivedData(data: NSMutableArray) { let menu:NSMutableArray = Utils.orderMenu(data) self.removeMenu() self.menuData = NSMutableDictionary() for obj in menu { self.addItem(obj as! DataObject) } self.table_Options.reloadData() self.table_Options.setNeedsDisplay() } func removeMenu() { if menuData == nil { return } let copy:NSMutableDictionary = NSMutableDictionary(dictionary: self.menuData!) for (menu, _) in copy.enumerate() { self.menuData?.removeObjectForKey(menu) } self.menuData = nil } func addItem(obj:DataObject!) { var tags:NSMutableArray? = self.menuData?.objectForKey(obj.type!) as? NSMutableArray if tags == nil { tags = NSMutableArray() tags?.addObject(obj.tag!) self.menuData?.setObject(tags!, forKey: obj.type!) return } tags?.addObject(obj.tag!) } func tableView(tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) { let header:UITableViewHeaderFooterView = view as! UITableViewHeaderFooterView header.textLabel!.textColor = UIColor.peterRiverColor() header.textLabel!.font = UIFont.boldSystemFontOfSize(17.0) if section > 0 { let border:UIView = UIView(frame: CGRectMake(0, 0, header.frame.size.width, 1)) border.layer.borderColor = UIColor(white: 0.8, alpha: 0.5).CGColor border.layer.borderWidth = 1.0 header.addSubview(border) } } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let ident:String = "cell" var cell:UITableViewCell? = tableView.dequeueReusableCellWithIdentifier(ident) as UITableViewCell? if cell == nil { cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: ident) } cell?.backgroundColor = UIColor.clearColor() cell?.textLabel?.textColor = UIColor.blackColor() if self.menuData?.allKeys == nil || indexPath.section == self.menuData?.allKeys.count { cell?.textLabel?.text = self.settings?.objectAtIndex(indexPath.row) as? String return cell! } let allKeys = self.menuData?.allKeys let key = allKeys![indexPath.section] as! String let val:NSArray = self.menuData?.objectForKey(key) as! NSArray let tag = val.objectAtIndex(indexPath.row) as! String cell?.textLabel?.text = tag return cell! } func numberOfSectionsInTableView(tableView: UITableView) -> Int { let sections:Int? = self.menuData?.count as Int! if sections == nil { return 1 }else{ return (sections! + 1) as Int } } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if self.menuData?.allKeys == nil || section == self.menuData?.allKeys.count { let settings:Int = self.settings?.count as Int! return settings } let allKeys = self.menuData?.allKeys let pSection = allKeys![section] as! String let elements:NSArray = self.menuData?.objectForKey(pSection) as! NSArray return elements.count } func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? { if self.menuData?.allKeys.count == nil || section == self.menuData?.allKeys.count { return "Session" } let allKeys = self.menuData?.allKeys return allKeys![section] as? String } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { if self.menuData?.allKeys == nil || indexPath.section == self.menuData?.allKeys.count { self.delegate?.didTap(self.settings?.objectAtIndex(indexPath.row) as! String, onSection: "Session") return } self.table_Options.deselectRowAtIndexPath(indexPath, animated: false) //let allKeys = self.menuData?.allKeys let section:NSString = self.menuData?.allKeys[indexPath.section] as! NSString let rows:NSArray = self.menuData?.objectForKey(section) as! NSArray self.delegate?.didTap(rows.objectAtIndex(indexPath.row) as! String, onSection: section) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
306eb46d92a1695b503b980136beeb95
31.283721
137
0.619795
4.847067
false
false
false
false
DanielAsher/SwiftParse
SwiftParse/Playgrounds/PrettyPrinter.playground/Pages/PrettyPrinter4.xcplaygroundpage/Contents.swift
1
4198
//: [Previous](@previous) //: [Previous](@previous) import Foundation enum Doc { case Nil indirect case Text(String, Doc) indirect case Line(Int, Doc) indirect case Union(Doc, Doc) } extension Doc : DocType { static var zero : Doc { return Doc.Nil } static func text(str: String) -> Doc { return Doc.Text(str, Doc.Nil) } static var line : Doc { return Doc.Line(0, Doc.Nil) } static func nest(i: Int) -> Doc -> Doc { return { doc in switch doc { case let .Text(str, d): return Doc.Text(str, nest(i)(d) ) case let .Line(j, d): return Doc.Line(i+j, nest(i)(d) ) case let .Union(lhs, rhs): return Doc.Union(nest(i)(lhs), nest(i)(rhs)) case .Nil: return Doc.Nil } } } func layout() -> String { switch self { // case .Text(let s, let .Union(x, y)): // return s + x.layout() + "\n" + s + y.layout() case let .Text(s, x): return s + x.layout() case let .Line(i, x): let prefix = "\n" + String(count: i, repeatedValue: Character(" ")) return prefix + x.layout() case let .Union(lhs, rhs): return lhs.layout() + "\n" + rhs.layout() case .Nil: return "" } } } func <§> (lhs: Doc, rhs: Doc) -> Doc { switch (lhs, rhs) { case (.Nil, .Nil): return .Nil case (_, .Nil): return lhs case (.Nil, _): return rhs case (let .Union(x, y), let z): return .Union(x <§> z, y <§> z) case (let x, let .Union(y, z)): return .Union(x <§> y, x <§> z) case (let .Text(s, x), _): return .Text(s, x <§> rhs) case (let .Line(i, x), _): return .Line(i, x <§> rhs) default: return .Union(lhs, rhs) } } infix operator <|> { associativity left } func <|> (lhs: Doc, rhs: Doc) -> Doc { switch (lhs, rhs) { case (let .Union(x, y), let z): return .Union(x <§> z, y <§> z) case (let x, let .Union(y, z)): return .Union(x <§> y, x <§> z) default: return Doc.Union(lhs, rhs) } } func group(doc: Doc) -> Doc { switch doc { case .Nil: return .Nil case let .Line(i, x): return .Union(.Text(" ", flatten(x)), .Line(i, x)) case let .Text(s, x): return .Text(s, group(x)) case let .Union(x, y): return .Union(group(x), y) } // return flatten(doc) <§> doc } func flatten(doc: Doc) -> Doc { switch doc { case .Nil: return .Nil case let .Line(_, x): return .Text(" ", flatten(x)) case let .Text(s, x): return .Text(s, flatten(x)) case let .Union(x, _): return flatten(x) } } func best(w: Int, _ k: Int, _ doc: Doc) -> Doc { switch doc { case .Nil: return .Nil case let .Line(i, x): return .Line(i, best(w, i, x)) case let .Text(s, x): return .Text(s, best(w, k + s.characters.count, x)) case let .Union(x, y): return better(w, k, best(w, k, x), best(w, k, y)) } } func better(w: Int, _ k: Int, _ x: Doc, _ y: Doc) -> Doc { if fits(w-k, doc: x) { return x } else { return y } } func fits(w: Int, doc: Doc) -> Bool { switch doc { case _ where w < 0: return false case .Nil: return true case let .Text(s, x): return fits(w - s.characters.count, doc: x) case .Line: return true default: return false } } func pretty(w: Int, doc: Doc) -> String { return best(w, 0, doc).layout() } let a = Doc.text("hello") <§> Doc.line <§> Doc.text("a") print("\na:", a, terminator: "\n") //print("a.layout:", "\n\(a.layout())", terminator: "\n") // //let ag = group(a) //print("\nag:", ag, terminator: "\n") //print("ag.layout:", ag.layout(), terminator: "\n") // //let b = group(a <§> Doc.line <§> Doc.text("b")) //print("\nb:", b, terminator: "\n") //print("b.layout:", b.layout(), terminator: "\n") let g1 = group( group( group(Doc.text("hello") <§> Doc.line <§> Doc.text("a")) <§> Doc.line <§> Doc.text("b")) <§> Doc.line <§> Doc.text("c")) //print("\ng1:", g1, terminator: "\n") print("g1 pretty:") print(pretty(12, doc: g1), terminator: "\n") print("Finished :)") //: [Next](@next) //: [Next](@next)
mit
3e03a90cb525cc569f6765c6b9094b35
27.026846
83
0.519875
2.997846
false
false
false
false
silence0201/Swift-Study
Swifter/29Reflect.playground/Contents.swift
1
1224
//: Playground - noun: a place where people can play import Foundation struct Person { let name: String let age: Int } let xiaoMing = Person(name: "XiaoMing", age: 16) let r = Mirror(reflecting: xiaoMing) // r 是 MirrorType print("xiaoMing 是 \(r.displayStyle!)") print("属性个数:\(r.children.count)") for child in r.children { print("属性名:\(child.label ?? ""),值:\(child.value)") } //for i in r.children.startIndex..<r.children.endIndex { // print("属性名:\(r.children[i].0!),值:\(r.children[i].1)") //} // 输出: // xiaoMing 是 Struct // 属性个数:2 // 属性名:name,值:XiaoMing // 属性名:age,值:16 dump(xiaoMing) // 输出: // ▿ Person // - name: XiaoMing // - age: 16 func valueFrom(_ object: Any, key: String) -> Any? { let mirror = Mirror(reflecting: object) for child in mirror.children { let (targetKey, targetMirror) = (child.label, child.value) if key == targetKey { return targetMirror } } return nil } // 接上面的 xiaoMing if let name = valueFrom(xiaoMing, key: "name") as? String { print("通过 key 得到值: \(name)") } // 输出: // 通过 key 得到值: XiaoMing
mit
ed3cb104a3695262294fc2288e61a9c5
18.54386
66
0.609515
3.06044
false
false
false
false
hovansuit/FoodAndFitness
FoodAndFitness/Model/1.0/Location.swift
1
1489
// // Location.swift // FoodAndFitness // // Created by Mylo Ho on 4/9/17. // Copyright © 2017 SuHoVan. All rights reserved. // import RealmSwift import ObjectMapper import RealmS import CoreLocation final class Location: Object, Mappable { private(set) dynamic var id = 0 dynamic var latitude: Double = 0.0 dynamic var longitude: Double = 0.0 override class func primaryKey() -> String? { return "id" } convenience required init?(map: Map) { self.init() id <- map["id"] assert(id > 0, "Location `id` must be greater than 0") } func mapping(map: Map) { latitude <- map["latitude"] longitude <- map["longitude"] } } // MARK: - Utils extension Location { var toCLLocation: CLLocation { return CLLocation(latitude: latitude, longitude: longitude) } } // MARK: - CLLocation extension CLLocation { var toLocation: Location { let location = Location() location.latitude = self.coordinate.latitude location.longitude = self.coordinate.longitude return location } } // MARK: - Array extension Array where Element: Location { func toJSObject() -> [JSObject] { var array: [JSObject] = [] for location in self { let json: JSObject = [ "latitude": location.latitude, "longitude": location.longitude ] array.append(json) } return array } }
mit
f802a83990ed7fb78eee8e4330a3c6f4
21.545455
67
0.59879
4.239316
false
false
false
false
mihaicris/digi-cloud
Digi Cloud/Models/Location.swift
1
1210
// // Location.swift // Digi Cloud // // Created by Mihai Cristescu on 22/11/16. // Copyright © 2016 Mihai Cristescu. All rights reserved. // import Foundation struct Location { // MARK: - Properties var mount: Mount let path: String } extension Location { var parentLocation: Location { var parentPath = (path as NSString).deletingLastPathComponent if parentPath != "/" { parentPath += "/" } return Location(mount: self.mount, path: parentPath) } func appendingPathComponentFrom(node: Node) -> Location { let newPath = path + node.name + (node.type == "dir" ? "/" : "") return Location(mount: mount, path: newPath) } func appendingPathComponent(_ name: String, isFolder: Bool) -> Location { let newPath = path + name + (isFolder ? "/" : "") return Location(mount: mount, path: newPath) } } extension Location: Equatable { static func == (lhs: Location, rhs: Location) -> Bool { return lhs.mount == rhs.mount && lhs.path == rhs.path } } extension Location: Hashable { var hashValue: Int { return mount.name.hashValue ^ (path.hashValue &* 72913) } }
mit
852534d458032a404ff108b865838733
22.25
77
0.608768
4.084459
false
false
false
false
mikelikespie/swiftled
src/main/swift/Swiftlights/ControlView.swift
1
886
// // Created by Michael Lewis on 7/20/17. // import UIKit import Fixtures import yoga_YogaKit import YogaKit_swift import yoga_yoga class ControlView : UIView { let control: Control let nameLabel = UILabel() let controlControl: UIView init(control: Control) { self.control = control self.controlControl = control.cell super.init(frame: .zero) configureLayout { $0.isEnabled = true $0.flexDirection = .column } nameLabel.text = control.name nameLabel.configureLayout { $0.isEnabled = true } control.cell.yoga.flexGrow = 1 addSubview(nameLabel) addSubview(control.cell) } @available(*, unavailable) public required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
mit
0aeebe4a15ab716539d38f8eb06bf0d8
19.136364
59
0.608352
4.321951
false
false
false
false
material-components/material-components-ios
components/Cards/examples/EditReorderCollectionViewController.swift
2
8626
// Copyright 2018-present the Material Components for iOS authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import UIKit import MaterialComponents.MaterialColorScheme import MaterialComponents.MaterialContainerScheme import MaterialComponents.MaterialTypographyScheme class EditReorderCollectionViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout { enum ToggleMode: Int { case edit = 1 case reorder } let collectionView = UICollectionView( frame: .zero, collectionViewLayout: UICollectionViewFlowLayout()) var toggle = ToggleMode.edit @objc var containerScheme: MDCContainerScheming override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { containerScheme = MDCContainerScheme() super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } let images = [ (image: "amsterdam-kadoelen", title: "Kadoelen"), (image: "amsterdam-zeeburg", title: "Zeeburg"), (image: "venice-st-marks-square", title: "St. Mark's Square"), (image: "venice-grand-canal", title: "Grand Canal"), (image: "austin-u-texas-pond", title: "Austin U"), ] var dataSource: [(image: String, title: String, selected: Bool)] = [] override func viewDidLoad() { super.viewDidLoad() collectionView.frame = view.bounds collectionView.dataSource = self collectionView.delegate = self collectionView.backgroundColor = containerScheme.colorScheme.backgroundColor collectionView.alwaysBounceVertical = true collectionView.register(CardEditReorderCollectionCell.self, forCellWithReuseIdentifier: "Cell") collectionView.translatesAutoresizingMaskIntoConstraints = false collectionView.allowsMultipleSelection = true view.addSubview(collectionView) navigationItem.rightBarButtonItem = UIBarButtonItem( title: "Reorder", style: .plain, target: self, action: #selector(toggleModes)) let longPressGesture = UILongPressGestureRecognizer( target: self, action: #selector(reorderCards(gesture:))) longPressGesture.cancelsTouchesInView = false collectionView.addGestureRecognizer(longPressGesture) let count = Int(images.count) for index in 0..<30 { let ind = index % count dataSource.append((image: images[ind].image, title: images[ind].title, selected: false)) } let guide = view.safeAreaLayoutGuide NSLayoutConstraint.activate([ collectionView.leftAnchor.constraint(equalTo: guide.leftAnchor), collectionView.rightAnchor.constraint(equalTo: guide.rightAnchor), collectionView.topAnchor.constraint(equalTo: view.topAnchor), collectionView.bottomAnchor.constraint(equalTo: guide.bottomAnchor), ]) collectionView.contentInsetAdjustmentBehavior = .always self.updateTitle() } func preiOS11Constraints() { self.view.addConstraints( NSLayoutConstraint.constraints( withVisualFormat: "H:|[view]|", options: [], metrics: nil, views: ["view": collectionView])) self.view.addConstraints( NSLayoutConstraint.constraints( withVisualFormat: "V:|[view]|", options: [], metrics: nil, views: ["view": collectionView])) } func updateTitle() { switch toggle { case .edit: navigationItem.rightBarButtonItem?.title = "Reorder" self.title = "Cards (Edit)" case .reorder: navigationItem.rightBarButtonItem?.title = "Edit" self.title = "Cards (Reorder)" } } @objc func toggleModes() { switch toggle { case .edit: toggle = .reorder case .reorder: toggle = .edit } self.updateTitle() collectionView.reloadData() } func collectionView( _ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath ) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) guard let cardCell = cell as? CardEditReorderCollectionCell else { return cell } cardCell.apply( containerScheme: containerScheme, typographyScheme: containerScheme.typographyScheme) let title = dataSource[indexPath.item].title let imageName = dataSource[indexPath.item].image cardCell.configure(title: title, imageName: imageName) cardCell.isSelectable = (toggle == .edit) if self.dataSource[indexPath.item].selected { collectionView.selectItem(at: indexPath, animated: true, scrollPosition: []) cardCell.isSelected = true } cardCell.isAccessibilityElement = true cardCell.accessibilityLabel = title return cardCell } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { guard toggle == .edit else { return } dataSource[indexPath.item].selected = true } func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) { guard toggle == .edit else { return } dataSource[indexPath.item].selected = false } func numberOfSections(in collectionView: UICollectionView) -> Int { return 1 } func collectionView( _ collectionView: UICollectionView, numberOfItemsInSection section: Int ) -> Int { return dataSource.count } func collectionView( _ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath ) -> CGSize { let cardSize = (collectionView.bounds.size.width / 3) - 12 return CGSize(width: cardSize, height: cardSize) } func collectionView( _ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int ) -> UIEdgeInsets { return UIEdgeInsets(top: 8, left: 8, bottom: 8, right: 8) } func collectionView( _ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int ) -> CGFloat { return 8 } func collectionView( _ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int ) -> CGFloat { return 8 } func collectionView( _ collectionView: UICollectionView, canMoveItemAt indexPath: IndexPath ) -> Bool { return toggle == .reorder } func collectionView( _ collectionView: UICollectionView, moveItemAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath ) { let sourceItem = dataSource[sourceIndexPath.item] // reorder all cells in between source and destination, moving each by 1 position if sourceIndexPath.item < destinationIndexPath.item { for ind in sourceIndexPath.item..<destinationIndexPath.item { dataSource[ind] = dataSource[ind + 1] } } else { for ind in (destinationIndexPath.item + 1...sourceIndexPath.item).reversed() { dataSource[ind] = dataSource[ind - 1] } } dataSource[destinationIndexPath.item] = sourceItem } @objc func reorderCards(gesture: UILongPressGestureRecognizer) { switch gesture.state { case .began: guard let selectedIndexPath = collectionView.indexPathForItem( at: gesture.location(in: collectionView)) else { break } collectionView.beginInteractiveMovementForItem(at: selectedIndexPath) case .changed: guard let gestureView = gesture.view else { break } collectionView.updateInteractiveMovementTargetPosition(gesture.location(in: gestureView)) case .ended: collectionView.endInteractiveMovement() default: collectionView.cancelInteractiveMovement() } } } extension EditReorderCollectionViewController { @objc class func catalogMetadata() -> [String: Any] { return [ "breadcrumbs": ["Cards", "Edit/Reorder"], "primaryDemo": false, "presentable": true, ] } }
apache-2.0
8fb6750c4ddbd4924e3db0464bc0ef72
30.140794
99
0.713772
5.044444
false
false
false
false
modnovolyk/MAVLinkSwift
Tests/MAVLinkTests/MAVLinkTests.swift
1
6356
// // MAVLinkTests.swift // MAVLink Protocol Swift Library // // Created by Max Odnovolyk on 10/6/16 // Copyright (c) 2016 Max Odnovolyk // // 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 XCTest @testable import MAVLink class MAVLinkTests: XCTestCase { override func setUp() { super.setUp() continueAfterFailure = false } // MARK: - Parsing tests func testParseDidParseMessageThatStartsRightAfterCorruptedMessageIdByte() { let corruptedByte = UInt8(0xC7) var data = Data(testHeartbeatData.prefix(upTo: 5)) data.append(corruptedByte) data.append(testStatustextData) var callsCount = 0 let delegate = Delegate(didParse: { message, _, _, _ in XCTAssert(message is Statustext, "Expects to get instance of Statustext from provided data") callsCount += 1 }) let mavLink = MAVLink() mavLink.delegate = delegate mavLink.parse(data: data, channel: 0) XCTAssert(callsCount == 1, "MAVLink instance should parse exactly one message from provided data") } func testParseDidParseMessageThatStartsRightAfterCorruptedCRCByte() { let corruptedByte = UInt8(0x00) var data = testHeartbeatData data.removeLast(2) data.append(corruptedByte) data.append(testStatustextData) var callsCount = 0 let delegate = Delegate(didParse: { message, _, _, _ in XCTAssert(message is Statustext, "Expects to get instance of Statustext from provided data") callsCount += 1 }) let mavLink = MAVLink() mavLink.delegate = delegate mavLink.parse(data: data, channel: 0) XCTAssert(callsCount == 1, "MAVLink instance should parse exactly one message from provided data") } // MARK: - Dispatching tests func testDispatchDidPutProperMessageId() { var callsCount = 0 let delegate = Delegate(didFinalize: { _, _, data, _, _ in XCTAssert(data[5] == Heartbeat.id, "Sixth byte of MAVLink packet should be message id (in this specific case \(Heartbeat.id))") callsCount += 1 }) let mavLink = MAVLink() mavLink.delegate = delegate try! mavLink.dispatch(message: testHeartbeatMessage, systemId: 0, componentId: 0, channel: 0) XCTAssert(callsCount == 1, "MAVLink instance should return exactly one finalized packet from provided message") } func testDispatchDidPutProperSystemId() { var callsCount = 0 let systemId = UInt8(0xFF) let delegate = Delegate(didFinalize: { _, _, data, _, _ in XCTAssert(data[3] == systemId, "Fourth byte of MAVLink packet should be system id (\(systemId))") callsCount += 1 }) let mavLink = MAVLink() mavLink.delegate = delegate try! mavLink.dispatch(message: testHeartbeatMessage, systemId: systemId, componentId: 0, channel: 0) XCTAssert(callsCount == 1, "MAVLink instance should return exactly one finalized packet from provided message") } func testDispatchDidPutProperComponentId() { var callsCount = 0 let componentId = UInt8(0xFF) let delegate = Delegate(didFinalize: { _, _, data, _, _ in XCTAssert(data[4] == componentId, "Fifth byte of generated MAVLink packet should contain component id (\(componentId))") callsCount += 1 }) let mavLink = MAVLink() mavLink.delegate = delegate try! mavLink.dispatch(message: testHeartbeatMessage, systemId: 0, componentId: componentId, channel: 0) XCTAssert(callsCount == 1, "MAVLink instance should return exactly one finalized packet from provided message") } func testDispatchDidPutProperCRC() { var callsCount = 0 let delegate = Delegate(didFinalize: { [unowned self] _, _, data, _, _ in let expectedData = self.testHeartbeatData XCTAssert(data == expectedData, "Test message`s bytes should match expected constant test data (including CRC)") callsCount += 1 }) let mavLink = MAVLink() mavLink.delegate = delegate try! mavLink.dispatch(message: testHeartbeatMessage, systemId: 0xFF, componentId: 0, channel: 0) XCTAssert(callsCount == 1, "MAVLink instance should return exactly one finalized packet from provided message") } func testDispatchRethrowsDataExtensionsErrors() { let mavLink = MAVLink() let message = Statustext(severity: MAVSeverity.notice, text:"💩") XCTAssertThrowsError(try mavLink.dispatch(message: message, systemId: 0, componentId: 0, channel: 0)) { error in switch error { case let PackError.invalidStringEncoding(offset, string) where offset == 1 && string == "💩": break default: XCTFail("Unexpected error thrown") } } } }
mit
75f0ef13fcaf8c452d6eae8f572944c6
37.023952
139
0.630079
4.735272
false
true
false
false
welbesw/BigcommerceApi
Pod/Classes/BigcommerceProductImage.swift
1
2439
// // BigcommerceProductImage.swift // Pods // // Created by William Welbes on 10/20/15. // // import Foundation open class BigcommerceProductImage: NSObject { open var productImageId:NSNumber? open var productId:NSNumber? open var imageFile:String? open var zoomUrl:String? open var thumbnailUrl:String? open var standardUrl:String? open var tinyUrl:String? open var isThumbnail:Bool = false open var sortOrder:NSNumber = 0 open var imageDescription:String? open var dateCreated:Date? open var dateModified:Date? public init(jsonDictionary:NSDictionary) { //Load the JSON dictionary into the object let dateFormatter = DateFormatter() dateFormatter.dateFormat = "EEE, d MMM yyyy HH:mm:ss zzz" if let id = jsonDictionary["id"] as? NSNumber { self.productImageId = id } if let stringValue = jsonDictionary["image_file"] as? String { self.imageFile = stringValue } if let stringValue = jsonDictionary["zoom_url"] as? String { self.zoomUrl = stringValue } if let stringValue = jsonDictionary["thumbnail_url"] as? String { self.thumbnailUrl = stringValue } if let stringValue = jsonDictionary["standard_url"] as? String { self.standardUrl = stringValue } if let stringValue = jsonDictionary["tiny_url"] as? String { self.tinyUrl = stringValue } if let numberValue = jsonDictionary["is_thumbnail"] as? NSNumber { self.isThumbnail = numberValue.boolValue } if let numberValue = jsonDictionary["sort_order"] as? NSNumber { self.sortOrder = numberValue.boolValue as NSNumber } if let stringValue = jsonDictionary["description"] as? String { self.imageDescription = stringValue } if let dateString = jsonDictionary["date_created"] as? String { if let date = dateFormatter.date(from: dateString) { dateCreated = date } } if let dateString = jsonDictionary["date_modified"] as? String { if let date = dateFormatter.date(from: dateString) { dateModified = date } } } }
mit
1264205077c40c26fd6aa6d4190e4c46
28.385542
74
0.584666
5.08125
false
false
false
false
sharplet/five-day-plan
Sources/FiveDayPlan/Models/PlanChapter+Extensions.swift
1
757
import CoreData extension PlanChapter { convenience init(scripture: Scripture.Chapter, order: Int, insertInto context: NSManagedObjectContext?) { self.init(entity: type(of: self).entity(), insertInto: context) self.book = scripture.book.rawValue self.name = scripture.description self.order = Int16(order) if let number = scripture.chapter { self.number = Int16(number) } } } extension Scripture.Chapter { init(_ chapter: PlanChapter) { self.init( book: Scripture.Book(rawValue: chapter.book!)!, chapter: Int(chapter.number) )! } } extension NSSortDescriptor { static var byPlanDayChapter: NSSortDescriptor { return NSSortDescriptor(key: #keyPath(PlanChapter.order), ascending: true) } }
mit
d99fe5aa283388dced6c1f5b6daed4a5
26.035714
107
0.704095
3.902062
false
false
false
false
RobinRH/family-history-booklet
PersonTableViewController.swift
1
7119
// // FatherTableViewController.swift // Copyright (c) 2017 Robin Reynolds. All rights reserved. // import UIKit class PersonTableViewController: UITableViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate, UITextFieldDelegate { @IBOutlet weak var nameText: UITextField! @IBOutlet weak var birthPlaceText: UITextField! @IBOutlet weak var birthDateText: UITextField! @IBOutlet weak var templeWordSegment: UISegmentedControl! @IBOutlet weak var familySearchSegment: UISegmentedControl! @IBOutlet weak var deathDateText: UITextField! @IBOutlet weak var deathPlaceText: UITextField! @IBOutlet weak var storiesText: UITextView! @IBOutlet weak var familySearchSwitch: UISwitch! @IBOutlet weak var templeWorkSwitch: UISwitch! @IBOutlet weak var photoImage: UIImageView! @IBOutlet weak var photoCell: UITableViewCell! @IBAction func doneClick(_ sender: AnyObject) { storiesText.resignFirstResponder(); } @IBOutlet weak var descriptionLabel: UILabel! let imagePicker = UIImagePickerController() @IBAction func selectPhoto(_ sender: AnyObject) { imagePicker.allowsEditing = false imagePicker.sourceType = .photoLibrary present(imagePicker, animated: true, completion: nil) } func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) { if let pickedImage = info[UIImagePickerControllerOriginalImage] as? UIImage { photoImage!.image = pickedImage GlobalData.selectedPerson.image = pickedImage } dismiss(animated: true, completion: nil) } func textFieldShouldReturn(_ textField: UITextField) -> Bool { self.view.endEditing(true) return false } func imagePickerControllerDidCancel(_ picker: UIImagePickerController) { dismiss(animated: true, completion: nil) } func configureView() { let person = GlobalData.selectedPerson nameText!.text = person.name birthDateText!.text = person.birth.date birthPlaceText!.text = person.birth.place deathDateText!.text = person.death.date deathPlaceText!.text = person.death.place photoImage!.image = person.image storiesText!.text = person.description } override func viewDidLoad() { super.viewDidLoad() imagePicker.delegate = self self.configureView() nameText.delegate = self birthDateText.delegate = self birthPlaceText.delegate = self deathDateText.delegate = self deathPlaceText.delegate = self storiesText.layer.borderColor = UIColor.lightGray.cgColor storiesText.layer.borderWidth = 0.5 storiesText.layer.cornerRadius = 5 // this part to set the width doesn't seem to work let width = storiesText.superview?.frame.width storiesText.frame.size = CGSize(width: width! - 16, height: storiesText.frame.size.height) self.navigationItem.title = GlobalData.selectedPerson.personType.toString() self.tableView.beginUpdates() self.tableView.endUpdates() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } override func viewWillAppear(_ animated: Bool) { photoImage.contentMode = .scaleAspectFit photoImage.image = GlobalData.selectedPerson.image } override func viewWillDisappear(_ animated: Bool) { // save the values back to the model let person = GlobalData.selectedPerson person.name = nameText!.text! person.birth.date = birthDateText!.text! person.birth.place = birthPlaceText!.text! person.death.date = deathDateText!.text! person.death.place = deathPlaceText!.text! //person.image = photoImage!.image! person.description = storiesText!.text! } override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { if (indexPath.section == 0 && indexPath.row == 1 && GlobalData.selectedPerson.personType == PersonType.child) { return 0 } else if (indexPath.section == 3 && indexPath.row == 2 && GlobalData.selectedPerson.personType == PersonType.child) { return 0 } else { return super.tableView(self.tableView, heightForRowAt: indexPath) } } // MARK: - Table view data source // override func numberOfSectionsInTableView(tableView: UITableView) -> Int { // // #warning Potentially incomplete method implementation. // // Return the number of sections. // return 0 // } // // override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // // #warning Incomplete method implementation. // // Return the number of rows in the section. // return 0 // } /* override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath) as! UITableViewCell // Configure the cell... return cell } */ /* // Override to support conditional editing of the table view. override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return NO if you do not want the specified item to be editable. return true } */ /* // Override to support editing the table view. override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { // Delete the row from the data source tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } else if editingStyle == .Insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } */ /* // Override to support rearranging the table view. override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return NO if you do not want the item to be re-orderable. return true } */ /* // 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. } */ }
apache-2.0
733038122400cae5b14aab52d0a8adc8
34.954545
157
0.672988
5.265533
false
false
false
false
xmartlabs/Bender
Sources/Layers/BatchNorm.swift
1
4745
// // BatchNorm.swift // MetalBender // // Created by Mathias Claassen on 2/12/18. // import MetalPerformanceShaders /// Implements Batch normalization. open class BatchNorm: NetworkLayer { public static var meanModifier = "mean" public static var varianceModifier = "variance" public static var scaleModifier = "scale" public static var offsetModifier = "offset" var kernel: MTLComputePipelineState! var params: Data? var allParamsSet = false var epsilon: Float public var paramBuffer: MTLBuffer! public init(mean: Data? = nil, variance: Data? = nil, offset: Data? = nil, scale: Data? = nil, epsilon: Float = 0, id: String? = nil) { self.epsilon = epsilon if let mean = mean, let variance = variance { params = mean params?.append(variance) if let scale = scale { params?.append(scale) } else { let scaleArr = [Float](repeating: 1.0, count: variance.count / MemoryLayout<Float>.size) params?.append(UnsafeBufferPointer(start: scaleArr, count: scaleArr.count)) } if let offset = offset { params?.append(offset) } else { let offsetArr = [Float](repeating: 0.0, count: variance.count / MemoryLayout<Float>.size) params?.append(UnsafeBufferPointer(start: offsetArr, count: offsetArr.count)) } params?.append(UnsafeBufferPointer(start: [epsilon], count: 1)) params = params?.toFloat16() allParamsSet = true } else if let scale = scale, let offset = offset { params = scale params?.append(offset) } super.init(id: id) } open override func validate() { let incoming = getIncoming() assert(incoming.count == 1, "BatchNorm must have one input, not \(incoming.count)") } open override func initialize(network: Network, device: MTLDevice, temporaryImage: Bool = true) { super.initialize(network: network, device: device, temporaryImage: temporaryImage) let incoming = getIncoming() outputSize = incoming[0].outputSize let isArray = outputSize.f > 4 kernel = MetalShaderManager.shared.getFunction(name: "batch_norm" + (isArray ? "" : "_3"), in: Bundle(for: BatchNorm.self)) if !allParamsSet { var d1 = Data(bytes: network.parameterLoader.loadWeights(for: id, modifier: BatchNorm.meanModifier, size: outputSize.f), count: outputSize.f * Constants.FloatSize) d1.append(Data(bytes: network.parameterLoader.loadWeights(for: id, modifier: BatchNorm.varianceModifier, size: outputSize.f), count: outputSize.f * Constants.FloatSize)) if let params = self.params { d1.append(params) } else { d1.append(Data(bytes: network.parameterLoader.loadWeights(for: id, modifier: BatchNorm.scaleModifier, size: outputSize.f), count: outputSize.f * Constants.FloatSize)) d1.append(Data(bytes: network.parameterLoader.loadWeights(for: id, modifier: BatchNorm.offsetModifier, size: outputSize.f), count: outputSize.f * Constants.FloatSize)) } d1.append(UnsafeBufferPointer(start: [epsilon], count: 1)) self.params = d1.toFloat16() } if let params = params { paramBuffer = device.makeBuffer(bytes: params.pointer()!, length: (max(4, outputSize.f) * 4 + 1) * Constants.HalfSize, options: []) } createOutputs(size: outputSize, temporary: temporaryImage) } open override func execute(commandBuffer: MTLCommandBuffer, executionIndex index: Int = 0) { let input = getIncoming()[0].getOutput(index: index) let output = getOrCreateOutput(commandBuffer: commandBuffer, index: index) let encoder = commandBuffer.makeComputeCommandEncoder()! encoder.label = "Batch Norm encoder" encoder.setComputePipelineState(kernel) encoder.setTexture(input.texture, index: 0) encoder.setTexture(output.texture, index: 1) encoder.setBuffer(paramBuffer, offset: 0, index: 0) let threadsPerGroups = MTLSizeMake(32, 8, 1) let threadGroups = output.texture.threadGrid(threadGroup: threadsPerGroups) encoder.dispatchThreadgroups(threadGroups, threadsPerThreadgroup: threadsPerGroups) encoder.endEncoding() input.setRead() } }
mit
02f5f7b3ab0164c40a0f7ff20a48d2a7
41.747748
139
0.607165
4.588975
false
false
false
false
willlarche/material-components-ios
components/ShadowElevations/examples/ShadowElevationsTypicalUseExample.swift
3
2152
/* Copyright 2017-present the Material Components for iOS authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import Foundation import MaterialComponents class ShadowElevationsTypicalUseExample: UIViewController { let appBar = MDCAppBar() let paper = ShadowElevationsPointsLabel() init() { super.init(nibName: nil, bundle: nil) self.title = "Shadow Elevations (Swift)" self.addChildViewController(appBar.headerViewController) let color = UIColor(white: 0.2, alpha:1) appBar.headerViewController.headerView.backgroundColor = color appBar.navigationBar.tintColor = .white appBar.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName : UIColor.white] let paperDim = CGFloat(200) paper.frame = CGRect(x: (view.frame.width - paperDim) / 2, y: paperDim, width: paperDim, height: paperDim) view.addSubview(paper) paper.elevation = .fabResting } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override func viewDidLoad() { super.viewDidLoad() appBar.addSubviewsToParent() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.view.backgroundColor = .white self.navigationController?.setNavigationBarHidden(true, animated: animated) } } // MARK: Catalog by convention extension ShadowElevationsTypicalUseExample { @objc class func catalogBreadcrumbs() -> [String] { return ["Shadow", "Shadow Elevations (Swift)"] } @objc class func catalogIsPrimaryDemo() -> Bool { return false } func catalogShouldHideNavigation() -> Bool { return true } }
apache-2.0
d2cad93006fc8b3f61ab8ded56495351
27.315789
98
0.738848
4.446281
false
false
false
false
boyXiong/XWSwiftRefreshT
XWSwiftRefreshT/Footer/XWRefreshAutoNormalFooter.swift
2
1896
// // XWRefreshAutoNormalFooter.swift // XWSwiftRefresh // // Created by Xiong Wei on 15/10/6. // Copyright © 2015年 Xiong Wei. All rights reserved. // 新浪微博: @爱吃香干炒肉 import UIKit /** footerView 带有菊花和状态文字的 */ public class XWRefreshAutoNormalFooter: XWRefreshAutoStateFooter { //MARK: 外部访问 /** 菊花样式 */ public var activityIndicatorViewStyle = UIActivityIndicatorViewStyle.Gray { didSet{ self.activityView.activityIndicatorViewStyle = activityIndicatorViewStyle self.setNeedsLayout() } } //MARK: 私有 //菊花 lazy var activityView:UIActivityIndicatorView = { [unowned self] in let activityView = UIActivityIndicatorView(activityIndicatorStyle: self.activityIndicatorViewStyle) activityView.hidesWhenStopped = true self.addSubview(activityView) return activityView }() //MARK: 重写 override func placeSubvies() { super.placeSubvies() //菊花 var activityViewCenterX = self.xw_width * 0.5 if !self.refreshingTitleHidden { activityViewCenterX -= XWRefreshFooterActivityViewDeviation } let activityViewCenterY = self.xw_height * 0.5 self.activityView.center = CGPointMake(activityViewCenterX, activityViewCenterY) } override var state:XWRefreshState{ didSet{ if oldValue == state { return } if state == XWRefreshState.NoMoreData || state == XWRefreshState.Idle { self.activityView.stopAnimating() }else if state == XWRefreshState.Refreshing { self.activityView.startAnimating() } } } }
mit
5c77428de8fd04459cc7b9deaf6287fd
25.391304
107
0.596376
5.324561
false
false
false
false
glessard/swift-channels
utilities/logging.swift
1
1658
// // syncprint.swift // // Created by Guillaume Lessard on 2014-08-22. // Copyright (c) 2014 Guillaume Lessard. All rights reserved. // // https://gist.github.com/glessard/826241431dcea3655d1e // import Dispatch import Foundation.NSThread private let PrintQueue = DispatchQueue(label: "com.tffenterprises.syncprint", attributes: []) private let PrintGroup = DispatchGroup() private var silenceOutput: Int32 = 0 /** A wrapper for println that runs all requests on a serial queue Writes a basic thread identifier (main or back), the textual representation of `object`, and a newline character onto the standard output. The textual representation is obtained from the `object` using its protocol conformances, in the following order of preference: `Streamable`, `Printable`, `DebugPrintable`. :param: object the item to be printed */ public func syncprint<T>(_ object: T) { let message = Foundation.Thread.current.isMainThread ? "[main] " : "[back] " PrintQueue.async(group: PrintGroup) { // There is no particularly straightforward way to ensure an atomic read if OSAtomicAdd32(0, &silenceOutput) == 0 { print(message, object) } } } /** Block until all tasks created by syncprint() have completed. */ public func syncprintwait() { // Wait at most 200ms for the last messages to print out. let res = PrintGroup.wait(timeout: DispatchTime.now() + Double(200_000_000) / Double(NSEC_PER_SEC)) if res == .timedOut { OSAtomicIncrement32Barrier(&silenceOutput) PrintGroup.notify(queue: PrintQueue) { print("Skipped output") OSAtomicDecrement32Barrier(&silenceOutput) } } }
mit
ed6c641b0b7366e305ac2963a211348e
26.633333
101
0.718335
3.864802
false
false
false
false
kentaiwami/FiNote
ios/FiNote/FiNote/Social/SocialViewController.swift
1
4079
// // SocialViewController.swift // FiNote // // Created by 岩見建汰 on 2018/01/29. // Copyright © 2018年 Kenta. All rights reserved. // import UIKit import PopupDialog class SocialViewController: UIViewController { var vc: UIViewController! override func viewDidLoad() { super.viewDidLoad() SetUpView(vc: SocialRecentlyViewController(), isRemove: false) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.tabBarController?.navigationItem.title = "Social" let menu = UIBarButtonItem(image: UIImage(named: "icon_menu"), style: .plain, target: self, action: #selector(TapMenuButton)) self.tabBarController?.navigationItem.setRightBarButton(menu, animated: true) } @objc func TapMenuButton() { let recently_title = "人気ランキング" let byage_title = "年代別ランキング" let contain_title = "オノマトペで検索" let comparison_title = "オノマトペの比較" let cancel = CancelButton(title: "Cancel", action: nil) let recently = DefaultButton(title: recently_title) { self.SetUpView(vc: SocialRecentlyViewController()) } let byage = DefaultButton(title: byage_title) { self.SetUpView(vc: SocialByAgeViewController()) } let contain = DefaultButton(title: contain_title) { self.SetUpView(vc: SocialContainViewController()) } let comparison = DefaultButton(title: comparison_title) { self.SetUpView(vc: SocialComparisonViewController()) } let recently_msg = "「\(recently_title)」では1週間で追加されたユーザ数が多い順に最近話題になっている映画を確認することができます。" let byage_msg = "「\(byage_title)」では10代〜50代で人気のある映画をランキングで見ることができます。" let contain_msg = "「\(contain_title)」は検索ワードに入れたオノマトペを含む映画を見つけることができます。" let comparison_msg = "「\(comparison_title)」ではあなたが登録した映画に付けたオノマトペと他の人がどのようなオノマトペを追加しているのかを見ることができます。" var dynamic_msg = "" var popup_buttons: [PopupDialogButton] = [] switch vc.GetClassName() { case "SocialRecentlyViewController": dynamic_msg = byage_msg + "\n\n" + contain_msg + "\n\n" + comparison_msg popup_buttons = [byage, contain, comparison, cancel] case "SocialByAgeViewController": dynamic_msg = recently_msg + "\n\n" + contain_msg + "\n\n" + comparison_msg popup_buttons = [recently, contain, comparison, cancel] case "SocialContainViewController": dynamic_msg = recently_msg + "\n\n" + byage_msg + "\n\n" + comparison_msg popup_buttons = [recently, byage, comparison, cancel] case "SocialComparisonViewController": dynamic_msg = recently_msg + "\n\n" + byage_msg + "\n\n" + contain_msg popup_buttons = [recently, byage, contain, cancel] default: popup_buttons = [cancel] } let popup = PopupDialog(title: "画面の切り替え", message: dynamic_msg) popup.addButtons(popup_buttons) self.present(popup, animated: true, completion: nil) } func SetUpView(vc: UIViewController, isRemove: Bool=true) { if isRemove { let lastVC = self.children.last! lastVC.view.removeFromSuperview() lastVC.removeFromParent() } self.vc = vc self.vc.view.frame = self.view.bounds self.addChild(self.vc) self.view.addSubview(self.vc.view) vc.didMove(toParent: self) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } }
mit
ad3b0fd2c2b65a07c7488e1a3edc28ba
37.020833
133
0.623014
3.720693
false
false
false
false
garricn/secret
FLYR/AddImageCell.swift
1
936
// // AddImageCell.swift // FLYR // // Created by Garric Nahapetian on 8/20/16. // Copyright © 2016 Garric Nahapetian. All rights reserved. // import UIKit import Cartography class AddImageCell: UITableViewCell { let flyrImageView = UIImageView() init() { super.init( style: .Default, reuseIdentifier: AddImageCell.description() ) accessoryType = .DisclosureIndicator addSubview(flyrImageView) flyrImageView.contentMode = .ScaleAspectFit constrain(flyrImageView) { imageView in imageView.top == imageView.superview!.top + 8 imageView.bottom == imageView.superview!.bottom - 8 imageView.leading == imageView.superview!.leading + 8 imageView.trailing == imageView.superview!.trailing - 8 } } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } }
mit
dbd78c0d28e4b6ad14bad93914cc4f2a
24.27027
67
0.629947
4.538835
false
false
false
false
objecthub/swift-lispkit
Sources/LispKit/Data/HashTable.swift
1
11361
// // HashTable.swift // LispKit // // Created by Matthias Zenger on 14/07/2016. // Copyright © 2016 ObjectHub. 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. // /// /// `HashTable` implements hash maps natively. /// public final class HashTable: ManagedObject, CustomStringConvertible { public struct CustomProcedures { let eql: Procedure let hsh: Procedure let get: Procedure let add: Procedure let del: Procedure } public enum Equivalence { case eq case eqv case equal case custom(CustomProcedures) } /// The hash buckets. internal private(set) var buckets: Exprs /// Number of mappings in this hash table public private(set) var count: Int /// Is this `HashTable` object mutable? public let mutable: Bool /// What equivalence relation is used? public private(set) var equiv: Equivalence /// Create a new empty hash table with the given size. public init(capacity: Int = 127, mutable: Bool = true, equiv: Equivalence) { self.buckets = Exprs(repeating: .null, count: capacity) self.count = 0 self.mutable = mutable self.equiv = equiv } /// Create a copy of another hash table. Make it immutable if `mutable` is set to false. public init(copy other: HashTable, mutable: Bool = true) { self.buckets = Exprs() for i in 0..<other.buckets.count { self.buckets.append(other.buckets[i]) } self.count = other.count self.mutable = mutable self.equiv = other.equiv } /// A string representation of this variable. public var description: String { return "«hashtable \(self.buckets)»" } /// Clear entries in hash table and resize if capacity is supposed to change. This /// method creates a new array of buckets if the `capacity` parameter is provided. public func clear(_ capacity: Int? = nil) -> Bool { guard self.mutable else { return false } if let capacity = capacity { self.buckets = Exprs(repeating: .null, count: capacity) } else { for i in self.buckets.indices { self.buckets[i] = .null } } self.count = 0 return true } /// Recreates the hash table for the given capacity; this only works for non-custom /// hash tables. public func rehash(_ capacity: Int) { // Skip custom hash tables if case .custom(_) = self.equiv { return } // Save old bucket array let oldBuckets = self.buckets // Create new bucket array self.buckets = Exprs(repeating: .null, count: capacity) // Rehash the mappings for bucket in oldBuckets { var current = bucket while case .pair(.pair(let key, let value), let next) = current { let bid = self.hash(key) %% capacity self.buckets[bid] = .pair(.pair(key, value), self.buckets[bid]) current = next } } } /// Array of mappings public var mappings: [(Expr, Expr)] { var res = [(Expr, Expr)]() for bucket in self.buckets { HashTable.insertMappings(into: &res, from: bucket) } return res } /// Insert the mappings from the given bucket list into the array `arr`. private static func insertMappings(into arr: inout [(Expr, Expr)], from bucket: Expr) { var current = bucket while case .pair(.pair(let key, let value), let next) = current { arr.append((key, value)) current = next } } /// Returns the number of hash buckets in the hash table. public var bucketCount: Int { return self.buckets.count } /// Returns the mappings in the hash table as an association list with boxed values public func bucketList(_ bid: Int? = nil) -> Expr { if let bid = bid { return self.buckets[bid] } else { var res: Expr = .null for bucket in self.buckets { var current = bucket while case .pair(let mapping, let next) = current { res = .pair(mapping, res) current = next } } return res } } // Key/value accessors /// Returns a list of all keys in the hash table public var keys: Exprs { var res = Exprs() for bucket in self.buckets { var current = bucket while case .pair(.pair(let key, _), let next) = current { res.append(key) current = next } } return res } /// Returns a list of all keys in the hash table public func keyList() -> Expr { var res: Expr = .null for bucket in self.buckets { var current = bucket while case .pair(.pair(let key, _), let next) = current { res = .pair(key, res) current = next } } return res } /// Returns a list of all values in the hash table public var values: Exprs { var res = Exprs() for bucket in self.buckets { var current = bucket while case .pair(.pair(_, let value), let next) = current { res.append(value) current = next } } return res } /// Returns a list of all values in the hash table public func valueList() -> Expr { var res: Expr = .null for bucket in self.buckets { var current = bucket while case .pair(.pair(_, let value), let next) = current { res = .pair(value, res) current = next } } return res } /// Array of mappings public var entries: [(Expr, Expr)] { var res = [(Expr, Expr)]() for bucket in self.buckets { HashTable.insertMappings(into: &res, from: bucket) } return res } /// Returns the mappings in the hash table as an association list public func entryList() -> Expr { var res: Expr = .null for bucket in self.buckets { var current = bucket while case .pair(.pair(let key, let value), let next) = current { res = .pair(.pair(key, value), res) current = next } } return res } // Setting and getting mappings /// Returns the value associated with `key` in bucket `bid`. public func get(_ bid: Int, _ key: Expr, _ eql: (Expr, Expr) -> Bool) -> Expr? { var current = self.buckets[bid] while case .pair(.pair(let k, let v), let next) = current { if eql(key, k) { return .pair(k, v) } current = next } return nil } /// Adds a new mapping to bucket `bid`. If the hash table load factor is above 0.75, rehash /// the whole table. @discardableResult public func add(_ bid: Int, _ key: Expr, _ value: Expr) -> Bool { guard self.mutable else { return false } self.buckets[bid] = .pair(.pair(key, value), self.buckets[bid]) self.count += 1 if (self.count * 4 / self.buckets.count) > 3 { self.rehash(self.buckets.count * 2 + 1) } return true } /// Replaces bucket `bid` with a new bucket expression. @discardableResult public func replace(_ bid: Int, _ bucket: Expr) -> Bool { guard self.mutable else { return false } self.count += bucket.length - self.buckets[bid].length self.buckets[bid] = bucket if (self.count * 4 / self.buckets.count) > 3 { self.rehash(self.buckets.count * 2 + 1) } return true } // Support for non-custom HashMaps /// Compares two expressions for non-custom HashMaps. internal func eql(_ left: Expr, _ right: Expr) -> Bool { switch self.equiv { case .eq: return eqExpr(right, left) case .eqv: return eqvExpr(right, left) case .equal: return equalExpr(right, left) case .custom(_): preconditionFailure("cannot access custom HashTable internally") } } /// Computes the hash value for non-custom HashMaps. internal func hash(_ expr: Expr) -> Int { switch self.equiv { case .eq: return eqHash(expr) case .eqv: return eqvHash(expr) case .equal: return equalHash(expr) case .custom(_): preconditionFailure("cannot access custom HashTable internally") } } public func get(_ key: Expr) -> Expr? { return self.get(self.hash(key) %% self.buckets.count, key, self.eql) } @discardableResult public func set(key: Expr, mapsTo value: Expr) -> Bool { return self.remove(key: key) != nil && self.add(key: key, mapsTo: value) } @discardableResult public func add(key: Expr, mapsTo value: Expr) -> Bool { return self.add(self.hash(key) %% self.buckets.count, key, value) } public func remove(key: Expr) -> Expr? { guard self.mutable else { return nil } return self.remove(self.hash(key) %% self.buckets.count, key: key) } private func remove(_ bid: Int, key: Expr) -> Expr? { var ms = [(Expr, Expr)]() var current = self.buckets[bid] while case .pair(.pair(let k, let v), let next) = current { if eql(key, k) { var bucket = next for (k2, v2) in ms.reversed() { bucket = .pair(.pair(k2, v2), bucket) } self.buckets[bid] = bucket self.count -= 1 return .pair(k, v) } ms.append((k, v)) current = next } return .false } public func union(_ map: HashTable) -> Bool { guard self.mutable else { return false } for bucket in map.buckets { var current = bucket while case .pair(.pair(let key, let value), let next) = current { let bid = self.hash(key) %% self.buckets.count if self.get(bid, key, self.eql) == nil { self.add(bid, key, value) } current = next } } return true } public func difference(_ map: HashTable, intersect: Bool) -> Bool { guard self.mutable else { return false } for i in self.buckets.indices { var current = self.buckets[i] var keysToRemove = Exprs() while case .pair(.pair(let key, _), let next) = current { if intersect == (map.get(key) == nil) { keysToRemove.append(key) } current = next } if !keysToRemove.isEmpty { var ms = [(Expr, Expr)]() current = self.buckets[i] var j = 0 while case .pair(.pair(let key, let value), let next) = current { if eql(key, keysToRemove[j]) { j += 1 if j >= keysToRemove.count { var bucket = next for (k, v) in ms.reversed() { bucket = .pair(.pair(k, v), bucket) } self.buckets[i] = bucket self.count -= 1 break } } else { ms.append((key, value)) } current = next } } } return true } // Support for managed objects /// Clear variable value public override func clean() { self.buckets = Exprs(repeating: .null, count: 1) self.count = 0 self.equiv = .eq } }
apache-2.0
f7c88c9373a5877b56085b7ac1b54beb
27.044444
93
0.594911
3.893726
false
false
false
false
Urinx/SomeCodes
Swift/swiftDemo/demo.2/demo.2/ViewController.swift
1
2257
// // ViewController.swift // demo.2 // // Created by Eular on 15-3-20. // Copyright (c) 2015年 Eular. All rights reserved. // import UIKit class ViewController: UIViewController,UITextFieldDelegate { @IBOutlet var name: UITextField @IBOutlet var gentle: UISegmentedControl @IBOutlet var birth: UIDatePicker @IBOutlet var heightSlide: UISlider @IBOutlet var heightLabel: UILabel @IBOutlet var house: UISwitch @IBOutlet var result: UILabel override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. name.delegate = self } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func touchesEnded(touches: NSSet!, withEvent event: UIEvent!) { name.resignFirstResponder() } func textFieldShouldReturn(textField: UITextField!) -> Bool { name.resignFirstResponder() return true } func getAge() -> Int { let now = NSDate() let gregorian = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian) let components = gregorian.components(NSCalendarUnit.YearCalendarUnit, fromDate: birth.date, toDate: now, options: NSCalendarOptions(0)) return components.year } @IBAction func heightChange(sender: AnyObject) { var slide = sender as UISlider var h = Int(slide.value) heightSlide.value = Float(h) heightLabel.text = "\(h)厘米" } @IBAction func sureClick(sender: AnyObject) { name.resignFirstResponder() if !name.text.isEmpty { let nameStr = name.text let gentleStr = ["高富帅","白富美"][gentle.selectedSegmentIndex] let hasHouse = (house.on ? "有":"没") + "房" let heightStr = heightLabel.text let ageStr = "\(getAge())岁" result.text = "\(nameStr), \(ageStr), \(gentleStr), 身高\(heightStr), \(hasHouse), 求交往" } else { result.text = "请输入姓名" } } }
gpl-2.0
d6ee12631cee3dac263a9a3b6ae52225
27.346154
144
0.607417
4.674419
false
false
false
false
ZhangHangwei/100_days_Swift
Project_10/Project_10/ViewController.swift
1
1634
// // ViewController.swift // Project_10 // // Created by 章航伟 on 26/01/2017. // Copyright © 2017 Harvie. All rights reserved. // import UIKit class ViewController: UITableViewController { fileprivate var datas = ["后裔","亚瑟","赵云","刘备"] override func viewDidLoad() { super.viewDidLoad() self.setupTableView() } fileprivate func setupTableView() { let refreshController = UIRefreshControl() refreshController.addTarget(self, action: #selector(loadNewData(_:)), for: .valueChanged) tableView.refreshControl = refreshController } @objc fileprivate func loadNewData(_ refreshControl: UIRefreshControl) { let dispatchTime = DispatchTime.now() + 0.5 DispatchQueue.main.asyncAfter(deadline: dispatchTime) { [unowned self] in self.tableView.refreshControl?.endRefreshing() self.datas += self.datas self.tableView.reloadData() } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } extension ViewController { override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return datas.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "CellID")! as UITableViewCell cell.textLabel?.text = datas[indexPath.row] return cell } }
mit
6b4b4f944fd3a5bffab57e51ac3bcc62
27.263158
109
0.649907
5.130573
false
false
false
false
jpvasquez/Eureka
Source/Core/Validation.swift
4
3337
// RowValidationType.swift // Eureka ( https://github.com/xmartlabs/Eureka ) // // Copyright (c) 2016 Xmartlabs SRL ( 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 public struct ValidationError: Equatable { public let msg: String public init(msg: String) { self.msg = msg } } public func == (lhs: ValidationError, rhs: ValidationError) -> Bool { return lhs.msg == rhs.msg } public protocol BaseRuleType { var id: String? { get set } var validationError: ValidationError { get set } } public protocol RuleType: BaseRuleType { associatedtype RowValueType func isValid(value: RowValueType?) -> ValidationError? } public struct ValidationOptions: OptionSet { public let rawValue: Int public init(rawValue: Int) { self.rawValue = rawValue } public static let validatesOnDemand = ValidationOptions(rawValue: 1 << 0) public static let validatesOnChange = ValidationOptions(rawValue: 1 << 1) public static let validatesOnBlur = ValidationOptions(rawValue: 1 << 2) public static let validatesOnChangeAfterBlurred = ValidationOptions(rawValue: 1 << 3) public static let validatesAlways: ValidationOptions = [.validatesOnChange, .validatesOnBlur] } public struct ValidationRuleHelper<T> where T: Equatable { let validateFn: ((T?) -> ValidationError?) let rule: BaseRuleType } public struct RuleSet<T: Equatable> { internal var rules: [ValidationRuleHelper<T>] = [] public init() {} /// Add a validation Rule to a Row /// - Parameter rule: RuleType object typed to the same type of the Row.value public mutating func add<Rule: RuleType>(rule: Rule) where T == Rule.RowValueType { let validFn: ((T?) -> ValidationError?) = { (val: T?) in return rule.isValid(value: val) } rules.append(ValidationRuleHelper(validateFn: validFn, rule: rule)) } public mutating func remove(ruleWithIdentifier identifier: String) { if let index = rules.firstIndex(where: { (validationRuleHelper) -> Bool in return validationRuleHelper.rule.id == identifier }) { rules.remove(at: index) } } public mutating func removeAllRules() { rules.removeAll() } }
mit
1c8540ae44074e34c1274ca19570c76a
32.707071
97
0.704525
4.46123
false
false
false
false
parthdubal/MyNewyorkTimes
MyNewyorkTimesTests/TestNetworkService.swift
1
3539
// // TestNetworkService.swift // MyNewyorkTimes // // Created by Parth Dubal on 7/27/17. // Copyright © 2017 Parth Dubal. All rights reserved. // import Foundation import UIKit @testable import MyNewyorkTimes /// MOCK Test services class for various types of response class TestNetworkService : NSObject , NetworkServiceInterface { private var baseURL:URL? private var httpHeaders = [String:String]() private var reachability = Reachability() static private var sharedNetworkServices:TestNetworkService = { let networkServicesObject = TestNetworkService() return networkServicesObject }() static func sharedServices() -> NetworkServiceInterface { return sharedNetworkServices } private func bundle() -> Bundle { return Bundle(for: self.classForCoder) } func setBaseUrl(stringURL:String) { } func setTimeInterval(_ interval : TimeInterval) { } func setShowNetworkIndicator(indicator:Bool) { } func setValue(_ value: String, forHTTPHeaderField field: String) { httpHeaders[field] = value } func removeHTTPHeaderField(_ field:String) { httpHeaders[field] = nil } func valueForHTTPHeaderField(_ field:String) -> String? { return httpHeaders[field] } /// Perform mock Get request for all network services /// /// - Parameters: /// - urlPath: url Path to retriev /// - parameters: http parameters /// - resultBlock: return request result /// - errorBlock: return request error if any func getRequest(urlPath: String, parameters: [String:String]?, resultBlock:@escaping ((_ response:Any) -> Void), errorBlock: @escaping ((NSError) -> Void)) { //We will perform checkpoint for all cases here. let bundle = self.bundle() guard (httpHeaders[APIConstant.APIKeyField] != nil) else { // no api key provided if let url = bundle.url(forResource: "NoKeyResponse", withExtension: "json"), let errorData = try? Data(contentsOf: url), let errorResponse = try? JSONSerialization.jsonObject(with: errorData, options: .mutableContainers) { resultBlock(errorResponse) } return } if let requestParameters = parameters { //check and validate parameters if let pageno = Int(requestParameters["page"] ?? "") , pageno > 120 { // page parameter excede limit send error if let url = bundle.url(forResource: "BadRequest", withExtension: "json"), let errorData = try? Data(contentsOf: url), let errorResponse = try? JSONSerialization.jsonObject(with: errorData, options: .mutableContainers) { resultBlock(errorResponse) } return } } // send success response if let url = bundle.url(forResource: "SuccessResponse", withExtension: "json"), let errorData = try? Data(contentsOf: url), let errorResponse = try? JSONSerialization.jsonObject(with: errorData, options: .mutableContainers) { resultBlock(errorResponse) } } func downloadImage(stringUrl:String, resultBlock:@escaping ((_ image:UIImage?)->Void)) { } }
mit
ef9a12f6d07217c3e0244877b697aefe
28
234
0.597795
5.180088
false
false
false
false
maxsokolov/TableKit
Sources/TableDirector.swift
3
17638
// // Copyright (c) 2015 Max Sokolov https://twitter.com/max_sokolov // // 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 /** Responsible for table view's datasource and delegate. */ open class TableDirector: NSObject, UITableViewDataSource, UITableViewDelegate { open private(set) weak var tableView: UITableView? open fileprivate(set) var sections = [TableSection]() private weak var scrollDelegate: UIScrollViewDelegate? private var cellRegisterer: TableCellRegisterer? public private(set) var rowHeightCalculator: RowHeightCalculator? private var sectionsIndexTitlesIndexes: [Int]? @available(*, deprecated, message: "Produced incorrect behaviour") open var shouldUsePrototypeCellHeightCalculation: Bool = false { didSet { if shouldUsePrototypeCellHeightCalculation { rowHeightCalculator = TablePrototypeCellHeightCalculator(tableView: tableView) } else { rowHeightCalculator = nil } } } open var isEmpty: Bool { return sections.isEmpty } public init( tableView: UITableView, scrollDelegate: UIScrollViewDelegate? = nil, shouldUseAutomaticCellRegistration: Bool = true, cellHeightCalculator: RowHeightCalculator?) { super.init() if shouldUseAutomaticCellRegistration { self.cellRegisterer = TableCellRegisterer(tableView: tableView) } self.rowHeightCalculator = cellHeightCalculator self.scrollDelegate = scrollDelegate self.tableView = tableView self.tableView?.delegate = self self.tableView?.dataSource = self NotificationCenter.default.addObserver(self, selector: #selector(didReceiveAction), name: NSNotification.Name(rawValue: TableKitNotifications.CellAction), object: nil) } public convenience init( tableView: UITableView, scrollDelegate: UIScrollViewDelegate? = nil, shouldUseAutomaticCellRegistration: Bool = true, shouldUsePrototypeCellHeightCalculation: Bool = false) { let heightCalculator: TablePrototypeCellHeightCalculator? = shouldUsePrototypeCellHeightCalculation ? TablePrototypeCellHeightCalculator(tableView: tableView) : nil self.init( tableView: tableView, scrollDelegate: scrollDelegate, shouldUseAutomaticCellRegistration: shouldUseAutomaticCellRegistration, cellHeightCalculator: heightCalculator ) } deinit { NotificationCenter.default.removeObserver(self) } open func reload() { tableView?.reloadData() } // MARK: - Private private func row(at indexPath: IndexPath) -> Row? { if indexPath.section < sections.count && indexPath.row < sections[indexPath.section].rows.count { return sections[indexPath.section].rows[indexPath.row] } return nil } // MARK: Public @discardableResult open func invoke( action: TableRowActionType, cell: UITableViewCell?, indexPath: IndexPath, userInfo: [AnyHashable: Any]? = nil) -> Any? { guard let row = row(at: indexPath) else { return nil } return row.invoke( action: action, cell: cell, path: indexPath, userInfo: userInfo ) } open override func responds(to selector: Selector) -> Bool { return super.responds(to: selector) || scrollDelegate?.responds(to: selector) == true } open override func forwardingTarget(for selector: Selector) -> Any? { return scrollDelegate?.responds(to: selector) == true ? scrollDelegate : super.forwardingTarget(for: selector) } // MARK: - Internal func hasAction(_ action: TableRowActionType, atIndexPath indexPath: IndexPath) -> Bool { guard let row = row(at: indexPath) else { return false } return row.has(action: action) } @objc func didReceiveAction(_ notification: Notification) { guard let action = notification.object as? TableCellAction, let indexPath = tableView?.indexPath(for: action.cell) else { return } invoke(action: .custom(action.key), cell: action.cell, indexPath: indexPath, userInfo: notification.userInfo) } // MARK: - Height open func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat { let row = sections[indexPath.section].rows[indexPath.row] if rowHeightCalculator != nil { cellRegisterer?.register(cellType: row.cellType, forCellReuseIdentifier: row.reuseIdentifier) } return row.defaultHeight ?? row.estimatedHeight ?? rowHeightCalculator?.estimatedHeight(forRow: row, at: indexPath) ?? UITableView.automaticDimension } open func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { let row = sections[indexPath.section].rows[indexPath.row] if rowHeightCalculator != nil { cellRegisterer?.register(cellType: row.cellType, forCellReuseIdentifier: row.reuseIdentifier) } let rowHeight = invoke(action: .height, cell: nil, indexPath: indexPath) as? CGFloat return rowHeight ?? row.defaultHeight ?? rowHeightCalculator?.height(forRow: row, at: indexPath) ?? UITableView.automaticDimension } // MARK: UITableViewDataSource - configuration open func numberOfSections(in tableView: UITableView) -> Int { return sections.count } open func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { guard section < sections.count else { return 0 } return sections[section].numberOfRows } open func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let row = sections[indexPath.section].rows[indexPath.row] cellRegisterer?.register(cellType: row.cellType, forCellReuseIdentifier: row.reuseIdentifier) let cell = tableView.dequeueReusableCell(withIdentifier: row.reuseIdentifier, for: indexPath) if cell.frame.size.width != tableView.frame.size.width { cell.frame = CGRect(x: 0, y: 0, width: tableView.frame.size.width, height: cell.frame.size.height) cell.layoutIfNeeded() } row.configure(cell) invoke(action: .configure, cell: cell, indexPath: indexPath) return cell } // MARK: UITableViewDataSource - section setup open func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { guard section < sections.count else { return nil } return sections[section].headerTitle } open func tableView(_ tableView: UITableView, titleForFooterInSection section: Int) -> String? { guard section < sections.count else { return nil } return sections[section].footerTitle } // MARK: UITableViewDelegate - section setup open func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { guard section < sections.count else { return nil } return sections[section].headerView } open func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? { guard section < sections.count else { return nil } return sections[section].footerView } open func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { guard section < sections.count else { return 0 } let section = sections[section] return section.headerHeight ?? section.headerView?.frame.size.height ?? UITableView.automaticDimension } open func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { guard section < sections.count else { return 0 } let section = sections[section] return section.footerHeight ?? section.footerView?.frame.size.height ?? UITableView.automaticDimension } // MARK: UITableViewDataSource - Index public func sectionIndexTitles(for tableView: UITableView) -> [String]? { var indexTitles = [String]() var indexTitlesIndexes = [Int]() sections.enumerated().forEach { index, section in if let title = section.indexTitle { indexTitles.append(title) indexTitlesIndexes.append(index) } } if !indexTitles.isEmpty { sectionsIndexTitlesIndexes = indexTitlesIndexes return indexTitles } sectionsIndexTitlesIndexes = nil return nil } public func tableView( _ tableView: UITableView, sectionForSectionIndexTitle title: String, at index: Int) -> Int { return sectionsIndexTitlesIndexes?[index] ?? 0 } // MARK: UITableViewDelegate - actions open func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let cell = tableView.cellForRow(at: indexPath) if invoke(action: .click, cell: cell, indexPath: indexPath) != nil { tableView.deselectRow(at: indexPath, animated: true) } else { invoke(action: .select, cell: cell, indexPath: indexPath) } } open func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) { invoke(action: .deselect, cell: tableView.cellForRow(at: indexPath), indexPath: indexPath) } open func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) { invoke(action: .willDisplay, cell: cell, indexPath: indexPath) } public func tableView(_ tableView: UITableView, didEndDisplaying cell: UITableViewCell, forRowAt indexPath: IndexPath) { invoke(action: .didEndDisplaying, cell: cell, indexPath: indexPath) } open func tableView(_ tableView: UITableView, shouldHighlightRowAt indexPath: IndexPath) -> Bool { return invoke(action: .shouldHighlight, cell: tableView.cellForRow(at: indexPath), indexPath: indexPath) as? Bool ?? true } open func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? { if hasAction(.willSelect, atIndexPath: indexPath) { return invoke(action: .willSelect, cell: tableView.cellForRow(at: indexPath), indexPath: indexPath) as? IndexPath } return indexPath } open func tableView(_ tableView: UITableView, willDeselectRowAt indexPath: IndexPath) -> IndexPath? { if hasAction(.willDeselect, atIndexPath: indexPath) { return invoke(action: .willDeselect, cell: tableView.cellForRow(at: indexPath), indexPath: indexPath) as? IndexPath } return indexPath } @available(iOS 13.0, *) open func tableView( _ tableView: UITableView, shouldBeginMultipleSelectionInteractionAt indexPath: IndexPath) -> Bool { invoke(action: .shouldBeginMultipleSelection, cell: tableView.cellForRow(at: indexPath), indexPath: indexPath) as? Bool ?? false } @available(iOS 13.0, *) open func tableView( _ tableView: UITableView, didBeginMultipleSelectionInteractionAt indexPath: IndexPath) { invoke(action: .didBeginMultipleSelection, cell: tableView.cellForRow(at: indexPath), indexPath: indexPath) } @available(iOS 13.0, *) open func tableView( _ tableView: UITableView, contextMenuConfigurationForRowAt indexPath: IndexPath, point: CGPoint) -> UIContextMenuConfiguration? { invoke(action: .showContextMenu, cell: tableView.cellForRow(at: indexPath), indexPath: indexPath, userInfo: [TableKitUserInfoKeys.ContextMenuInvokePoint: point]) as? UIContextMenuConfiguration } // MARK: - Row editing open func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { return sections[indexPath.section].rows[indexPath.row].isEditingAllowed(forIndexPath: indexPath) } open func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? { return sections[indexPath.section].rows[indexPath.row].editingActions } open func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCell.EditingStyle { if invoke(action: .canDelete, cell: tableView.cellForRow(at: indexPath), indexPath: indexPath) as? Bool ?? false { return UITableViewCell.EditingStyle.delete } return UITableViewCell.EditingStyle.none } public func tableView(_ tableView: UITableView, shouldIndentWhileEditingRowAt indexPath: IndexPath) -> Bool { return false } public func tableView(_ tableView: UITableView, targetIndexPathForMoveFromRowAt sourceIndexPath: IndexPath, toProposedIndexPath proposedDestinationIndexPath: IndexPath) -> IndexPath { return invoke(action: .canMoveTo, cell: tableView.cellForRow(at: sourceIndexPath), indexPath: sourceIndexPath, userInfo: [TableKitUserInfoKeys.CellCanMoveProposedIndexPath: proposedDestinationIndexPath]) as? IndexPath ?? proposedDestinationIndexPath } open func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { invoke(action: .clickDelete, cell: tableView.cellForRow(at: indexPath), indexPath: indexPath) } } open func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool { return invoke(action: .canMove, cell: tableView.cellForRow(at: indexPath), indexPath: indexPath) as? Bool ?? false } open func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) { invoke(action: .move, cell: tableView.cellForRow(at: sourceIndexPath), indexPath: sourceIndexPath, userInfo: [TableKitUserInfoKeys.CellMoveDestinationIndexPath: destinationIndexPath]) } open func tableView(_ tableView: UITableView, accessoryButtonTappedForRowWith indexPath: IndexPath) { let cell = tableView.cellForRow(at: indexPath) invoke(action: .accessoryButtonTap, cell: cell, indexPath: indexPath) } } // MARK: - Sections manipulation extension TableDirector { @discardableResult open func append(section: TableSection) -> Self { append(sections: [section]) return self } @discardableResult open func append(sections: [TableSection]) -> Self { self.sections.append(contentsOf: sections) return self } @discardableResult open func append(rows: [Row]) -> Self { append(section: TableSection(rows: rows)) return self } @discardableResult open func insert(section: TableSection, atIndex index: Int) -> Self { sections.insert(section, at: index) return self } @discardableResult open func replaceSection(at index: Int, with section: TableSection) -> Self { if index < sections.count { sections[index] = section } return self } @discardableResult open func delete(sectionAt index: Int) -> Self { sections.remove(at: index) return self } @discardableResult open func remove(sectionAt index: Int) -> Self { return delete(sectionAt: index) } @discardableResult open func clear() -> Self { rowHeightCalculator?.invalidate() sections.removeAll() return self } // MARK: - deprecated methods @available(*, deprecated, message: "Use 'delete(sectionAt:)' method instead") @discardableResult open func delete(index: Int) -> Self { sections.remove(at: index) return self } }
mit
8606412905a71ba98bff7513d0e72434
37.427015
257
0.662037
5.306258
false
false
false
false
naithar/Kitura-net
Sources/KituraNet/HTTPParser/HTTPParser.swift
1
5662
/* * Copyright IBM Corporation 2016 * * 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 CHTTPParser import Foundation // MARK: HTTPParser class HTTPParser { /// A Handle to the HTTPParser C-library var parser: http_parser /// Settings used for HTTPParser var settings: http_parser_settings /// Parsing a request? (or a response) var isRequest = true /// Delegate used for the parsing var delegate: HTTPParserDelegate? { didSet { if let _ = delegate { withUnsafeMutablePointer(to: &delegate) { ptr in self.parser.data = UnsafeMutableRawPointer(ptr) } } } } /// Whether to upgrade the HTTP connection to HTTP 1.1 var upgrade = 1 /// Initializes a HTTPParser instance /// /// - Parameter isRequest: whether or not this HTTP message is a request /// /// - Returns: an HTTPParser instance init(isRequest: Bool) { self.isRequest = isRequest parser = http_parser() settings = http_parser_settings() settings.on_url = { (parser, chunk, length) -> Int32 in let ptr = UnsafeRawPointer(chunk!).assumingMemoryBound(to: UInt8.self) getDelegate(parser)?.onURL(ptr, count: length) return 0 } settings.on_header_field = { (parser, chunk, length) -> Int32 in let ptr = UnsafeRawPointer(chunk!).assumingMemoryBound(to: UInt8.self) getDelegate(parser)?.onHeaderField(ptr, count: length) return 0 } settings.on_header_value = { (parser, chunk, length) -> Int32 in let ptr = UnsafeRawPointer(chunk!).assumingMemoryBound(to: UInt8.self) getDelegate(parser)?.onHeaderValue(ptr, count: length) return 0 } settings.on_body = { (parser, chunk, length) -> Int32 in let delegate = getDelegate(parser) if delegate?.saveBody == true { let ptr = UnsafeRawPointer(chunk!).assumingMemoryBound(to: UInt8.self) delegate?.onBody(ptr, count: length) } return 0 } settings.on_headers_complete = { (parser) -> Int32 in // TODO: Clean and refactor //let method = String( get_method(parser)) let po = get_method(parser) var message = "" var i = 0 while((po!+i).pointee != Int8(0)) { message += String(UnicodeScalar(UInt8((po!+i).pointee))) i += 1 } getDelegate(parser)?.onHeadersComplete(method: message, versionMajor: (parser?.pointee.http_major)!, versionMinor: (parser?.pointee.http_minor)!) return 0 } settings.on_message_begin = { (parser) -> Int32 in getDelegate(parser)?.onMessageBegin() return 0 } settings.on_message_complete = { (parser) -> Int32 in let delegate = getDelegate(parser) if get_status_code(parser) == 100 { delegate?.prepareToReset() } else { delegate?.onMessageComplete() } return 0 } reset() } /// Executes the parsing on the byte array /// /// - Parameter data: pointer to a byte array /// - Parameter length: length of the byte array /// /// - Returns: ??? func execute (_ data: UnsafePointer<Int8>, length: Int) -> (Int, UInt32) { let nparsed = http_parser_execute(&parser, &settings, data, length) let upgrade = get_upgrade_value(&parser) return (nparsed, upgrade) } /// Reset the http_parser context structure. func reset() { http_parser_init(&parser, isRequest ? HTTP_REQUEST : HTTP_RESPONSE) } /// Did the request include a Connection: keep-alive header? func isKeepAlive() -> Bool { return isRequest && http_should_keep_alive(&parser) == 1 } /// Get the HTTP status code on responses var statusCode: HTTPStatusCode { return isRequest ? .unknown : HTTPStatusCode(rawValue: Int(parser.status_code)) ?? .unknown } } fileprivate func getDelegate(_ parser: UnsafeMutableRawPointer?) -> HTTPParserDelegate? { let p = parser?.assumingMemoryBound(to: http_parser.self) return p?.pointee.data.assumingMemoryBound(to: HTTPParserDelegate.self).pointee } /// Delegate protocol for HTTP parsing stages protocol HTTPParserDelegate: class { var saveBody : Bool { get } func onURL(_ url: UnsafePointer<UInt8>, count: Int) func onHeaderField(_ bytes: UnsafePointer<UInt8>, count: Int) func onHeaderValue(_ bytes: UnsafePointer<UInt8>, count: Int) func onHeadersComplete(method: String, versionMajor: UInt16, versionMinor: UInt16) func onMessageBegin() func onMessageComplete() func onBody(_ bytes: UnsafePointer<UInt8>, count: Int) func prepareToReset() }
apache-2.0
e83fd1a50a667890b6b3a10b07fc261f
32.305882
112
0.59396
4.618271
false
false
false
false
tensorflow/swift-apis
Sources/x10/swift_bindings/XLAScalarType.swift
1
4512
// Copyright 2020 TensorFlow Authors // // 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. @_implementationOnly import x10_xla_tensor_wrapper extension XLAScalar { init(_ v: Double) { self.init() self.tag = XLAScalarTypeTag_d self.value.d = v } init(_ v: Int64) { self.init() self.tag = XLAScalarTypeTag_i self.value.i = v } } public enum XLAScalarWrapper { public init(_ v: Double) { self = .d(v) } public init(_ v: Int64) { self = .i(v) } case d(Double) case i(Int64) var xlaScalar: XLAScalar { switch self { case .d(let v): return XLAScalar(v) case .i(let v): return XLAScalar(v) } } } /// A supported datatype in x10. public protocol XLAScalarType { var xlaScalarWrapper: XLAScalarWrapper { get } static var xlaTensorScalarTypeRawValue: UInt32 { get } } extension XLAScalarType { var xlaScalar: XLAScalar { xlaScalarWrapper.xlaScalar } static var xlaTensorScalarType: XLATensorScalarType { #if os(Windows) return XLATensorScalarType(rawValue: Int32(xlaTensorScalarTypeRawValue)) #else return XLATensorScalarType(rawValue: UInt32(xlaTensorScalarTypeRawValue)) #endif } } extension Float: XLAScalarType { public var xlaScalarWrapper: XLAScalarWrapper { XLAScalarWrapper(Double(self)) } static public var xlaTensorScalarTypeRawValue: UInt32 { return UInt32(XLATensorScalarType_Float.rawValue) } } extension Double: XLAScalarType { public var xlaScalarWrapper: XLAScalarWrapper { XLAScalarWrapper(self) } static public var xlaTensorScalarTypeRawValue: UInt32 { return UInt32(XLATensorScalarType_Double.rawValue) } } extension Int64: XLAScalarType { public var xlaScalarWrapper: XLAScalarWrapper { XLAScalarWrapper(self) } static public var xlaTensorScalarTypeRawValue: UInt32 { return UInt32(XLATensorScalarType_Int64.rawValue) } } extension Int32: XLAScalarType { public var xlaScalarWrapper: XLAScalarWrapper { XLAScalarWrapper(Int64(self)) } static public var xlaTensorScalarTypeRawValue: UInt32 { return UInt32(XLATensorScalarType_Int32.rawValue) } } extension Int16: XLAScalarType { public var xlaScalarWrapper: XLAScalarWrapper { XLAScalarWrapper(Int64(self)) } static public var xlaTensorScalarTypeRawValue: UInt32 { return UInt32(XLATensorScalarType_Int16.rawValue) } } extension Int8: XLAScalarType { public var xlaScalarWrapper: XLAScalarWrapper { XLAScalarWrapper(Int64(self)) } static public var xlaTensorScalarTypeRawValue: UInt32 { return UInt32(XLATensorScalarType_Int8.rawValue) } } extension UInt8: XLAScalarType { public var xlaScalarWrapper: XLAScalarWrapper { XLAScalarWrapper(Int64(self)) } static public var xlaTensorScalarTypeRawValue: UInt32 { return UInt32(XLATensorScalarType_UInt8.rawValue) } } extension Bool: XLAScalarType { public var xlaScalarWrapper: XLAScalarWrapper { XLAScalarWrapper(Int64(self ? 1 : 0)) } static public var xlaTensorScalarTypeRawValue: UInt32 { return UInt32(XLATensorScalarType_Bool.rawValue) } } /// Error implementations extension BFloat16: XLAScalarType { public var xlaScalarWrapper: XLAScalarWrapper { fatalError("BFloat16 not suported") } static public var xlaTensorScalarTypeRawValue: UInt32 { return UInt32(XLATensorScalarType_BFloat16.rawValue) } } extension UInt64: XLAScalarType { public var xlaScalarWrapper: XLAScalarWrapper { fatalError("UInt64 not suported") } static public var xlaTensorScalarTypeRawValue: UInt32 { fatalError("UInt64 not suported") } } extension UInt32: XLAScalarType { public var xlaScalarWrapper: XLAScalarWrapper { fatalError("UInt32 not suported") } static public var xlaTensorScalarTypeRawValue: UInt32 { fatalError("UInt32 not suported") } } extension UInt16: XLAScalarType { public var xlaScalarWrapper: XLAScalarWrapper { fatalError("UInt16 not suported") } static public var xlaTensorScalarTypeRawValue: UInt32 { fatalError("UInt16 not suported") } }
apache-2.0
79b48231814db80858b051fadc126e73
28.490196
89
0.750222
3.763136
false
false
false
false
tatey/LIFXHTTPKit
Source/Scene.swift
1
489
// // Created by Tate Johnson on 6/10/2015. // Copyright © 2015 Tate Johnson. All rights reserved. // import Foundation public struct Scene: Equatable { public let uuid: String public let name: String public let states: [State] public func toSelector() -> LightTargetSelector { return LightTargetSelector(type: .SceneID, value: uuid) } } public func ==(lhs: Scene, rhs: Scene) -> Bool { return lhs.uuid == rhs.uuid && lhs.name == rhs.name && lhs.states == rhs.states }
mit
7187c186326745785f3f1566d42bd316
21.181818
57
0.688525
3.297297
false
false
false
false
practicalswift/swift
test/DebugInfo/patternmatching.swift
14
3502
// RUN: %target-swift-frontend -primary-file %s -emit-ir -g -o %t.ll // RUN: %FileCheck %s < %t.ll // RUN: %FileCheck --check-prefix=CHECK-SCOPES %s < %t.ll // RUN: %target-swift-frontend -emit-sil -emit-verbose-sil -primary-file %s -o - | %FileCheck %s --check-prefix=SIL-CHECK func markUsed<T>(_ t: T) {} // CHECK-SCOPES: define {{.*}}classifyPoint2 func classifyPoint2(_ p: (Double, Double)) { func return_same (_ input : Double) -> Double { return input; // return_same gets called in both where statements } switch p { case (let x, let y) where // CHECK: call {{.*}}double {{.*}}return_same{{.*}}, !dbg ![[LOC1:.*]] // CHECK: br {{.*}}, label {{.*}}, label {{.*}}, !dbg ![[LOC2:.*]] // CHECK: call{{.*}}markUsed{{.*}}, !dbg ![[LOC3:.*]] // CHECK: ![[LOC1]] = !DILocation(line: [[@LINE+2]], // CHECK: ![[LOC2]] = !DILocation(line: [[@LINE+1]], return_same(x) == return_same(y): // CHECK: ![[LOC3]] = !DILocation(line: [[@LINE+1]], markUsed(x) // SIL-CHECK: dealloc_stack{{.*}}line:[[@LINE-1]]:17:cleanup // Verify that the branch has a location >= the cleanup. // SIL-CHECK-NEXT: br{{.*}}auto_gen // CHECK-SCOPES: call void @llvm.dbg // CHECK-SCOPES: call void @llvm.dbg // CHECK-SCOPES: call void @llvm.dbg // CHECK-SCOPES: call void @llvm.dbg{{.*}}metadata ![[X1:[0-9]+]], // CHECK-SCOPES-SAME: !dbg ![[X1LOC:[0-9]+]] // CHECK-SCOPES: call void @llvm.dbg // CHECK-SCOPES: call void @llvm.dbg{{.*}}metadata ![[X2:[0-9]+]], // CHECK-SCOPES-SAME: !dbg ![[X2LOC:[0-9]+]] // CHECK-SCOPES: call void @llvm.dbg // CHECK-SCOPES: call void @llvm.dbg{{.*}}metadata ![[X3:[0-9]+]], // CHECK-SCOPES-SAME: !dbg ![[X3LOC:[0-9]+]] case (let x, let y) where x == -y: // Verify that all variables end up in separate appropriate scopes. // CHECK-SCOPES: ![[X1]] = !DILocalVariable(name: "x", scope: ![[SCOPE1:[0-9]+]], // CHECK-SCOPES-SAME: line: [[@LINE-3]] // CHECK-SCOPES: ![[X1LOC]] = !DILocation(line: [[@LINE-4]], column: 15, // CHECK-SCOPES-SAME: scope: ![[SCOPE1]]) // FIXME: ![[SCOPE1]] = distinct !DILexicalBlock({{.*}}line: [[@LINE-6]] markUsed(x) case (let x, let y) where x >= -10 && x < 10 && y >= -10 && y < 10: // CHECK-SCOPES: ![[X2]] = !DILocalVariable(name: "x", scope: ![[SCOPE2:[0-9]+]], // CHECK-SCOPES-SAME: line: [[@LINE-2]] // CHECK-SCOPES: ![[X2LOC]] = !DILocation(line: [[@LINE-3]], column: 15, // CHECK-SCOPES-SAME: scope: ![[SCOPE2]]) markUsed(x) case (let x, let y): // CHECK-SCOPES: ![[X3]] = !DILocalVariable(name: "x", scope: ![[SCOPE3:[0-9]+]], // CHECK-SCOPES-SAME: line: [[@LINE-2]] // CHECK-SCOPES: ![[X3LOC]] = !DILocation(line: [[@LINE-3]], column: 15, // CHECK-SCOPES-SAME: scope: ![[SCOPE3]]) markUsed(x) } switch p { case (let x, let y) where x == 0: if y == 0 { markUsed(x) } else { markUsed(y) } // SIL-CHECK-NOT: br{{.*}}line:[[@LINE]]:31:cleanup case (let x, let y): do { if y == 0 { markUsed(x) } else { markUsed(y) } } // SIL-CHECK: br{{.*}}line:[[@LINE]]:5:cleanup } // CHECK: !DILocation(line: [[@LINE+1]], }
apache-2.0
c0c6f09da1c4936df1cfe63e9458a3c8
47.638889
121
0.500857
3.242593
false
false
false
false
lfaoro/Cast
Carthage/Checkouts/RxSwift/RxCocoa/Common/Observables/NSObject+Rx.swift
1
4914
// // NSObject+Rx.swift // RxCocoa // // Created by Krunoslav Zaher on 2/21/15. // Copyright (c) 2015 Krunoslav Zaher. All rights reserved. // import Foundation #if !RX_NO_MODULE import RxSwift #endif #if !DISABLE_SWIZZLING var deallocatingSubjectTriggerContext: UInt8 = 0 var deallocatingSubjectContext: UInt8 = 0 #endif var deallocatedSubjectTriggerContext: UInt8 = 0 var deallocatedSubjectContext: UInt8 = 0 // KVO is a tricky mechanism. // // When observing child in a ownership hierarchy, usually retaining observing target is wanted behavior. // When observing parent in a ownership hierarchy, usually retaining target isn't wanter behavior. // // KVO with weak references is especially tricky. For it to work, some kind of swizzling is required. // That can be done by // * replacing object class dynamically (like KVO does) // * by swizzling `dealloc` method on all instances for a class. // * some third method ... // // Both approaches can fail in certain scenarios: // * problems arise when swizzlers return original object class (like KVO does when nobody is observing) // * Problems can arise because replacing dealloc method isn't atomic operation (get implementation, // set implementation). // // Second approach is chosen. It can fail in case there are multiple libraries dynamically trying // to replace dealloc method. In case that isn't the case, it should be ok. // // KVO extension NSObject { // Observes values on `keyPath` starting from `self` with `options` and retainsSelf if `retainSelf` is set. public func rx_observe<Element>(keyPath: String, options: NSKeyValueObservingOptions = NSKeyValueObservingOptions.New.union(NSKeyValueObservingOptions.Initial), retainSelf: Bool = true) -> Observable<Element?> { return KVOObservable(object: self, keyPath: keyPath, options: options, retainTarget: retainSelf) } } #if !DISABLE_SWIZZLING // KVO extension NSObject { // Observes values on `keyPath` starting from `self` with `options` // Doesn't retain `self` and when `self` is deallocated, completes the sequence. public func rx_observeWeakly<Element>(keyPath: String, options: NSKeyValueObservingOptions = NSKeyValueObservingOptions.New.union(NSKeyValueObservingOptions.Initial)) -> Observable<Element?> { return observeWeaklyKeyPathFor(self, keyPath: keyPath, options: options) .map { n in return n as? Element } } } #endif // Dealloc extension NSObject { // Sends next element when object is deallocated and immediately completes sequence. public var rx_deallocated: Observable<Void> { return rx_synchronized { if let subject = objc_getAssociatedObject(self, &deallocatedSubjectContext) as? ReplaySubject<Void> { return subject } else { let subject = ReplaySubject<Void>.create(bufferSize: 1) let deinitAction = DeinitAction { sendNext(subject, ()) sendCompleted(subject) } objc_setAssociatedObject(self, &deallocatedSubjectContext, subject, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) objc_setAssociatedObject(self, &deallocatedSubjectTriggerContext, deinitAction, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) return subject } } } #if !DISABLE_SWIZZLING // Sends element when object `dealloc` message is sent to `self`. // Completes when `self` was deallocated. // // Has performance penalty, so prefer `rx_deallocated` when ever possible. public var rx_deallocating: Observable<Void> { return rx_synchronized { if let subject = objc_getAssociatedObject(self, &deallocatingSubjectContext) as? ReplaySubject<Void> { return subject } else { let subject = ReplaySubject<Void>.create(bufferSize: 1) objc_setAssociatedObject( self, &deallocatingSubjectContext, subject, .OBJC_ASSOCIATION_RETAIN_NONATOMIC ) let proxy = Deallocating { sendNext(subject, ()) } let deinitAction = DeinitAction { sendCompleted(subject) } objc_setAssociatedObject(self, RXDeallocatingAssociatedAction, proxy, .OBJC_ASSOCIATION_RETAIN_NONATOMIC ) objc_setAssociatedObject(self, &deallocatingSubjectTriggerContext, deinitAction, .OBJC_ASSOCIATION_RETAIN_NONATOMIC ) RX_ensure_deallocating_swizzled(self.dynamicType) return subject } } } #endif }
mit
1d184ae778416732c03d9c5027d9ceb2
36.51145
215
0.641433
5.014286
false
false
false
false
dvor/TextWiki
TextWiki/Modules/WikiText/Factory/WikiTextModuleFactory.swift
1
815
// // WikiTextModuleFactory.swift // TextWiki // // Created by Dmytro Vorobiov on 23/05/2017. // Copyright © 2017 Dmytro Vorobiov. All rights reserved. // import UIKit struct WikiTextModuleFactory { static func create() -> (moduleInput: WikiTextModuleInput, viewController: UIViewController) { let viewController = WikiTextViewController() let router = WikiTextRouter() router.viewController = viewController let presenter = WikiTextPresenter() presenter.view = viewController presenter.router = router let interactor = WikiTextInteractor() interactor.output = presenter presenter.interactor = interactor viewController.output = presenter return (moduleInput: presenter, viewController: viewController) } }
mit
da1498ba0bed816ff7f2a8dc3543098c
26.133333
98
0.695332
5.119497
false
false
false
false
Ben21hao/edx-app-ios-enterprise-new
Source/DataManager.swift
3
1170
// // DataManager.swift // edX // // Created by Akiva Leffert on 5/6/15. // Copyright (c) 2015 edX. All rights reserved. // import Foundation public class DataManager : NSObject { let courseDataManager : CourseDataManager let enrollmentManager : EnrollmentManager let interface : OEXInterface? let pushSettings : OEXPushSettingsManager let userProfileManager : UserProfileManager let userPreferenceManager: UserPreferenceManager public init( courseDataManager : CourseDataManager, enrollmentManager: EnrollmentManager, interface : OEXInterface?, pushSettings : OEXPushSettingsManager, userProfileManager : UserProfileManager, userPreferenceManager: UserPreferenceManager ) { self.courseDataManager = courseDataManager self.enrollmentManager = enrollmentManager self.pushSettings = pushSettings self.interface = interface self.userProfileManager = userProfileManager self.userPreferenceManager = userPreferenceManager } } @objc public protocol DataManagerProvider { var dataManager : DataManager { get } }
apache-2.0
d1c99d5ffcb00b8b7f2efd5f318e5326
27.560976
58
0.711966
5.366972
false
false
false
false
luinily/hOme
hOme/Model/ButtonManager.swift
1
3428
// // ButtonManager.swift // hOme // // Created by Coldefy Yoann on 2016/03/08. // Copyright © 2016年 YoannColdefy. All rights reserved. // import Foundation import CloudKit enum ButtonType: Int { case flic = 1 } class ButtonManager: CloudKitObject, Manager { private var _buttons = [String: Button]() private var _flicManager = FlicManager() private var _currentCKRecordName: String? private var _onNewFlic: (() -> Void)? var buttons: [Button] { return _buttons.values.sorted() { (button1, button2) in return button1.name < button2.name } } var count: Int {return _buttons.count} init() { _flicManager.setOnButtonGrabbed(flicGrabbed) } func createNewButton(buttonType: ButtonType, name: String, completionHandler: @escaping () -> Void) { if buttonType == .flic { createNewFlic(completionHandler: completionHandler) } } func deleteButton(_ button: Button) { if let flic = button as? FlicButton { _flicManager.deleteButton(flic) } _buttons[button.internalName] = nil } func getButton(internalName: String) -> Button? { return _buttons[internalName] } //MARK - flic functions private func createNewFlic(completionHandler: @escaping () -> Void) { _onNewFlic = completionHandler _flicManager.grabButton() } private func flicGrabbed(_ flic: Button) { if _buttons.index(forKey: flic.internalName) == nil { _buttons[flic.internalName] = flic _onNewFlic?() updateCloudKit() } } //MARK: - CloudKitObject convenience init(ckRecord: CKRecord, getCommandOfUniqueName: @escaping (_ uniqueName: String) -> CommandProtocol?) throws { self.init() _currentCKRecordName = ckRecord.recordID.recordName if let buttonList = ckRecord["buttonData"] as? [String] { for recordName in buttonList { CloudKitHelper.sharedHelper.importRecord(recordName) { (record) in do { if let record = record { guard let buttonTypeRawValue = record["type"] as? Int else { throw CommandManagerClassError.commandClassInvalid } guard let buttonType = ButtonType(rawValue: buttonTypeRawValue) else { throw CommandManagerClassError.commandClassInvalid } var button: Button? switch buttonType { case .flic: button = try FlicButton(ckRecord: record, getCommandOfUniqueName: getCommandOfUniqueName, getButtonOfIdentifier: self._flicManager.getButton) } if let button = button { self._buttons[button.internalName] = button } } } catch { } } } } } func getNewCKRecordName() -> String { return "ButtonManager" } func getCurrentCKRecordName() -> String? { return _currentCKRecordName } func getCKRecordType() -> String { return "ButtonManager" } func setUpCKRecord(_ record: CKRecord) { _currentCKRecordName = record.recordID.recordName var buttonList = [String]() for button in _buttons { buttonList.append(button.1.getNewCKRecordName()) } if !buttonList.isEmpty { record["buttonData"] = buttonList as CKRecordValue? } } func updateCloudKit() { CloudKitHelper.sharedHelper.export(self) _currentCKRecordName = getNewCKRecordName() } //MARK: - Manager func getUniqueNameBase() -> String { return "Button" } func isNameUnique(_ name: String) -> Bool { return _buttons.index(forKey: name) == nil } }
mit
8f7c3e2082f277c55a6a4534fac59b87
22.29932
149
0.673869
3.512821
false
false
false
false
RetroRebirth/Micronaut
platformer/platformer/Controller.swift
1
4271
// // Controller.swift // Micronaut // // Created by Christopher Williams on 1/16/16. // Copyright © 2016 Christopher Williams. All rights reserved. // // Handles all the input from the user. import Foundation import SpriteKit class Controller: NSObject { static var debug = false // Keep track of the relative positioning on the remote static private var initialTouchPos = CGPointMake(0, 0) static private var currentTouchPos = CGPointMake(0, 0) class func initialize(view: SKView) { loadGestures(view) } class func loadGestures(view: SKView) { // Tap let tapRecognizer = UITapGestureRecognizer(target: Controller.self, action: #selector(Controller.tapped(_:))) tapRecognizer.allowedPressTypes = [NSNumber(integer: UIPressType.Select.rawValue)]; view.addGestureRecognizer(tapRecognizer) // Swipe Up let swipeUpRecognizer = UISwipeGestureRecognizer(target: Controller.self, action: #selector(Controller.swipedUp(_:))) swipeUpRecognizer.direction = .Up view.addGestureRecognizer(swipeUpRecognizer) // Swipe Down let swipeDownRecognizer = UISwipeGestureRecognizer(target: Controller.self, action: #selector(Controller.swipedDown(_:))) swipeDownRecognizer.direction = .Down view.addGestureRecognizer(swipeDownRecognizer) // Swipe Right let swipeRightRecognizer = UISwipeGestureRecognizer(target: Controller.self, action: #selector(Controller.swipedRight(_:))) swipeRightRecognizer.direction = .Right view.addGestureRecognizer(swipeRightRecognizer) // Swipe Left let swipeLeftRecognizer = UISwipeGestureRecognizer(target: Controller.self, action: #selector(Controller.swipedLeft(_:))) swipeLeftRecognizer.direction = .Left view.addGestureRecognizer(swipeLeftRecognizer) // Pressed play/pause button let playRecognizer = UITapGestureRecognizer(target: Controller.self, action: #selector(Controller.play(_:))) playRecognizer.allowedPressTypes = [NSNumber(integer: UIPressType.PlayPause.rawValue)]; view.addGestureRecognizer(playRecognizer) } class func play(gestureRecognizer: UIGestureRecognizer) { // Toggle debug controls Controller.debug = !Controller.debug Player.clearVelocity() Player.node?.physicsBody?.affectedByGravity = !Controller.debug } class func tapped(gestureRecognizer: UIGestureRecognizer) { if Controller.debug { Player.warp() } else { Player.setShrink(Player.isBig()) } } class func swipedUp(gestureRecognizer: UIGestureRecognizer) { if Controller.debug { Player.clearVelocity() Player.setVelocityY(Constants.PlayerSpeed, force: true) } else { Player.jump() } } class func swipedDown(gestureRecognizer: UIGestureRecognizer) { if Controller.debug { Player.clearVelocity() Player.setVelocityY(-Constants.PlayerSpeed, force: true) } else { Player.setVelocityX(0.0, force: false) } } class func swipedRight(gestureRecognizer: UIGestureRecognizer) { if debug { Player.clearVelocity() } Player.setVelocityX(Constants.PlayerSpeed, force: false) } class func swipedLeft(gestureRecognizer: UIGestureRecognizer) { if debug { Player.clearVelocity() } Player.setVelocityX(-Constants.PlayerSpeed, force: false) } class func touchBegan(pos: CGPoint) { initialTouchPos = pos currentTouchPos = pos } class func touchMoved(pos: CGPoint) { currentTouchPos = pos } class func touchEnded() { // initialTouchPos = CGPointMake(0, 0) // currentTouchPos = CGPointMake(0, 0) } // Calculates the distance the user has moved their input along the X axis class func getTouchMagnitudeX() -> CGFloat { return (currentTouchPos - initialTouchPos).x } // class func calcNewPlayerVelocityDx() -> CGFloat { // return Constants.PlayerSpeed * Controller.getTouchMagnitudeX() // } }
mit
3dc7d455b61c90e3019d8c9d38e49d84
34.890756
131
0.664169
5.029446
false
false
false
false
commscheck/minesweeper
Minesweeper/Controllers/GameController.swift
1
1306
// // GameController.swift // Minesweeper // // Created by Benjamin Lea on 13/12/2015. // Copyright © 2015 Benjamin Lea. All rights reserved. // import Foundation class GameController { var board: GameBoard var delegate: GameControllerDelegate? init(width: Int, height: Int, bombs: Int) { board = GameBoard(width: width, height: height, bombs: bombs) } func revealCellAt(location: Coordinate) { if var cell: BoardCell = board.cellAt(location) { if cell.revealed == true { return } cell.revealed = true board.setCell(cell, coordinate: location) delegate?.cellRevealedAt(location) switch cell.value { case .Empty(neighbours: 0): board.accessNeighbours(location, operation: { (cell) in self.revealCellAt(cell.coordinate) }) case .Bomb: delegate?.gameOverOccurred() default: break } } } func revealNeighbours(location: Coordinate) { let x = location.x let y = location.y if x > 0 { revealCellAt(Coordinate(x - 1, y)) } if y > 0 { revealCellAt(Coordinate(x, y - 1)) } if x < board.width - 1 { revealCellAt(Coordinate(x + 1, y)) } if y < board.height - 1 { revealCellAt(Coordinate(x, y + 1)) } } }
mit
ea5c0033ad1d39442fd9556707126b53
21.5
65
0.605364
3.614958
false
false
false
false
blockchain/My-Wallet-V3-iOS
Modules/FeatureCardIssuing/Sources/FeatureCardIssuingUI/Manage/Activity/Transaction+Activity.swift
1
3611
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import BigInt import BlockchainComponentLibrary import FeatureCardIssuingDomain import Localization import MoneyKit import SwiftUI import ToolKit extension Card.Transaction { var displayDateTime: String { let dateFormatter = DateFormatter() dateFormatter.dateStyle = .short dateFormatter.timeStyle = .short return dateFormatter.string(from: userTransactionTime) } var displayTime: String { let dateFormatter = DateFormatter() dateFormatter.dateStyle = .none dateFormatter.timeStyle = .short return dateFormatter.string(from: userTransactionTime) } var displayDate: String { let dateFormatter = DateFormatter() dateFormatter.dateStyle = .short return dateFormatter.string(from: userTransactionTime) } var displayTitle: String { typealias L10n = LocalizationConstants.CardIssuing.Manage.Transaction.TransactionType switch transactionType { case .payment: return merchantName case .cashback: return [L10n.cashback, merchantName].joined(separator: " ") case .refund: return [L10n.refund, merchantName].joined(separator: " ") case .chargeback: return [L10n.chargeback, merchantName].joined(separator: " ") case .funding: return [L10n.payment, merchantName].joined(separator: " ") } } var displayStatus: String { typealias L10n = LocalizationConstants.CardIssuing.Manage.Transaction.Status switch state { case .pending: return L10n.pending case .cancelled: return L10n.cancelled case .declined: return L10n.declined case .completed: return L10n.completed } } var statusColor: Color { switch state { case .pending: return .WalletSemantic.muted case .cancelled: return .WalletSemantic.muted case .declined: return .WalletSemantic.error case .completed: return .WalletSemantic.success } } var icon: Icon { switch (state, transactionType) { case (.pending, _): return Icon.pending case (.cancelled, _): return Icon.error case (.declined, _): return Icon.error case (.completed, .chargeback), (.completed, .refund), (.completed, .cashback): return Icon.arrowDown case (.completed, _): return Icon.creditcard } } var tag: TagView { switch state { case .pending: return TagView(text: displayStatus, variant: .infoAlt) case .cancelled: return TagView(text: displayStatus, variant: .default) case .declined: return TagView(text: displayStatus, variant: .error) case .completed: return TagView(text: displayStatus, variant: .success) } } } extension FeatureCardIssuingDomain.Money { var displayString: String { guard let currency = try? CurrencyType(code: symbol), let decimal = Decimal(string: value) else { return "" } return MoneyValue.create(major: decimal, currency: currency).displayString } var isZero: Bool { guard let decimal = Decimal(string: value) else { return true } return decimal.isZero || decimal.isNaN } }
lgpl-3.0
13e8d77afb425875b0d578acf957b86a
27.650794
93
0.603324
4.951989
false
false
false
false
WickedColdfront/Slide-iOS
Pods/reddift/reddift/Model/Link.swift
1
12454
// // Link.swift // reddift // // Created by generator.rb via from https://github.com/reddit/reddit/wiki/JSON // Created at 2015-04-15 11:23:32 +0900 // import Foundation /** Returns string by replacing NOT ASCII characters with a percent escaped string using UTF8. If an argument is nil, returns vacant string. */ private func convertObjectToEscapedURLString(_ object: AnyObject?) -> String { if let urlstring = object as? String { return urlstring.addPercentEncoding } else { return "" } } /** Link content. */ public struct Link: Thing { /// identifier of Thing like 15bfi0. public let id: String /// name of Thing, that is fullname, like t3_15bfi0. public let name: String /// type of Thing, like t3. public static let kind = "t3" /** example: self.redditdev */ public let domain: String /** example: */ public let bannedBy: String /** Used for streaming video. Technical embed specific information is found here. example: {} */ public let mediaEmbed: MediaEmbed? /** subreddit of thing excluding the /r/ prefix. "pics" example: redditdev */ public let subreddit: String /** the formatted escaped HTML text. this is the HTML formatted version of the marked up text. Items that are boldened by ** or *** will now have &lt;em&gt; or *** tags on them. Additionally, bullets and numbered lists will now be in HTML list format. NOTE: The HTML string will be escaped. You must unescape to get the raw HTML. Null if not present. example: &lt;!-- SC_OFF --&gt;&lt;div class="md"&gt;&lt;p&gt;So this is the code I ran:&lt;/p&gt; &lt;pre&gt;&lt;code&gt;r = praw.Reddit(&amp;quot;/u/habnpam sflkajsfowifjsdlkfj test test test&amp;quot;) for c in praw.helpers.comment_stream(reddit_session=r, subreddit=&amp;quot;helpmefind&amp;quot;, limit=500, verbosity=1): print(c.author) &lt;/code&gt;&lt;/pre&gt; &lt;hr/&gt; &lt;p&gt;From what I understand, comment_stream() gets the most recent comments. So if we specify the limit to be 100, it will initially get the 100 newest comment, and then constantly update to get new comments. It seems to works appropriately for every subreddit except &lt;a href="/r/helpmefind"&gt;/r/helpmefind&lt;/a&gt;. For &lt;a href="/r/helpmefind"&gt;/r/helpmefind&lt;/a&gt;, it fetches around 30 comments, regardless of the limit.&lt;/p&gt; &lt;/div&gt;&lt;!-- SC_ON --&gt; */ public let selftextHtml: String /** the raw text. this is the unformatted text which includes the raw markup characters such as ** for bold. &lt;, &gt;, and &amp; are escaped. Empty if not present. example: So this is the code I ran: r = praw.Reddit("/u/habnpam sflkajsfowifjsdlkfj test test test") for c in praw.helpers.comment_stream(reddit_session=r, subreddit="helpmefind", limit=500, verbosity=1): print(c.author) --- From what I understand, comment_stream() gets the most recent comments. So if we specify the limit to be 100, it will initially get the 100 newest comment, and then constantly update to get new comments. It seems to works appropriately for every subreddit except /r/helpmefind. For /r/helpmefind, it fetches around 30 comments, regardless of the limit. */ public let selftext: String /** how the logged-in user has voted on the link - True = upvoted, False = downvoted, null = no vote example: */ public let likes: VoteDirection /** example: [] */ public let userReports: [AnyObject] /** example: */ public let secureMedia: AnyObject? /** the text of the link's flair. example: */ public let linkFlairText: String /** example: 0 */ public let gilded: Int /** example: false */ public let archived: Bool public let locked: Bool /** probably always returns false example: false */ public let clicked: Bool /** example: */ public let reportReasons: [AnyObject] /** the account name of the poster. null if this is a promotional link example: habnpam */ public let author: String /** the number of comments that belong to this link. includes removed comments. example: 10 */ public let numComments: Int /** the net-score of the link. note: A submission's score is simply the number of upvotes minus the number of downvotes. If five users like the submission and three users don't it will have a score of 2. Please note that the vote numbers are not "real" numbers, they have been "fuzzed" to prevent spam bots etc. So taking the above example, if five users upvoted the submission, and three users downvote it, the upvote/downvote numbers may say 23 upvotes and 21 downvotes, or 12 upvotes, and 10 downvotes. The points score is correct, but the vote totals are "fuzzed". example: 2 */ public let score: Int /** example: */ public let approvedBy: String /** true if the post is tagged as NSFW. False if otherwise example: false */ public let over18: Bool /** true if the post is hidden by the logged in user. false if not logged in or not hidden. example: false */ public let hidden: Bool /** full URL to the thumbnail for this link; "self" if this is a self post; "default" if a thumbnail is not available example: */ public let thumbnail: String public let baseJson: JSONDictionary /** the id of the subreddit in which the thing is located example: t5_2qizd */ public let subredditId: String /** example: false */ public let edited: Int /** the CSS class of the link's flair. example: */ public let linkFlairCssClass: String /** the CSS class of the author's flair. subreddit specific example: */ public let authorFlairCssClass: String /** example: 0 */ public let downs: Int /** example: [] */ public let modReports: [AnyObject] /** example: */ public let secureMediaEmbed: AnyObject? /** true if this post is saved by the logged in user example: false */ public let saved: Bool /** true if this link is a selfpost example: true */ public let isSelf: Bool /** relative URL of the permanent link for this link example: /r/redditdev/comments/32wnhw/praw_comment_stream_messes_up_when_getting/ */ public let permalink: String /** true if the post is set as the sticky in its subreddit. example: false */ public let stickied: Bool /** example: 1429292148 */ public let created: Int /** the link of this post. the permalink if this is a self-post example: http://www.reddit.com/r/redditdev/comments/32wnhw/praw_comment_stream_messes_up_when_getting/ */ public let url: URL? /** the text of the author's flair. subreddit specific example: */ public let authorFlairText: String /** the title of the link. may contain newlines for some reason example: [PRAW] comment_stream() messes up when getting comments from a certain subreddit. */ public let title: String /** example: 1429263348 */ public let createdUtc: Int /** example: 2 */ public let ups: Int /** example: 0.75 */ public let upvoteRatio: Double /** Used for streaming video. Detailed information about the video and it's origins are placed here example: */ public let media: Media? /** example: false */ public let visited: Bool /** example: 0 */ public let numReports: Int /** example: false */ public let distinguished: String public init(id: String) { self.id = id self.name = "\(Link.kind)_\(self.id)" domain = "" bannedBy = "" subreddit = "" selftextHtml = "" selftext = "" likes = .none linkFlairText = "" gilded = 0 archived = false locked = false clicked = false author = "" numComments = 0 score = 0 approvedBy = "" over18 = false hidden = false thumbnail = "" subredditId = "" edited = 0 linkFlairCssClass = "" authorFlairCssClass = "" downs = 0 saved = false isSelf = false permalink = "" stickied = false created = 0 url = URL.init(string: "") authorFlairText = "" title = "" createdUtc = 0 ups = 0 upvoteRatio = 0 visited = false numReports = 0 distinguished = "" media = Media(json: [:]) mediaEmbed = MediaEmbed(json: [:]) userReports = [] secureMedia = nil reportReasons = [] modReports = [] secureMediaEmbed = nil baseJson = JSONDictionary.init() } /** Parse t3 object. - parameter data: Dictionary, must be generated parsing "t3". - returns: Link object as Thing. */ public init(json data: JSONDictionary) { baseJson = data id = data["id"] as? String ?? "" domain = data["domain"] as? String ?? "" bannedBy = data["banned_by"] as? String ?? "" subreddit = data["subreddit"] as? String ?? "" let tempSelftextHtml = data["selftext_html"] as? String ?? "" selftextHtml = tempSelftextHtml.gtm_stringByUnescapingFromHTML() let tempSelftext = data["selftext"] as? String ?? "" selftext = tempSelftext.gtm_stringByUnescapingFromHTML() if let temp = data["likes"] as? Bool { likes = temp ? .up : .down } else { likes = .none } let tempFlair = data["link_flair_text"] as? String ?? "" linkFlairText = tempFlair.gtm_stringByUnescapingFromHTML() gilded = data["gilded"] as? Int ?? 0 archived = data["archived"] as? Bool ?? false locked = data["locked"] as? Bool ?? false clicked = data["clicked"] as? Bool ?? false author = data["author"] as? String ?? "" numComments = data["num_comments"] as? Int ?? 0 score = data["score"] as? Int ?? 0 approvedBy = data["approved_by"] as? String ?? "" over18 = data["over_18"] as? Bool ?? false hidden = data["hidden"] as? Bool ?? false thumbnail = convertObjectToEscapedURLString(data["thumbnail"]) subredditId = data["subreddit_id"] as? String ?? "" edited = data["edited"] as? Int ?? 0 linkFlairCssClass = data["link_flair_css_class"] as? String ?? "" authorFlairCssClass = data["author_flair_css_class"] as? String ?? "" downs = data["downs"] as? Int ?? 0 saved = data["saved"] as? Bool ?? false isSelf = data["is_self"] as? Bool ?? false let tempName = data["name"] as? String ?? "" name = tempName.gtm_stringByUnescapingFromHTML() permalink = data["permalink"] as? String ?? "" stickied = data["stickied"] as? Bool ?? false created = data["created"] as? Int ?? 0 var tempUrl = data["url"] as? String ?? "" tempUrl = tempUrl.gtm_stringByEscapingForHTML() url = URL.init(string: tempUrl.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!) authorFlairText = data["author_flair_text"] as? String ?? "" let tempTitle = data["title"] as? String ?? "" title = tempTitle.gtm_stringByUnescapingFromHTML() createdUtc = data["created_utc"] as? Int ?? 0 ups = data["ups"] as? Int ?? 0 upvoteRatio = data["upvote_ratio"] as? Double ?? 0 visited = data["visited"] as? Bool ?? false numReports = data["num_reports"] as? Int ?? 0 distinguished = data["distinguished"] as? String ?? "" media = Media(json: data["media"] as? JSONDictionary ?? [:]) mediaEmbed = MediaEmbed(json: data["media_embed"] as? JSONDictionary ?? [:]) userReports = [] secureMedia = nil reportReasons = [] modReports = [] secureMediaEmbed = nil } }
apache-2.0
862a210862b247755b0b95e71ef3d61f
32.659459
570
0.602698
4.085958
false
false
false
false
fruitcoder/ReplaceAnimation
ReplaceAnimation/PullToRefreshHeader.swift
1
18571
// // PullToRefreshHeader.swift // ReplaceAnimation // // Created by Alexander Hüllmandel on 05/03/16. // Copyright © 2016 Alexander Hüllmandel. All rights reserved. // import UIKit struct Boundary { let from : CGFloat let to : CGFloat } class PullToRefreshHeader: UICollectionReusableView { // MARK: Private properties private struct AnimationKey { static let FlyOutAnimation = "FlyOutAnimation" static let FlyInAnimation1 = "FlyInAnimation1" static let FlyInAnimation2 = "FlyInAnimation2" } private let maxPaperplaneRotation = -CGFloat(Double.pi/4) private var planeLayerCopy : PlaneLayer? private var skipSecondAnimation = false private var wiggling = false // do you call that wiggling? private var finishedFirstAnimation = false // since the network request can be too fast, we need to store the completion block passed into finishRefreshAnimation and call it // in the CATransaction completion handler of the startRefreshAnimation, to avoid interrupting the first animation private var secondAnimationCompletion : (()->Void)? = nil // constraints private var mailButtonBottomConstraintRange = Boundary(from: CGFloat(5), to : -CGFloat(28)) private var mountainsBottomConstraintRange = Boundary(from: CGFloat(-25), to: CGFloat(0)) // MARK: IBOutlets @IBOutlet weak var fgRightTreeView: TreeView! @IBOutlet weak var fgMiddleTreeView: TreeView! @IBOutlet weak var fgLeftTreeView: TreeView! @IBOutlet weak var bgLeftTreeView: TreeView! @IBOutlet weak var bgRightTreeView: TreeView! @IBOutlet weak var mailButton: MailButton! @IBOutlet weak var bottomView: UIView! @IBOutlet weak var fgMountainView: MountainView! @IBOutlet weak var mgMountainView: MountainView! // left // Constraints @IBOutlet weak var frontMountainViewBottomConstraint: NSLayoutConstraint! @IBOutlet weak var middleMountainView1BottomConstraint: NSLayoutConstraint! @IBOutlet weak var middleMountainView2BottomConstraint: NSLayoutConstraint! @IBOutlet weak var backMountainView1BottomConstraint: NSLayoutConstraint! @IBOutlet weak var backMountainView2BottomConstraint: NSLayoutConstraint! // tree constraints foreground @IBOutlet weak var fgRightTreeBottomConstraint: NSLayoutConstraint! @IBOutlet weak var fgRightTreeTrailingConstraint: NSLayoutConstraint! @IBOutlet weak var fgRightTreePropWidthConstraint: NSLayoutConstraint! @IBOutlet weak var fgMiddleTreePropWidthConstraint: NSLayoutConstraint! @IBOutlet weak var fgMiddleTreeBottomConstraint: NSLayoutConstraint! @IBOutlet weak var fgMiddleTreeTrailingConstraint: NSLayoutConstraint! @IBOutlet weak var fgLeftTreeBottomConstraint: NSLayoutConstraint! @IBOutlet weak var fgLeftTreePropWidthConstraint: NSLayoutConstraint! @IBOutlet weak var fgLeftTreeTrailingConstraint: NSLayoutConstraint! // tree constraints foreground @IBOutlet weak var bgRightTreeBottomConstraint: NSLayoutConstraint! @IBOutlet weak var bgLeftTreeBottomConstraint: NSLayoutConstraint! @IBOutlet weak var bgLeftTreeLeadingConstraint: NSLayoutConstraint! @IBOutlet weak var bgRightTreeLeadingConstraint: NSLayoutConstraint! // mail button costraints @IBOutlet weak var mailButtonBottomConstraint: NSLayoutConstraint! @IBAction func mailButtonPressed(sender: MailButton) { switch sender.buttonState { case .Default: onMailButtonPress?() case .Loading: // stop network request cancelRefreshAnimation() } } // MARK: Public properties static let Kind = "StickyHeaderLayoutAttributesKind" var onRefresh : (() -> Void)? var onMailButtonPress : (() -> Void)? var onCancel : (() -> Void)? private (set) var isLoading : Bool { get { return mailButton.buttonState == .Loading } set { mailButton.switchButtonState(animated : true) } } // MARK: - Functions // MARK: Superclass overrides override func apply(_ layoutAttributes: UICollectionViewLayoutAttributes) { guard let layoutAttributes:StickyHeaderLayoutAttributes = layoutAttributes as? StickyHeaderLayoutAttributes else { return } // when start wiggling = true, we add a wiggle animation to the trees and animate the mountains to their silent position if wiggling { fgRightTreeView.startWiggle() { self.wiggling = false } fgMiddleTreeView.startWiggle() fgLeftTreeView.startWiggle() bgLeftTreeView.startWiggle() bgRightTreeView.startWiggle() } // only synch tree bending with layout attributes if not currently wiggling if !wiggling { let bendingRight = (layoutAttributes.progress - 1.0) fgRightTreeView.currentBending = bendingRight fgMiddleTreeView.currentBending = bendingRight fgLeftTreeView.currentBending = bendingRight let bendingLeft = -(layoutAttributes.progress - 1.0) bgLeftTreeView.currentBending = bendingLeft bgRightTreeView.currentBending = bendingLeft } mailButton.planeRotation = max(0.0, (layoutAttributes.progress - 1.0)) * (-CGFloat(Double.pi/4)) // PARALLAX: first step if layoutAttributes.progress >= 1.0 && layoutAttributes.progress < 1.1 { let progress = (1.1 - layoutAttributes.progress) / 0.1 * mountainsBottomConstraintRange.from frontMountainViewBottomConstraint.constant = progress middleMountainView1BottomConstraint.constant = progress middleMountainView2BottomConstraint.constant = progress backMountainView1BottomConstraint.constant = progress backMountainView2BottomConstraint.constant = progress // force auto layout to calculate the correct frame for front mountain, this is necessary after view is loaded from xib since the frame is not yet calculated if fgMountainView.frame.width != UIScreen.main.bounds.width { layoutIfNeeded() } // Update trees updateTrees() } // second step if layoutAttributes.progress >= 1.1 && layoutAttributes.progress < 1.2 { let progress = abs(mountainsBottomConstraintRange.from) + (1.2 - layoutAttributes.progress) / 0.1 * (mountainsBottomConstraintRange.from) middleMountainView1BottomConstraint.constant = progress middleMountainView2BottomConstraint.constant = progress backMountainView1BottomConstraint.constant = progress backMountainView2BottomConstraint.constant = progress // Update trees updateTrees() } // third step if layoutAttributes.progress >= 1.2 && layoutAttributes.progress < 1.3 { let progress = 2.0 * abs(mountainsBottomConstraintRange.from) + (1.3 - layoutAttributes.progress) / 0.1 * (mountainsBottomConstraintRange.from) backMountainView1BottomConstraint.constant = progress backMountainView2BottomConstraint.constant = progress } // fourth step : progressively set the alpha of the bottom view if layoutAttributes.progress < 0.25 && layoutAttributes.progress > 0.03 { bottomView.alpha = (0.25 - layoutAttributes.progress) / 0.22 } // fifth step : animate the button up or down if layoutAttributes.progress < 0.03 && mailButtonBottomConstraint.constant != mailButtonBottomConstraintRange.to { mailButtonBottomConstraint.constant = mailButtonBottomConstraintRange.to UIView.animate(withDuration: 0.2, delay: 0.0, options: [.beginFromCurrentState], animations: { () -> Void in self.layoutIfNeeded() }, completion: nil) } if layoutAttributes.progress >= 0.03 && mailButtonBottomConstraint.constant != mailButtonBottomConstraintRange.from { mailButtonBottomConstraint.constant = mailButtonBottomConstraintRange.from UIView.animate(withDuration: 0.2, delay: 0.0, options: [.beginFromCurrentState], animations: { () -> Void in self.layoutIfNeeded() }, completion: nil) } // for fast scrolling assure values are at their boundaries if layoutAttributes.progress >= 0.25 { bottomView.alpha = 0.0 } if layoutAttributes.progress <= 0.03 { bottomView.alpha = 1.0 } if layoutAttributes.progress < 1.0 { frontMountainViewBottomConstraint.constant = mountainsBottomConstraintRange.from middleMountainView1BottomConstraint.constant = mountainsBottomConstraintRange.from middleMountainView2BottomConstraint.constant = mountainsBottomConstraintRange.from backMountainView1BottomConstraint.constant = mountainsBottomConstraintRange.from backMountainView2BottomConstraint.constant = mountainsBottomConstraintRange.from updateTrees() } if layoutAttributes.progress >= 1.3 { frontMountainViewBottomConstraint.constant = 0.0 middleMountainView1BottomConstraint.constant = abs(mountainsBottomConstraintRange.from) middleMountainView2BottomConstraint.constant = abs(mountainsBottomConstraintRange.from) backMountainView1BottomConstraint.constant = 2.0 * abs(mountainsBottomConstraintRange.from) backMountainView2BottomConstraint.constant = 2.0 * abs(mountainsBottomConstraintRange.from) updateTrees() } } override func prepareForReuse() { onRefresh = nil onMailButtonPress = nil onCancel = nil planeLayerCopy?.removeAllAnimations() planeLayerCopy?.removeFromSuperlayer() planeLayerCopy = nil } override func awakeFromNib() { let screenWidth = UIScreen.main.bounds.width mountainsBottomConstraintRange = Boundary(from: floor(-0.07 * screenWidth), to: 0) mailButtonBottomConstraintRange = Boundary(from: floor(0.014 * screenWidth), to : -floor(0.078 * screenWidth)) fgRightTreeTrailingConstraint.constant = 0.16*screenWidth fgMiddleTreeTrailingConstraint.constant = 0.0625*screenWidth fgLeftTreeTrailingConstraint.constant = 0.025*screenWidth bgLeftTreeLeadingConstraint.constant = 0.17*screenWidth bgRightTreeLeadingConstraint.constant = 0.016*screenWidth } // MARK: Private functions private func updateTrees() { let fgTreeBottomConstraint = fgMountainView.frame.height + frontMountainViewBottomConstraint.constant - floor(0.15 * fgMountainView.frame.height) fgRightTreeBottomConstraint.constant = fgTreeBottomConstraint fgMiddleTreeBottomConstraint.constant = fgTreeBottomConstraint fgLeftTreeBottomConstraint.constant = fgTreeBottomConstraint let bgTreeBottomConstraint = mgMountainView.frame.height + middleMountainView1BottomConstraint.constant - floor(0.1 * mgMountainView.frame.height) bgLeftTreeBottomConstraint.constant = bgTreeBottomConstraint bgRightTreeBottomConstraint.constant = bgTreeBottomConstraint } // MARK: Public interface func startRefreshAnimation() { if isLoading { return } else { mailButton.switchButtonState(animated: true) // hide original button layers } finishedFirstAnimation = false // set flag to react different in apply layout attributes wiggling = true // create copy of plane layer (might change to initWithLayer) planeLayerCopy = PlaneLayer() planeLayerCopy!.contentsScale = UIScreen.main.scale planeLayerCopy!.frame = mailButton.bounds planeLayerCopy!.transform = CATransform3DMakeRotation(maxPaperplaneRotation, 0.0, 0.0, 1.0) planeLayerCopy!.setNeedsDisplay() planeLayerCopy!.position = CGPoint(x: 1.1 * bounds.width, y: -0.45 * bounds.height) // model value updated to be in synch with final animation frame mailButton.layer.addSublayer(planeLayerCopy!) // position animation let flyOutAnimation = CAKeyframeAnimation(keyPath: "position") flyOutAnimation.path = { let path = UIBezierPath() path.move(to: CGPoint(x: mailButton.bounds.midX, y: mailButton.bounds.midY)) path.addQuadCurve(to: CGPoint(x: 1.1 * bounds.width, y: -0.45 * bounds.height), controlPoint: CGPoint(x: 0.6 * bounds.width, y: -0.3 * bounds.height)) return path.cgPath }() // scale animation let shrinkAnimation = CABasicAnimation(keyPath: "transform.scale") shrinkAnimation.toValue = CGFloat(0.2) // position + scale animations grouped let flyOutGroupAnimation = CAAnimationGroup() flyOutGroupAnimation.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeIn) flyOutGroupAnimation.duration = 0.5 flyOutGroupAnimation.animations = [flyOutAnimation, shrinkAnimation] flyOutAnimation.fillMode = CAMediaTimingFillMode.forwards flyOutGroupAnimation.isRemovedOnCompletion = false // add animation CATransaction.begin() CATransaction.setCompletionBlock { () -> Void in self.finishedFirstAnimation = true if (self.secondAnimationCompletion != nil) { self.finishRefreshAnimation(onCompletion: self.secondAnimationCompletion) self.secondAnimationCompletion = nil } } planeLayerCopy?.add(flyOutGroupAnimation, forKey: AnimationKey.FlyOutAnimation) CATransaction.commit() // call refresh block onRefresh?() } /// This will cancel the refresh animation by fading out the flying paperplane and fading in /// the original one on the button func cancelRefreshAnimation() { // cancel animations planeLayerCopy?.removeAllAnimations() // remove second layer from superlayer planeLayerCopy?.removeFromSuperlayer() planeLayerCopy = nil // synch model and show orinial paperplane mailButton.switchButtonState(animated: true) skipSecondAnimation = true onCancel?() } /// This will fly in the paperplane back to its original position func finishRefreshAnimation(onCompletion : (()->Void)? = nil) { // if the first animation is still in progress, "enqueue" the second animation guard finishedFirstAnimation else { secondAnimationCompletion = onCompletion; return } guard let plane = planeLayerCopy else { return } // change direction of plane plane.transform = CATransform3DMakeRotation(CGFloat(Double.pi), 0.0, 1.0, 0.0) plane.position = CGPoint(x: 1.1 * bounds.width, y: -0.4 * bounds.height) // reset flag to start second animation self.skipSecondAnimation = false // position animation let flyInAnimation1 = CAKeyframeAnimation(keyPath: "position") flyInAnimation1.path = { let path = UIBezierPath() path.move(to: CGPoint(x: 1.1 * bounds.width, y: -0.4 * bounds.height)) // start roughly where we left off path.addQuadCurve(to: CGPoint(x: -0.4 * bounds.width, y: 0.5 * mailButton.bounds.height), controlPoint: CGPoint(x: 0.4 * bounds.width, y: -0.8 * bounds.height)) return path.cgPath }() // second step position animation let flyInAnimation2 = CABasicAnimation(keyPath: "position") flyInAnimation2.fromValue = NSValue(cgPoint: CGPoint(x: -0.4 * bounds.width, y: mailButton.bounds.midY)) flyInAnimation2.toValue = NSValue(cgPoint: CGPoint(x: mailButton.bounds.midX, y: mailButton.bounds.midY)) flyInAnimation2.duration = 0.8 flyInAnimation2.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeOut) // scale animation let shrinkAnimation = CABasicAnimation(keyPath: "transform.scale") shrinkAnimation.toValue = CGFloat(1.0) // position + scale animations grouped let flyInGroupAnimation = CAAnimationGroup() flyInGroupAnimation.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeIn) flyInGroupAnimation.duration = 0.5 flyInGroupAnimation.animations = [flyInAnimation1, shrinkAnimation] flyInGroupAnimation.fillMode = CAMediaTimingFillMode.forwards flyInGroupAnimation.isRemovedOnCompletion = false CATransaction.begin() CATransaction.setCompletionBlock { () -> Void in if !self.skipSecondAnimation { // second transaction CATransaction.begin() CATransaction.setCompletionBlock({ () -> Void in if !self.skipSecondAnimation { // synch model and show orinial paperplane self.mailButton.switchButtonState(animated: false) onCompletion?() } // remove second layer from superlayer plane.removeFromSuperlayer() }) // already fade out close button self.mailButton.showCLose(show: false, animated: true) plane.position = CGPoint(x: self.mailButton.bounds.midX, y: self.mailButton.bounds.midY) // update model plane.transform = CATransform3DIdentity plane.add(flyInAnimation2, forKey: AnimationKey.FlyInAnimation2) CATransaction.commit() } } plane.add(flyInGroupAnimation, forKey: AnimationKey.FlyInAnimation1) CATransaction.commit() } } func delay(delay:Double, closure:@escaping ()->()) { DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + delay, execute: closure) }
mit
f0a418259ad434700f07371c7477268f
45.189055
172
0.668085
5.160645
false
false
false
false
Swift3Home/TLSwiftCommon
003-刷新控件/003-刷新控件/TLRefreshControl/TLRefreshView.swift
1
2061
// // TLRefreshView.swift // 003-刷新控件 // // Created by lichuanjun on 2017/7/31. // Copyright © 2017年 lichuanjun. All rights reserved. // import UIKit /// 刷新视图 - 负责刷新相关的 UI 显示和动画 class TLRefreshView: UIView { /// 刷新状态 /** iOS 系统中 UIView 封装的旋转动画 - 默认顺时针旋转 - 就近原则 - 要想实现同方向旋转,需要调整一个,非常小的数字(近) - 要想实现 360度旋转,需要核心动画 CABaseAnimation */ var refreshState: TLRefreshState = .Normal { didSet { switch refreshState { case .Normal: // 恢复状态 tipIcon.isHidden = false indicator.stopAnimating() tipLabel.text = "继续使劲拉..." UIView.animate(withDuration: 0.25){ self.tipIcon.transform = CGAffineTransform.identity } break case .Pulling: tipLabel.text = "放手就刷新..." UIView.animate(withDuration: 0.25){ self.tipIcon.transform = CGAffineTransform(rotationAngle: CGFloat(Double.pi + 0.001)) } break case .WillRefresh: tipLabel.text = "正在刷新中..." // 隐藏提示图标 tipIcon.isHidden = true // 显示菊花 indicator.startAnimating() break } } } /// 指示器 @IBOutlet weak var indicator: UIActivityIndicatorView! /// 提示图标 @IBOutlet weak var tipIcon: UIImageView! /// 提示标签 @IBOutlet weak var tipLabel: UILabel! class func refreshView() -> TLRefreshView { let nib = UINib(nibName: "TLHumanRefreshView", bundle: nil) return nib.instantiate(withOwner: nil, options: nil)[0] as! TLRefreshView } }
mit
53e6341b124716652fc2565b2b140236
25.647059
105
0.507726
4.419512
false
false
false
false
swizzlr/Either
Either/EitherType.swift
1
1311
// Copyright (c) 2014 Rob Rix. All rights reserved. /// A type representing an alternative of one of two types. /// /// By convention, and where applicable, `Left` is used to indicate failure, while `Right` is to indicate success. (Mnemonic: “right is right,” i.e. “right” is a synonym for “correct.”) /// /// Otherwise it is implied that `Left` and `Right` are effectively unordered. public protocol EitherType { typealias Left typealias Right /// Constructs a `Left` instance. class func left(value: Left) -> Self /// Constructs a `Right` instance. class func right(value: Right) -> Self /// Returns the result of applying `f` to `Left` values, or `g` to `Right` values. func either<Result>(f: Left -> Result, _ g: Right -> Result) -> Result } // MARK: API /// Equality (tho not `Equatable`) over `EitherType` where `Left` & `Right` : `Equatable`. public func == <E: EitherType where E.Left: Equatable, E.Right: Equatable> (lhs: E, rhs: E) -> Bool { return lhs.either({ $0 == rhs.either(id, const(nil)) }, { $0 == rhs.either(const(nil), id) }) } /// Inequality over `EitherType` where `Left` & `Right` : `Equatable`. public func != <E: EitherType where E.Left: Equatable, E.Right: Equatable> (lhs: E, rhs: E) -> Bool { return !(lhs == rhs) } // MARK: Imports import Prelude
mit
087cbbc4f25f864d9e036bbbf70a4f51
32.307692
185
0.665897
3.339332
false
false
false
false
azfx/Sapporo
Example/Example/Simple/SimpleViewController.swift
1
3121
// // SimpleViewController.swift // Example // // Created by Le VanNghia on 6/29/15. // Copyright (c) 2015 Le Van Nghia. All rights reserved. // import UIKit import Sapporo class SimpleViewController: UIViewController { @IBOutlet weak var collectionView: UICollectionView! lazy var sapporo: Sapporo = { [unowned self] in return Sapporo(collectionView: self.collectionView) }() override func viewDidLoad() { super.viewDidLoad() sapporo.registerNibForClass(SimpleCell) sapporo.registerNibForSupplementaryClass(SimpleHeaderView.self, kind: UICollectionElementKindSectionHeader) let layout = SAFlowLayout() //layout.sectionInset = UIEdgeInsets(top: 20, left: 0, bottom: 20, right: 0) sapporo.setLayout(layout) sapporo.loadmoreEnabled = true sapporo.loadmoreHandler = { println("Loadmore") } let section = sapporo[0] section.inset = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10) section.minimumLineSpacing = 10 section.headerViewModel = SimpleHeaderViewModel(title: "Section 0 header", height: 25) let cellmodels = (0...4).map { index -> SimpleCellModel in return SimpleCellModel(title: "cell \(index)", des: "section 0") { cell in let indexPath = cell.cellmodel?.indexPath println("Selected: indexPath: \(indexPath?.section), \(indexPath?.row)") } } section.reset(cellmodels[0]) section.bump() delay(2) { section.append([cellmodels[1], cellmodels[3], cellmodels[4]]) section.bump() println("bump") } delay(4) { section.insert(cellmodels[2], atIndex: 2) .bump() println("bump") } delay(6) { cellmodels[0].des = "changed" cellmodels[0].bump() println("bump") } delay(8) { section.remove(1) section.bump() println("bump") } delay(10) { section.move(fromIndex: 2, toIndex: 0) section.bump() println("bump") } let newSection = SASection() newSection.inset = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10) newSection.minimumLineSpacing = 10 newSection.headerViewModel = SimpleHeaderViewModel(title: "Section 1 header", height: 45) let newCellmodels = (0...16).map { index -> SimpleCellModel in let cm = SimpleCellModel(title: "cell \(index)", des: "section 1") { cell in let indexPath = cell.cellmodel?.indexPath println("Selected: indexPath: \(indexPath?.section), \(indexPath?.row)") } cm.size = CGSize(width: 170, height: 150) return cm } newSection.append(newCellmodels) delay(12) { sapporo.insert(newSection, atIndex: 1) .bump() } } }
mit
c933057a9a2a68e7c760d5dd8eba773a
31.185567
115
0.559436
4.562865
false
false
false
false
hejunbinlan/BFKit-Swift
BFKitDemo/BFKitDemo/InfoViewController.swift
3
3059
// // InfoViewController.swift // BFKitDemo // // Created by Fabrizio on 24/06/15. // Copyright (c) 2015 Fabrizio Brancati. All rights reserved. // import UIKit class InfoViewController : UIViewController { @IBOutlet var scrollView: UIScrollView! override func viewDidLoad() { let profileImage: UIImageView = UIImageView(image: UIImage(named: "Profile")!, size: CGSizeMake(200, 200), center: CGPointMake(SCREEN_WIDTH / 2, SCREEN_WIDTH / 2.5)) profileImage.setCornerRadius(profileImage.frame.size.width / 2) profileImage.createBordersWithColor(UIColor ( red: 0.9218, green: 0.565, blue: 0.139, alpha: 1.0 ), radius: 100, width: 5) let shadowLayer: UIView = UIView(frame: CGRectMake(profileImage.frame.origin.x, profileImage.frame.origin.y, profileImage.frame.size.width, profileImage.frame.size.height)) shadowLayer.createCornerRadiusShadowWithCornerRadius(profileImage.frame.size.width / 2, offset: CGSizeMake(0, 0), opacity: 0.5, radius: 10) scrollView.addSubview(shadowLayer) scrollView.addSubview(profileImage) var logoImage: UIImageView = UIImageView(image: UIImage(named: "Logo2")!, size: CGSizeMake(80, 80), center: CGPointMake(profileImage.frame.origin.x + profileImage.frame.size.width - 30, profileImage.frame.origin.y + profileImage.frame.size.height - 30)) scrollView.addSubview(logoImage) let nameLabel: UILabel = UILabel(frame: CGRectMake(0, profileImage.frame.origin.y + profileImage.frame.size.height + 50, SCREEN_WIDTH, 30), text: "Fabrizio Brancati", font: .HelveticaNeueMedium, size: 25, color: UIColor.blackColor(), alignment: .Center, lines: 1) scrollView.addSubview(nameLabel) let workLabel: UILabel = UILabel(frame: CGRectMake(0, nameLabel.frame.origin.y + nameLabel.frame.size.height + 40, SCREEN_WIDTH, 80), text: "iOS Developer\n&\nWeb Developer", font: .HelveticaNeue, size: 22, color: UIColor.blackColor(), alignment: .Center, lines: 3) scrollView.addSubview(workLabel) let siteButton: UIButton = UIButton(frame: CGRectMake(0, workLabel.frame.origin.y + workLabel.frame.size.height + 35, SCREEN_WIDTH, 44), title: "www.fabriziobrancati.com") siteButton.setTitleColor(UIColor ( red: 0.8934, green: 0.3935, blue: 0.0746, alpha: 1.0 )) siteButton.setTitleFont(.HelveticaNeueMedium, size: 20) siteButton.addTarget(self, action: "openWebsite", forControlEvents: .TouchDown) scrollView.addSubview(siteButton) scrollView.contentSize = CGSizeMake(SCREEN_WIDTH, profileImage.frame.origin.y + profileImage.frame.size.height + 50 + nameLabel.frame.size.height + 40 + workLabel.frame.size.height + 35 + siteButton.frame.size.height + 20) } @IBAction func closeInfo(sender: UIBarButtonItem) { self.dismissViewControllerAnimated(true, completion: nil) } func openWebsite() { UIApplication.sharedApplication().openURL(NSURL(string: "http://www.fabriziobrancati.com")!) } }
mit
ee618a10417bc4563f0fd2d42cc43add
57.826923
273
0.708401
4.03562
false
false
false
false
AndrewBennet/readinglist
ReadingList/Models/Book+Validation.swift
1
3606
import Foundation extension Book { @objc func validateAuthors(_ value: AutoreleasingUnsafeMutablePointer<AnyObject?>) throws { // nil authors property will be validated by the validation set on the model guard let authors = value.pointee as? [Author] else { return } if authors.isEmpty { throw BookValidationError.noAuthors.NSError() } } @objc func validateTitle(_ value: AutoreleasingUnsafeMutablePointer<AnyObject?>) throws { // nil title property will be validated by the validation set on the model guard let title = value.pointee as? String else { return } if title.isEmptyOrWhitespace { throw BookValidationError.missingTitle.NSError() } } @objc func validateIsbn13(_ value: AutoreleasingUnsafeMutablePointer<AnyObject?>) throws { guard let isbn13 = value.pointee as? Int64 else { return } if !ISBN13.isValid(isbn13) { throw BookValidationError.invalidIsbn.NSError() } } @objc func validateLanguageCode(_ value: AutoreleasingUnsafeMutablePointer<AnyObject?>) throws { guard let languageCode = value.pointee as? String else { return } if LanguageIso639_1(rawValue: languageCode) == nil { throw BookValidationError.invalidLanguageCode.NSError() } } override func validateForUpdate() throws { try super.validateForUpdate() try interPropertyValiatation() } override func validateForInsert() throws { try super.validateForInsert() try interPropertyValiatation() } func interPropertyValiatation() throws { switch readState { case .toRead: if startedReading != nil || finishedReading != nil { throw BookValidationError.invalidReadDates.NSError() } case .reading: if startedReading == nil || finishedReading != nil { throw BookValidationError.invalidReadDates.NSError() } case .finished: if startedReading == nil || finishedReading == nil { throw BookValidationError.invalidReadDates.NSError() } } if readState != .reading && (currentPage != nil || currentPercentage != nil) { throw BookValidationError.presentCurrentPage.NSError() } if googleBooksId == nil && manualBookId == nil { throw BookValidationError.missingIdentifier.NSError() } } } enum BookValidationError: Int { case missingTitle = 1 case invalidIsbn = 2 case invalidReadDates = 3 case invalidLanguageCode = 4 case missingIdentifier = 5 case noAuthors = 6 case presentCurrentPage = 7 } extension BookValidationError { var description: String { switch self { case .missingTitle: return "Title must be non-empty or whitespace" case .invalidIsbn: return "Isbn13 must be a valid ISBN" case .invalidReadDates: return "StartedReading and FinishedReading must align with ReadState" case .invalidLanguageCode: return "LanguageCode must be an ISO-639.1 value" case .missingIdentifier: return "GoogleBooksId and ManualBooksId cannot both be nil" case .noAuthors: return "Authors array must be non-empty" case .presentCurrentPage: return "CurrentPage must be nil when not Currently Reading" } } func NSError() -> NSError { return Foundation.NSError(domain: "BookErrorDomain", code: self.rawValue, userInfo: [NSLocalizedDescriptionKey: self.description]) } }
gpl-3.0
67c5f2ebaadaa7aff01591c1c64b363a
37.361702
138
0.658625
5.043357
false
false
false
false
zmeyc/GRDB.swift
Tests/GRDBTests/Record+QueryInterfaceRequestTests.swift
1
3167
import XCTest #if USING_SQLCIPHER import GRDBCipher #elseif USING_CUSTOMSQLITE import GRDBCustomSQLite #else import GRDB #endif private class Reader : Record { var id: Int64? let name: String let age: Int? init(id: Int64?, name: String, age: Int?) { self.id = id self.name = name self.age = age super.init() } required init(row: Row){ self.id = row.value(named: "id") self.name = row.value(named: "name") self.age = row.value(named: "age") super.init(row: row) } override class var databaseTableName: String { return "readers" } override var persistentDictionary: [String: DatabaseValueConvertible?] { return ["id": id, "name": name, "age": age] } override func didInsert(with rowID: Int64, for column: String?) { id = rowID } } class RecordQueryInterfaceRequestTests: GRDBTestCase { override func setup(_ dbWriter: DatabaseWriter) throws { var migrator = DatabaseMigrator() migrator.registerMigration("createReaders") { db in try db.execute( "CREATE TABLE readers (" + "id INTEGER PRIMARY KEY, " + "name TEXT NOT NULL, " + "age INT" + ")") } try migrator.migrate(dbWriter) } // MARK: - Fetch Record func testFetch() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in let arthur = Reader(id: nil, name: "Arthur", age: 42) try arthur.insert(db) let barbara = Reader(id: nil, name: "Barbara", age: 36) try barbara.insert(db) let request = Reader.all() do { let readers = try request.fetchAll(db) XCTAssertEqual(lastSQLQuery, "SELECT * FROM \"readers\"") XCTAssertEqual(readers.count, 2) XCTAssertEqual(readers[0].id!, arthur.id!) XCTAssertEqual(readers[0].name, arthur.name) XCTAssertEqual(readers[0].age, arthur.age) XCTAssertEqual(readers[1].id!, barbara.id!) XCTAssertEqual(readers[1].name, barbara.name) XCTAssertEqual(readers[1].age, barbara.age) } do { let reader = try request.fetchOne(db)! XCTAssertEqual(lastSQLQuery, "SELECT * FROM \"readers\"") XCTAssertEqual(reader.id!, arthur.id!) XCTAssertEqual(reader.name, arthur.name) XCTAssertEqual(reader.age, arthur.age) } do { let cursor = try request.fetchCursor(db) let names = cursor.map { $0.name } XCTAssertEqual(lastSQLQuery, "SELECT * FROM \"readers\"") XCTAssertEqual(try names.next()!, arthur.name) XCTAssertEqual(try names.next()!, barbara.name) XCTAssertTrue(try names.next() == nil) } } } }
mit
4dbd81ef4209f187ef8d676d6169b640
30.356436
76
0.529839
4.677991
false
false
false
false
brianpartridge/Life
Life/Game.swift
1
1320
// // Game.swift // Life // // Created by Brian Partridge on 10/25/15. // Copyright © 2015 PearTreeLabs. All rights reserved. // import Foundation public struct Game { // MARK: - Public Properties public let initialBoard: Board public private(set) var currentGeneration: Generation public let rules: RuleSet // MARK: - Initializers public init(board: Board, rules:RuleSet) { self.initialBoard = board self.currentGeneration = Generation(number: 0, board: board) self.rules = rules } // MARK: - Public Methods public mutating func tick() { let current = currentGeneration let board = currentGeneration.board let newCells = board.map { rules.evaluateForCellAtCoordinate($0, inBoard: board) } let next = Generation(number: current.number+1, board: Board(size: board.size, cells: newCells)) currentGeneration = next } } /// Represents a snapshot of a single generation in a Game. public struct Generation: CustomStringConvertible { // MARK: - Public Properties public let number: Int public let board: Board // MARK: - CustomStringConvertable public var description: String { return "Generation \(number)\n\(board.description)" } }
mit
43f3204a17aa7433f13e442486717337
23.886792
104
0.648218
4.396667
false
false
false
false
StreamOneNL/iOS-SDK-ObjC
StreamOneSDKTests/SessionTest.swift
1
9636
// // SessionTest.swift // StreamOneSDK // // Created by Nicky Gerritsen on 16-08-15. // Copyright © 2015 StreamOne. All rights reserved. // import Quick import Nimble @testable import StreamOneSDK // Request factory that returns requests that we can use during testing class SessionTestRequestFactory : RequestFactory { // Set to a list of responses to have returned each time var nextMockResponses: [String] = [] @objc func newRequest(command command: String, action: String, config: Config) -> Request { let request = TestRequest(command: command, action: action, config: config) if let mockResponse = nextMockResponses.first { request.mockResponse = mockResponse nextMockResponses.removeFirst() } return request } @objc func newSessionRequest(command command: String, action: String, config: Config, sessionStore: SessionStore) -> SessionRequest? { let request = TestSessionRequest(command: command, action: action, config: config, sessionStore: sessionStore) if let mockResponse = nextMockResponses.first { request?.mockResponse = mockResponse nextMockResponses.removeFirst() } return request } } class SessionTest : QuickSpec { override func spec() { var config: Config! let requestFactory = SessionTestRequestFactory() beforeEach { config = Config(authenticationType: .Application, authenticatorId: "id", authenticatorPsk: "psk") config.requestFactory = requestFactory } it("should use the session store from the configuration if none given during initialization") { let session = Session(config: config) expect(session.sessionStore as? MemorySessionStore).to(beIdenticalTo(config.sessionStore as? MemorySessionStore)) } it("should use the session store from the initializer if given") { let sessionStore = MemorySessionStore() let session = Session(config: config, sessionStore: sessionStore) expect(session.sessionStore as? MemorySessionStore).to(beIdenticalTo(sessionStore)) expect(session.sessionStore as? MemorySessionStore).toNot(beIdenticalTo(config.sessionStore as? MemorySessionStore)) } it("should not have an active session if setSession() has not been called on the session store") { let session = Session(config: config) expect(session.isActive).to(beFalse()) expect(session.newRequest(command: "command", action: "action")).to(beNil()) } it("should have an active session if setSession() has been called on the session store") { let session = Session(config: config) session.sessionStore.setSession(id: "id", key: "key", userId: "user_id", timeout: 1234) expect(session.isActive).to(beTrue()) expect(session.newRequest(command: "command", action: "action")).toNot(beNil()) } it("should be able to start a session with correct responses") { let testSessionStart: (firstResponse: String, secondResponse: String) -> Void = { firstResponse, secondResponse in let session = Session(config: config) var done = false requestFactory.nextMockResponses = [] requestFactory.nextMockResponses.append(firstResponse) requestFactory.nextMockResponses.append(secondResponse) session.start(username: "user", password: "password", ip: "ip") { success, lastResponse in done = true expect(success).to(beTrue()) expect(session.sessionStore.hasSession).to(beTrue()) } expect(done).toEventually(beTrue()) } testSessionStart( firstResponse: "{\"header\":{\"status\":0,\"statusmessage\":\"OK\",\"apiversion\":3,\"cacheable\":false,\"timezone\":\"Europe/Amsterdam\"},\"body\":{\"challenge\":\"OTzt9VSAQHQSFuEf03PZT6e5P4OoS1sw\",\"salt\":\"$2y$12$jyhye3p43mjoxvtfxflfkv\",\"needsv2hash\":false}}", secondResponse: "{\"header\":{\"status\":0,\"statusmessage\":\"OK\",\"apiversion\":3,\"cacheable\":false,\"timezone\":\"Europe/Amsterdam\"},\"body\":{\"id\":\"Hz1kPspd2Bk1\",\"key\":\"SQKEyak6R2BcwH3qnTakY50SKeABxXcg\",\"timeout\":3600,\"user\":\"QIpMpsuPCBKn\"}}" ) // Force v2 hash testSessionStart( firstResponse: "{\"header\":{\"status\":0,\"statusmessage\":\"OK\",\"apiversion\":3,\"cacheable\":false,\"timezone\":\"Europe/Amsterdam\"},\"body\":{\"challenge\":\"OTzt9VSAQHQSFuEf03PZT6e5P4OoS1sw\",\"salt\":\"$2y$12$jyhye3p43mjoxvtfxflfkv\",\"needsv2hash\":true}}", secondResponse: "{\"header\":{\"status\":0,\"statusmessage\":\"OK\",\"apiversion\":3,\"cacheable\":false,\"timezone\":\"Europe/Amsterdam\"},\"body\":{\"id\":\"Hz1kPspd2Bk1\",\"key\":\"SQKEyak6R2BcwH3qnTakY50SKeABxXcg\",\"timeout\":3600,\"user\":\"QIpMpsuPCBKn\"}}" ) } it("should not be able to start a session with incorrect responses") { let testSessionStart: (firstResponse: String, secondResponse: String) -> Void = { firstResponse, secondResponse in let session = Session(config: config) var done = false requestFactory.nextMockResponses = [] requestFactory.nextMockResponses.append(firstResponse) requestFactory.nextMockResponses.append(secondResponse) session.start(username: "user", password: "password", ip: "ip") { success, lastResponse in done = true expect(success).to(beFalse()) expect(session.sessionStore.hasSession).to(beFalse()) } expect(done).toEventually(beTrue()) } // Unsuccessful initialize response testSessionStart( firstResponse: "{\"header\":{\"status\":1,\"statusmessage\":\"Error\",\"apiversion\":3,\"cacheable\":false,\"timezone\":\"Europe/Amsterdam\"},\"body\":{\"challenge\":\"OTzt9VSAQHQSFuEf03PZT6e5P4OoS1sw\",\"salt\":\"$2y$12$jyhye3p43mjoxvtfxflfkv\",\"needsv2hash\":false}}", secondResponse: "" // Doesn't matter, first response not OK ) // Invalid body testSessionStart( firstResponse: "{\"header\":{\"status\":0,\"statusmessage\":\"OK\",\"apiversion\":3,\"cacheable\":false,\"timezone\":\"Europe/Amsterdam\"},\"body\":{\"typo\":\"OTzt9VSAQHQSFuEf03PZT6e5P4OoS1sw\",\"a\":\"$2y$12$jyhye3p43mjoxvtfxflfkv\",\"nebedsv2hash\":false}}", secondResponse: "" // Doesn't matter, first response has invalid body ) // Non-valid salt testSessionStart( firstResponse: "{\"header\":{\"status\":0,\"statusmessage\":\"OK\",\"apiversion\":3,\"cacheable\":false,\"timezone\":\"Europe/Amsterdam\"},\"body\":{\"challenge\":\"OTzt9VSAQHQSFuEf03PZT6e5P4OoS1sw\",\"salt\":\"$XX$12$thisisnotasalt\",\"needsv2hash\":false}}", secondResponse: "" // Doesn't matter, first response not OK ) // Unsuccessful create response testSessionStart( firstResponse: "{\"header\":{\"status\":0,\"statusmessage\":\"OK\",\"apiversion\":3,\"cacheable\":false,\"timezone\":\"Europe/Amsterdam\"},\"body\":{\"challenge\":\"OTzt9VSAQHQSFuEf03PZT6e5P4OoS1sw\",\"salt\":\"$2y$12$jyhye3p43mjoxvtfxflfkv\",\"needsv2hash\":false}}", secondResponse: "{\"header\":{\"status\":1,\"statusmessage\":\"Error\",\"apiversion\":3,\"cacheable\":false,\"timezone\":\"Europe/Amsterdam\"},\"body\":{\"id\":\"Hz1kPspd2Bk1\",\"key\":\"SQKEyak6R2BcwH3qnTakY50SKeABxXcg\",\"timeout\":3600,\"user\":\"QIpMpsuPCBKn\"}}" ) // Invalid body testSessionStart( firstResponse: "{\"header\":{\"status\":0,\"statusmessage\":\"OK\",\"apiversion\":3,\"cacheable\":false,\"timezone\":\"Europe/Amsterdam\"},\"body\":{\"challenge\":\"OTzt9VSAQHQSFuEf03PZT6e5P4OoS1sw\",\"salt\":\"$2y$12$jyhye3p43mjoxvtfxflfkv\",\"needsv2hash\":false}}", secondResponse: "{\"header\":{\"status\":0,\"statusmessage\":\"OK\",\"apiversion\":3,\"cacheable\":false,\"timezone\":\"Europe/Amsterdam\"},\"body\":{\"a\":\"Hz1kPspd2Bk1\",\"b\":\"SQKEyak6R2BcwH3qnTakY50SKeABxXcg\",\"c\":3600,\"d\":\"QIpMpsuPCBKn\"}}" ) } it("should not be able to end a session if none has been started") { let session = Session(config: config) var done = false session.end({ (success) -> Void in expect(success).to(beFalse()) done = true }) expect(done).toEventually(beTrue()) } it("should be able to end a session if one has been started") { let session = Session(config: config) session.sessionStore.setSession(id: "id", key: "key", userId: "user_id", timeout: 1234) var done = false // Have some response, doesn't matter what as long as the header is OK requestFactory.nextMockResponses.append("{}") session.end { _ in expect(session.isActive).to(beFalse()) expect(session.sessionStore.hasSession).to(beFalse()) done = true } expect(done).toEventually(beTrue()) } } }
mit
25f422103e6e90a948d65b8832c98bc4
48.163265
287
0.602387
4.349887
false
true
false
false
qiuncheng/CuteAttribute
CuteAttribute/TapableLabel.swift
1
6442
// // TapableLabel.swift // CuteAttribute // // Created by vsccw on 2017/11/12. // Copyright © 2017年 https://vsccw.com. All rights reserved. // import UIKit /// The delegate to handle tap of label. @objc public protocol TapableLabelDelegate: AnyObject { @objc optional func tapableLabel(_ label: TapableLabel, didTap range: NSRange, text: String?) } /// a subclass UILabel used to handle tap with CuteAttribute's `tap(_ type: CuteAttributeTapType)` @IBDesignable open class TapableLabel: UILabel { public weak var delegate: TapableLabelDelegate? private var tappingRange: NSRange? private var highlight: CuteHighlight? private var previousAttributes: Box<CuteAttribute<NSMutableAttributedString>?>? public override init(frame: CGRect) { super.init(frame: frame) commitInit() } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) commitInit() } open override func awakeFromNib() { super.awakeFromNib() commitInit() } open override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? { let superHitTest = super.hitTest(point, with: event) guard bounds.contains(point) else { return superHitTest } guard let tapRanges = cute.attributedText?.tapRanges else { return superHitTest } guard didTapRangeOfLink(inRanges: tapRanges, tapLocation: point) != nil else { return superHitTest } return self } open override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { guard let touch = touches.first else { super.touchesBegan(touches, with: event) return } let location = touch.location(in: self) guard bounds.contains(location) else { super.touchesBegan(touches, with: event) return } guard let tapRanges = cute.attributedText?.tapRanges else { super.touchesBegan(touches, with: event) return } guard let tappedRange = didTapRangeOfLink(inRanges: tapRanges, tapLocation: location) else { super.touchesBegan(touches, with: event) return } tappingRange = tappedRange let attriubes = attributedText?.attributes(at: tappedRange.location, longestEffectiveRange: nil, in: tappedRange) let attributedColor = attriubes?[.foregroundColor] as? UIColor highlight = CuteHighlight(textColor: attributedColor ?? textColor) let highlightColor = cute.attributedText?.labelHighlight?.textColor ?? CuteHighlight.default.textColor cute.attributedText = cute.attributedText? .match(range: tappedRange) .color(highlightColor) } open override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { super.touchesEnded(touches, with: event) if let tappingRange = self.tappingRange { delegate?.tapableLabel?(self, didTap: tappingRange, text: text?.nsstring.substring(with: tappingRange)) let textColor = highlight?.textColor ?? .clear cute.attributedText = cute.attributedText? .match(range: tappingRange) .color(textColor) } tappingRange = nil highlight = nil previousAttributes = nil } open override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) { super.touchesCancelled(touches, with: event) if let tappingRange = self.tappingRange { let textColor = highlight?.textColor ?? .clear cute.attributedText = cute.attributedText? .match(range: tappingRange) .color(textColor) } tappingRange = nil highlight = nil previousAttributes = nil } internal func commitInit() { isUserInteractionEnabled = true } } extension TapableLabel { internal func didTapRangeOfLink(inRanges ranges: [NSRange]?, tapLocation: CGPoint) -> NSRange? { guard let ranges = ranges, let text = self.text else { return nil } let attributedString = NSMutableAttributedString(string: text) let textRange = NSRange(location: 0, length: attributedString.length) if let font = self.font { attributedString.addAttributes([.font: font], range: textRange) } let paragraphStyle = NSMutableParagraphStyle() paragraphStyle.alignment = self.textAlignment if !text.isEmpty { let attrs = attributedText?.attributes(at: 0, effectiveRange: nil) if let paragraph = attrs?[NSAttributedString.Key.paragraphStyle] as? NSMutableParagraphStyle { paragraphStyle.lineSpacing = paragraph.lineSpacing } } attributedString.addAttributes([.paragraphStyle: paragraphStyle], range: textRange) let size = self.bounds.size let layoutManager = NSLayoutManager() let textContainer = NSTextContainer(size: CGSize.zero) let textStorage = NSTextStorage(attributedString: attributedString) layoutManager.addTextContainer(textContainer) textStorage.addLayoutManager(layoutManager) textContainer.lineFragmentPadding = 0.0 textContainer.lineBreakMode = self.lineBreakMode textContainer.maximumNumberOfLines = self.numberOfLines textContainer.size = CGSize(width: size.width, height: (size.height + CGFloat(self.numberOfLines))) let boundingBox = layoutManager.usedRect(for: textContainer) let originY = (size.height - boundingBox.height) * 0.5 - boundingBox.minY let location = CGPoint(x: tapLocation.x, y: tapLocation.y - originY) guard location.x >= boundingBox.minX, location.x <= boundingBox.minX + boundingBox.width, location.y >= boundingBox.minY, location.y <= boundingBox.minY + boundingBox.height else { return nil } let characterIndex = layoutManager.glyphIndex(for: location, in: textContainer, fractionOfDistanceThroughGlyph: nil) return ranges.filter { NSLocationInRange(characterIndex, $0) }.first } }
mit
4291eb793ae48d513c40c4a1b51ecbd2
38.503067
110
0.638453
5.130677
false
false
false
false
plus44/mhml-2016
app/Helmo/Carthage/Checkouts/MarqueeLabel/Extras/NoReturnAnimation.swift
6
841
// // NoAnimationReturn.swift // MarqueeLabel // // Created by Charles Powell on 10/23/16. // Copyright © 2016 Charles Powell. All rights reserved. import UIKit open class NoAnimationReturn: MarqueeLabel { // Override labelWillBeginScroll to catch when a scroll animation starts override open func labelWillBeginScroll() { // This only makes sense for leftRight and rightLeft types if type == .leftRight || type == .rightLeft { // Calculate "away" position time after scroll start let awayTime = animationDelay + animationDuration // Schedule a timer to restart the label when it hits the "away" position Timer.scheduledTimer(timeInterval: TimeInterval(awayTime), target: self, selector: #selector(restartLabel), userInfo: nil, repeats: false) } } }
gpl-3.0
9316e8a935821844895ce7f6c313de1c
39
150
0.689286
4.745763
false
false
false
false
RadioBear/CalmKit
CalmKit/Animators/BRBCalmKitSpectrumColumnAnimator.swift
1
3578
// // BRBCalmKitSpectrumColumnAnimator.swift // CalmKit // // Copyright (c) 2016 RadioBear // // Permission is hereby granted, free of charge, to any person obtaining a copy of // this software and associated documentation files (the "Software"), to deal in // the Software without restriction, including without limitation the rights to // use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of // the Software, and to permit persons to whom the Software is furnished to do so, // subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS // FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR // COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER // IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN // CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // // import UIKit class BRBCalmKitSpectrumColumnAnimator: BRBCalmKitAnimator { var totalDuration: NSTimeInterval = 1.0 // 空位与条型比例 var columnAndPaddingRate: CGFloat = 1.0 / 2.0 var columnsHeightRate = [CGFloat](arrayLiteral: 0.38, 0.32, 0.5, 0.25) func setupAnimation(inLayer layer : CALayer, withSize size : CGSize, withColor color : UIColor) { if columnsHeightRate.isEmpty { return ; } let beginTime = CACurrentMediaTime() let columnCount = columnsHeightRate.count let columnWidth = (size.width * columnAndPaddingRate) / ((columnAndPaddingRate * CGFloat(columnCount)) + CGFloat(columnCount - 1)) let paddingWidth = columnWidth / columnAndPaddingRate let maxHeightRate = columnsHeightRate.maxElement()! var curX: CGFloat = 0.0 for i in 0..<columnCount { let columnLayer = CALayer() columnLayer.anchorPoint = CGPointMake(0.5, 1.0) columnLayer.frame = CGRectMake(curX, 0.0, columnWidth, size.height * columnsHeightRate[i]) columnLayer.position = CGPointMake(columnLayer.position.x, size.height) columnLayer.backgroundColor = color.CGColor columnLayer.shouldRasterize = true layer.addSublayer(columnLayer) curX += columnWidth + paddingWidth let anim = CAKeyframeAnimation(keyPath: "transform.scale.y") anim.removedOnCompletion = false anim.repeatCount = HUGE anim.duration = totalDuration anim.beginTime = beginTime + (((i % 2) == 0) ? 0 : (totalDuration * 0.5)) anim.keyTimes = [0.0, 0.5, 1.0] anim.timingFunctions = [ CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut), CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut), CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut), ] let maxScale = min((maxHeightRate + columnsHeightRate[i]), 1.0) / columnsHeightRate[i] anim.values = [ 1.0, maxScale, 1.0, ] columnLayer.addAnimation(anim, forKey:"calmkit-anim") } } }
mit
67ff062f96ca5f2c6832bd0adcc43833
39.977011
138
0.645062
4.882192
false
false
false
false
silt-lang/silt
Sources/Crust/Shine.swift
1
9620
/// Parser.swift /// /// Copyright 2017-2018, The Silt Language Project. /// /// This project is released under the MIT license, a copy of which is /// available in the repository. import Lithosphere enum LayoutBlockSource { case letKeyword case whereKeyword } struct WhitespaceSummary { enum Spacer: Equatable { case spaces(Int) case tabs(Int) static func == (lhs: Spacer, rhs: Spacer) -> Bool { switch (lhs, rhs) { case let (.spaces(l), .spaces(r)): return l == r case let (.tabs(l), .tabs(r)): return l == r default: return false } } static func < (lhs: Spacer, rhs: Spacer) -> Bool { switch (lhs, rhs) { case let (.spaces(l), .spaces(r)): return l < r case let (.tabs(l), .tabs(r)): return l < r default: return false } } static func <= (lhs: Spacer, rhs: Spacer) -> Bool { switch (lhs, rhs) { case let (.spaces(l), .spaces(r)): return l <= r case let (.tabs(l), .tabs(r)): return l <= r default: return false } } } func asTrivia(_ newline: Bool) -> Trivia { var trivia: [TriviaPiece] = newline ? [.newlines(1)] : [] for val in self.sequence { switch val { case let .spaces(n): trivia.append(.spaces(n)) case let .tabs(n): trivia.append(.tabs(n)) } } return Trivia(pieces: trivia) } let sequence: [Spacer] let totals: (Int, Int) let hasNewline: Bool init(_ t: Trivia) { var seq = [Spacer]() var spaces = 0 var tabs = 0 var newl = false for i in (0..<t.count).reversed() { switch t[i] { case .spaces(let ss): spaces += ss seq.append(.spaces(ss)) continue case .tabs(let ts): tabs += ts seq.append(.tabs(ts)) continue case .comment(_): continue default: newl = true } break } self.sequence = seq self.totals = (spaces, tabs) self.hasNewline = newl } func equivalentTo(_ other: WhitespaceSummary) -> Bool { guard self.sequence.count == other.sequence.count else { return false } guard self.totals == other.totals else { return false } return true } func equalTo(_ other: WhitespaceSummary) -> Bool { guard self.equivalentTo(other) else { return false } for (l, r) in zip(self.sequence, other.sequence) { guard l == r else { return false } } return true } func lessThan(_ other: WhitespaceSummary) -> Bool { guard self.sequence.count <= other.sequence.count else { return false } for (l, r) in zip(self.sequence, other.sequence) { guard l < r else { return false } } return true } func lessThanOrEqual(_ other: WhitespaceSummary) -> Bool { guard self.sequence.count <= other.sequence.count else { return false } for (l, r) in zip(self.sequence, other.sequence) { guard l <= r else { return false } } return true } var totalWhitespaceCount: Int { return self.totals.0 + self.totals.1 } } fileprivate extension TokenSyntax { func hasEquivalentLeadingWhitespace(to other: TokenSyntax) -> Bool { guard WhitespaceSummary(self.leadingTrivia) .equalTo(WhitespaceSummary(other.leadingTrivia)) else { return false } return true } } /// Process a raw Silt token stream into a Stainless Silt token stream by /// inserting layout markers in the appropriate places. This ensures that we /// have an explicitly-scoped input to the Parser before we even try to do a /// Scope Check. public func dumpToks(_ toks: [TokenSyntax]) { for tok in toks { print(tok.text, terminator: "") } } public func layout(_ ts: [TokenSyntax]) -> [TokenSyntax] { var toks = ts if toks.isEmpty { toks.append(SyntaxFactory.makeToken(.eof, presence: .implicit)) } var stainlessToks = [TokenSyntax]() var layoutBlockStack = [(LayoutBlockSource, WhitespaceSummary)]() while toks[0].tokenKind != .eof { let tok = toks.removeFirst() let peekTok = toks[0] let wsp = WhitespaceSummary(peekTok.leadingTrivia) let ws = WhitespaceSummary(tok.leadingTrivia) guard tok.tokenKind != .letKeyword else { stainlessToks.append(tok) layoutBlockStack.append((.letKeyword, wsp)) stainlessToks.append(SyntaxFactory.makeToken(.leftBrace, presence: .implicit, leadingTrivia: .spaces(1))) stainlessToks.append(toks.removeFirst()) continue } guard tok.tokenKind != .inKeyword else { while let (src, block) = layoutBlockStack.last, src != .letKeyword { _ = layoutBlockStack.popLast() if !layoutBlockStack.isEmpty { stainlessToks.append(SyntaxFactory.makeToken(.semicolon, presence: .implicit)) stainlessToks.append(SyntaxFactory.makeToken(.rightBrace, presence: .implicit, leadingTrivia: block.asTrivia(true))) } } stainlessToks.append(SyntaxFactory.makeToken(.semicolon, presence: .implicit)) stainlessToks.append(SyntaxFactory.makeToken(.rightBrace, presence: .implicit, leadingTrivia: .spaces(1))) _ = layoutBlockStack.popLast() stainlessToks.append(tok) continue } guard tok.tokenKind != .whereKeyword else { stainlessToks.append(tok) if ws.equivalentTo(wsp) && !layoutBlockStack.isEmpty { stainlessToks.append(SyntaxFactory.makeToken(.leftBrace, presence: .implicit, leadingTrivia: .spaces(1))) stainlessToks.append(SyntaxFactory.makeToken(.rightBrace, presence: .implicit, leadingTrivia: .spaces(1))) continue } else { while let (_, block) = layoutBlockStack.last, !block.lessThanOrEqual(wsp) { _ = layoutBlockStack.popLast() if !layoutBlockStack.isEmpty { stainlessToks.append(SyntaxFactory.makeToken(.rightBrace, presence: .implicit, leadingTrivia: .newlines(1))) stainlessToks.append(SyntaxFactory.makeToken(.semicolon, presence: .implicit)) } } if layoutBlockStack.isEmpty { layoutBlockStack.append((.whereKeyword, wsp)) } else if let (_, block) = layoutBlockStack.last, !wsp.equivalentTo(block) { // If we must, begin a new layout block layoutBlockStack.append((.whereKeyword, wsp)) } stainlessToks.append(SyntaxFactory.makeToken(.leftBrace, presence: .implicit, leadingTrivia: .spaces(1))) } // Ignore the EOF guard peekTok.tokenKind != .eof else { continue } stainlessToks.append(toks.removeFirst()) continue } // If we've hit the end, push the token and bail. guard peekTok.tokenKind != .eof else { stainlessToks.append(tok) break } if ws.hasNewline, let (_, lastBlock) = layoutBlockStack.last { if ws.equivalentTo(lastBlock) { stainlessToks.append(SyntaxFactory.makeToken(.semicolon, presence: .implicit)) } else if ws.lessThan(lastBlock) { stainlessToks.append(SyntaxFactory.makeToken(.semicolon, presence: .implicit)) while let (_, block) = layoutBlockStack.last, !block.lessThanOrEqual(ws) { _ = layoutBlockStack.popLast() if !layoutBlockStack.isEmpty { stainlessToks.append(SyntaxFactory.makeToken(.rightBrace, presence: .implicit, leadingTrivia: .newlines(1))) stainlessToks.append(SyntaxFactory.makeToken(.semicolon, presence: .implicit)) } } if let (_, block) = layoutBlockStack.last, !ws.equivalentTo(block) { // If we must, begin a new layout block layoutBlockStack.append((.whereKeyword, ws)) } } } stainlessToks.append(tok) } while let _ = layoutBlockStack.popLast() { stainlessToks.append(SyntaxFactory.makeToken(.semicolon, presence: .implicit)) stainlessToks.append(SyntaxFactory.makeToken(.rightBrace, presence: .implicit, leadingTrivia: .newlines(1))) } stainlessToks.append(SyntaxFactory.makeToken(.semicolon, presence: .implicit)) // Append the EOF on the way out guard let lastTok = toks.last, case .eof = lastTok.tokenKind else { fatalError("Did not find EOF as the last token?") } stainlessToks.append(lastTok) return stainlessToks }
mit
7cc2a896cfd9e56ff26618a6051a1cd0
30.335505
80
0.54896
4.474419
false
false
false
false
Esri/tips-and-tricks-ios
DevSummit2015_TipsAndTricksDemos/Tips-And-Tricks/CoordinateConversion/CoordinateConversionViewController.swift
1
3321
// Copyright 2015 Esri // // 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 ArcGIS class CoordinateConversionViewController: UIViewController, AGSMapViewTouchDelegate, UITextFieldDelegate { @IBOutlet var textField: UITextField! @IBOutlet var mapView: AGSMapView! var graphicsLayer:AGSSketchGraphicsLayer! var symbol:AGSPictureMarkerSymbol! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. self.textField.delegate = self; // set up a starting value self.textField.text = "34 2 2.8 N, 117 53 24.66 E"; // respond to touch events self.mapView.touchDelegate = self; // add a base layer/graphics layer let mapUrl = NSURL(string: "http://services.arcgisonline.com/ArcGIS/rest/services/Canvas/World_Light_Gray_Base/MapServer") let tiledLyr = AGSTiledMapServiceLayer(URL: mapUrl); self.graphicsLayer = AGSSketchGraphicsLayer() self.mapView.addMapLayer(tiledLyr, withName:"Tiled Layer") self.mapView.addMapLayer(self.graphicsLayer, withName:"Graphics Layer") self.symbol = AGSPictureMarkerSymbol(imageNamed:"red_pin") self.symbol.offset = CGPointMake(-1, 18) // prevent content from going under the Navigation Bar self.edgesForExtendedLayout = UIRectEdge.None; } //MARK: - UITextFieldDelegate func textFieldShouldReturn(textField: UITextField) -> Bool { textField.resignFirstResponder() self.graphicsLayer.removeAllGraphics() if (!textField.text.isEmpty) { // convert DMS string to AGSPoint in our map view's spatial reference let convertedPoint: AGSPoint! = AGSPoint(fromDegreesMinutesSecondsString: textField.text, withSpatialReference: self.mapView.spatialReference) // create a graphic let graphic: AGSGraphic! = AGSGraphic(geometry: convertedPoint, symbol:self.symbol, attributes: nil) // display on the map self.graphicsLayer.addGraphic(graphic) } return false } //MARK: - AGSMapViewTouchDelegate func mapView(mapView: AGSMapView!, didClickAtPoint screen: CGPoint, mapPoint mappoint: AGSPoint!, features: [NSObject : AnyObject]!) { //clear graphic layer before any update self.graphicsLayer?.removeAllGraphics() // convert from map point to DMS string let dmsString = mappoint.degreesMinutesSecondsStringWithNumDigits(3) self.textField.text = dmsString let graphic = AGSGraphic(geometry: mappoint, symbol: self.symbol, attributes: nil) self.graphicsLayer.addGraphic(graphic) } }
apache-2.0
dc9634b1ee7aa2fa591d3f88a2fb91fb
38.070588
154
0.682023
4.956716
false
false
false
false
DarthMike/SwiftAnimations
Demo/Demo/ViewController.swift
1
1671
// // Created by Miguel Angel Quinones // Copyright 2015 Miguel Angel Quinones. See LICENSE // import UIKit import SwiftAnimations class ViewController: UIViewController { override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) } @IBAction func startAnimations() { let reset: () -> Void = { self.red.transform = CGAffineTransform.identity self.green.transform = CGAffineTransform.identity self.yellow.transform = CGAffineTransform.identity self.blue.transform = CGAffineTransform.identity } animate { self.red.transform = CGAffineTransform(rotationAngle: CGFloat(Double.pi)) }.thenAnimate { self.green.transform = CGAffineTransform(rotationAngle: CGFloat(-Double.pi)) }.afterDelay(1) .thenAnimate { self.blue.transform = CGAffineTransform(scaleX: 1.5, y: 1) }.withOptions(.curveLinear).withDuration(1).thenAnimate { self.yellow.transform = CGAffineTransform(scaleX: 1, y: 1.5) }.withOptions(.curveEaseIn) .thenAnimate { let scale = CGAffineTransform(scaleX: 0.5, y: 0.5) self.red.transform = scale self.green.transform = scale self.blue.transform = scale self.yellow.transform = scale }.thenAnimate(reset).completion { _ in print("Completed!") } } @IBOutlet fileprivate var red: UIView! @IBOutlet fileprivate var green: UIView! @IBOutlet fileprivate var blue: UIView! @IBOutlet fileprivate var yellow: UIView! }
mit
85741ce3e4242b32e50fd57f606bc6c1
32.42
88
0.622382
4.87172
false
false
false
false
clarkio/ios-favorite-movies
Favorite Movies/Favorite Movies/SearchViewController.swift
1
3583
// // SearchViewController.swift // Favorite Movies // // Created by Brian on 12/10/16. // Copyright © 2016 bc. All rights reserved. // import UIKit class SearchViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { weak var delegate: ViewController! var searchResults: [Movie] = [] @IBOutlet var searchText: UITextField! @IBOutlet var tableView: UITableView! @IBAction func search(sender: UIButton) { print("Searching for \(self.searchText.text!)") var searchTerm = searchText.text! if searchTerm.characters.count > 2 { retrieveMoviesByTerm(searchTerm: searchTerm) } } @IBAction func addFav (sender: UIButton) { print("Item #\(sender.tag) was selected as a favorite") self.delegate.favoriteMovies.append(searchResults[sender.tag]) } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return searchResults.count } func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return "Search Results" } func numberOfSections(in tableView: UITableView) -> Int { // grouped vertical sections of the tableview return 1 } func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return 0.1 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { // at init/appear ... this runs for each visible cell that needs to render let moviecell = tableView.dequeueReusableCell(withIdentifier: "customcell", for: indexPath) as! CustomTableViewCell let idx: Int = indexPath.row moviecell.favButton.tag = idx //title moviecell.movieTitle?.text = searchResults[idx].title //year moviecell.movieYear?.text = searchResults[idx].year // image displayMovieImage(idx, moviecell: moviecell) return moviecell } func displayMovieImage(_ row: Int, moviecell: CustomTableViewCell) { let url: String = (URL(string: searchResults[row].imageUrl)?.absoluteString)! URLSession.shared.dataTask(with: URL(string: url)!, completionHandler: { (data, response, error) -> Void in if error != nil { print(error!) return } DispatchQueue.main.async(execute: { let image = UIImage(data: data!) moviecell.movieImageView?.image = image }) }).resume() } override func viewDidLoad() { super.viewDidLoad() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func retrieveMoviesByTerm(searchTerm: String) { let url = "https://www.omdbapi.com/?apikey=PlzBanMe&s=\(searchTerm)&type=movie&r=json" HTTPHandler.getJson(urlString: url, completionHandler: parseDataIntoMovies) } func parseDataIntoMovies(data: Data?) -> Void { if let data = data { let object = JSONParser.parse(data: data) if let object = object { self.searchResults = MovieDataProcessor.mapJsonToMovies(object: object, moviesKey: "Search") DispatchQueue.main.async { self.tableView.reloadData() } } } } }
mit
963e8983cc436e9668c14ccbf74cd83b
32.476636
123
0.616136
4.988858
false
false
false
false
KaiCode2/swift-corelibs-foundation
Foundation/NSTextCheckingResult.swift
3
3283
// 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 // import CoreFoundation /* NSTextCheckingType in this project is limited to regular expressions. */ public struct NSTextCheckingType : OptionSet { public let rawValue: UInt64 public init(rawValue: UInt64) { self.rawValue = rawValue } public static let RegularExpression = NSTextCheckingType(rawValue: 1 << 10) // regular expression matches } public class NSTextCheckingResult : NSObject, NSCopying, NSCoding { public override init() { super.init() } public class func regularExpressionCheckingResultWithRanges(_ ranges: NSRangePointer, count: Int, regularExpression: NSRegularExpression) -> NSTextCheckingResult { return _NSRegularExpressionTextCheckingResultResult(ranges: ranges, count: count, regularExpression: regularExpression) } public required init?(coder aDecoder: NSCoder) { NSUnimplemented() } public func encodeWithCoder(_ aCoder: NSCoder) { NSUnimplemented() } public override func copy() -> AnyObject { return copyWithZone(nil) } public func copyWithZone(_ zone: NSZone) -> AnyObject { NSUnimplemented() } /* Mandatory properties, used with all types of results. */ public var resultType: NSTextCheckingType { NSUnimplemented() } public var range: NSRange { return range(at: 0) } /* A result must have at least one range, but may optionally have more (for example, to represent regular expression capture groups). The range at index 0 always matches the range property. Additional ranges, if any, will have indexes from 1 to numberOfRanges-1. */ public func range(at idx: Int) -> NSRange { NSUnimplemented() } public var regularExpression: NSRegularExpression? { return nil } public var numberOfRanges: Int { return 1 } } internal class _NSRegularExpressionTextCheckingResultResult : NSTextCheckingResult { var _ranges = [NSRange]() let _regularExpression: NSRegularExpression init(ranges: NSRangePointer, count: Int, regularExpression: NSRegularExpression) { _regularExpression = regularExpression super.init() let notFound = NSRange(location: NSNotFound,length: 0) for i in 0..<count { ranges[i].location == kCFNotFound ? _ranges.append(notFound) : _ranges.append(ranges[i]) } } internal required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override var resultType: NSTextCheckingType { return .RegularExpression } override func range(at idx: Int) -> NSRange { return _ranges[idx] } override var numberOfRanges: Int { return _ranges.count } override var regularExpression: NSRegularExpression? { return _regularExpression } } extension NSTextCheckingResult { public func resultByAdjustingRangesWithOffset(_ offset: Int) -> NSTextCheckingResult { NSUnimplemented() } }
apache-2.0
b35a9aa71e49b839206d6f813afebd72
39.036585
271
0.709717
5.137715
false
false
false
false
pawel-sp/AppFlowController
AppFlowControllerTests/AppFlowController+TransitionTests.swift
1
15152
// // AppFlowController+TransitionTests.swift // AppFlowController // // Created by Paweł Sporysz on 21.06.2017. // Copyright © 2017 Paweł Sporysz. All rights reserved. // import XCTest @testable import AppFlowController class AppFlowController_TransitionTests: XCTestCase { // MARK: - Helpers class CustomNavigationBar:UINavigationBar {} class CustomViewController:UIViewController {} class AnotherViewController:UIViewController {} // MARK: - Properties var mockNavigationController:MockNavigationController! var mockPopNavigationController:MockPopNavigationController! var viewController:UIViewController! // MARK: - Setup override func setUp() { mockNavigationController = MockNavigationController() mockPopNavigationController = MockPopNavigationController() viewController = UIViewController() } // MARK: - PushPopFlowTransition func testPushAndPopTransition_defaultAlwaysReturnsTheSameObject() { let default1 = PushPopFlowTransition.default let default2 = PushPopFlowTransition.default XCTAssertTrue(default1 === default2) } func testPushAndPopTransition_forwardTransitionUsesPush_withoutAnimation() { let transition = PushPopFlowTransition.default let exp = expectation(description: "Block need to be invoked after pushing view controller") let completion = { exp.fulfill() } let transitionBlock = transition.performForwardTransition(animated: false, completion: completion) transitionBlock(mockNavigationController, viewController) waitForExpectations(timeout: 0.1) { error in if let error = error { XCTFail(error.localizedDescription) } } XCTAssertEqual(mockNavigationController.pushViewControllerParams?.0, viewController) XCTAssertFalse(mockNavigationController.pushViewControllerParams?.1 ?? true) } func testPushAndPopTransition_forwardTransitionUsesPush_animated() { let transition = PushPopFlowTransition.default let exp = expectation(description: "Block need to be invoked after pushing view controller") let completion = { exp.fulfill() } let transitionBlock = transition.performForwardTransition(animated: true, completion: completion) transitionBlock(mockNavigationController, viewController) waitForExpectations(timeout: 0.1) { error in if let error = error { XCTFail(error.localizedDescription) } } XCTAssertEqual(mockNavigationController.pushViewControllerParams?.0, viewController) XCTAssertTrue(mockNavigationController.pushViewControllerParams?.1 ?? false) } func testPushAndPopTransition_backwardTransitionUsesPop_withoutAnimation() { let transition = PushPopFlowTransition.default let exp = expectation(description: "Block need to be invoked after poping view controller") let completion = { exp.fulfill() } let transitionBlock = transition.performBackwardTransition(animated: false, completion: completion) mockPopNavigationController.viewControllers = [viewController] transitionBlock(viewController) waitForExpectations(timeout: 0.1) { error in if let error = error { XCTFail(error.localizedDescription) } } XCTAssertFalse(mockPopNavigationController.popViewControllerParams ?? true) } func testPushAndPopTransition_backwardTransitionUsesPop_animated() { let transition = PushPopFlowTransition.default let exp = expectation(description: "Block need to be invoked after poping view controller") let completion = { exp.fulfill() } let transitionBlock = transition.performBackwardTransition(animated: true, completion: completion) mockPopNavigationController.viewControllers = [viewController] transitionBlock(viewController) waitForExpectations(timeout: 0.1) { error in if let error = error { XCTFail(error.localizedDescription) } } XCTAssertTrue(mockPopNavigationController.popViewControllerParams ?? false) } // MARK: - ModalFlowTransition func testModalTransition_forwardTransitionPresentsViewController_navigationControllerIsNil_withoutAnimation() { let transition = ModalFlowTransition() let exp = expectation(description: "Block need to be invoked after poping view controller") let completion = { exp.fulfill() } let transitionBlock = transition.performForwardTransition(animated: false, completion: completion) transitionBlock(mockNavigationController, viewController) waitForExpectations(timeout: 0.1) { error in if let error = error { XCTFail(error.localizedDescription) } } XCTAssertEqual(mockNavigationController.presentViewControllerParams?.0, viewController) XCTAssertFalse(mockNavigationController.presentViewControllerParams?.1 ?? true) } func testModalTransition_forwardTransitionPresentsViewController_navigationControllerIsNil_animated() { let transition = ModalFlowTransition() let exp = expectation(description: "Block need to be invoked after poping view controller") let completion = { exp.fulfill() } let transitionBlock = transition.performForwardTransition(animated: true, completion: completion) transitionBlock(mockNavigationController, viewController) waitForExpectations(timeout: 0.1) { error in if let error = error { XCTFail(error.localizedDescription) } } XCTAssertEqual(mockNavigationController.presentViewControllerParams?.0, viewController) XCTAssertTrue(mockNavigationController.presentViewControllerParams?.1 ?? false) } func testModalTransition_forwardTransitionPresentsViewController_navigationControllerIsNotNil_withoutAnimation() { let transition = ModalFlowTransition() let exp = expectation(description: "Block need to be invoked after poping view controller") let completion = { exp.fulfill() } let transitionBlock = transition.performForwardTransition(animated: false, completion: completion) let _ = UINavigationController(rootViewController: viewController) transitionBlock(mockNavigationController, viewController) waitForExpectations(timeout: 0.1) { error in if let error = error { XCTFail(error.localizedDescription) } } XCTAssertFalse(mockNavigationController.presentViewControllerParams?.0 is UINavigationController) XCTAssertFalse((mockNavigationController.presentViewControllerParams?.0 as? UINavigationController)?.navigationBar.isKind(of: CustomNavigationBar.self) ?? false) XCTAssertEqual(mockNavigationController.presentViewControllerParams?.0, viewController) XCTAssertFalse(mockNavigationController.presentViewControllerParams?.1 ?? true) } func testModalTransition_forwardTransitionPresentsViewController_navigationControllerIsNotNil_animated() { let transition = ModalFlowTransition() let exp = expectation(description: "Block need to be invoked after poping view controller") let completion = { exp.fulfill() } let transitionBlock = transition.performForwardTransition(animated: true, completion: completion) let _ = UINavigationController(rootViewController: viewController) transitionBlock(mockNavigationController, viewController) waitForExpectations(timeout: 0.1) { error in if let error = error { XCTFail(error.localizedDescription) } } XCTAssertFalse(mockNavigationController.presentViewControllerParams?.0 is UINavigationController) XCTAssertFalse((mockNavigationController.presentViewControllerParams?.0 as? UINavigationController)?.navigationBar.isKind(of: CustomNavigationBar.self) ?? false) XCTAssertEqual(mockNavigationController.presentViewControllerParams?.0, viewController) XCTAssertTrue(mockNavigationController.presentViewControllerParams?.1 ?? false) } func testModalTransition_backwardTransitionDismissViewController_withoutAnimation() { let transition = ModalFlowTransition() let exp = expectation(description: "Block need to be invoked after poping view controller") let completion = { exp.fulfill() } let transitionBlock = transition.performBackwardTransition(animated: false, completion: completion) let viewController = MockViewController() transitionBlock(viewController) waitForExpectations(timeout: 0.1) { error in if let error = error { XCTFail(error.localizedDescription) } } XCTAssertFalse(viewController.dismissParams ?? true) } func testModalTransition_backwardTransitionDismissViewController_animated() { let transition = ModalFlowTransition() let exp = expectation(description: "Block need to be invoked after poping view controller") let completion = { exp.fulfill() } let transitionBlock = transition.performBackwardTransition(animated: true, completion: completion) let viewController = MockViewController() transitionBlock(viewController) waitForExpectations(timeout: 0.1) { error in if let error = error { XCTFail(error.localizedDescription) } } XCTAssertTrue(viewController.dismissParams ?? false) } // MARK: - DefaultModalFlowTransition func testDefaultModalTransition_defaultAlwaysReturnsTheSameObject() { let default1 = DefaultModalFlowTransition.default let default2 = DefaultModalFlowTransition.default XCTAssertTrue(default1 === default2) } // MARK: - TabBarAppFlowControllerTransition func testTabBarTransition_defaultAlwaysReturnsTheSameObject() { let default1 = DefaultTabBarFlowTransition.default let default2 = DefaultTabBarFlowTransition.default XCTAssertTrue(default1 === default2) } func testTabBarTransition_forwardTransitionChangesSelectedIndexForExistingViewController() { let transition = DefaultTabBarFlowTransition.default let exp = expectation(description: "Block need to be invoked after displaying view controller") let completion = { exp.fulfill() } let transitionBlock = transition.performForwardTransition(animated: true, completion: completion) let tab1ViewController = UIViewController() let tab2ViewController = CustomViewController() let tabBarController = UITabBarController() tabBarController.viewControllers = [ UINavigationController(rootViewController: tab1ViewController), UINavigationController(rootViewController: tab2ViewController) ] XCTAssertEqual(tabBarController.selectedIndex, 0) transitionBlock(tab2ViewController.navigationController!, tab2ViewController) waitForExpectations(timeout: 0.1) { error in if let error = error { XCTFail(error.localizedDescription) } } XCTAssertEqual(tabBarController.selectedIndex, 1) } func testTabBarTransition_forwardTransitionWontChangeIndexIfViewControllerDoesntExists() { let transition = DefaultTabBarFlowTransition.default let exp = expectation(description: "Block need to be invoked after displaying view controller") let completion = { exp.fulfill() } let transitionBlock = transition.performForwardTransition(animated: true, completion: completion) let tab1ViewController = UIViewController() let tab2ViewController = CustomViewController() let wrongViewController = AnotherViewController() let tabBarController = UITabBarController() tabBarController.viewControllers = [ UINavigationController(rootViewController: tab1ViewController), UINavigationController(rootViewController: tab2ViewController) ] XCTAssertEqual(tabBarController.selectedIndex, 0) transitionBlock(UINavigationController(), wrongViewController) waitForExpectations(timeout: 0.1) { error in if let error = error { XCTFail(error.localizedDescription) } } XCTAssertEqual(tabBarController.selectedIndex, 0) } func testTabBarTransition_forwardTransitionWontChangeIndexIfTopViewControllerIsNotTabBarController() { let transition = DefaultTabBarFlowTransition.default let exp = expectation(description: "Block need to be invoked after displaying view controller") let completion = { exp.fulfill() } let transitionBlock = transition.performForwardTransition(animated: true, completion: completion) let navigationController = StubNavigationController() let tab1ViewController = UIViewController() let tab2ViewController = CustomViewController() let wrongViewController = AnotherViewController() let tabBarController = UITabBarController() tabBarController.viewControllers = [ tab1ViewController, tab2ViewController ] XCTAssertEqual(tabBarController.selectedIndex, 0) transitionBlock(navigationController, wrongViewController) waitForExpectations(timeout: 0.1) { error in if let error = error { XCTFail(error.localizedDescription) } } XCTAssertEqual(tabBarController.selectedIndex, 0) } func testTabBarTransition_backwardTransitionInvokesCompletion() { let transition = DefaultTabBarFlowTransition.default let exp = expectation(description: "Block need to be invoked after displaying view controller") let completion = { exp.fulfill() } let transitionBlock = transition.performBackwardTransition(animated: true, completion: completion) transitionBlock(viewController) waitForExpectations(timeout: 0.1) { error in if let error = error { XCTFail(error.localizedDescription) } } } }
mit
26c6ab8e20ffa6356bab3140ad5b85cc
42.406877
169
0.679385
6.023459
false
true
false
false
airspeedswift/swift
test/expr/closure/closures.swift
3
29880
// RUN: %target-typecheck-verify-swift var func6 : (_ fn : (Int,Int) -> Int) -> () var func6a : ((Int, Int) -> Int) -> () var func6b : (Int, (Int, Int) -> Int) -> () func func6c(_ f: (Int, Int) -> Int, _ n: Int = 0) {} // Expressions can be auto-closurified, so that they can be evaluated separately // from their definition. var closure1 : () -> Int = {4} // Function producing 4 whenever it is called. var closure2 : (Int,Int) -> Int = { 4 } // expected-error{{contextual type for closure argument list expects 2 arguments, which cannot be implicitly ignored}} {{36-36= _,_ in}} var closure3a : () -> () -> (Int,Int) = {{ (4, 2) }} // multi-level closing. var closure3b : (Int,Int) -> (Int) -> (Int,Int) = {{ (4, 2) }} // expected-error{{contextual type for closure argument list expects 2 arguments, which cannot be implicitly ignored}} {{52-52=_,_ in }} // expected-error@-1 {{contextual type for closure argument list expects 1 argument, which cannot be implicitly ignored}} {{53-53= _ in}} var closure4 : (Int,Int) -> Int = { $0 + $1 } var closure5 : (Double) -> Int = { $0 + 1.0 // expected-error@-1 {{cannot convert value of type 'Double' to closure result type 'Int'}} } var closure6 = $0 // expected-error {{anonymous closure argument not contained in a closure}} var closure7 : Int = { 4 } // expected-error {{function produces expected type 'Int'; did you mean to call it with '()'?}} {{27-27=()}} // expected-note {{Remove '=' to make 'closure7' a computed property}}{{20-22=}} var capturedVariable = 1 var closure8 = { [capturedVariable] in capturedVariable += 1 // expected-error {{left side of mutating operator isn't mutable: 'capturedVariable' is an immutable capture}} } func funcdecl1(_ a: Int, _ y: Int) {} func funcdecl3() -> Int {} func funcdecl4(_ a: ((Int) -> Int), _ b: Int) {} func funcdecl5(_ a: Int, _ y: Int) { // Pass in a closure containing the call to funcdecl3. funcdecl4({ funcdecl3() }, 12) // expected-error {{contextual type for closure argument list expects 1 argument, which cannot be implicitly ignored}} {{14-14= _ in}} func6({$0 + $1}) // Closure with two named anonymous arguments func6({($0) + $1}) // Closure with sequence expr inferred type func6({($0) + $0}) // // expected-error {{contextual closure type '(Int, Int) -> Int' expects 2 arguments, but 1 was used in closure body}} var testfunc : ((), Int) -> Int // expected-note {{'testfunc' declared here}} testfunc({$0+1}) // expected-error {{missing argument for parameter #2 in call}} // expected-error@-1 {{cannot convert value of type '(Int) -> Int' to expected argument type '()'}} funcdecl5(1, 2) // recursion. // Element access from a tuple. var a : (Int, f : Int, Int) var b = a.1+a.f // Tuple expressions with named elements. var i : (y : Int, x : Int) = (x : 42, y : 11) // expected-warning {{expression shuffles the elements of this tuple; this behavior is deprecated}} funcdecl1(123, 444) // Calls. 4() // expected-error {{cannot call value of non-function type 'Int'}}{{4-6=}} // rdar://12017658 - Infer some argument types from func6. func6({ a, b -> Int in a+b}) // Return type inference. func6({ a,b in a+b }) // Infer incompatible type. func6({a,b -> Float in 4.0 }) // expected-error {{declared closure result 'Float' is incompatible with contextual type 'Int'}} {{17-22=Int}} // Pattern doesn't need to name arguments. func6({ _,_ in 4 }) func6({a,b in 4.0 }) // expected-error {{cannot convert value of type 'Double' to closure result type 'Int'}} // TODO: This diagnostic can be improved: rdar://22128205 func6({(a : Float, b) in 4 }) // expected-error {{cannot convert value of type '(Float, Int) -> Int' to expected argument type '(Int, Int) -> Int'}} var fn = {} var fn2 = { 4 } var c : Int = { a,b -> Int in a+b} // expected-error{{cannot convert value of type '(Int, Int) -> Int' to specified type 'Int'}} } func unlabeledClosureArgument() { func add(_ x: Int, y: Int) -> Int { return x + y } func6a({$0 + $1}) // single closure argument func6a(add) func6b(1, {$0 + $1}) // second arg is closure func6b(1, add) func6c({$0 + $1}) // second arg is default int func6c(add) } // rdar://11935352 - closure with no body. func closure_no_body(_ p: () -> ()) { return closure_no_body({}) } // rdar://12019415 func t() { let u8 : UInt8 = 1 let x : Bool = true if 0xA0..<0xBF ~= Int(u8) && x { } } // <rdar://problem/11927184> func f0(_ a: Any) -> Int { return 1 } assert(f0(1) == 1) var selfRef = { selfRef() } // expected-error {{variable used within its own initial value}} var nestedSelfRef = { var recursive = { nestedSelfRef() } // expected-error {{variable used within its own initial value}} recursive() } var shadowed = { (shadowed: Int) -> Int in let x = shadowed return x } // no-warning var shadowedShort = { (shadowedShort: Int) -> Int in shadowedShort+1 } // no-warning func anonymousClosureArgsInClosureWithArgs() { func f(_: String) {} var a1 = { () in $0 } // expected-error {{anonymous closure arguments cannot be used inside a closure that has explicit arguments}} var a2 = { () -> Int in $0 } // expected-error {{anonymous closure arguments cannot be used inside a closure that has explicit arguments}} var a3 = { (z: Int) in $0 } // expected-error {{anonymous closure arguments cannot be used inside a closure that has explicit arguments; did you mean 'z'?}} {{26-28=z}} var a4 = { (z: [Int], w: [Int]) in f($0.count) // expected-error {{anonymous closure arguments cannot be used inside a closure that has explicit arguments; did you mean 'z'?}} {{7-9=z}} expected-error {{cannot convert value of type 'Int' to expected argument type 'String'}} f($1.count) // expected-error {{anonymous closure arguments cannot be used inside a closure that has explicit arguments; did you mean 'w'?}} {{7-9=w}} expected-error {{cannot convert value of type 'Int' to expected argument type 'String'}} } var a5 = { (_: [Int], w: [Int]) in f($0.count) // expected-error {{anonymous closure arguments cannot be used inside a closure that has explicit arguments}} f($1.count) // expected-error {{anonymous closure arguments cannot be used inside a closure that has explicit arguments; did you mean 'w'?}} {{7-9=w}} } } func doStuff(_ fn : @escaping () -> Int) {} func doVoidStuff(_ fn : @escaping () -> ()) {} // <rdar://problem/16193162> Require specifying self for locations in code where strong reference cycles are likely class ExplicitSelfRequiredTest { var x = 42 func method() -> Int { // explicit closure requires an explicit "self." base or an explicit capture. doVoidStuff({ self.x += 1 }) doVoidStuff({ [self] in x += 1 }) doVoidStuff({ [self = self] in x += 1 }) doVoidStuff({ [unowned self] in x += 1 }) doVoidStuff({ [unowned(unsafe) self] in x += 1 }) doVoidStuff({ [unowned self = self] in x += 1 }) doStuff({ [self] in x+1 }) doStuff({ [self = self] in x+1 }) doStuff({ self.x+1 }) doStuff({ [unowned self] in x+1 }) doStuff({ [unowned(unsafe) self] in x+1 }) doStuff({ [unowned self = self] in x+1 }) doStuff({ x+1 }) // expected-error {{reference to property 'x' in closure requires explicit use of 'self' to make capture semantics explicit}} expected-note{{capture 'self' explicitly to enable implicit 'self' in this closure}} {{14-14= [self] in}} expected-note{{reference 'self.' explicitly}} {{15-15=self.}} doVoidStuff({ doStuff({ x+1 })}) // expected-error {{reference to property 'x' in closure requires explicit use of 'self' to make capture semantics explicit}} expected-note{{capture 'self' explicitly to enable implicit 'self' in this closure}} {{28-28= [self] in}} expected-note{{reference 'self.' explicitly}} {{29-29=self.}} doVoidStuff({ x += 1 }) // expected-error {{reference to property 'x' in closure requires explicit use of 'self' to make capture semantics explicit}} expected-note{{capture 'self' explicitly to enable implicit 'self' in this closure}} {{18-18= [self] in}} expected-note{{reference 'self.' explicitly}} {{19-19=self.}} doVoidStuff({ _ = "\(x)"}) // expected-error {{reference to property 'x' in closure requires explicit use of 'self' to make capture semantics explicit}} expected-note{{capture 'self' explicitly to enable implicit 'self' in this closure}} {{18-18= [self] in}} expected-note{{reference 'self.' explicitly}} {{26-26=self.}} doVoidStuff({ [y = self] in x += 1 }) // expected-warning {{capture 'y' was never used}} expected-error {{reference to property 'x' in closure requires explicit use of 'self' to make capture semantics explicit}} expected-note{{capture 'self' explicitly to enable implicit 'self' in this closure}} {{20-20=self, }} expected-note{{reference 'self.' explicitly}} {{33-33=self.}} doStuff({ [y = self] in x+1 }) // expected-warning {{capture 'y' was never used}} expected-error {{reference to property 'x' in closure requires explicit use of 'self' to make capture semantics explicit}} expected-note{{capture 'self' explicitly to enable implicit 'self' in this closure}} {{16-16=self, }} expected-note{{reference 'self.' explicitly}} {{29-29=self.}} doVoidStuff({ [weak self] in x += 1 }) // expected-note {{weak capture of 'self' here does not enable implicit 'self'}} expected-warning {{variable 'self' was written to, but never read}} expected-error {{reference to property 'x' in closure requires explicit use of 'self' to make capture semantics explicit}} doStuff({ [weak self] in x+1 }) // expected-note {{weak capture of 'self' here does not enable implicit 'self'}} expected-warning {{variable 'self' was written to, but never read}} expected-error {{reference to property 'x' in closure requires explicit use of 'self' to make capture semantics explicit}} doVoidStuff({ [self = self.x] in x += 1 }) // expected-note {{variable other than 'self' captured here under the name 'self' does not enable implicit 'self'}} expected-warning {{capture 'self' was never used}} expected-error {{reference to property 'x' in closure requires explicit use of 'self' to make capture semantics explicit}} doStuff({ [self = self.x] in x+1 }) // expected-note {{variable other than 'self' captured here under the name 'self' does not enable implicit 'self'}} expected-warning {{capture 'self' was never used}} expected-error {{reference to property 'x' in closure requires explicit use of 'self' to make capture semantics explicit}} // Methods follow the same rules as properties, uses of 'self' without capturing must be marked with "self." doStuff { method() } // expected-error {{call to method 'method' in closure requires explicit use of 'self' to make capture semantics explicit}} expected-note{{capture 'self' explicitly to enable implicit 'self' in this closure}} {{14-14= [self] in}} expected-note{{reference 'self.' explicitly}} {{15-15=self.}} doVoidStuff { _ = method() } // expected-error {{call to method 'method' in closure requires explicit use of 'self' to make capture semantics explicit}} expected-note{{capture 'self' explicitly to enable implicit 'self' in this closure}} {{18-18= [self] in}} expected-note{{reference 'self.' explicitly}} {{23-23=self.}} doVoidStuff { _ = "\(method())" } // expected-error {{call to method 'method' in closure requires explicit use of 'self' to make capture semantics explicit}} expected-note{{capture 'self' explicitly to enable implicit 'self' in this closure}} {{18-18= [self] in}} expected-note{{reference 'self.' explicitly}} {{26-26=self.}} doVoidStuff { () -> () in _ = method() } // expected-error {{call to method 'method' in closure requires explicit use of 'self' to make capture semantics explicit}} expected-note{{capture 'self' explicitly to enable implicit 'self' in this closure}} {{18-18= [self]}} expected-note{{reference 'self.' explicitly}} {{35-35=self.}} doVoidStuff { [y = self] in _ = method() } // expected-warning {{capture 'y' was never used}} expected-error {{call to method 'method' in closure requires explicit use of 'self' to make capture semantics explicit}} expected-note{{capture 'self' explicitly to enable implicit 'self' in this closure}} {{20-20=self, }} expected-note{{reference 'self.' explicitly}} {{37-37=self.}} doStuff({ [y = self] in method() }) // expected-warning {{capture 'y' was never used}} expected-error {{call to method 'method' in closure requires explicit use of 'self' to make capture semantics explicit}} expected-note{{capture 'self' explicitly to enable implicit 'self' in this closure}} {{16-16=self, }} expected-note{{reference 'self.' explicitly}} {{29-29=self.}} doVoidStuff({ [weak self] in _ = method() }) // expected-note {{weak capture of 'self' here does not enable implicit 'self'}} expected-warning {{variable 'self' was written to, but never read}} expected-error {{call to method 'method' in closure requires explicit use of 'self' to make capture semantics explicit}} doStuff({ [weak self] in method() }) // expected-note {{weak capture of 'self' here does not enable implicit 'self'}} expected-warning {{variable 'self' was written to, but never read}} expected-error {{call to method 'method' in closure requires explicit use of 'self' to make capture semantics explicit}} doVoidStuff({ [self = self.x] in _ = method() }) // expected-note {{variable other than 'self' captured here under the name 'self' does not enable implicit 'self'}} expected-warning {{capture 'self' was never used}} expected-error {{call to method 'method' in closure requires explicit use of 'self' to make capture semantics explicit}} doStuff({ [self = self.x] in method() }) // expected-note {{variable other than 'self' captured here under the name 'self' does not enable implicit 'self'}} expected-warning {{capture 'self' was never used}} expected-error {{call to method 'method' in closure requires explicit use of 'self' to make capture semantics explicit}} doVoidStuff { _ = self.method() } doVoidStuff { [self] in _ = method() } doVoidStuff { [self = self] in _ = method() } doVoidStuff({ [unowned self] in _ = method() }) doVoidStuff({ [unowned(unsafe) self] in _ = method() }) doVoidStuff({ [unowned self = self] in _ = method() }) doStuff { self.method() } doStuff { [self] in method() } doStuff({ [self = self] in method() }) doStuff({ [unowned self] in method() }) doStuff({ [unowned(unsafe) self] in method() }) doStuff({ [unowned self = self] in method() }) // When there's no space between the opening brace and the first expression, insert it doStuff {method() } // expected-error {{call to method 'method' in closure requires explicit use of 'self' to make capture semantics explicit}} expected-note{{capture 'self' explicitly to enable implicit 'self' in this closure}} {{14-14= [self] in }} expected-note{{reference 'self.' explicitly}} {{14-14=self.}} doVoidStuff {_ = method() } // expected-error {{call to method 'method' in closure requires explicit use of 'self' to make capture semantics explicit}} expected-note{{capture 'self' explicitly to enable implicit 'self' in this closure}} {{18-18= [self] in }} expected-note{{reference 'self.' explicitly}} {{22-22=self.}} doVoidStuff {() -> () in _ = method() } // expected-error {{call to method 'method' in closure requires explicit use of 'self' to make capture semantics explicit}} expected-note{{capture 'self' explicitly to enable implicit 'self' in this closure}} {{18-18= [self]}} expected-note{{reference 'self.' explicitly}} {{34-34=self.}} // With an empty capture list, insertion should should be suggested without a comma doStuff { [] in method() } // expected-error {{call to method 'method' in closure requires explicit use of 'self' to make capture semantics explicit}} expected-note{{capture 'self' explicitly to enable implicit 'self' in this closure}} {{16-16=self}} expected-note{{reference 'self.' explicitly}} {{21-21=self.}} doStuff { [ ] in method() } // expected-error {{call to method 'method' in closure requires explicit use of 'self' to make capture semantics explicit}} expected-note{{capture 'self' explicitly to enable implicit 'self' in this closure}} {{16-16=self}} expected-note{{reference 'self.' explicitly}} {{23-23=self.}} doStuff { [ /* This space intentionally left blank. */ ] in method() } // expected-error {{call to method 'method' in closure requires explicit use of 'self' to make capture semantics explicit}} expected-note{{capture 'self' explicitly to enable implicit 'self' in this closure}} {{16-16=self}} expected-note{{reference 'self.' explicitly}} {{65-65=self.}} // expected-note@+1 {{capture 'self' explicitly to enable implicit 'self' in this closure}} {{16-16=self}} doStuff { [ // Nothing in this capture list! ] in method() // expected-error {{call to method 'method' in closure requires explicit use of 'self' to make capture semantics explicit}} expected-note{{reference 'self.' explicitly}} {{9-9=self.}} } // An inserted capture list should be on the same line as the opening brace, immediately following it. // expected-note@+1 {{capture 'self' explicitly to enable implicit 'self' in this closure}} {{14-14= [self] in}} doStuff { method() // expected-error {{call to method 'method' in closure requires explicit use of 'self' to make capture semantics explicit}} expected-note{{reference 'self.' explicitly}} {{7-7=self.}} } // expected-note@+2 {{capture 'self' explicitly to enable implicit 'self' in this closure}} {{14-14= [self] in}} // Note: Trailing whitespace on the following line is intentional and should not be removed! doStuff { method() // expected-error {{call to method 'method' in closure requires explicit use of 'self' to make capture semantics explicit}} expected-note{{reference 'self.' explicitly}} {{7-7=self.}} } // expected-note@+1 {{capture 'self' explicitly to enable implicit 'self' in this closure}} {{14-14= [self] in}} doStuff { // We have stuff to do. method() // expected-error {{call to method 'method' in closure requires explicit use of 'self' to make capture semantics explicit}} expected-note{{reference 'self.' explicitly}} {{7-7=self.}} } // expected-note@+1 {{capture 'self' explicitly to enable implicit 'self' in this closure}} {{14-14= [self] in}} doStuff {// We have stuff to do. method() // expected-error {{call to method 'method' in closure requires explicit use of 'self' to make capture semantics explicit}} expected-note{{reference 'self.' explicitly}} {{7-7=self.}} } // String interpolation should offer the diagnosis and fix-its at the expected locations doVoidStuff { _ = "\(method())" } // expected-error {{call to method 'method' in closure requires explicit use of 'self' to make capture semantics explicit}} expected-note{{reference 'self.' explicitly}} {{26-26=self.}} expected-note {{capture 'self' explicitly to enable implicit 'self' in this closure}} {{18-18= [self] in}} doVoidStuff { _ = "\(x+1)" } // expected-error {{reference to property 'x' in closure requires explicit use of 'self' to make capture semantics explicit}} expected-note{{reference 'self.' explicitly}} {{26-26=self.}} expected-note {{capture 'self' explicitly to enable implicit 'self' in this closure}} {{18-18= [self] in}} // If we already have a capture list, self should be added to the list let y = 1 doStuff { [y] in method() } // expected-warning {{capture 'y' was never used}} expected-error {{call to method 'method' in closure requires explicit use of 'self' to make capture semantics explicit}} expected-note{{capture 'self' explicitly to enable implicit 'self' in this closure}} {{16-16=self, }} expected-note{{reference 'self.' explicitly}} {{22-22=self.}} doStuff { [ // expected-note{{capture 'self' explicitly to enable implicit 'self' in this closure}} {{16-16=self, }} y // expected-warning {{capture 'y' was never used}} ] in method() } // expected-error {{call to method 'method' in closure requires explicit use of 'self' to make capture semantics explicit}} expected-note{{reference 'self.' explicitly}} {{14-14=self.}} // <rdar://problem/18877391> "self." shouldn't be required in the initializer expression in a capture list // This should not produce an error, "x" isn't being captured by the closure. doStuff({ [myX = x] in myX }) // This should produce an error, since x is used within the inner closure. doStuff({ [myX = {x}] in 4 }) // expected-error {{reference to property 'x' in closure requires explicit use of 'self' to make capture semantics explicit}} expected-note{{capture 'self' explicitly to enable implicit 'self' in this closure}} {{23-23= [self] in }} expected-note{{reference 'self.' explicitly}} {{23-23=self.}} // expected-warning @-1 {{capture 'myX' was never used}} return 42 } } // If the implicit self is of value type, no diagnostic should be produced. struct ImplicitSelfAllowedInStruct { var x = 42 mutating func method() -> Int { doStuff({ x+1 }) doVoidStuff({ x += 1 }) doStuff({ method() }) doVoidStuff({ _ = method() }) } func method2() -> Int { doStuff({ x+1 }) doVoidStuff({ _ = x+1 }) doStuff({ method2() }) doVoidStuff({ _ = method2() }) } } enum ImplicitSelfAllowedInEnum { case foo var x: Int { 42 } mutating func method() -> Int { doStuff({ x+1 }) doVoidStuff({ _ = x+1 }) doStuff({ method() }) doVoidStuff({ _ = method() }) } func method2() -> Int { doStuff({ x+1 }) doVoidStuff({ _ = x+1 }) doStuff({ method2() }) doVoidStuff({ _ = method2() }) } } class SomeClass { var field : SomeClass? func foo() -> Int {} } func testCaptureBehavior(_ ptr : SomeClass) { // Test normal captures. weak var wv : SomeClass? = ptr unowned let uv : SomeClass = ptr unowned(unsafe) let uv1 : SomeClass = ptr unowned(safe) let uv2 : SomeClass = ptr doStuff { wv!.foo() } doStuff { uv.foo() } doStuff { uv1.foo() } doStuff { uv2.foo() } // Capture list tests let v1 : SomeClass? = ptr let v2 : SomeClass = ptr doStuff { [weak v1] in v1!.foo() } // expected-warning @+2 {{variable 'v1' was written to, but never read}} doStuff { [weak v1, // expected-note {{previous}} weak v1] in v1!.foo() } // expected-error {{definition conflicts with previous value}} doStuff { [unowned v2] in v2.foo() } doStuff { [unowned(unsafe) v2] in v2.foo() } doStuff { [unowned(safe) v2] in v2.foo() } doStuff { [weak v1, weak v2] in v1!.foo() + v2!.foo() } let i = 42 // expected-warning @+1 {{variable 'i' was never mutated}} {{19-20=let}} doStuff { [weak i] in i! } // expected-error {{'weak' may only be applied to class and class-bound protocol types, not 'Int'}} } extension SomeClass { func bar() { doStuff { [unowned self] in self.foo() } doStuff { [unowned xyz = self.field!] in xyz.foo() } doStuff { [weak xyz = self.field] in xyz!.foo() } // rdar://16889886 - Assert when trying to weak capture a property of self in a lazy closure // FIXME: We should probably offer a fix-it to the field capture error and suppress the 'implicit self' error. https://bugs.swift.org/browse/SR-11634 doStuff { [weak self.field] in field!.foo() } // expected-error {{fields may only be captured by assigning to a specific name}} expected-error {{reference to property 'field' in closure requires explicit use of 'self' to make capture semantics explicit}} expected-note {{reference 'self.' explicitly}} {{36-36=self.}} expected-note {{capture 'self' explicitly to enable implicit 'self' in this closure}} {{16-16=self, }} // expected-warning @+1 {{variable 'self' was written to, but never read}} doStuff { [weak self&field] in 42 } // expected-error {{expected ']' at end of capture list}} } func strong_in_capture_list() { // <rdar://problem/18819742> QOI: "[strong self]" in capture list generates unhelpful error message _ = {[strong self] () -> () in return } // expected-error {{expected 'weak', 'unowned', or no specifier in capture list}} } } // <rdar://problem/16955318> Observed variable in a closure triggers an assertion var closureWithObservedProperty: () -> () = { var a: Int = 42 { // expected-warning {{variable 'a' was never used; consider replacing with '_' or removing it}} willSet { _ = "Will set a to \(newValue)" } didSet { _ = "Did set a with old value of \(oldValue)" } } } ; {}() // expected-error{{top-level statement cannot begin with a closure expression}} // rdar://19179412 - Crash on valid code. func rdar19179412() -> (Int) -> Int { return { x in class A { let d : Int = 0 } return 0 } } // Test coercion of single-expression closure return types to void. func takesVoidFunc(_ f: () -> ()) {} var i: Int = 1 // expected-warning @+1 {{expression of type 'Int' is unused}} takesVoidFunc({i}) // expected-warning @+1 {{expression of type 'Int' is unused}} var f1: () -> () = {i} var x = {return $0}(1) func returnsInt() -> Int { return 0 } takesVoidFunc(returnsInt) // expected-error {{cannot convert value of type '() -> Int' to expected argument type '() -> ()'}} takesVoidFunc({() -> Int in 0}) // expected-error {{declared closure result 'Int' is incompatible with contextual type '()'}} {{22-25=()}} // These used to crash the compiler, but were fixed to support the implementation of rdar://problem/17228969 Void(0) // expected-error{{argument passed to call that takes no arguments}} _ = {0} // <rdar://problem/22086634> "multi-statement closures require an explicit return type" should be an error not a note let samples = { // expected-error {{unable to infer complex closure return type; add explicit type to disambiguate}} {{16-16= () -> <#Result#> in }} if (i > 10) { return true } else { return false } }() // <rdar://problem/19756953> Swift error: cannot capture '$0' before it is declared func f(_ fp : (Bool, Bool) -> Bool) {} f { $0 && !$1 } // <rdar://problem/18123596> unexpected error on self. capture inside class method func TakesIntReturnsVoid(_ fp : ((Int) -> ())) {} struct TestStructWithStaticMethod { static func myClassMethod(_ count: Int) { // Shouldn't require "self." TakesIntReturnsVoid { _ in myClassMethod(0) } } } class TestClassWithStaticMethod { class func myClassMethod(_ count: Int) { // Shouldn't require "self." TakesIntReturnsVoid { _ in myClassMethod(0) } } } // Test that we can infer () as the result type of these closures. func genericOne<T>(_ a: () -> T) {} func genericTwo<T>(_ a: () -> T, _ b: () -> T) {} genericOne {} genericTwo({}, {}) // <rdar://problem/22344208> QoI: Warning for unused capture list variable should be customized class r22344208 { func f() { let q = 42 let _: () -> Int = { [unowned self, // expected-warning {{capture 'self' was never used}} q] in // expected-warning {{capture 'q' was never used}} 1 } } } var f = { (s: Undeclared) -> Int in 0 } // expected-error {{cannot find type 'Undeclared' in scope}} // <rdar://problem/21375863> Swift compiler crashes when using closure, declared to return illegal type. func r21375863() { var width = 0 // expected-warning {{variable 'width' was never mutated}} var height = 0 // expected-warning {{variable 'height' was never mutated}} var bufs: [[UInt8]] = (0..<4).map { _ -> [asdf] in // expected-error {{cannot find type 'asdf' in scope}} expected-warning {{variable 'bufs' was never used}} [UInt8](repeating: 0, count: width*height) } } // <rdar://problem/25993258> // Don't crash if we infer a closure argument to have a tuple type containing inouts. func r25993258_helper(_ fn: (inout Int, Int) -> ()) {} func r25993258a() { r25993258_helper { x in () } // expected-error {{contextual closure type '(inout Int, Int) -> ()' expects 2 arguments, but 1 was used in closure body}} } func r25993258b() { r25993258_helper { _ in () } // expected-error {{contextual closure type '(inout Int, Int) -> ()' expects 2 arguments, but 1 was used in closure body}} } // We have to map the captured var type into the right generic environment. class GenericClass<T> {} func lvalueCapture<T>(c: GenericClass<T>) { var cc = c weak var wc = c func innerGeneric<U>(_: U) { _ = cc _ = wc cc = wc! } } // Don't expose @lvalue-ness in diagnostics. let closure = { // expected-error {{unable to infer complex closure return type; add explicit type to disambiguate}} {{16-16= () -> <#Result#> in }} var helper = true return helper } // SR-9839 func SR9839(_ x: @escaping @convention(block) () -> Void) {} func id<T>(_ x: T) -> T { return x } var qux: () -> Void = {} SR9839(qux) SR9839(id(qux)) // expected-error {{conflicting arguments to generic parameter 'T' ('() -> Void' vs. '@convention(block) () -> Void')}} func forceUnwrap<T>(_ x: T?) -> T { return x! } var qux1: (() -> Void)? = {} SR9839(qux1!) SR9839(forceUnwrap(qux1)) // rdar://problem/65155671 - crash referencing parameter of outer closure func rdar65155671(x: Int) { { a in _ = { [a] in a } }(x) } func sr3186<T, U>(_ f: (@escaping (@escaping (T) -> U) -> ((T) -> U))) -> ((T) -> U) { return { x in return f(sr3186(f))(x) } } class SR3186 { init() { // expected-warning@+1{{capture 'self' was never used}} let v = sr3186 { f in { [unowned self, f] x in x != 1000 ? f(x + 1) : "success" } }(0) print("\(v)") } }
apache-2.0
da63d72363d1d9544df362b6f0d90422
55.914286
426
0.659839
3.737803
false
false
false
false
banjun/NorthLayout
Example/NorthLayout-ios-Tests/VFLSyntaxTests.swift
1
7746
// // VFLSyntaxTests.swift // NorthLayout-ios-Tests // // Created by BAN Jun on 2017/11/22. // Copyright © 2017 banjun. All rights reserved. // import Foundation import Quick import Nimble @testable import NorthLayout public func equal(_ expectedValue: VFL.PredicateList) -> Predicate<VFL.PredicateList> { let expectedDescription = String(describing: expectedValue) return .define { .init(bool: (try $0.evaluate()).map {String(describing: $0)} == expectedDescription, message: ExpectationMessage.expectedActualValueTo("equal <\(expectedDescription)>")) } } final class VFLSyntaxTests: QuickSpec { override func spec() { describe("VFL Parse") { context("orientation") { it("implicit -> h") { expect(try? VFL(format: "[v]").orientation) == .h } it("H: orientation is h") { expect(try? VFL(format: "H:[v]").orientation) == .h } it("V: orientation is v") { expect(try? VFL(format: "V:[v]").orientation) == .v } } context("firstBound") { it("nil") { let b = try! VFL(format: "H:[v]").firstBound expect(b).to(beNil()) } it("zero width") { let b = try! VFL(format: "H:|[v]").firstBound expect(b).notTo(beNil()) expect(b!.0).to(equal(VFL.Bound.superview)) expect(b!.1.predicateList).to(equal(.simplePredicate(.positiveNumber(0)))) } it("system width") { let b = try! VFL(format: "H:|-[v]").firstBound expect(b).notTo(beNil()) expect(b!.0).to(equal(VFL.Bound.superview)) expect(b!.1.predicateList).to(equal(.simplePredicate(.positiveNumber(8)))) } it("constant width") { let b = try! VFL(format: "H:|-42-[v]").firstBound expect(b).notTo(beNil()) expect(b!.0).to(equal(VFL.Bound.superview)) expect(b!.1.predicateList).to(equal(.simplePredicate(.positiveNumber(42)))) } it("metric width") { let b = try! VFL(format: "H:|-p-[v]").firstBound expect(b).notTo(beNil()) expect(b!.0).to(equal(VFL.Bound.superview)) expect(b!.1.predicateList).to(equal(.simplePredicate(.metricName("p")))) } it(">= width") { let b = try! VFL(format: "H:|-(>=0)-[v]").firstBound expect(b).notTo(beNil()) expect(b!.0).to(equal(VFL.Bound.superview)) expect(b!.1.predicateList).to(equal(.predicateListWithParens([VFL.Predicate(relation: .ge, objectOfPredicate: .constant(.number(0)), priority: nil)]))) } it(">=,<= width") { let b = try! VFL(format: "H:|-(>=0,<=100)-[v]").firstBound expect(b).notTo(beNil()) expect(b!.0).to(equal(VFL.Bound.superview)) expect(b!.1.predicateList).to(equal(.predicateListWithParens([ VFL.Predicate(relation: .ge, objectOfPredicate: .constant(.number(0)), priority: nil), VFL.Predicate(relation: .le, objectOfPredicate: .constant(.number(100)), priority: nil)]))) } } context("firstView") { it("various bounds") { expect {try VFL(format: "|[v]").firstView.name} == "v" expect {try VFL(format: "|-[v]").firstView.name} == "v" expect {try VFL(format: "|-42-[v]").firstView.name} == "v" expect {try VFL(format: "|-(>=p)-[v]").firstView.name} == "v" expect {try VFL(format: "|-(>=0,<=100)-[v]").firstView.name} == "v" } } context("lastBound") { it("nil") { let b = try! VFL(format: "H:[v]").lastBound expect(b).to(beNil()) } it("zero width") { let b = try! VFL(format: "H:[v]|").lastBound expect(b).notTo(beNil()) expect(b!.1).to(equal(VFL.Bound.superview)) expect(b!.0.predicateList).to(equal(.simplePredicate(.positiveNumber(0)))) } it("system width") { let b = try! VFL(format: "H:[v]-|").lastBound expect(b).notTo(beNil()) expect(b!.1).to(equal(VFL.Bound.superview)) expect(b!.0.predicateList).to(equal(.simplePredicate(.positiveNumber(8)))) } it("constant width") { let b = try! VFL(format: "H:[v]-42-|").lastBound expect(b).notTo(beNil()) expect(b!.1).to(equal(VFL.Bound.superview)) expect(b!.0.predicateList).to(equal(.simplePredicate(.positiveNumber(42)))) } it("metric width") { let b = try! VFL(format: "H:[v]-p-|").lastBound expect(b).notTo(beNil()) expect(b!.1).to(equal(VFL.Bound.superview)) expect(b!.0.predicateList).to(equal(.simplePredicate(.metricName("p")))) } it(">= width") { let b = try! VFL(format: "H:[v]-(>=0)-|").lastBound expect(b).notTo(beNil()) expect(b!.1).to(equal(VFL.Bound.superview)) expect(b!.0.predicateList).to(equal(.predicateListWithParens([VFL.Predicate(relation: .ge, objectOfPredicate: .constant(.number(0)), priority: nil)]))) } it(">=,<= width") { let b = try! VFL(format: "H:[v]-(>=0,<=100)-|").lastBound expect(b).notTo(beNil()) expect(b!.1).to(equal(VFL.Bound.superview)) expect(b!.0.predicateList).to(equal(.predicateListWithParens([ VFL.Predicate(relation: .ge, objectOfPredicate: .constant(.number(0)), priority: nil), VFL.Predicate(relation: .le, objectOfPredicate: .constant(.number(100)), priority: nil)]))) } } context("lastView") { it("various bounds") { expect {try VFL(format: "[v]|").lastView.name} == "v" expect {try VFL(format: "[v]-|").lastView.name} == "v" expect {try VFL(format: "[v]-42-|").lastView.name} == "v" expect {try VFL(format: "[v]-(>=p)-|").lastView.name} == "v" expect {try VFL(format: "[v]-(>=0,<=100)-|").lastView.name} == "v" } } } describe("Extended VFL Parse (|| layout margin)") { it("first bound") { expect {try VFL(format: "||[v]").firstBound?.0} == .layoutMargin expect {try VFL(format: "H:||[v]").firstBound?.0} == .layoutMargin expect {try VFL(format: "V:||[v]").firstBound?.0} == .layoutMargin } it("last bound") { expect {try VFL(format: "[v]||").lastBound?.1} == .layoutMargin expect {try VFL(format: "H:[v]||").lastBound?.1} == .layoutMargin expect {try VFL(format: "V:[v]||").lastBound?.1} == .layoutMargin } } } }
mit
612df1c708757cb056d47ffe99d71cc2
48.33121
171
0.46572
4.191017
false
false
false
false