repo_name
stringlengths
7
91
path
stringlengths
8
658
copies
stringclasses
125 values
size
stringlengths
3
6
content
stringlengths
118
674k
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6.09
99.2
line_max
int64
17
995
alpha_frac
float64
0.3
0.9
ratio
float64
2
9.18
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
nathan-hekman/Stupefy
Stupefy/Utils/Utils.swift
1
7350
/** * 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 UIKit import BMSCore class Utils: NSObject { /** Method gets a key from a plist, both specified in parameters - parameter plist: String - parameter key: String - returns: Bool? */ class func getBoolValueWithKeyFromPlist(_ plist: String, key: String) -> Bool? { if let path: String = Bundle.main.path(forResource: plist, ofType: "plist"), let keyList = NSDictionary(contentsOfFile: path), let key = keyList.object(forKey: key) as? Bool { return key } return nil } /** Method gets a key from a plist, both specified in parameters - parameter plist: String - parameter key: String - returns: String */ class func getStringValueWithKeyFromPlist(_ plist: String, key: String) -> String? { if let path: String = Bundle.main.path(forResource: plist, ofType: "plist"), let keyList = NSDictionary(contentsOfFile: path), let key = keyList.object(forKey: key) as? String { return key } return nil } /** Method returns an instance of the Main.storyboard - returns: UIStoryboard */ class func mainStoryboard() -> UIStoryboard { let storyboard = UIStoryboard(name: "Main", bundle: Bundle.main) return storyboard } /** Method returns an instance of the storyboard defined by the storyboardName String parameter - parameter storyboardName: UString - returns: UIStoryboard */ class func storyboardBoardWithName(_ storyboardName: String) -> UIStoryboard { let storyboard = UIStoryboard(name: storyboardName, bundle: Bundle.main) return storyboard } /** Method returns an instance of the view controller defined by the vcName paramter from the storyboard defined by the storyboardName parameter - parameter vcName: String - parameter storyboardName: String - returns: UIViewController? */ class func vcWithNameFromStoryboardWithName(_ vcName: String, storyboardName: String) -> UIViewController? { let storyboard = storyboardBoardWithName(storyboardName) return storyboard.instantiateViewController(withIdentifier: vcName) } /** Method returns an instance of a nib defined by the name String parameter - parameter name: String - returns: UINib? */ class func nib(_ name: String) -> UINib? { let nib: UINib? = UINib(nibName: name, bundle: Bundle.main) return nib } /** Method registers a nib name defined by the nibName String parameter with the collectionView given by the collectionView parameter - parameter nibName: String - parameter collectionView: UICollectionView */ class func registerNibWith(_ nibName: String, collectionView: UICollectionView) { let nib = Utils.nib(nibName) collectionView.register(nib, forCellWithReuseIdentifier: nibName) } class func registerNibWith(_ nibName: String, tableView: UITableView) { let nib = Utils.nib(nibName) tableView.register(nib, forCellReuseIdentifier: nibName) } /** Method registers a supplementary element of kind nib defined by the nibName String parameter and the kind String parameter with the collectionView parameter - parameter nibName: String - parameter kind: String - parameter collectionView: UICollectionView */ class func registerSupplementaryElementOfKindNibWithCollectionView(_ nibName: String, kind: String, collectionView: UICollectionView) { let nib = Utils.nib(nibName) collectionView.register(nib, forSupplementaryViewOfKind: kind, withReuseIdentifier: nibName) } /** Method converts a string to a dictionary - parameter text: String - returns: [String : Any]? */ class func convertStringToDictionary(_ text: String) -> [String : Any]? { if let data = text.data(using: String.Encoding.utf8) { do { let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String : Any] return json } catch { print(NSLocalizedString("Convert String To Dictionary Error", comment: "")) } } return nil } /** Method converts a response to a dictionary - parameter response: Response? - returns: [String : Any] */ class func convertResponseToDictionary(_ response: Response?) -> [String : Any]? { if let resp = response { if let responseText = resp.responseText { return convertStringToDictionary(responseText) } else { return nil } } else { return nil } } /** Method takes in a label and a spacing value and kerns the labels text to this value - parameter label: UILabel - parameter spacingValue: CGFloat */ class func kernLabelString(_ label: UILabel, spacingValue: CGFloat) { if let text = label.text { let attributedString = NSMutableAttributedString(string: text) attributedString.addAttribute(NSKernAttributeName, value: spacingValue, range: NSRange(location: 0, length: attributedString.length)) label.attributedText = attributedString } } /** Method takes in latitude and longitude and formats these coordinates into a fancy format - parameter latitude: Double - parameter longitude: Double - returns: String */ class func coordinateString(_ latitude: Double, longitude: Double) -> String { var latSeconds = Int(latitude * 3600) let latDegrees = latSeconds / 3600 latSeconds = abs(latSeconds % 3600) let latMinutes = latSeconds / 60 latSeconds %= 60 var longSeconds = Int(longitude * 3600) let longDegrees = longSeconds / 3600 longSeconds = abs(longSeconds % 3600) let longMinutes = longSeconds / 60 longSeconds %= 60 return String(format:"%d° %d' %d\" %@, %d° %d' %d\" %@", latDegrees, latMinutes, latSeconds, {return latDegrees >= 0 ? NSLocalizedString("N", comment: "first letter of the word North") : NSLocalizedString("S", comment: "first letter of the word South")}(), longDegrees, longMinutes, longSeconds, {return longDegrees >= 0 ? NSLocalizedString("E", comment: "first letter of the word East") : NSLocalizedString("W", comment: "first letter of the word West")}() ) } }
mit
11276b7938b0cddf196d147f8c98435f
32.552511
198
0.641399
5.064094
false
false
false
false
talisk/SKNavigationController
SKNavigationController/SKNavigationController.swift
1
1592
// // SKNavigationController.swift // PopEventDemo // // Created by 孙恺 on 16/4/19. // Copyright © 2016年 sunkai. All rights reserved. // http://www.talisk.cn/ // https://github.com/talisk // import UIKit class SKNavigationController: UINavigationController, UINavigationControllerDelegate, UINavigationBarDelegate, UIGestureRecognizerDelegate { override func viewDidLoad() { super.viewDidLoad() let m_panGR = UIPanGestureRecognizer(target: self.interactivePopGestureRecognizer!.delegate, action: NSSelectorFromString("handleNavigationTransition:")) m_panGR.delegate = self self.view.addGestureRecognizer(m_panGR) self.delegate = self self.interactivePopGestureRecognizer?.enabled = false } /// MARK: - NavigationController 代理,布尔量初值设定 func navigationController(navigationController: UINavigationController, willShowViewController viewController: UIViewController, animated: Bool) { viewController.m_hasPopEvent = false } /// MARK: - 手势代理 func gestureRecognizerShouldBegin(gestureRecognizer: UIGestureRecognizer) -> Bool { if self.childViewControllers.count == 1 { return false } if topViewController is SKNavigationControllerDelegate { if ((topViewController?.viewControllerHasPopEvent(topViewController!)) != nil) { return (topViewController?.viewControllerHasPopEvent(topViewController!))! } } return true } }
mit
b24c65f3d617e54ec01f887af40d8625
32.12766
161
0.682081
5.425087
false
false
false
false
ioscreator/ioscreator
IOSSpriteKitMoveSpritePathTutorial/IOSSpriteKitMoveSpritePathTutorial/GameViewController.swift
1
1265
// // GameViewController.swift // IOSSpriteKitMoveSpritePathTutorial // // Created by Arthur Knopper on 15/11/2018. // Copyright © 2018 Arthur Knopper. All rights reserved. // import UIKit import SpriteKit import GameplayKit class GameViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() if let view = self.view as! SKView? { // Load the SKScene from 'GameScene.sks' if let scene = SKScene(fileNamed: "GameScene") { // Set the scale mode to scale to fit the window scene.scaleMode = .aspectFill // Present the scene view.presentScene(scene) } view.ignoresSiblingOrder = true view.showsFPS = true view.showsNodeCount = true } } override var shouldAutorotate: Bool { return true } override var supportedInterfaceOrientations: UIInterfaceOrientationMask { if UIDevice.current.userInterfaceIdiom == .phone { return .allButUpsideDown } else { return .all } } override var prefersStatusBarHidden: Bool { return true } }
mit
c09f81a0e22362d7afe82203550345de
24.28
77
0.580696
5.54386
false
false
false
false
arnaudbenard/my-npm
Pods/Charts/Charts/Classes/Components/ChartAxisBase.swift
79
3065
// // ChartAxisBase.swift // Charts // // Created by Daniel Cohen Gindi on 23/2/15. // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/ios-charts // import Foundation import UIKit public class ChartAxisBase: ChartComponentBase { public var labelFont = UIFont.systemFontOfSize(10.0) public var labelTextColor = UIColor.blackColor() public var axisLineColor = UIColor.grayColor() public var axisLineWidth = CGFloat(0.5) public var axisLineDashPhase = CGFloat(0.0) public var axisLineDashLengths: [CGFloat]! public var gridColor = UIColor.grayColor().colorWithAlphaComponent(0.9) public var gridLineWidth = CGFloat(0.5) public var gridLineDashPhase = CGFloat(0.0) public var gridLineDashLengths: [CGFloat]! public var drawGridLinesEnabled = true public var drawAxisLineEnabled = true /// flag that indicates of the labels of this axis should be drawn or not public var drawLabelsEnabled = true /// Sets the used x-axis offset for the labels on this axis. /// :default: 5.0 public var xOffset = CGFloat(5.0) /// Sets the used y-axis offset for the labels on this axis. /// :default: 5.0 (or 0.0 on ChartYAxis) public var yOffset = CGFloat(5.0) /// array of limitlines that can be set for the axis private var _limitLines = [ChartLimitLine]() /// Are the LimitLines drawn behind the data or in front of the data? /// :default: false public var drawLimitLinesBehindDataEnabled = false public override init() { super.init() } public func getLongestLabel() -> String { fatalError("getLongestLabel() cannot be called on ChartAxisBase") } public var isDrawGridLinesEnabled: Bool { return drawGridLinesEnabled; } public var isDrawAxisLineEnabled: Bool { return drawAxisLineEnabled; } public var isDrawLabelsEnabled: Bool { return drawLabelsEnabled; } /// Are the LimitLines drawn behind the data or in front of the data? /// :default: false public var isDrawLimitLinesBehindDataEnabled: Bool { return drawLimitLinesBehindDataEnabled; } /// Adds a new ChartLimitLine to this axis. public func addLimitLine(line: ChartLimitLine) { _limitLines.append(line) } /// Removes the specified ChartLimitLine from the axis. public func removeLimitLine(line: ChartLimitLine) { for (var i = 0; i < _limitLines.count; i++) { if (_limitLines[i] === line) { _limitLines.removeAtIndex(i) return } } } /// Removes all LimitLines from the axis. public func removeAllLimitLines() { _limitLines.removeAll(keepCapacity: false) } /// Returns the LimitLines of this axis. public var limitLines : [ChartLimitLine] { return _limitLines } }
mit
645da90404c54b2c746bc0ea4fe5f021
28.480769
98
0.653507
4.744582
false
false
false
false
saoudrizwan/Disk
DiskExample/DiskExample/ViewController.swift
1
5322
// // ViewController.swift // DiskExample // // Created by Saoud Rizwan on 7/23/17. // Copyright © 2017 Saoud Rizwan. All rights reserved. // import UIKit import Disk class ViewController: UIViewController { // MARK: Properties var posts = [Post]() // MARK: IBOutlets @IBOutlet weak var resultsTextView: UITextView! // MARK: IBActions @IBAction func getTapped(_ sender: Any) { // Be sure to check out the comments in the networking function below UIApplication.shared.isNetworkActivityIndicatorVisible = true getPostsFromWeb { (posts) in UIApplication.shared.isNetworkActivityIndicatorVisible = false print("Posts retrieved from network request successfully!") self.posts = posts } } @IBAction func saveTapped(_ sender: Any) { // Disk is thorough when it comes to error handling, so make sure you understand why an error occurs when it does. do { try Disk.save(self.posts, to: .documents, as: "posts.json") } catch let error as NSError { fatalError(""" Domain: \(error.domain) Code: \(error.code) Description: \(error.localizedDescription) Failure Reason: \(error.localizedFailureReason ?? "") Suggestions: \(error.localizedRecoverySuggestion ?? "") """) } // Notice how we use a do, catch, try block when using Disk, this is because almost all of Disk's methods // are throwing functions, meaning they will throw an error if something goes wrong. In almost all cases, these // errors come with a lot of information like a description, failure reason, and recover suggestions. // You could alternatively use try! or try? instead of do, catch, try blocks // try? Disk.save(self.posts, to: .documents, as: "posts.json") // returns a discardable result of nil // try! Disk.save(self.posts, to: .documents, as: "posts.json") // will crash the app during runtime if this fails // You can also save files in folder hierarchies, for example: // try? Disk.save(self.posts, to: .caches, as: "Posts/MyCoolPosts/1.json") // This will automatically create the Posts and MyCoolPosts folders // If you want to save new data to a file location, you can treat the file as an array and simply append to it as well. let newPost = Post(userId: 0, id: self.posts.count + 1, title: "Appended Post", body: "...") try? Disk.append(newPost, to: "posts.json", in: .documents) print("Saved posts to disk!") } @IBAction func retrieveTapped(_ sender: Any) { // We'll keep things simple here by using try?, but it's good practice to handle Disk with do, catch, try blocks // so you can make sure everything is going according to plan. if let retrievedPosts = try? Disk.retrieve("posts.json", from: .documents, as: [Post].self) { // If you Option+Click 'retrievedPosts' above, you'll notice that its type is [Post] // Pretty neat, huh? var result: String = "" for post in retrievedPosts { result.append("\(post.id): \(post.title)\n\(post.body)\n\n") } self.resultsTextView.text = result print("Retrieved posts from disk!") } } // MARK: Networking func getPostsFromWeb(completion: (([Post]) -> Void)?) { var urlComponents = URLComponents() urlComponents.scheme = "https" urlComponents.host = "jsonplaceholder.typicode.com" urlComponents.path = "/posts" let userIdItem = URLQueryItem(name: "userId", value: "1") urlComponents.queryItems = [userIdItem] guard let url = urlComponents.url else { fatalError("Could not create URL from components") } var request = URLRequest(url: url) request.httpMethod = "GET" let config = URLSessionConfiguration.default let session = URLSession(configuration: config) let task = session.dataTask(with: request) { (data, response, error) in DispatchQueue.main.async { guard error == nil else { fatalError(error!.localizedDescription) } guard let data = data else { fatalError("No data retrieved") } // We could directly save this data to disk... // try? Disk.save(data, to: .caches, as: "posts.json") // ... and retrieve it later as [Post]... // let posts = try? Disk.retrieve("posts.json", from: .caches, as: [Post].self) // ... but that's not good practice! Our networking and persistence logic should be separate. // Let's return the posts in our completion handler: do { let decoder = JSONDecoder() let posts = try decoder.decode([Post].self, from: data) completion?(posts) } catch { fatalError(error.localizedDescription) } } } task.resume() } }
mit
52139efca07c67bbc89100cb3ffa436a
42.614754
127
0.588423
4.759392
false
false
false
false
hirohitokato/SimpleGaplessPlayer
HKLAVGaplessPlayer/misc/HKLCMTimeUtils.swift
1
6944
// // HKLCMTimeUtils.swift // // Created by Hirohito Kato on 2014/12/19. // import CoreMedia // MARK: Initialization public extension CMTime { public init(value: Int64, _ timescale: Int = 1) { self = CMTimeMake(value, Int32(timescale)) } public init(value: Int64, _ timescale: Int32 = 1) { self = CMTimeMake(value, timescale) } public init(seconds: Float64, preferredTimeScale: Int32 = 1_000_000_000) { self = CMTimeMakeWithSeconds(seconds, preferredTimeScale) } public init(seconds: Float, preferredTimeScale: Int32 = 1_000_000_000) { self = CMTime(seconds: Float64(seconds), preferredTimeScale: preferredTimeScale) } } // MARK: - FloatingPointType Protocol (subset) public extension CMTime /* : FloatingPointType */ { /// true iff self is negative var isSignMinus: Bool { if self == kCMTimePositiveInfinity { return false } if self == kCMTimeNegativeInfinity { return false } if !self.flags.contains(.valid) { return false } return (self.value < 0) } /// true iff self is zero, subnormal, or normal (not infinity or NaN). var isZero: Bool { return self == kCMTimeZero } } // MARK: - Arithmetic Protocol // MARK: Add func + (left: CMTime, right: CMTime) -> CMTime { return CMTimeAdd(left, right) } @discardableResult func += ( left: inout CMTime, right: CMTime) -> CMTime { left = left + right return left } // MARK: Subtract func - (minuend: CMTime, subtrahend: CMTime) -> CMTime { return CMTimeSubtract(minuend, subtrahend) } @discardableResult func -= (minuend: inout CMTime, subtrahend: CMTime) -> CMTime { minuend = minuend - subtrahend return minuend } // MARK: Multiply func * (time: CMTime, multiplier: Int32) -> CMTime { return CMTimeMultiply(time, multiplier) } func * (multiplier: Int32, time: CMTime) -> CMTime { return CMTimeMultiply(time, multiplier) } func * (time: CMTime, multiplier: Float64) -> CMTime { return CMTimeMultiplyByFloat64(time, multiplier) } func * (time: CMTime, multiplier: Float) -> CMTime { return CMTimeMultiplyByFloat64(time, Float64(multiplier)) } func * (multiplier: Float64, time: CMTime) -> CMTime { return time * multiplier } func * (multiplier: Float, time: CMTime) -> CMTime { return time * multiplier } @discardableResult func *= (time: inout CMTime, multiplier: Int32) -> CMTime { time = time * multiplier return time } @discardableResult func *= (time: inout CMTime, multiplier: Float64) -> CMTime { time = time * multiplier return time } @discardableResult func *= (time: inout CMTime, multiplier: Float) -> CMTime { time = time * multiplier return time } // MARK: Divide func / (time: CMTime, divisor: Int32) -> CMTime { return CMTimeMultiplyByRatio(time, 1, divisor) } @discardableResult func /= (time: inout CMTime, divisor: Int32) -> CMTime { time = time / divisor return time } // MARK: - Convenience methods extension CMTime { func isNearlyEqualTo(_ time: CMTime, _ tolerance: CMTime=CMTimeMake(1,600)) -> Bool { let delta = CMTimeAbsoluteValue(self - time) return delta < tolerance } func isNearlyEqualTo(time: CMTime, _ tolerance: Float64=1.0/600) -> Bool { let t = Double(tolerance) return isNearlyEqualTo(time, CMTime(seconds:t, preferredTimescale:600)) } func isNearlyEqualTo(time: CMTime, _ tolerance: Float=1.0/600) -> Bool { let t = Double(tolerance) return isNearlyEqualTo(time, CMTime(seconds:t, preferredTimescale:600)) } } extension CMTime { var f: Float { return Float(self.f64) } var f64: Float64 { return CMTimeGetSeconds(self) } } func == (time: CMTime, seconds: Float64) -> Bool { return time == CMTime(seconds: seconds) } func == (time: CMTime, seconds: Float) -> Bool { return time == Float64(seconds) } func == (seconds: Float64, time: CMTime) -> Bool { return time == seconds } func == (seconds: Float, time: CMTime) -> Bool { return time == seconds } func != (time: CMTime, seconds: Float64) -> Bool { return !(time == seconds) } func != (time: CMTime, seconds: Float) -> Bool { return time != Float64(seconds) } func != (seconds: Float64, time: CMTime) -> Bool { return time != seconds } func != (seconds: Float, time: CMTime) -> Bool { return time != seconds } public func < (time: CMTime, seconds: Float64) -> Bool { return time < CMTime(seconds: seconds) } public func < (time: CMTime, seconds: Float) -> Bool { return time < Float64(seconds) } public func <= (time: CMTime, seconds: Float64) -> Bool { return time < seconds || time == seconds } public func <= (time: CMTime, seconds: Float) -> Bool { return time < seconds || time == seconds } public func < (seconds: Float64, time: CMTime) -> Bool { return CMTime(seconds: seconds) < time } public func < (seconds: Float, time: CMTime) -> Bool { return Float64(seconds) < time } public func <= (seconds: Float64, time: CMTime) -> Bool { return seconds < time || seconds == time } public func <= (seconds: Float, time: CMTime) -> Bool { return seconds < time || seconds == time } public func > (time: CMTime, seconds: Float64) -> Bool { return time > CMTime(seconds: seconds) } public func > (time: CMTime, seconds: Float) -> Bool { return time > Float64(seconds) } public func >= (time: CMTime, seconds: Float64) -> Bool { return time > seconds || time == seconds } public func >= (time: CMTime, seconds: Float) -> Bool { return time > seconds || time == seconds } public func > (seconds: Float64, time: CMTime) -> Bool { return CMTime(seconds: seconds) > time } public func > (seconds: Float, time: CMTime) -> Bool { return Float64(seconds) > time } public func >= (seconds: Float64, time: CMTime) -> Bool { return seconds > time || seconds == time } public func >= (seconds: Float, time: CMTime) -> Bool { return seconds > time || seconds == time } // MARK: - Debugging extension CMTime: CustomStringConvertible,CustomDebugStringConvertible { public var description: String { return "\(CMTimeGetSeconds(self))" } public var debugDescription: String { return String(describing: CMTimeCopyDescription(nil, self)) } } extension CMTimeRange: CustomStringConvertible,CustomDebugStringConvertible { public var description: String { return "{\(self.start.value)/\(self.start.timescale),\(self.duration.value)/\(self.duration.timescale)}" } public var debugDescription: String { return "{start:\(self.start), duration:\(self.duration)}" } } extension CMTimeMapping: CustomStringConvertible, CustomDebugStringConvertible { public var description: String { return "{ source:\(source.description), target:\(target.description) }" } public var debugDescription: String { return description } }
bsd-3-clause
ca84a011b9947d0c388d283949beb62a
29.45614
112
0.658986
3.890196
false
false
false
false
eneko/DSAA
Sources/DataStructures/StreamMedian.swift
1
1481
// // StreamMedian.swift // DSAA // // Created by Eneko Alonso on 2/17/16. // Copyright © 2016 Eneko Alonso. All rights reserved. // //public protocol Averageable { //: FloatLiteralConvertible, IntegerArithmeticType { // // public func average( // //} public struct StreamMedian<T: IntegerType> { var leftQueue = PriorityQueue<T>(order: .Max) var rightQueue = PriorityQueue<T>(order: .Min) public mutating func insert(item: T) { guard let median = median() else { rightQueue.add(item) return } if item < median { if leftQueue.count > rightQueue.count { if let item = leftQueue.remove() { rightQueue.add(item) } } leftQueue.add(item) } else { if rightQueue.count > leftQueue.count { if let item = rightQueue.remove() { leftQueue.add(item) } } rightQueue.add(item) } } public func median() -> T? { let leftSize = leftQueue.count let rightSize = rightQueue.count let diff = leftSize - rightSize if diff > 0 { return leftQueue.peek() } else if diff < 0 { return rightQueue.peek() } guard let left = leftQueue.peek(), let right = rightQueue.peek() else { return nil } return (left + right) / 2 } }
mit
aea97888e704807451b72fc609d0594e
24.084746
84
0.523649
4.277457
false
false
false
false
siutsin/fish
RingMDFish/Fish.swift
1
7080
// // Fish.swift // RingMDFish // // Created by simon on 18/11/2015. // Copyright © 2015 Simon Li. All rights reserved. // import UIKit struct FishConstants { static let DEAD_COLOR = UIColor.redColor() } class Fish: NSObject { var color = UIColor.clearColor() var fishDeadCallback: (() -> ())? var biteCallback: ((amount: Float) -> Bool)? var isNotifier = false /* eg: Alewife: C:100 i:2 S: 2 second / bite T: 20 seconds Cm:10 */ private var C: Float = 0 // Call ‘C’ is capacity of the fish when it’s full. private var Ci: Float = 0 // Call ‘Ci’ is the food left in when it’s hungry. private var i: Float = 0 // Call ‘i’ is the unit the fish receive everytime it bite. private var S: Float = 0 // Call S is the speed of biting. calculated by x seconds. private var T: Float = 0 // Call T is the speed of going to hungry. calculated by value of food decrease per seconds. private var Cm: Float = 0 // Call Cm is the number that says : "I'm hugry". So we have this fact : 0 < Cm < C. When ever Ci is smaller than Cm, the fish will be hungry. private var biteTimer: NSTimer? override init() { super.init() NSNotificationCenter.defaultCenter().addObserver(self, selector:"oneSecondPassed", name: Event.OneSecondPassed.rawValue, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector:"eat:", name: Event.FoundFood.rawValue, object: nil) } deinit { NSNotificationCenter.defaultCenter().removeObserver(self) } // MARK: Public func setAsNotifier() { print("setAsNotifier") NSNotificationCenter.defaultCenter().addObserver(self, selector:"didFarmerFeed", name: Event.Feed.rawValue, object: nil) self.isNotifier = true } // MARK: Private private func postInit() { self.Ci = self.C // assume the fish is full when init } @objc private func oneSecondPassed() { print("Ci: \(self.Ci)") if self.isDead() { if let callback = self.fishDeadCallback { callback() NSNotificationCenter.defaultCenter().removeObserver(self) } return } self.goingToHungry() } @objc private func didFarmerFeed() { print("didFarmerFeed") // That one will tell to the others of its group that, the food M has just came. // As soon as possible, the fish will notify the others and go to eat. NSNotificationCenter.defaultCenter().postNotificationName(Event.FoundFood.rawValue, object: self, userInfo: ["type": self.getClassName()]) } @objc private func eat(notification: NSNotification) { let userInfo: Dictionary<String, String> = notification.userInfo as! Dictionary<String, String> let className = userInfo["type"] // Fish of kind A can comunicate with the others of kind A only, can not comunicate with kind B or C, etc if className == self.getClassName() { // Only the hungry one wanna eat, It will ignore the notify and won't notify to the others. if self.isHungry() { self.bite() if self.biteTimer == nil { self.biteTimer = NSTimer.scheduledTimerWithTimeInterval(SceneConstants.TIMER_RATE, target: self, selector: "bite", userInfo: nil, repeats:true) } } } } private func stopBiteTimer() { if let timer = self.biteTimer { timer.invalidate() } self.biteTimer = nil } @objc private func bite() { print("bite") // As we know, the Ci will increase every time the fish bite food M, and the M will be decrease a value equal to i. let foodNeeded = self.C - self.Ci let amountToBite = foodNeeded < self.i ? foodNeeded : self.i if let callback = self.biteCallback { let biteSuccess = callback(amount: amountToBite) if biteSuccess { self.Ci += self.i if self.Ci >= self.C { print("Full") self.Ci = self.C self.stopBiteTimer() } } else { print("No Food") self.stopBiteTimer() } } } private func isHungry() -> Bool { return self.Ci < self.Cm } private func isDead() -> Bool { return self.Ci <= 0 } private func goingToHungry() { let foodNeededToConsumeToBecomeHungry = self.C - self.Cm let foodNeededPerSecond = foodNeededToConsumeToBecomeHungry / self.T self.Ci -= foodNeededPerSecond if self.isHungry() { print("\(self.getClassName()) isHungry") NSNotificationCenter.defaultCenter().postNotificationName(Event.Hungry.rawValue, object: self, userInfo: ["type": self.getClassName()]) } } } // MARK: Fish Classes enum FishType: String { case Alewife case Betta case Codlet case Dory case EagleRay case Firefish static let allValues = [Alewife, Betta, Codlet, Dory, EagleRay, Firefish] } //Alewife: C:100 i:2 Cm:10 S: 2 second / bite T: 20 seconds class Alewife: Fish { override init() { super.init() self.C = 100 self.i = 2 self.Cm = 10 self.S = 2 self.T = 20 self.color = UIColor.blackColor() self.postInit() } } //Betta: C:150 i:5 Cm:20 S: 3 second / bite T: 60 seconds class Betta: Fish { override init() { super.init() self.C = 150 self.i = 5 self.Cm = 20 self.S = 3 self.T = 60 self.color = UIColor.yellowColor() self.postInit() } } //Codlet: C:90 i:1 Cm:30 S: 1 second / bite T: 10 seconds class Codlet: Fish { override init() { super.init() self.C = 90 self.i = 1 self.Cm = 30 self.S = 1 self.T = 10 self.color = UIColor.blueColor() self.postInit() } } //Dory: C:160 i:4 Cm:50 S: 7 second / bite T: 40 seconds class Dory: Fish { override init() { super.init() self.C = 160 self.i = 4 self.Cm = 50 self.S = 7 self.T = 40 self.color = UIColor.greenColor() self.postInit() } } //Eagle ray: C: 200 i:10 Cm: 30 S: 5 second / bite T: 50 seconds class EagleRay: Fish { override init() { super.init() self.C = 200 self.i = 10 self.Cm = 30 self.S = 5 self.T = 50 self.color = UIColor.purpleColor() self.postInit() } } //Firefish: C:7 i:1 Cm: 2 S: 1 second / bite T: 5 seconds class Firefish: Fish { override init() { super.init() self.C = 7 self.i = 1 self.Cm = 2 self.S = 1 self.T = 5 self.color = UIColor.brownColor() self.postInit() } }
mit
6b844461286545391c3567e1c72a540d
28.552301
172
0.569952
3.936455
false
false
false
false
xuephil/Perfect
Examples/Authenticator/Authenticator Client/LoginViewController.swift
2
3554
// // LoginViewController.swift // Authenticator // // Created by Kyle Jessup on 2015-11-12. // Copyright © 2015 PerfectlySoft. All rights reserved. // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as // published by the Free Software Foundation, either version 3 of the // License, or (at your option) any later version, as supplemented by the // Perfect Additional Terms. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License, as supplemented by the // Perfect Additional Terms, for more details. // // You should have received a copy of the GNU Affero General Public License // and the Perfect Additional Terms that immediately follow the terms and // conditions of the GNU Affero General Public License along with this // program. If not, see <http://www.perfect.org/AGPL_3_0_With_Perfect_Additional_Terms.txt>. // import UIKit let LOGIN_SEGUE_ID = "loginSegue" class LoginViewController: UIViewController, NSURLSessionDelegate, UITextFieldDelegate { @IBOutlet var emailAddressText: UITextField? @IBOutlet var passwordText: UITextField? var message = "" override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. self.emailAddressText?.delegate = self self.passwordText?.delegate = self } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func shouldPerformSegueWithIdentifier(identifier: String, sender: AnyObject?) -> Bool { if identifier == LOGIN_SEGUE_ID { // start login process tryLogin() return false } return true } // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if let dest = segue.destinationViewController as? ResultViewController { dest.message = self.message } } func tryLogin() { let urlSessionDelegate = URLSessionDelegate(username: self.emailAddressText!.text!, password: self.passwordText!.text!) { (d:NSData?, res:NSURLResponse?, e:NSError?) -> Void in if let _ = e { self.message = "Failed with error \(e!)" } else if let httpRes = res as? NSHTTPURLResponse where httpRes.statusCode != 200 { self.message = "Failed with HTTP code \(httpRes.statusCode)" } else { let deserialized = try! NSJSONSerialization.JSONObjectWithData(d!, options: NSJSONReadingOptions.AllowFragments) self.message = "Logged in \(deserialized["firstName"]!!) \(deserialized["lastName"]!!)" } dispatch_async(dispatch_get_main_queue()) { self.performSegueWithIdentifier(LOGIN_SEGUE_ID, sender: nil) } } let sessionConfig = NSURLSession.sharedSession().configuration let session = NSURLSession(configuration: sessionConfig, delegate: urlSessionDelegate, delegateQueue: nil) let req = NSMutableURLRequest(URL: NSURL(string: END_POINT + "login")!) req.addValue("application/json", forHTTPHeaderField: "Accept") let task = session.dataTaskWithRequest(req) task.resume() } func textFieldShouldReturn(textField: UITextField) -> Bool { textField.resignFirstResponder() return true } }
agpl-3.0
fde8652ca6b6227726d955d54e9ba0ca
33.495146
123
0.720799
4.408189
false
false
false
false
CPRTeam/CCIP-iOS
Pods/CryptoSwift/Sources/CryptoSwift/Array+Extension.swift
3
4094
// // CryptoSwift // // Copyright (C) 2014-2017 Marcin Krzyżanowski <[email protected]> // This software is provided 'as-is', without any express or implied warranty. // // In no event will the authors be held liable for any damages arising from the use of this software. // // Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: // // - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. // - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. // - This notice may not be removed or altered from any source or binary distribution. // extension Array { init(reserveCapacity: Int) { self = Array<Element>() self.reserveCapacity(reserveCapacity) } var slice: ArraySlice<Element> { self[self.startIndex ..< self.endIndex] } } extension Array where Element == UInt8 { public init(hex: String) { self.init(reserveCapacity: hex.unicodeScalars.lazy.underestimatedCount) var buffer: UInt8? var skip = hex.hasPrefix("0x") ? 2 : 0 for char in hex.unicodeScalars.lazy { guard skip == 0 else { skip -= 1 continue } guard char.value >= 48 && char.value <= 102 else { removeAll() return } let v: UInt8 let c: UInt8 = UInt8(char.value) switch c { case let c where c <= 57: v = c - 48 case let c where c >= 65 && c <= 70: v = c - 55 case let c where c >= 97: v = c - 87 default: removeAll() return } if let b = buffer { append(b << 4 | v) buffer = nil } else { buffer = v } } if let b = buffer { append(b) } } public func toHexString() -> String { `lazy`.reduce(into: "") { var s = String($1, radix: 16) if s.count == 1 { s = "0" + s } $0 += s } } } extension Array where Element == UInt8 { /// split in chunks with given chunk size @available(*, deprecated) public func chunks(size chunksize: Int) -> Array<Array<Element>> { var words = Array<Array<Element>>() words.reserveCapacity(count / chunksize) for idx in stride(from: chunksize, through: count, by: chunksize) { words.append(Array(self[idx - chunksize ..< idx])) // slow for large table } let remainder = suffix(count % chunksize) if !remainder.isEmpty { words.append(Array(remainder)) } return words } public func md5() -> [Element] { Digest.md5(self) } public func sha1() -> [Element] { Digest.sha1(self) } public func sha224() -> [Element] { Digest.sha224(self) } public func sha256() -> [Element] { Digest.sha256(self) } public func sha384() -> [Element] { Digest.sha384(self) } public func sha512() -> [Element] { Digest.sha512(self) } public func sha2(_ variant: SHA2.Variant) -> [Element] { Digest.sha2(self, variant: variant) } public func sha3(_ variant: SHA3.Variant) -> [Element] { Digest.sha3(self, variant: variant) } public func crc32(seed: UInt32? = nil, reflect: Bool = true) -> UInt32 { Checksum.crc32(self, seed: seed, reflect: reflect) } public func crc32c(seed: UInt32? = nil, reflect: Bool = true) -> UInt32 { Checksum.crc32c(self, seed: seed, reflect: reflect) } public func crc16(seed: UInt16? = nil) -> UInt16 { Checksum.crc16(self, seed: seed) } public func encrypt(cipher: Cipher) throws -> [Element] { try cipher.encrypt(self.slice) } public func decrypt(cipher: Cipher) throws -> [Element] { try cipher.decrypt(self.slice) } public func authenticate<A: Authenticator>(with authenticator: A) throws -> [Element] { try authenticator.authenticate(self) } }
gpl-3.0
de1bfb65f4059a83973b1283f2e09bf3
26.655405
217
0.625214
3.807442
false
false
false
false
cabarique/TheProposalGame
MyProposalGame/GameViewController.swift
1
1688
// // GameViewController.swift // MyProposalGame // // Created by Luis Cabarique on 9/12/16. // Copyright (c) 2016 Luis Cabarique. All rights reserved. // import UIKit import SpriteKit class GameViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() let scene = GameScene(size: CGSize(width: 1024, height: 768)) let skView = self.view as! SKView skView.multipleTouchEnabled = true if GameSettings.Debugging.ALL_TellMeStatus { skView.showsFPS = GameSettings.Debugging.ALL_ShowFrameRate skView.showsNodeCount = GameSettings.Debugging.ALL_ShowNodeCount skView.showsDrawCount = GameSettings.Debugging.IOS_ShowDrawCount skView.showsQuadCount = GameSettings.Debugging.IOS_ShowQuadCount skView.showsPhysics = GameSettings.Debugging.IOS_ShowPhysics skView.showsFields = GameSettings.Debugging.IOS_ShowFields } skView.ignoresSiblingOrder = true scene.scaleMode = .AspectFill _ = SGResolution(screenSize: view.bounds.size, canvasSize: scene.size) skView.presentScene(scene) } override func shouldAutorotate() -> Bool { return true } override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask { return .Landscape } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Release any cached data, images, etc that aren't in use. } override func prefersStatusBarHidden() -> Bool { return true } }
mit
81c97809ab5486891940f870eec45d96
28.614035
82
0.64455
5.099698
false
false
false
false
caicai0/ios_demo
load/thirdpart/SwiftKuery/ConditionalClause.swift
1
6015
/** Copyright IBM Corporation 2016, 2017 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. */ // MARK: ConditionalClause /// A protocol for conditions used in SQL WHERE, ON and HAVING clauses. public protocol ConditionalClause: Buildable { /// The type of the clause: either `Filter` or `Having`. associatedtype ClauseType: Buildable /// The type of the column expression used in the clause: either `ScalarColumnExpression` or `AggregateColumnExpression`. associatedtype ColumnExpressionType: Field /// The left hand side of the conditional clause. var lhs: Predicate<ClauseType, ColumnExpressionType>? { get } /// The right hand side of the conditional clause. var rhs: Predicate<ClauseType, ColumnExpressionType>? { get } /// The operator of the conditional clause. var condition: Condition { get } /// Build the clause using `QueryBuilder`. /// /// - Parameter queryBuilder: The QueryBuilder to use. /// - Returns: A String representation of the clause. /// - Throws: QueryError.syntaxError if query build fails. func build(queryBuilder: QueryBuilder) throws -> String } /// An extension of `ConditionalClause` with implementation of `Buildable` protocol. public extension ConditionalClause { /// Build the clause using `QueryBuilder`. /// /// - Parameter queryBuilder: The QueryBuilder to use. /// - Returns: A String representation of the clause. /// - Throws: QueryError.syntaxError if query build fails. public func build(queryBuilder: QueryBuilder) throws -> String { guard lhs != nil else { if condition == .exists || condition == .notExists { guard rhs != nil else { throw QueryError.syntaxError("No right hand side operand in conditional clause.") } return try condition.build(queryBuilder: queryBuilder) + " " + rhs!.build(queryBuilder: queryBuilder) } throw QueryError.syntaxError("No left hand side operand in conditional clause.") } guard rhs != nil else { if condition == .isNull || condition == .isNotNull { return try lhs!.build(queryBuilder: queryBuilder) + " " + condition.build(queryBuilder: queryBuilder) } throw QueryError.syntaxError("No right hand side operand in conditional clause.") } let lhsBuilt = try lhs!.build(queryBuilder: queryBuilder) let conditionBuilt = condition.build(queryBuilder: queryBuilder) var rhsBuilt = "" if condition == .between || condition == .notBetween { switch rhs! { case .arrayOfString(let array): rhsBuilt = Utils.packType(array[0]) + " AND " + Utils.packType(array[1]) case .arrayOfInt(let array): rhsBuilt = Utils.packType(array[0]) + " AND " + Utils.packType(array[1]) case .arrayOfFloat(let array): rhsBuilt = Utils.packType(array[0]) + " AND " + Utils.packType(array[1]) case .arrayOfDouble(let array): rhsBuilt = Utils.packType(array[0]) + " AND " + Utils.packType(array[1]) case .arrayOfBool(let array): rhsBuilt = try Utils.packType(array[0], queryBuilder: queryBuilder) + " AND " + Utils.packType(array[1], queryBuilder: queryBuilder) case .arrayOfDate(let array): rhsBuilt = try Utils.packType(array[0], queryBuilder: queryBuilder) + " AND " + Utils.packType(array[1], queryBuilder: queryBuilder) case .arrayOfParameter(let array): rhsBuilt = try Utils.packType(array[0], queryBuilder: queryBuilder) + " AND " + Utils.packType(array[1], queryBuilder: queryBuilder) default: throw QueryError.syntaxError("Wrong type for right hand side operand in \(conditionBuilt) expression.") } } else if condition == .in || condition == .notIn { switch rhs! { case .arrayOfString(let array): rhsBuilt = "(\(array.map { Utils.packType($0) }.joined(separator: ", ")))" case .arrayOfInt(let array): rhsBuilt = "(\(array.map { Utils.packType($0) }.joined(separator: ", ")))" case .arrayOfFloat(let array): rhsBuilt = "(\(array.map { Utils.packType($0) }.joined(separator: ", ")))" case .arrayOfDouble(let array): rhsBuilt = "(\(array.map { Utils.packType($0) }.joined(separator: ", ")))" case .arrayOfBool(let array): rhsBuilt = try "(\(array.map { try Utils.packType($0, queryBuilder: queryBuilder) }.joined(separator: ", ")))" case .arrayOfDate(let array): rhsBuilt = try "(\(array.map { try Utils.packType($0, queryBuilder: queryBuilder) }.joined(separator: ", ")))" case .arrayOfParameter(let array): rhsBuilt = try "(\(array.map { try Utils.packType($0, queryBuilder: queryBuilder) }.joined(separator: ", ")))" case .select(let query): rhsBuilt = try "(" + query.build(queryBuilder: queryBuilder) + ")" default: throw QueryError.syntaxError("Wrong type for right hand side operand in \(conditionBuilt) expression.") } } else { rhsBuilt = try rhs!.build(queryBuilder: queryBuilder) } return lhsBuilt + " " + conditionBuilt + " " + rhsBuilt } }
mit
7f807465be8eafe37adea021ad666906
51.304348
148
0.622278
4.69555
false
false
false
false
cubixlabs/GIST-Framework
GISTFramework/Classes/Controls/InputMaskTextField.swift
1
7649
// // InputMaskTextField.swift // GISTFramework // // Created by Shoaib Abdul on 17/05/2017. // Copyright © 2017 Social Cubix. All rights reserved. // import UIKit import InputMask import PhoneNumberKit open class InputMaskTextField: BaseUITextField, MaskedTextFieldDelegateListener, MaskedPhoneTextFieldDelegateListener { open var planText:String? open var isValidMask:Bool = false; @IBInspectable public var maskFormat: String? { didSet { guard maskFormat != oldValue else { return; } self.updateMaskFormate(); } } //P.E. @IBInspectable public var sendMaskedText:Bool = false; @IBInspectable public var maskPhone: Bool = false { didSet { guard maskPhone != oldValue else { return; } self.updateMaskFormate(); } } //P.E. @IBInspectable public var phonePrefix: Bool = true; var curText: String? { get { return (self.maskFormat != nil || maskPhone) ? self.planText:self.text; } } //P.E. @IBInspectable public var defaultRegion = PhoneNumberKit.defaultRegionCode() { didSet { _maskPhoneTextFieldDelegate?.defaultRegion = defaultRegion; } } private var _polyMaskTextFieldDelegate:MaskedTextFieldDelegate?; private var _maskPhoneTextFieldDelegate:MaskedPhoneTextFieldDelegate?; ///Maintainig Own delegate. private weak var _delegate:UITextFieldDelegate?; open override weak var delegate: UITextFieldDelegate? { get { return _delegate; } set { _delegate = newValue; } } //P.E. override func commonInit() { super.commonInit(); if (self.maskFormat == nil && !self.maskPhone) { super.delegate = self; } } //F.E. //MARK: - Methods open func updateData(_ data: Any?) { let dicData:NSMutableDictionary? = data as? NSMutableDictionary; //Masking self.maskFormat = dicData?["maskFormat"] as? String; self.sendMaskedText = dicData?["sendMaskedText"] as? Bool ?? false; self.maskPhone = dicData?["maskPhone"] as? Bool ?? false; if let defRegion = dicData?["defaultRegion"] as? String { self.defaultRegion = defRegion; } } //F.E. func updateMaskFormate() { if let mskFormate:String = maskFormat { _maskPhoneTextFieldDelegate?.listener = nil; _maskPhoneTextFieldDelegate = nil; if (_polyMaskTextFieldDelegate == nil) { _polyMaskTextFieldDelegate = MaskedTextFieldDelegate(primaryFormat: mskFormate); _polyMaskTextFieldDelegate!.listener = self; super.delegate = _polyMaskTextFieldDelegate; } else { _polyMaskTextFieldDelegate!.primaryMaskFormat = mskFormate; } } else if maskPhone { _polyMaskTextFieldDelegate?.listener = nil; _polyMaskTextFieldDelegate = nil; if (_maskPhoneTextFieldDelegate == nil) { _maskPhoneTextFieldDelegate = MaskedPhoneTextFieldDelegate(self, with:self.phonePrefix); _maskPhoneTextFieldDelegate!.listener = self; _maskPhoneTextFieldDelegate!.defaultRegion = defaultRegion; super.delegate = _maskPhoneTextFieldDelegate; } } else { _polyMaskTextFieldDelegate?.listener = nil; _polyMaskTextFieldDelegate = nil; _maskPhoneTextFieldDelegate?.listener = nil; _maskPhoneTextFieldDelegate = nil; super.delegate = self; } } //F.E. open func applyMaskFormat() { let mask: Mask = try! Mask(format: self.maskFormat!) let input: String = self.text! let result: Mask.Result = mask.apply( toText: CaretString( string: input, caretPosition: input.endIndex, caretGravity: CaretString.CaretGravity.forward(autocomplete: true) ) ) self.isValidMask = result.complete; self.planText = result.extractedValue; super.text = result.formattedText.string; } //F.E. open func applyPhoneMaskFormat() { if let result = _maskPhoneTextFieldDelegate?.applyMask() { super.text = result.formattedText; self.planText = result.extractedValue; } } //F.E. //Mark: - UITextField Delegate Methods /// Protocol method of textFieldShouldBeginEditing. /// /// - Parameter textField: Text Field /// - Returns: Bool flag for should begin edititng open func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool { return _delegate?.textFieldShouldBeginEditing?(textField) ?? true; } //F.E. /// Protocol method of textFieldDidBeginEditing. /// /// - Parameter textField: Text Field open func textFieldDidBeginEditing(_ textField: UITextField) { _delegate?.textFieldDidBeginEditing?(textField); } //F.E. /// Protocol method of textFieldShouldEndEditing. - Default value is true /// /// - Parameter textField: Text Field /// - Returns: Bool flag for should end edititng open func textFieldShouldEndEditing(_ textField: UITextField) -> Bool { return _delegate?.textFieldShouldEndEditing?(textField) ?? true; } //F.E. /// Protocol method of textFieldDidEndEditing /// /// - Parameter textField: Text Field open func textFieldDidEndEditing(_ textField: UITextField) { _delegate?.textFieldDidEndEditing?(textField); } //F.E. /// Protocol method of shouldChangeCharactersIn range /// /// - Parameters: /// - textField: Text Field /// - range: Change Characters Range /// - string: Replacement String /// - Returns: Bool flag for should change characters in range open func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { return _delegate?.textField?(textField, shouldChangeCharactersIn:range, replacementString:string) ?? true; } //F.E. /// Protocol method of textFieldShouldClear. - Default value is true /// /// - Parameter textField: Text Field /// - Returns: Bool flag for should clear text field open func textFieldShouldClear(_ textField: UITextField) -> Bool { return _delegate?.textFieldShouldClear?(textField) ?? true; } //F.E. /// Protocol method of textFieldShouldReturn. - Default value is true /// /// - Parameter textField: Text Field /// - Returns: Bool flag for text field should return. open func textFieldShouldReturn(_ textField: UITextField) -> Bool { return _delegate?.textFieldShouldReturn?(textField) ?? true; } //F.E. open func textField(_ textField: UITextField, didFillMandatoryCharacters complete: Bool, didExtractValue value: String) { self.planText = value; self.isValidMask = complete; } //F.E. public func textField(_ textField: UITextField, didMaskPhoneWithExtractValue value: String) { self.planText = value; } //F.E. } //CLS END
agpl-3.0
8516e7b04585356ded9bc862b2864af2
31.965517
134
0.598588
5.185085
false
false
false
false
qiuncheng/study-for-swift
learn-rx-swift/Chocotastic-starter/Pods/RxSwift/RxSwift/Observables/Implementations/RetryWhen.swift
6
5084
// // RetryWhen.swift // Rx // // Created by Junior B. on 06/10/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // import Foundation class RetryTriggerSink<S: Sequence, O: ObserverType, TriggerObservable: ObservableType, Error> : ObserverType where S.Iterator.Element : ObservableType, S.Iterator.Element.E == O.E { typealias E = TriggerObservable.E typealias Parent = RetryWhenSequenceSinkIter<S, O, TriggerObservable, Error> fileprivate let _parent: Parent init(parent: Parent) { _parent = parent } func on(_ event: Event<E>) { switch event { case .next: _parent._parent._lastError = nil _parent._parent.schedule(.moveNext) case .error(let e): _parent._parent.forwardOn(.error(e)) _parent._parent.dispose() case .completed: _parent._parent.forwardOn(.completed) _parent._parent.dispose() } } } class RetryWhenSequenceSinkIter<S: Sequence, O: ObserverType, TriggerObservable: ObservableType, Error> : SingleAssignmentDisposable , ObserverType where S.Iterator.Element : ObservableType, S.Iterator.Element.E == O.E { typealias E = O.E typealias Parent = RetryWhenSequenceSink<S, O, TriggerObservable, Error> fileprivate let _parent: Parent fileprivate let _errorHandlerSubscription = SingleAssignmentDisposable() init(parent: Parent) { _parent = parent } func on(_ event: Event<E>) { switch event { case .next: _parent.forwardOn(event) case .error(let error): _parent._lastError = error if let failedWith = error as? Error { // dispose current subscription super.dispose() let errorHandlerSubscription = _parent._notifier.subscribe(RetryTriggerSink(parent: self)) _errorHandlerSubscription.disposable = errorHandlerSubscription _parent._errorSubject.on(.next(failedWith)) } else { _parent.forwardOn(.error(error)) _parent.dispose() } case .completed: _parent.forwardOn(event) _parent.dispose() } } override func dispose() { super.dispose() _errorHandlerSubscription.dispose() } } class RetryWhenSequenceSink<S: Sequence, O: ObserverType, TriggerObservable: ObservableType, Error> : TailRecursiveSink<S, O> where S.Iterator.Element : ObservableType, S.Iterator.Element.E == O.E { typealias Element = O.E typealias Parent = RetryWhenSequence<S, TriggerObservable, Error> let _lock = NSRecursiveLock() fileprivate let _parent: Parent fileprivate var _lastError: Swift.Error? fileprivate let _errorSubject = PublishSubject<Error>() fileprivate let _handler: Observable<TriggerObservable.E> fileprivate let _notifier = PublishSubject<TriggerObservable.E>() init(parent: Parent, observer: O) { _parent = parent _handler = parent._notificationHandler(_errorSubject).asObservable() super.init(observer: observer) } override func done() { if let lastError = _lastError { forwardOn(.error(lastError)) _lastError = nil } else { forwardOn(.completed) } dispose() } override func extract(_ observable: Observable<E>) -> SequenceGenerator? { // It is important to always return `nil` here because there are sideffects in the `run` method // that are dependant on particular `retryWhen` operator so single operator stack can't be reused in this // case. return nil } override func subscribeToNext(_ source: Observable<E>) -> Disposable { let iter = RetryWhenSequenceSinkIter(parent: self) iter.disposable = source.subscribe(iter) return iter } override func run(_ sources: SequenceGenerator) -> Disposable { let triggerSubscription = _handler.subscribe(_notifier.asObserver()) let superSubscription = super.run(sources) return Disposables.create(superSubscription, triggerSubscription) } } class RetryWhenSequence<S: Sequence, TriggerObservable: ObservableType, Error> : Producer<S.Iterator.Element.E> where S.Iterator.Element : ObservableType { typealias Element = S.Iterator.Element.E fileprivate let _sources: S fileprivate let _notificationHandler: (Observable<Error>) -> TriggerObservable init(sources: S, notificationHandler: @escaping (Observable<Error>) -> TriggerObservable) { _sources = sources _notificationHandler = notificationHandler } override func run<O : ObserverType>(_ observer: O) -> Disposable where O.E == Element { let sink = RetryWhenSequenceSink<S, O, TriggerObservable, Error>(parent: self, observer: observer) sink.disposable = sink.run((self._sources.makeIterator(), nil)) return sink } }
mit
042e626350e9263205cef9ddf4fc7741
32.886667
155
0.640763
4.702128
false
false
false
false
andrelind/Breeze
Breeze/NSManagedObject+Finding.swift
1
5900
// // NSManagedObject+Finding.swift // Breeze // // Created by André Lind on 2014-08-11. // Copyright (c) 2014 André Lind. All rights reserved. // import Foundation import CoreData extension NSManagedObject { // MARK: - Find in context public func inContextOfType(type: BreezeContextType) -> NSManagedObject? { if objectID.temporaryID { var error: NSError? if managedObjectContext!.obtainPermanentIDsForObjects([self], error: &error) == false { println("Breeze - Unable to obtain permantent IDs for object: \(self). Error: \(error)") return nil } } return BreezeStore.contextForType(type).objectWithID(objectID) } // MARK: - Find first public class func findFirst(attribute: String? = nil, value: AnyObject?, contextType: BreezeContextType = .Main) -> NSManagedObject? { let predicate = predicateForAttribute(attribute, value: value) return findFirst(predicate: predicate, sortedBy: nil, ascending: false, contextType: contextType) } public class func findFirst(predicate: NSPredicate? = nil, sortedBy: String? = nil, ascending: Bool = true, contextType: BreezeContextType = .Main) -> NSManagedObject? { return findFirst(predicate: predicate, sortedBy: sortedBy, ascending: ascending, context: BreezeStore.contextForType(contextType)) } public class func findFirst(attribute: String? = nil, value: AnyObject?, context: NSManagedObjectContext) -> NSManagedObject? { let predicate = predicateForAttribute(attribute, value: value) return findFirst(predicate: predicate, sortedBy: nil, ascending: false, context: context) } public class func findFirst(predicate: NSPredicate? = nil, sortedBy: String? = nil, ascending: Bool = true, context: NSManagedObjectContext) -> NSManagedObject? { let request = fetchRequest(predicate, sortedBy: sortedBy, ascending: ascending) request.fetchLimit = 1 return BreezeStore.executeRequest(request, context: context).result.first } // MARK: - Find all public class func findAll(attribute: String? = nil, value: AnyObject?, contextType: BreezeContextType = .Main) -> [NSManagedObject] { let predicate = predicateForAttribute(attribute, value: value) return findAll(predicate: predicate, sortedBy: nil, ascending: false, contextType: contextType) } public class func findAll(predicate: NSPredicate? = nil, sortedBy: String? = nil, ascending: Bool = true, contextType: BreezeContextType = .Main) -> [NSManagedObject] { return findAll(predicate: predicate, sortedBy: sortedBy, ascending: ascending, context: BreezeStore.contextForType(contextType)) } public class func findAll(attribute: String? = nil, value: AnyObject?, context: NSManagedObjectContext) -> [NSManagedObject] { let predicate = predicateForAttribute(attribute, value: value) return findAll(predicate: predicate, sortedBy: nil, ascending: false, context: context) } public class func findAll(predicate: NSPredicate? = nil, sortedBy: String? = nil, ascending: Bool = true, context: NSManagedObjectContext) -> [NSManagedObject] { let request = fetchRequest(predicate, sortedBy: sortedBy, ascending: ascending) return BreezeStore.executeRequest(request, context: context).result } // MARK: - Count public class func countAll(predicate: NSPredicate? = nil, sortedBy: String? = nil, ascending: Bool = true, contextType: BreezeContextType = .Main) -> Int { return countAll(predicate: predicate, sortedBy: sortedBy, ascending: ascending, context: BreezeStore.contextForType(contextType)) } public class func countAll(predicate: NSPredicate? = nil, sortedBy: String? = nil, ascending: Bool = true, context: NSManagedObjectContext) -> Int { let request = fetchRequest(predicate, sortedBy: sortedBy, ascending: ascending) request.includesSubentities = false let countRequest = BreezeStore.executeCountRequest(request, context: context) if countRequest.error != nil { println("Breeze - Error executing count request: \(countRequest.error)") } return countRequest.count } // MARK: - Fetch all public class func fetchAll(predicate: NSPredicate? = nil, groupedBy: String? = nil, sortedBy: String? = nil, ascending: Bool = true, delegate: NSFetchedResultsControllerDelegate?, contextType: BreezeContextType = .Main) -> NSFetchedResultsController? { let request = fetchRequest(predicate, sortedBy: sortedBy, ascending: ascending) let fetchedResultsController = NSFetchedResultsController(fetchRequest: request, managedObjectContext: BreezeStore.contextForType(contextType), sectionNameKeyPath: groupedBy, cacheName: nil) fetchedResultsController.delegate = delegate var error: NSError? if fetchedResultsController.performFetch(&error) == false { println("Breeze - Error setting up NSFetchedResultsController \(fetchedResultsController). Error: \(error)") return nil } return fetchedResultsController } // MARK: - Private area, keep off private class func predicateForAttribute(attribute: String?, value: AnyObject?) -> NSPredicate { return NSPredicate(format: "%K = %@", argumentArray: [attribute!, value!]) } private class func fetchRequest(predicate: NSPredicate?, sortedBy: String? = nil, ascending: Bool = true) -> NSFetchRequest! { let fetchRequest = NSFetchRequest(entityName: NSStringFromClass(self)) fetchRequest.predicate = predicate fetchRequest.sortDescriptors = sortedBy != nil ? [NSSortDescriptor(key: sortedBy!, ascending: ascending)] : nil return fetchRequest } }
mit
2de2a3862e8db29aac89962d345f80ed
50.295652
256
0.696338
4.771845
false
false
false
false
youkchansim/CSPhotoGallery
Pod/Classes/CSPhotoGalleryDetailCollectionViewCell.swift
1
1604
// // CSPhotoGalleryDetailCollectionViewCell.swift // CSPhotoGallery // // Created by Youk Chansim on 2016. 12. 14.. // Copyright © 2016년 Youk Chansim. All rights reserved. // import UIKit class CSPhotoGalleryDetailCollectionViewCell: UICollectionViewCell { var representedAssetIdentifier: String? @IBOutlet weak var imageView: UIImageView! @IBOutlet weak var scrollView: UIScrollView! { didSet { // let doubleTapGesture = UITapGestureRecognizer(target: self, action: #selector(doubleTap)) // doubleTapGesture.numberOfTapsRequired = 2 // doubleTapGesture.delaysTouchesBegan = true // scrollView.addGestureRecognizer(doubleTapGesture) } } override func prepareForReuse() { representedAssetIdentifier = nil imageView.image = nil } } // MARK:- Extension extension CSPhotoGalleryDetailCollectionViewCell { func doubleTap(gesture: UIGestureRecognizer) { if scrollView.zoomScale > 1.0 { scrollView.setZoomScale(1.0, animated: true) } else { let scale: CGFloat = 5.0 let point = gesture.location(in: imageView) let scrollSize = scrollView.frame.size let size = CGSize(width: scrollSize.width / scale, height: scrollSize.height / scale) let origin = CGPoint(x: point.x - size.width / 2, y: point.y - size.height / 2) scrollView.zoom(to:CGRect(origin: origin, size: size), animated: true) } } }
mit
b37a176855970bdd9684f08b4515028b
32.354167
103
0.623985
5.003125
false
false
false
false
abertelrud/swift-package-manager
Sources/PackageCollectionsSigning/Utilities/Base64URL.swift
2
3010
//===----------------------------------------------------------------------===// // // This source file is part of the Swift open source project // // Copyright (c) 2021 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 // //===----------------------------------------------------------------------===// //===----------------------------------------------------------------------===// // // This source file is part of the Vapor open source project // // Copyright (c) 2017-2020 Vapor project authors // Licensed under MIT // // See LICENSE for license information // // SPDX-License-Identifier: MIT // //===----------------------------------------------------------------------===// import Foundation // Source: https://github.com/vapor/jwt-kit/blob/master/Sources/JWTKit/Utilities/Base64URL.swift extension DataProtocol { func base64URLDecodedBytes() -> Data? { var data = Data(self) data.base64URLUnescape() return Data(base64Encoded: data) } func base64URLEncodedBytes() -> Data { var data = Data(self).base64EncodedData() data.base64URLEscape() return data } } extension Data { /// Converts base64-url encoded data to a base64 encoded data. /// /// https://tools.ietf.org/html/rfc4648#page-7 mutating func base64URLUnescape() { for i in 0 ..< self.count { switch self[i] { case 0x2D: self[self.index(self.startIndex, offsetBy: i)] = 0x2B case 0x5F: self[self.index(self.startIndex, offsetBy: i)] = 0x2F default: break } } /// https://stackoverflow.com/questions/43499651/decode-base64url-to-base64-swift let padding = count % 4 if padding > 0 { self += Data(repeating: 0x3D, count: 4 - padding) } } /// Converts base64 encoded data to a base64-url encoded data. /// /// https://tools.ietf.org/html/rfc4648#page-7 mutating func base64URLEscape() { for i in 0 ..< self.count { switch self[i] { case 0x2B: self[self.index(self.startIndex, offsetBy: i)] = 0x2D case 0x2F: self[self.index(self.startIndex, offsetBy: i)] = 0x5F default: break } } self = split(separator: 0x3D).first ?? .init() } /// Converts base64-url encoded data to a base64 encoded data. /// /// https://tools.ietf.org/html/rfc4648#page-7 func base64URLUnescaped() -> Data { var data = self data.base64URLUnescape() return data } /// Converts base64 encoded data to a base64-url encoded data. /// /// https://tools.ietf.org/html/rfc4648#page-7 func base64URLEscaped() -> Data { var data = self data.base64URLEscape() return data } }
apache-2.0
f22d12e9ea9648e0dd05fa8e7abfa69c
31.021277
96
0.551495
4.095238
false
false
false
false
uasys/swift
stdlib/public/core/OptionSet.swift
1
14887
//===--- OptionSet.swift --------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// /// A type that presents a mathematical set interface to a bit set. /// /// You use the `OptionSet` protocol to represent bitset types, where /// individual bits represent members of a set. Adopting this protocol in /// your custom types lets you perform set-related operations such as /// membership tests, unions, and intersections on those types. What's more, /// when implemented using specific criteria, adoption of this protocol /// requires no extra work on your part. /// /// When creating an option set, include a `rawValue` property in your type /// declaration. The `rawValue` property must be of a type that conforms to /// the `FixedWidthInteger` protocol, such as `Int` or `UInt8`. Next, create /// unique options as static properties of your custom type using unique /// powers of two (1, 2, 4, 8, 16, and so forth) for each individual /// property's raw value so that each property can be represented by a single /// bit of the type's raw value. /// /// For example, consider a custom type called `ShippingOptions` that is an /// option set of the possible ways to ship a customer's purchase. /// `ShippingOptions` includes a `rawValue` property of type `Int` that stores /// the bit mask of available shipping options. The static members `nextDay`, /// `secondDay`, `priority`, and `standard` are unique, individual options. /// /// struct ShippingOptions: OptionSet { /// let rawValue: Int /// /// static let nextDay = ShippingOptions(rawValue: 1 << 0) /// static let secondDay = ShippingOptions(rawValue: 1 << 1) /// static let priority = ShippingOptions(rawValue: 1 << 2) /// static let standard = ShippingOptions(rawValue: 1 << 3) /// /// static let express: ShippingOptions = [.nextDay, .secondDay] /// static let all: ShippingOptions = [.express, .priority, .standard] /// } /// /// Declare additional preconfigured option set values as static properties /// initialized with an array literal containing other option values. In the /// example, because the `express` static property is assigned an array /// literal with the `nextDay` and `secondDay` options, it will contain those /// two elements. /// /// Using an Option Set Type /// ======================== /// /// When you need to create an instance of an option set, assign one of the /// type's static members to your variable or constant. Alternatively, to /// create an option set instance with multiple members, assign an array /// literal with multiple static members of the option set. To create an empty /// instance, assign an empty array literal to your variable. /// /// let singleOption: ShippingOptions = .priority /// let multipleOptions: ShippingOptions = [.nextDay, .secondDay, .priority] /// let noOptions: ShippingOptions = [] /// /// Use set-related operations to check for membership and to add or remove /// members from an instance of your custom option set type. The following /// example shows how you can determine free shipping options based on a /// customer's purchase price: /// /// let purchasePrice = 87.55 /// /// var freeOptions: ShippingOptions = [] /// if purchasePrice > 50 { /// freeOptions.insert(.priority) /// } /// /// if freeOptions.contains(.priority) { /// print("You've earned free priority shipping!") /// } else { /// print("Add more to your cart for free priority shipping!") /// } /// // Prints "You've earned free priority shipping!" public protocol OptionSet : SetAlgebra, RawRepresentable { // We can't constrain the associated Element type to be the same as // Self, but we can do almost as well with a default and a // constrained extension /// The element type of the option set. /// /// To inherit all the default implementations from the `OptionSet` protocol, /// the `Element` type must be `Self`, the default. associatedtype Element = Self // FIXME: This initializer should just be the failable init from // RawRepresentable. Unfortunately, current language limitations // that prevent non-failable initializers from forwarding to // failable ones would prevent us from generating the non-failing // default (zero-argument) initializer. Since OptionSet's main // purpose is to create convenient conformances to SetAlgebra, // we opt for a non-failable initializer. /// Creates a new option set from the given raw value. /// /// This initializer always succeeds, even if the value passed as `rawValue` /// exceeds the static properties declared as part of the option set. This /// example creates an instance of `ShippingOptions` with a raw value beyond /// the highest element, with a bit mask that effectively contains all the /// declared static members. /// /// let extraOptions = ShippingOptions(rawValue: 255) /// print(extraOptions.isStrictSuperset(of: .all)) /// // Prints "true" /// /// - Parameter rawValue: The raw value of the option set to create. Each bit /// of `rawValue` potentially represents an element of the option set, /// though raw values may include bits that are not defined as distinct /// values of the `OptionSet` type. init(rawValue: RawValue) } /// `OptionSet` requirements for which default implementations /// are supplied. /// /// - Note: A type conforming to `OptionSet` can implement any of /// these initializers or methods, and those implementations will be /// used in lieu of these defaults. extension OptionSet { /// Returns a new option set of the elements contained in this set, in the /// given set, or in both. /// /// This example uses the `union(_:)` method to add two more shipping options /// to the default set. /// /// let defaultShipping = ShippingOptions.standard /// let memberShipping = defaultShipping.union([.secondDay, .priority]) /// print(memberShipping.contains(.priority)) /// // Prints "true" /// /// - Parameter other: An option set. /// - Returns: A new option set made up of the elements contained in this /// set, in `other`, or in both. public func union(_ other: Self) -> Self { var r: Self = Self(rawValue: self.rawValue) r.formUnion(other) return r } /// Returns a new option set with only the elements contained in both this /// set and the given set. /// /// This example uses the `intersection(_:)` method to limit the available /// shipping options to what can be used with a PO Box destination. /// /// // Can only ship standard or priority to PO Boxes /// let poboxShipping: ShippingOptions = [.standard, .priority] /// let memberShipping: ShippingOptions = /// [.standard, .priority, .secondDay] /// /// let availableOptions = memberShipping.intersection(poboxShipping) /// print(availableOptions.contains(.priority)) /// // Prints "true" /// print(availableOptions.contains(.secondDay)) /// // Prints "false" /// /// - Parameter other: An option set. /// - Returns: A new option set with only the elements contained in both this /// set and `other`. public func intersection(_ other: Self) -> Self { var r = Self(rawValue: self.rawValue) r.formIntersection(other) return r } /// Returns a new option set with the elements contained in this set or in /// the given set, but not in both. /// /// - Parameter other: An option set. /// - Returns: A new option set with only the elements contained in either /// this set or `other`, but not in both. public func symmetricDifference(_ other: Self) -> Self { var r = Self(rawValue: self.rawValue) r.formSymmetricDifference(other) return r } } /// `OptionSet` requirements for which default implementations are /// supplied when `Element == Self`, which is the default. /// /// - Note: A type conforming to `OptionSet` can implement any of /// these initializers or methods, and those implementations will be /// used in lieu of these defaults. extension OptionSet where Element == Self { /// Returns a Boolean value that indicates whether a given element is a /// member of the option set. /// /// This example uses the `contains(_:)` method to check whether next-day /// shipping is in the `availableOptions` instance. /// /// let availableOptions = ShippingOptions.express /// if availableOptions.contains(.nextDay) { /// print("Next day shipping available") /// } /// // Prints "Next day shipping available" /// /// - Parameter member: The element to look for in the option set. /// - Returns: `true` if the option set contains `member`; otherwise, /// `false`. public func contains(_ member: Self) -> Bool { return self.isSuperset(of: member) } /// Adds the given element to the option set if it is not already a member. /// /// In the following example, the `.secondDay` shipping option is added to /// the `freeOptions` option set if `purchasePrice` is greater than 50.0. For /// the `ShippingOptions` declaration, see the `OptionSet` protocol /// discussion. /// /// let purchasePrice = 87.55 /// /// var freeOptions: ShippingOptions = [.standard, .priority] /// if purchasePrice > 50 { /// freeOptions.insert(.secondDay) /// } /// print(freeOptions.contains(.secondDay)) /// // Prints "true" /// /// - Parameter newMember: The element to insert. /// - Returns: `(true, newMember)` if `newMember` was not contained in /// `self`. Otherwise, returns `(false, oldMember)`, where `oldMember` is /// the member of the set equal to `newMember`. @discardableResult public mutating func insert( _ newMember: Element ) -> (inserted: Bool, memberAfterInsert: Element) { let oldMember = self.intersection(newMember) let shouldInsert = oldMember != newMember let result = ( inserted: shouldInsert, memberAfterInsert: shouldInsert ? newMember : oldMember) if shouldInsert { self.formUnion(newMember) } return result } /// Removes the given element and all elements subsumed by it. /// /// In the following example, the `.priority` shipping option is removed from /// the `options` option set. Attempting to remove the same shipping option /// a second time results in `nil`, because `options` no longer contains /// `.priority` as a member. /// /// var options: ShippingOptions = [.secondDay, .priority] /// let priorityOption = options.remove(.priority) /// print(priorityOption == .priority) /// // Prints "true" /// /// print(options.remove(.priority)) /// // Prints "nil" /// /// In the next example, the `.express` element is passed to `remove(_:)`. /// Although `.express` is not a member of `options`, `.express` subsumes /// the remaining `.secondDay` element of the option set. Therefore, /// `options` is emptied and the intersection between `.express` and /// `options` is returned. /// /// let expressOption = options.remove(.express) /// print(expressOption == .express) /// // Prints "false" /// print(expressOption == .secondDay) /// // Prints "true" /// /// - Parameter member: The element of the set to remove. /// - Returns: The intersection of `[member]` and the set, if the /// intersection was nonempty; otherwise, `nil`. @discardableResult public mutating func remove(_ member: Element) -> Element? { let r = isSuperset(of: member) ? Optional(member) : nil self.subtract(member) return r } /// Inserts the given element into the set. /// /// If `newMember` is not contained in the set but subsumes current members /// of the set, the subsumed members are returned. /// /// var options: ShippingOptions = [.secondDay, .priority] /// let replaced = options.update(with: .express) /// print(replaced == .secondDay) /// // Prints "true" /// /// - Returns: The intersection of `[newMember]` and the set if the /// intersection was nonempty; otherwise, `nil`. @discardableResult public mutating func update(with newMember: Element) -> Element? { let r = self.intersection(newMember) self.formUnion(newMember) return r.isEmpty ? nil : r } } /// `OptionSet` requirements for which default implementations are /// supplied when `RawValue` conforms to `FixedWidthInteger`, /// which is the usual case. Each distinct bit of an option set's /// `.rawValue` corresponds to a disjoint value of the `OptionSet`. /// /// - `union` is implemented as a bitwise "or" (`|`) of `rawValue`s /// - `intersection` is implemented as a bitwise "and" (`&`) of /// `rawValue`s /// - `symmetricDifference` is implemented as a bitwise "exclusive or" /// (`^`) of `rawValue`s /// /// - Note: A type conforming to `OptionSet` can implement any of /// these initializers or methods, and those implementations will be /// used in lieu of these defaults. extension OptionSet where RawValue : FixedWidthInteger { /// Creates an empty option set. /// /// This initializer creates an option set with a raw value of zero. public init() { self.init(rawValue: 0) } /// Inserts the elements of another set into this option set. /// /// This method is implemented as a `|` (bitwise OR) operation on the /// two sets' raw values. /// /// - Parameter other: An option set. public mutating func formUnion(_ other: Self) { self = Self(rawValue: self.rawValue | other.rawValue) } /// Removes all elements of this option set that are not /// also present in the given set. /// /// This method is implemented as a `&` (bitwise AND) operation on the /// two sets' raw values. /// /// - Parameter other: An option set. public mutating func formIntersection(_ other: Self) { self = Self(rawValue: self.rawValue & other.rawValue) } /// Replaces this set with a new set containing all elements /// contained in either this set or the given set, but not in both. /// /// This method is implemented as a `^` (bitwise XOR) operation on the two /// sets' raw values. /// /// - Parameter other: An option set. public mutating func formSymmetricDifference(_ other: Self) { self = Self(rawValue: self.rawValue ^ other.rawValue) } }
apache-2.0
4a04ec61aa4fdc551068f1ffbc78d9e5
40.352778
80
0.664405
4.394038
false
false
false
false
cdtschange/SwiftMKit
SwiftMKit/UI/View/JDJellyButton/JDJellyButtonView.swift
1
1882
// // JDJellyButtonView.swift // SwiftMKitDemo // // Created by Mao on 06/01/2017. // Copyright © 2017 cdts. All rights reserved. // import UIKit protocol JellyButtonDelegate { func JellyButtonHasBeenTap(touch:UITouch,image:UIImage,groupindex:Int,arrindex:Int) } extension JellyButtonDelegate{ func JellyButtonHasBeenTap(touch:UITouch,image:UIImage,groupindex:Int,arrindex:Int) { } } class JDJellyButtonView:UIView { var tapdelegate:JellyButtonDelegate? var dependingMainButton:JDJellyMainButton? var imgView:UIImageView? override init(frame: CGRect) { super.init(frame: frame) } init(frame: CGRect,BGColor:UIColor) { super.init(frame: frame) self.layer.cornerRadius = 0.4 * self.frame.width self.backgroundColor = BGColor } init(frame: CGRect,bgimg:UIImage) { super.init(frame: frame) self.layer.cornerRadius = 0.4 * self.frame.width imgView = UIImageView(image: bgimg) imgView?.frame = self.bounds imgView?.contentMode = .scaleAspectFit imgView?.mBorderColor = UIColor.black imgView?.mBorderWidth = 2 imgView?.mCornerRadius = (imgView?.size.width ?? 0) / 2 self.addSubview(imgView!) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { let image = self.imgView?.image let groupindex = dependingMainButton?.getGroupIndex() let arrindex = dependingMainButton?.getJellyButtonIndex(jelly: self) print("\(groupindex ?? 0),\(arrindex ?? 0)") tapdelegate?.JellyButtonHasBeenTap(touch: touches.first!,image: image!,groupindex: groupindex!,arrindex: arrindex!) } }
mit
d6c581a76c66357d2b5b805f1e38f9c4
26.26087
123
0.652844
4.161504
false
false
false
false
vector-im/vector-ios
RiotSwiftUI/Modules/Onboarding/Avatar/Coordinator/OnboardingAvatarCoordinator.swift
1
7644
// // Copyright 2021 New Vector Ltd // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import SwiftUI import CommonKit struct OnboardingAvatarCoordinatorParameters { let userSession: UserSession } @available(iOS 14.0, *) final class OnboardingAvatarCoordinator: Coordinator, Presentable { // MARK: - Properties // MARK: Private private let parameters: OnboardingAvatarCoordinatorParameters private let onboardingAvatarHostingController: VectorHostingController private var onboardingAvatarViewModel: OnboardingAvatarViewModelProtocol private var indicatorPresenter: UserIndicatorTypePresenterProtocol private var waitingIndicator: UserIndicator? private lazy var cameraPresenter: CameraPresenter = { let presenter = CameraPresenter() presenter.delegate = self return presenter }() private lazy var mediaPickerPresenter: MediaPickerPresenter = { let presenter = MediaPickerPresenter() presenter.delegate = self return presenter }() private lazy var mediaUploader: MXMediaLoader = MXMediaManager.prepareUploader(withMatrixSession: parameters.userSession.matrixSession, initialRange: 0, andRange: 1.0) // MARK: Public // Must be used only internally var childCoordinators: [Coordinator] = [] var completion: ((UserSession) -> Void)? // MARK: - Setup init(parameters: OnboardingAvatarCoordinatorParameters) { self.parameters = parameters let viewModel = OnboardingAvatarViewModel(userId: parameters.userSession.userId, displayName: parameters.userSession.account.userDisplayName, avatarColorCount: DefaultThemeSwiftUI().colors.namesAndAvatars.count) let view = OnboardingAvatarScreen(viewModel: viewModel.context) onboardingAvatarViewModel = viewModel onboardingAvatarHostingController = VectorHostingController(rootView: view) onboardingAvatarHostingController.vc_removeBackTitle() onboardingAvatarHostingController.enableNavigationBarScrollEdgeAppearance = true indicatorPresenter = UserIndicatorTypePresenter(presentingViewController: onboardingAvatarHostingController) } // MARK: - Public func start() { MXLog.debug("[OnboardingAvatarCoordinator] did start.") onboardingAvatarViewModel.completion = { [weak self] result in guard let self = self else { return } MXLog.debug("[OnboardingAvatarCoordinator] OnboardingAvatarViewModel did complete with result: \(result).") switch result { case .pickImage: self.pickImage() case .takePhoto: self.takePhoto() case .save(let avatar): self.setAvatar(avatar) case .skip: self.completion?(self.parameters.userSession) } } } func toPresentable() -> UIViewController { return self.onboardingAvatarHostingController } // MARK: - Private /// Show a blocking activity indicator whilst saving. private func startWaiting() { waitingIndicator = indicatorPresenter.present(.loading(label: VectorL10n.saving, isInteractionBlocking: true)) } /// Hide the currently displayed activity indicator. private func stopWaiting() { waitingIndicator = nil } /// Present an image picker for the device photo library. private func pickImage() { let controller = toPresentable() mediaPickerPresenter.presentPicker(from: controller, with: .images, animated: true) } /// Present a camera view to take a photo to use for the avatar. private func takePhoto() { let controller = toPresentable() cameraPresenter.presentCamera(from: controller, with: [.image], animated: true) } /// Set the supplied image as user's avatar, completing the screen's display if successful. func setAvatar(_ image: UIImage?) { guard let image = image else { MXLog.error("[OnboardingAvatarCoordinator] setAvatar called with a nil image.") return } startWaiting() guard let avatarData = MXKTools.forceImageOrientationUp(image)?.jpegData(compressionQuality: 0.5) else { MXLog.error("[OnboardingAvatarCoordinator] Failed to create jpeg data.") self.stopWaiting() self.onboardingAvatarViewModel.processError(nil) return } mediaUploader.uploadData(avatarData, filename: nil, mimeType: "image/jpeg") { [weak self] urlString in guard let self = self else { return } guard let urlString = urlString else { MXLog.error("[OnboardingAvatarCoordinator] Missing URL string for avatar.") self.stopWaiting() self.onboardingAvatarViewModel.processError(nil) return } self.parameters.userSession.account.setUserAvatarUrl(urlString) { [weak self] in guard let self = self else { return } self.stopWaiting() self.completion?(self.parameters.userSession) } failure: { [weak self] error in guard let self = self else { return } self.stopWaiting() self.onboardingAvatarViewModel.processError(error as NSError?) } } failure: { [weak self] error in guard let self = self else { return } self.stopWaiting() self.onboardingAvatarViewModel.processError(error as NSError?) } } } // MARK: - MediaPickerPresenterDelegate @available(iOS 14.0, *) extension OnboardingAvatarCoordinator: MediaPickerPresenterDelegate { func mediaPickerPresenter(_ presenter: MediaPickerPresenter, didPickImage image: UIImage) { onboardingAvatarViewModel.updateAvatarImage(with: image) presenter.dismiss(animated: true, completion: nil) } func mediaPickerPresenterDidCancel(_ presenter: MediaPickerPresenter) { presenter.dismiss(animated: true, completion: nil) } } // MARK: - CameraPresenterDelegate @available(iOS 14.0, *) extension OnboardingAvatarCoordinator: CameraPresenterDelegate { func cameraPresenter(_ presenter: CameraPresenter, didSelectImage image: UIImage) { onboardingAvatarViewModel.updateAvatarImage(with: image) presenter.dismiss(animated: true, completion: nil) } func cameraPresenter(_ presenter: CameraPresenter, didSelectVideoAt url: URL) { presenter.dismiss(animated: true, completion: nil) } func cameraPresenterDidCancel(_ presenter: CameraPresenter) { presenter.dismiss(animated: true, completion: nil) } }
apache-2.0
3c7aaa63ce51d041a21892da5a0ea589
37.606061
139
0.649791
5.467811
false
false
false
false
vector-im/vector-ios
Riot/Modules/ContextMenu/RoomContextPreviewViewController.swift
1
8986
// File created from ScreenTemplate // $ createScreen.sh Spaces/SpaceRoomList/SpaceChildRoomDetail ShowSpaceChildRoomDetail /* Copyright 2021 New Vector Ltd Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import UIKit import MatrixSDK /// `RoomContextPreviewViewController` is used to dsplay room preview data within a `UIContextMenuContentPreviewProvider` final class RoomContextPreviewViewController: UIViewController { // MARK: - Constants private enum Constants { static let popoverWidth: CGFloat = 300 } // MARK: Outlets @IBOutlet private weak var titleLabel: UILabel! @IBOutlet private weak var avatarView: RoomAvatarView! @IBOutlet private weak var spaceAvatarView: SpaceAvatarView! @IBOutlet private weak var userIconView: UIImageView! @IBOutlet private weak var membersLabel: UILabel! @IBOutlet private weak var roomsIconView: UIImageView! @IBOutlet private weak var roomsLabel: UILabel! @IBOutlet private weak var topicLabel: UILabel! @IBOutlet private weak var topicLabelBottomMargin: NSLayoutConstraint! @IBOutlet private weak var spaceTagView: UIView! @IBOutlet private weak var spaceTagLabel: UILabel! @IBOutlet private weak var stackView: UIStackView! @IBOutlet private weak var inviteHeaderView: UIView! @IBOutlet private weak var inviterAvatarView: UserAvatarView! @IBOutlet private weak var inviteTitleLabel: UILabel! @IBOutlet private weak var inviteDetailLabel: UILabel! @IBOutlet private weak var inviteSeparatorView: UIView! // MARK: Private private var theme: Theme! private var viewModel: RoomContextPreviewViewModelProtocol! private var mediaManager: MXMediaManager? // MARK: - Setup class func instantiate(with viewModel: RoomContextPreviewViewModelProtocol, mediaManager: MXMediaManager?) -> RoomContextPreviewViewController { let viewController = StoryboardScene.RoomContextPreviewViewController.initialScene.instantiate() viewController.viewModel = viewModel viewController.mediaManager = mediaManager viewController.theme = ThemeService.shared().theme return viewController } // MARK: - Life cycle override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. viewModel.viewDelegate = self setupView() self.registerThemeServiceDidChangeThemeNotification() self.update(theme: self.theme) self.viewModel.process(viewAction: .loadData) } override var preferredContentSize: CGSize { get { return CGSize(width: Constants.popoverWidth, height: self.intrisicHeight(with: Constants.popoverWidth)) } set { super.preferredContentSize = newValue } } // MARK: - Private private func update(theme: Theme) { self.theme = theme self.view.backgroundColor = theme.headerBackgroundColor if let navigationBar = self.navigationController?.navigationBar { theme.applyStyle(onNavigationBar: navigationBar) } self.titleLabel.textColor = theme.textPrimaryColor self.titleLabel.font = theme.fonts.title3SB self.membersLabel.font = theme.fonts.caption1 self.membersLabel.textColor = theme.colors.tertiaryContent self.topicLabel.font = theme.fonts.caption1 self.topicLabel.textColor = theme.colors.tertiaryContent self.userIconView.tintColor = theme.colors.tertiaryContent self.roomsIconView.tintColor = theme.colors.tertiaryContent self.roomsLabel.font = theme.fonts.caption1 self.roomsLabel.textColor = theme.colors.tertiaryContent self.spaceTagView.backgroundColor = theme.colors.quinaryContent self.spaceTagLabel.font = theme.fonts.caption1 self.spaceTagLabel.textColor = theme.colors.tertiaryContent self.inviteTitleLabel.textColor = theme.colors.tertiaryContent self.inviteTitleLabel.font = theme.fonts.calloutSB self.inviteDetailLabel.textColor = theme.colors.tertiaryContent self.inviteDetailLabel.font = theme.fonts.caption1 self.inviteSeparatorView.backgroundColor = theme.colors.quinaryContent self.inviterAvatarView.alpha = 0.7 } private func registerThemeServiceDidChangeThemeNotification() { NotificationCenter.default.addObserver(self, selector: #selector(themeDidChange), name: .themeServiceDidChangeTheme, object: nil) } @objc private func themeDidChange() { self.update(theme: ThemeService.shared().theme) } private func renderLoaded(with parameters: RoomContextPreviewLoadedParameters) { self.titleLabel.text = parameters.displayName self.spaceTagView.isHidden = parameters.roomType != .space self.avatarView.isHidden = parameters.roomType == .space self.spaceAvatarView.isHidden = parameters.roomType != .space let avatarViewData = AvatarViewData(matrixItemId: parameters.roomId, displayName: parameters.displayName, avatarUrl: parameters.avatarUrl, mediaManager: mediaManager, fallbackImage: .matrixItem(parameters.roomId, parameters.displayName)) if !self.avatarView.isHidden { self.avatarView.fill(with: avatarViewData) } if !self.spaceAvatarView.isHidden { self.spaceAvatarView.fill(with: avatarViewData) } if parameters.membership != .invite { self.stackView.removeArrangedSubview(self.inviteHeaderView) self.inviteHeaderView.isHidden = true } self.membersLabel.text = parameters.membersCount == 1 ? VectorL10n.roomTitleOneMember : VectorL10n.roomTitleMembers("\(parameters.membersCount)") if let inviterId = parameters.inviterId { if let inviter = parameters.inviter { let avatarData = AvatarViewData(matrixItemId: inviterId, displayName: inviter.displayname, avatarUrl: inviter.avatarUrl, mediaManager: mediaManager, fallbackImage: .matrixItem(inviterId, inviter.displayname)) self.inviterAvatarView.fill(with: avatarData) if let inviterName = inviter.displayname { self.inviteTitleLabel.text = VectorL10n.noticeRoomInviteYou(inviterName) self.inviteDetailLabel.text = inviterId } else { self.inviteTitleLabel.text = VectorL10n.noticeRoomInviteYou(inviterId) } } else { self.inviteTitleLabel.text = VectorL10n.noticeRoomInviteYou(inviterId) } } self.topicLabel.text = parameters.topic topicLabelBottomMargin.constant = self.topicLabel.text.isEmptyOrNil ? 0 : 16 self.roomsIconView.isHidden = parameters.roomType != .space self.roomsLabel.isHidden = parameters.roomType != .space self.view.layoutIfNeeded() } private func setupView() { self.spaceTagView.layer.masksToBounds = true self.spaceTagView.layer.cornerRadius = 2 self.spaceTagLabel.text = VectorL10n.spaceTag } private func intrisicHeight(with width: CGFloat) -> CGFloat { if self.topicLabel.text.isEmptyOrNil { return self.topicLabel.frame.minY } let topicHeight = self.topicLabel.sizeThatFits(CGSize(width: width - self.topicLabel.frame.minX * 2, height: 0)).height return self.topicLabel.frame.minY + topicHeight + 16 } } // MARK: - RoomContextPreviewViewModelViewDelegate extension RoomContextPreviewViewController: RoomContextPreviewViewModelViewDelegate { func roomContextPreviewViewModel(_ viewModel: RoomContextPreviewViewModelProtocol, didUpdateViewState viewSate: RoomContextPreviewViewState) { switch viewSate { case .loaded(let parameters): self.renderLoaded(with: parameters) } } }
apache-2.0
c386e7ef56e9edb214c2a72bc4dcc680
40.031963
153
0.670376
5.242707
false
false
false
false
daniel-hall/SymbiOSis
Source/Symbiosis/SymbiOSis.swift
1
47836
// // SymbiOSis.swift // SymbiOSis-Alpha // // Created by Daniel Hall on 10/3/15. // Copyright © 2015 Daniel Hall. All rights reserved. // import Foundation import UIKit // MARK: - General SymbiOSis protocols - // A protocol for all objects participating in SymbiOSis to get initialized at the proper time. Default implementations are provided bythe framework and shouldn't be overridden protocol InternallyInitializable { func internalInitialize() } // A protocol for users of the framework to conform to in order to get a custom initialization point that happens right after internalInitialize() protocol Initializable { func initialize() } // MARK: - Internal Data Classes and Protocols - // A generic container for DataSources to hold a specific type of data in, which can be observed for changes and can provide values for specifc index paths. class Data<DataType> { private var observers:[AnyDataObserver<DataType>] = [AnyDataObserver<DataType>]() private var data:[DataType] = [DataType]() var first:DataType? { get { return get(NSIndexPath(forRow: 0, inSection: 0)) } } var count:Int { get { return self.data.count } } func add<ConcreteObserver:DataObserver where ConcreteObserver.ObservedDataType == DataType>(observer: ConcreteObserver) { observers.append(AnyDataObserver(observer)) if data.count > 0 { observer.updateWith(self) } } func updateObservers() { self.observers = self.observers.filter{ return $0.isNil == false } for observer in observers { observer.updateWith(self) } } func set(data:DataType) { self.data = [data] self.updateObservers() } func set(data:[DataType]) { self.data = data self.updateObservers() } //If the contained data is an array of arrays (2D array), then this method is used to retrieve by section and row func get<DataType:CollectionType where DataType.Index == Int>(index:NSIndexPath?) -> DataType.Generator.Element? { if index == nil || self.data.count <= index!.section { return nil } if let section:DataType = self.data[index!.section] as? DataType { if (section.count <= index!.row) { return section.first } return section[index!.row] } return nil } //If the contained data is a flat array, retrieve using the row value of the index path func get(index:NSIndexPath?) -> DataType? { if index == nil || index!.section > 0 || self.data.count <= index!.row { return nil } return self.data[index!.row] } func copy() -> [DataType] { return self.data } } // A type eraser used by Data<DataType> to store multiple types that conform to the generic DataObserver protocol in a homogenous array private class AnyDataObserver<DataType>: DataObserver { let updateClosure:(Data<DataType>)->() let isNilClosure:()->Bool var isNil:Bool { get { return isNilClosure() } } init<ConcreteObserver:DataObserver where ConcreteObserver.ObservedDataType == DataType>(_ dataObserver:ConcreteObserver){ weak var observer = dataObserver; self.updateClosure = { (data:Data<DataType>) in observer?.updateWith(data) } self.isNilClosure = { return observer == nil } } func updateWith(data: Data<DataType>) { self.updateClosure(data) } } // A protocol for any object that wants to get notified when a Data<DataType> object is updated protocol DataObserver:class { associatedtype ObservedDataType func updateWith(data:Data<ObservedDataType>) } // A type eraser for Data<DataType> that can still retrieve the count (and in the future, if needed, can still retrieve values downcast to Any. Needed for generic bindings like Table View Bindings which need to work with all data types without caring about what type they are public struct AnyData { var count:Int { get { return countClosure() } } private var copyClosure:()->Any private var countClosure:()->Int init<DataType>(data:Data<DataType>) { self.countClosure = { return data.count } self.copyClosure = { return data.copy() } } func copy()-> Any { return self.copyClosure() } } // An observer of type erased data protocol GenericDataObserver:class { func updateWith(data:AnyData) } // Act as a typed data observer, erase the type of the observed data, and pass it on to an untyped observer private class GenericDataObserverConverter <DataType> : DataObserver { private var updateClosure:(Data<DataType>)->() func updateWith(data: Data<DataType>) { self.updateClosure(data) } init(data:Data<DataType>, observer:GenericDataObserver) { weak var weakObserver = observer self.updateClosure = { if let genericObserver = weakObserver { genericObserver.updateWith(AnyData(data: $0)) } } data.add(self) } } // MARK: - Data Source Protocols and Classes - // Base class for all SymbiOSis data sources. Responsible for retrieving, filtering and pushing data through to bindings and sometimes other data sources. class DataSource : NSObject { // Does this data source allow itself to be injected with data from the previous view controller via segue? @IBInspectable var segueCanSet:Bool = true private var genericObservers = [AnyObject]() private var _initialized = false } // Type defining / constraining protocol that must be adopted by all Data Sources. protocol DataSourceProtocol : TypeEraseableDataSource, GenericallyObservableDataSource, SegueCompatibleDataSource, InternallyInitializable { associatedtype DataType var data:Data<DataType> { get } } // Default internal initialization method. Don't override. extension InternallyInitializable where Self:DataSourceProtocol, Self:DataSource { func internalInitialize() { if (!_initialized) { if let initializable = self as? Initializable { initializable.initialize() } _initialized = true } } } protocol PageableDataSource { var moreDataAvailable:Bool { get } func loadMoreData() } protocol RefreshableDataSource { func refresh() } // Any Data Sources that support generically observable data (which is all of them) get an immplementation to wrap their typed Data<DataType> with a converter to allow untyped data observers. Used by classes like Table View Bindings, which need to observe updates to all kinds of data source without caring about their type protocol GenericallyObservableDataSource { func add(observer:GenericDataObserver) } // Default implementation extension GenericallyObservableDataSource where Self:DataSourceProtocol, Self:DataSource { func add(observer:GenericDataObserver) { self.genericObservers.append(GenericDataObserverConverter(data: self.data, observer:observer)) } } // Allows UIKit component subclasses or extensions to TableViewCell etc. to specify what data source should be used in any segues triggered by the component. This allows the process of pushing data through a segue to the next scene to be automated protocol SegueDataProvider:class { var segueDataSource:DataSource! { get } } // Allows a SegueDataProvider to specify a specific index in the data source which to push through the segue, as opposed to the full set of data. protocol IndexedSegueDataProvider:SegueDataProvider { var dataIndex:UInt { get } } // A protocol that enables retrieving a data source for pushing through a segue that is created with only the value at the specified index protocol SegueCompatibleDataSource { func getSegueDataSource(withSegueDataIndex index:UInt)->DataSource } // Default implementation for all DataSources extension SegueCompatibleDataSource where Self:DataSourceProtocol, Self:DataSource { func getSegueDataSource(withSegueDataIndex index:UInt)->DataSource { let segueDataSource = AnyDataSource<DataType>() if index == UInt.max { segueDataSource.data.set(self.data.copy()) } else { let indexPath = NSIndexPath(forRow: Int(index), inSection:0) if let data = self.data.get(indexPath) { segueDataSource.data.set(data) } } return segueDataSource } } // TypeEraseableDataSource protocol and default implementations are used to pass out and accept type-erased data, so that unconstrained / untyped code like view controllers and segue handlers can pass it between different data sources automatically protocol TypeEraseableDataSource { var get:AnyData { get } func set(data:AnyData) } // Default implementation for all DataSources extension TypeEraseableDataSource where Self:DataSourceProtocol, Self:DataSource { var get:AnyData { get { return AnyData(data: self.data) } } func set(data:AnyData) { if let matchingData = data.copy() as? [Self.DataType] { self.data.set(matchingData) } } } // A type-remembering concrete class that conforms to the DataSourceProtocol for use in declaring variable types, etc. class AnyDataSource <DataType> : DataSource, DataSourceProtocol { let data:Data<DataType> = Data<DataType>() } // MARK: - Binding Protocols and Classes - // The base protocol of all binding-like SymbiOSis components, including Bindings, BindingSets, TableViewBindings, and other specialized types of bindings protocol BindingType:class { var dataIndexPath:NSIndexPath? { get set } func reset() } // Base class for all bindings, provides storage for composed elements (whether Bindings in a BindingSet, or the BindingArbitration in a single Binding) public class Binding : UIView, BindingType { private var _composedBindings = [BindingType]() private var _initialized = false private var _bindingSetMember = false private var _explicitDataIndex = false var dataIndexPath:NSIndexPath? { didSet { for composedBinding in _composedBindings { composedBinding.dataIndexPath = dataIndexPath } } } func reset() { for composedBinding in _composedBindings { composedBinding.reset() } } } // The type-constrained / type-defined generic class that links a data source's data with a binding and its view. Enforces same types where important. class BindingArbitration <DataType, ViewType:UIView, ConcreteBinding:Binding where ConcreteBinding:BindingProtocol, ConcreteBinding.ViewType == ViewType, ConcreteBinding.BindingDataSource.DataType == DataType, ConcreteBinding.BindingDataSource:DataSource> : BindingType, DataObserver { private weak var binding:ConcreteBinding? private var _viewStates = [ViewState]() var dataIndexPath:NSIndexPath? { didSet { if let concreteBinding = binding { for view in concreteBinding.views { if let value = concreteBinding.dataSource.data.get(dataIndexPath) { concreteBinding.update(view, value:value) } } } } } func updateWith(data:Data<DataType>) { if let concreteBinding = binding { for view in concreteBinding.views { if let value = data.get(dataIndexPath) { concreteBinding.update(view, value:value) } } } } init(binding:ConcreteBinding) { self.binding = binding; if let concreteBinding = self.binding { for view in concreteBinding.views { addViewStates(view, array: &_viewStates) } concreteBinding.dataSource.data.add(self) } } func addViewStates(view:UIView, inout array:[ViewState]) { for subview in view.subviews { addViewStates(subview, array: &array) } array.append(view.viewState) } func reset() { for viewState in _viewStates { viewState.view?.viewState = viewState } } } // The type-constrained / type-defined protocol that all Bindings must adopt and which powers static type checking protocol BindingProtocol :class, InternallyInitializable, SegueDataProvider { associatedtype BindingDataSource:DataSourceProtocol associatedtype ViewType:UIView var dataSource:BindingDataSource! { get set } var views:[ViewType]! { get set } func update(view:ViewType, value:BindingDataSource.DataType) } // Default implementations to set up binding mediator on initialize, hide the binding, etc. Also helps enforce that implementors both subclass Binding and adopt BindingProtocol. extension InternallyInitializable where Self:BindingProtocol, Self:Binding, Self.BindingDataSource:DataSource { var segueDataSource:DataSource! { get { let segueSource = AnyDataSource<BindingDataSource.DataType>() if let index = dataIndexPath, let value = self.dataSource.data.get(index) { segueSource.data.set(value) return segueSource } return nil } } func internalInitialize() { if (!_initialized) { self.hidden = true self.frame = CGRectZero self.alpha = 0 guard self.dataSource != nil else { fatalError("Binding \(self) does not have a DataSource outlet connected") } guard self.views != nil || _bindingSetMember == true else { fatalError("Binding \(self) does not have any views connected to the 'views' outlet collection") } if self.views != nil { if let initializable = self as? Initializable { initializable.initialize() } let arbitration = BindingArbitration(binding:self) arbitration.dataIndexPath = self.dataIndexPath _composedBindings.append(BindingArbitration(binding:self)) if (!_explicitDataIndex) { self.dataIndexPath = self.dataIndexPath ?? NSIndexPath(forRow: 0, inSection: 0) } } _initialized = true } } func reset() { for composedBinding in _composedBindings { composedBinding.reset() } } } // MARK: - Binding Set Protocols and Classes - // Protocol that must be adopted by all binding sets. Create generate foundation for type matching the data source and child bindings protocol BindingSetProtocol:class, InternallyInitializable, Initializable, BindingType, SegueDataProvider { associatedtype BindingSetDataSource:DataSourceProtocol var dataSource:BindingSetDataSource! { get set } } // Base class for all binding sets. Provides storage and a type constrained method to add child bindings that use the same-type data source public class BindingSet : Binding { private func associate<ViewType:UIView, ConcreteDataSource:DataSourceProtocol, ConcreteBinding:Binding where ConcreteBinding:BindingProtocol, ConcreteBinding.BindingDataSource == ConcreteDataSource, ConcreteBinding.ViewType == ViewType, ConcreteDataSource:DataSource>(dataSource dataSource:ConcreteDataSource!, withbinding binding:ConcreteBinding, andOutlet outlet:[ViewType]!) { binding.dataSource = dataSource binding.views = outlet binding._bindingSetMember = true binding._explicitDataIndex = _explicitDataIndex binding.dataIndexPath = dataIndexPath binding.internalInitialize() _composedBindings.append(binding) } } // Default implementations to add initialization, segue data source creation, and a convenience method for associating child bindings with the data source extension InternallyInitializable where Self:BindingSetProtocol, Self:BindingSet, Self.BindingSetDataSource:DataSource { var segueDataSource:DataSource! { get { let segueSource = AnyDataSource<BindingSetDataSource.DataType>() if let value = self.dataSource.data.get(dataIndexPath) { segueSource.data.set(value) return segueSource } return nil } } func associate<ViewType:UIView, ConcreteBinding:BindingProtocol where ConcreteBinding.ViewType == ViewType, Self.BindingSetDataSource == ConcreteBinding.BindingDataSource, ConcreteBinding:Binding>(binding binding:ConcreteBinding, withOutlet views:[ViewType]!) { self.associate(dataSource: self.dataSource, withbinding: binding, andOutlet: views) } func internalInitialize() { if (!_initialized) { self.hidden = true self.frame = CGRectZero self.alpha = 0 guard self.dataSource != nil else { fatalError("BindingSet \(self) does not have a DataSource outlet connected") } self.initialize() guard self._composedBindings.count > 0 else { fatalError("BindingSet \(self) did not associate any bindings with views. Please ensure your 'initialize' method calls 'self.associate()' for at least one binding and outlet collection of views.") } _initialized = true } } } // MARK: - Table View Binding Protocols and Classes - // Protocol used for all TableView Bindings (simple, sectioned etc.) to require a data source and a table view, plus a function to update when the data source data updates protocol TableViewBinding:class, InternallyInitializable, GenericDataObserver { associatedtype GenericDataSource:DataSource var dataSource:GenericDataSource! { get set } var tableView:UITableView! { get set } func update(table:UITableView, data:AnyData) } // Default implementation to hide the binding if add as a subview, and to start type-erased observation of the data source for updates. extension TableViewBinding where Self:Binding { func internalInitialize() { if (!_initialized) { self.hidden = true self.frame = CGRectZero self.alpha = 0 guard tableView != nil else { fatalError("SymbiOSis TableViewBinding has no UITableView connected to the 'tableView' outlet.") } if let initializable = self as? Initializable { initializable.initialize() } guard let genericallyObservableDataSource = self.dataSource as? GenericallyObservableDataSource else { fatalError("SymbiOSis TableViewBinding has no connected data source, or an invalid data source. Data sources must subclass 'DataSource' and conform to 'DataSourceProtocol'") } genericallyObservableDataSource.add(self) _initialized = true } } func updateWith(data: AnyData) { self.update(self.tableView, data: data) } } // Binding used for connecting single-section tables to a data source. Requires that the connected TableView has had a protoype cell created in Interface Builder and given a reuse identifier. Note that the Simple Table View Binding exclusively uses self-sizing prototype cells and supports only iOS 8 and later. Whatever constraints are calculated for each cell at layout time will be the height for that cell's row class SimpleTableViewBinding : Binding, TableViewBinding, UITableViewDataSource, UITableViewDelegate, Initializable { private var _data:AnyData = AnyData(data: Data<Any>()) private var _originalSeparatorStyle:UITableViewCellSeparatorStyle! @IBOutlet var dataSource:DataSource! @IBOutlet var tableView:UITableView! @IBOutlet var cellSelectionResponders:[TableCellSelectionResponder]! func update(tableView:UITableView, data:AnyData) { _data = data let currentOffset = tableView.contentOffset tableView.separatorStyle = _originalSeparatorStyle tableView.reloadData() tableView.contentOffset = currentOffset loadMoreDataIfAppropriate() } func initialize() { tableView.estimatedRowHeight = 50 tableView.rowHeight = UITableViewAutomaticDimension tableView.delegate = self tableView.dataSource = self _originalSeparatorStyle = tableView.separatorStyle tableView.separatorStyle = UITableViewCellSeparatorStyle.None } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return _data.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { guard let identifier = (tableView.valueForKey("nibMap") as? Dictionary<NSString, NSObject>)?.keys.first as? String else { fatalError("There are no prototype cells created for the SymbiOSis SimpleTableViewBinding to retrieve from the UITableView. Please make sure there is a prototype cell and that you have given it a reuse identifer") } return tableView.dequeReusableCell(withIdentifier: identifier, dataIndexPath: indexPath) } func scrollViewDidScroll(scrollView: UIScrollView) { loadMoreDataIfAppropriate() } func loadMoreDataIfAppropriate() { if let pageableDataSource = dataSource as? PageableDataSource where (tableView.contentSize.height - tableView.contentOffset.y <= tableView.frame.height) { if pageableDataSource.moreDataAvailable { pageableDataSource.loadMoreData() } } } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { if let responders = cellSelectionResponders { for responder in responders { responder.tableView(tableView, selectedCell: tableView.cellForRowAtIndexPath(indexPath)!, indexPath: indexPath) } } } } // MARK: - Responders - class Responder:NSObject, InternallyInitializable { weak var viewController:ViewController! func internalInitialize() { if let initializable = self as? Initializable { initializable.initialize() } } } class ActionResponder : Responder { @IBAction func performActionWith(sender:AnyObject) { //override in subclasses } } class TableCellSelectionResponder:Responder { func tableView(tableView:UITableView, selectedCell:UITableViewCell, indexPath:NSIndexPath) { //override in subclasses } } // MARK: - SymbiOSis Components - // Use as the custom class for all scenes in a storyboard, as as a superclass in the unlikely event you would want to add logic into the VC directly within a SymbiOSis scene class ViewController: UIViewController, InternallyInitializable { private var _initialized = false lazy var topLevelObjects:[NSObject] = { var array = [NSObject]() if let objects = self.valueForKey("topLevelObjectsToKeepAliveFromStoryboard") as? [NSObject] { for object in objects { array.append(object) } } return array }() lazy var dataSources:[DataSource] = { var array = [DataSource]() for object in self.topLevelObjects { if let dataSource = object as? DataSource { array.append(dataSource) } } return array }() lazy var internalInitializables:[InternallyInitializable] = { var array = [InternallyInitializable]() for object in self.topLevelObjects { if let initializable = object as? InternallyInitializable { array.append(initializable) } } return array }() func internalInitialize() { if (!_initialized) { if let initializable = self as? Initializable { initializable.initialize() } for internalInitializable in self.internalInitializables { if let responder = internalInitializable as? Responder { responder.viewController = self } internalInitializable.internalInitialize() } _initialized = true } } override func viewDidLoad() { super.viewDidLoad() internalInitialize() } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if let dataProvider = sender as? SegueDataProvider { if let dataSource = dataProvider.segueDataSource as? TypeEraseableDataSource, let destination = segue.destinationViewController as? ViewController { var _ = destination.view destination.setDataSourcesFromDataSource(dataSource) } else { print("SymbiOSis Warning: Segueing to a non-SymbiOSis View Controller class -- is this intentional? All Storyboard view controllers should be of the custom class 'ViewController' or a subclass") } } if let tableCell = sender as? UITableViewCell { tableCell.setSelected(false, animated: true) } } func setDataSourcesFromDataSource(dataSource:TypeEraseableDataSource) { for possibleTarget in self.dataSources { if possibleTarget.segueCanSet, let settableTarget = possibleTarget as? TypeEraseableDataSource { settableTarget.set(dataSource.get) } } } } // Use as a class or superclass for any buttons that trigger segues and should send data from the current view controller to the next view controller through the segue public class SegueButton : UIButton, IndexedSegueDataProvider { private var _dataSourceStorage:DataSource! @IBInspectable var dataIndex:UInt = UInt.max @IBOutlet var segueDataSource:DataSource! { get { if let dataSource = self._dataSourceStorage as? SegueCompatibleDataSource { return dataSource.getSegueDataSource(withSegueDataIndex: self.dataIndex) } fatalError("SegueButton was used to trigger a segue, but has no DataSource connected to its segueDataSource outlet. If you don't want to have a data source for this segue, use a normal UIButton subclass rather than a SegueButton") } set { _dataSourceStorage = newValue } } } // MARK: - UIKit Extensions - // Add methods to work with bindings in UITableViewCells extension UITableViewCell : BindingType, SegueDataProvider { private var bindings:[Binding] { get { var bindingsForView = [Binding]() self.populateBindings(self, array: &bindingsForView) return bindingsForView } } private func populateBindings(view:UIView, inout array:[Binding]) { for subview in view.subviews { if let binding = subview as? Binding { array.append(binding) } populateBindings(subview, array: &array) } } var dataIndexPath:NSIndexPath? { set { for binding in bindings { binding.dataIndexPath = newValue } } get { return bindings.first?.dataIndexPath } } func reset() { for binding in bindings { binding._explicitDataIndex = true if let initializable = binding as? InternallyInitializable { initializable.internalInitialize() } binding.reset() } } var segueDataSource:DataSource! { get { if let binding = bindings.first as? SegueDataProvider, let dataSource = binding.segueDataSource { return dataSource } return nil } } } // Add method to assign an IndexPath to bindings in a dequeued cell and reset bindings on dequeue (which is the equivalent of the the work normally done in prepareForReuse() public extension UITableView { func dequeReusableCell(withIdentifier identifier:String, dataIndexPath:NSIndexPath) -> UITableViewCell { let cell = self.dequeueReusableCellWithIdentifier(identifier, forIndexPath: dataIndexPath) cell.frame = CGRect(x: 0, y: 0, width: CGRectGetWidth(self.bounds), height: self.estimatedRowHeight) cell.contentView.frame = cell.frame cell.layoutIfNeeded() cell.reset() cell.dataIndexPath = dataIndexPath cell.layoutIfNeeded() return cell } } // Thin classes that capture the initial state of views that are connected to bindings in reusable cells. They are used to restore the original properties of the view as they were defined in the storyboard before setting new values. Part of the mechanism that replaces prepareForReuse() class ViewState : NSObject { weak var view:UIView? var frame:CGRect! var bounds:CGRect! var clipsToBounds:Bool! var backgroundColor:UIColor! var alpha:CGFloat! var hidden:Bool! var contentMode:UIViewContentMode! var tintColor:UIColor! var tintAdjustmentMode: UIViewTintAdjustmentMode! var userInteractionEnabled:Bool! var layerBackgroundColor:UIColor? var layerCornerRadius:CGFloat! var layerBorderWidth:CGFloat! var layerBorderColor:UIColor? } class LabelViewState : ViewState { var text:String! var font:UIFont! var textColor:UIColor! var shadowColor:UIColor! var shadowOffset:CGSize! var textAlignment:NSTextAlignment! var lineBreakMode:NSLineBreakMode! var attributedText:NSAttributedString! var highlightedTextColor:UIColor! var highlighted:Bool! var enabled:Bool! var numberOfLines:Int! var adjustsFontSizeToFitWidth:Bool! var baselineAdjustment:UIBaselineAdjustment! var minimumScaleFactor:CGFloat! var preferredMaxLayoutWidth:CGFloat! } class ImageViewState : ViewState { var image:UIImage! var highlightedImage:UIImage! var highlighted:Bool! var animationImages:[UIImage]! var highlightedAnimationImages:[UIImage]! var animationDuration:NSTimeInterval! var animationRepeatCount:Int! } class ButtonViewState : ViewState { var enabled:Bool! var contentEdgeInsets:UIEdgeInsets! var titleEdgeInsets:UIEdgeInsets! var reversesTitleShadowWhenHighlighted:Bool! var imageEdgeInsets:UIEdgeInsets! var adjustsImageWhenHighlighted:Bool! var adjustsImageWhenDisabled:Bool! var showsTouchWhenHighlighted:Bool! var stateTitles = [UInt : String]() var stateTitleColors = [UInt : UIColor]() var stateTitleShadowColors = [UInt : UIColor]() var stateImages = [UInt : UIImage]() var stateBackgroundImages = [UInt : UIImage]() var stateAttributedTitles = [UInt : NSAttributedString]() } // Extensions to get and set ViewStates for common components used in reusable cells. extension UIView { var viewState:ViewState { get { var viewState:ViewState! if self is UILabel { viewState = LabelViewState() } else if self is UIImageView { viewState = ImageViewState() } else if self is UIButton { viewState = ButtonViewState() } else { viewState = ViewState() } viewState.view = self viewState.clipsToBounds = self.clipsToBounds viewState.backgroundColor = self.backgroundColor viewState.alpha = self.alpha viewState.hidden = self.hidden viewState.contentMode = self.contentMode viewState.tintColor = self.tintColor viewState.tintAdjustmentMode = self.tintAdjustmentMode viewState.userInteractionEnabled = self.userInteractionEnabled viewState.layerBackgroundColor = (self.layer.backgroundColor != nil) ? UIColor(CGColor: self.layer.backgroundColor!) : nil viewState.layerCornerRadius = self.layer.cornerRadius viewState.layerBorderWidth = self.layer.borderWidth viewState.layerBorderColor = (self.layer.borderColor != nil) ? UIColor(CGColor: self.layer.borderColor!) : nil return viewState; } set { self.clipsToBounds = newValue.clipsToBounds; self.backgroundColor = newValue.backgroundColor; self.alpha = newValue.alpha; self.hidden = newValue.hidden; self.contentMode = newValue.contentMode; self.tintColor = newValue.tintColor; self.tintAdjustmentMode = newValue.tintAdjustmentMode; self.userInteractionEnabled = newValue.userInteractionEnabled; if self.layer.self === CALayer.self { self.layer.backgroundColor = newValue.layerBackgroundColor?.CGColor; self.layer.borderColor = newValue.layerBorderColor?.CGColor; } self.layer.cornerRadius = newValue.layerCornerRadius; self.layer.borderWidth = newValue.layerBorderWidth; self.setNeedsLayout() } } } extension UILabel { override var viewState:ViewState { get { let viewState = super.viewState as! LabelViewState viewState.text = self.text viewState.font = self.font viewState.textColor = self.textColor viewState.shadowColor = self.shadowColor viewState.shadowOffset = self.shadowOffset viewState.textAlignment = self.textAlignment viewState.lineBreakMode = self.lineBreakMode viewState.attributedText = self.attributedText viewState.highlightedTextColor = self.highlightedTextColor viewState.highlighted = self.highlighted viewState.enabled = self.enabled viewState.numberOfLines = self.numberOfLines viewState.adjustsFontSizeToFitWidth = self.adjustsFontSizeToFitWidth viewState.baselineAdjustment = self.baselineAdjustment viewState.minimumScaleFactor = self.minimumScaleFactor viewState.preferredMaxLayoutWidth = self.preferredMaxLayoutWidth return viewState; } set { let labelViewState = newValue as! LabelViewState self.text = labelViewState.text self.font = labelViewState.font self.textColor = labelViewState.textColor self.shadowColor = labelViewState.shadowColor self.shadowOffset = labelViewState.shadowOffset self.textAlignment = labelViewState.textAlignment self.lineBreakMode = labelViewState.lineBreakMode self.attributedText = labelViewState.attributedText self.highlightedTextColor = labelViewState.highlightedTextColor self.highlighted = labelViewState.highlighted self.enabled = labelViewState.enabled self.numberOfLines = labelViewState.numberOfLines self.adjustsFontSizeToFitWidth = labelViewState.adjustsFontSizeToFitWidth self.baselineAdjustment = labelViewState.baselineAdjustment self.minimumScaleFactor = labelViewState.minimumScaleFactor self.preferredMaxLayoutWidth = labelViewState.preferredMaxLayoutWidth super.viewState = labelViewState } } } extension UIImageView { override var viewState:ViewState { get { let viewState = super.viewState as! ImageViewState viewState.image = self.image viewState.highlightedImage = self.highlightedImage viewState.highlighted = self.highlighted viewState.animationImages = self.animationImages viewState.highlightedAnimationImages = self.highlightedAnimationImages viewState.animationDuration = self.animationDuration viewState.animationRepeatCount = self.animationRepeatCount return viewState; } set { let imageViewState = newValue as! ImageViewState self.image = imageViewState.image self.highlightedImage = imageViewState.highlightedImage self.highlighted = imageViewState.highlighted self.animationImages = imageViewState.animationImages self.highlightedAnimationImages = imageViewState.highlightedAnimationImages self.animationDuration = imageViewState.animationDuration self.animationRepeatCount = imageViewState.animationRepeatCount super.viewState = imageViewState } } } extension UIButton { override var viewState:ViewState { get { let viewState = super.viewState as! ButtonViewState viewState.enabled = self.enabled viewState.contentEdgeInsets = self.contentEdgeInsets viewState.titleEdgeInsets = self.titleEdgeInsets viewState.reversesTitleShadowWhenHighlighted = self.reversesTitleShadowWhenHighlighted viewState.imageEdgeInsets = self.imageEdgeInsets viewState.adjustsImageWhenHighlighted = self.adjustsImageWhenHighlighted viewState.adjustsImageWhenDisabled = self.adjustsImageWhenDisabled viewState.showsTouchWhenHighlighted = self.showsTouchWhenHighlighted readTo(&viewState.stateTitles, titleColors: &viewState.stateTitleColors, titleShadowColors: &viewState.stateTitleShadowColors, images: &viewState.stateImages, backgroundImages: &viewState.stateBackgroundImages, attributedTitles: &viewState.stateAttributedTitles, state: .Normal) readTo(&viewState.stateTitles, titleColors: &viewState.stateTitleColors, titleShadowColors: &viewState.stateTitleShadowColors, images: &viewState.stateImages, backgroundImages: &viewState.stateBackgroundImages, attributedTitles: &viewState.stateAttributedTitles, state: .Disabled) readTo(&viewState.stateTitles, titleColors: &viewState.stateTitleColors, titleShadowColors: &viewState.stateTitleShadowColors, images: &viewState.stateImages, backgroundImages: &viewState.stateBackgroundImages, attributedTitles: &viewState.stateAttributedTitles, state: .Highlighted) readTo(&viewState.stateTitles, titleColors: &viewState.stateTitleColors, titleShadowColors: &viewState.stateTitleShadowColors, images: &viewState.stateImages, backgroundImages: &viewState.stateBackgroundImages, attributedTitles: &viewState.stateAttributedTitles, state: .Selected) return viewState } set { let buttonViewState = newValue as! ButtonViewState self.enabled = buttonViewState.enabled self.contentEdgeInsets = buttonViewState.contentEdgeInsets self.titleEdgeInsets = buttonViewState.titleEdgeInsets self.reversesTitleShadowWhenHighlighted = buttonViewState.reversesTitleShadowWhenHighlighted self.imageEdgeInsets = buttonViewState.imageEdgeInsets self.adjustsImageWhenHighlighted = buttonViewState.adjustsImageWhenHighlighted self.adjustsImageWhenDisabled = buttonViewState.adjustsImageWhenDisabled self.showsTouchWhenHighlighted = buttonViewState.showsTouchWhenHighlighted writeFrom(buttonViewState.stateTitles, titleColors: buttonViewState.stateTitleColors, titleShadowColors: buttonViewState.stateTitleShadowColors, images: buttonViewState.stateImages, backgroundImages: buttonViewState.stateBackgroundImages, attributedTitles: buttonViewState.stateAttributedTitles, state: .Normal) writeFrom(buttonViewState.stateTitles, titleColors: buttonViewState.stateTitleColors, titleShadowColors: buttonViewState.stateTitleShadowColors, images: buttonViewState.stateImages, backgroundImages: buttonViewState.stateBackgroundImages, attributedTitles: buttonViewState.stateAttributedTitles, state: .Disabled) writeFrom(buttonViewState.stateTitles, titleColors: buttonViewState.stateTitleColors, titleShadowColors: buttonViewState.stateTitleShadowColors, images: buttonViewState.stateImages, backgroundImages: buttonViewState.stateBackgroundImages, attributedTitles: buttonViewState.stateAttributedTitles, state: .Highlighted) writeFrom(buttonViewState.stateTitles, titleColors: buttonViewState.stateTitleColors, titleShadowColors: buttonViewState.stateTitleShadowColors, images: buttonViewState.stateImages, backgroundImages: buttonViewState.stateBackgroundImages, attributedTitles: buttonViewState.stateAttributedTitles, state: .Selected) } } func readTo(inout titles:[UInt : String], inout titleColors:[UInt : UIColor], inout titleShadowColors:[UInt : UIColor], inout images:[UInt : UIImage], inout backgroundImages:[UInt : UIImage], inout attributedTitles:[UInt : NSAttributedString], state:UIControlState) { if let title = self.titleForState(state) { titles[state.rawValue] = title } if let titleColor = self.titleColorForState(state) { titleColors[state.rawValue] = titleColor } if let titleShadowColor = self.titleShadowColorForState(state) { titleShadowColors[state.rawValue] = titleShadowColor } if let image = self.imageForState(state) { images[state.rawValue] = image } if let backgroundImage = self.backgroundImageForState(state) { backgroundImages[state.rawValue] = backgroundImage } if let attributedTitle = self.attributedTitleForState(state) { attributedTitles[state.rawValue] = attributedTitle } } func writeFrom(titles:[UInt : String], titleColors:[UInt : UIColor], titleShadowColors:[UInt : UIColor], images:[UInt : UIImage], backgroundImages:[UInt : UIImage], attributedTitles:[UInt : NSAttributedString], state:UIControlState) { self.setTitle(titles[state.rawValue], forState: state) self.setTitleColor(titleColors[state.rawValue], forState: state) self.setTitleShadowColor(titleShadowColors[state.rawValue], forState: state) self.setImage(images[state.rawValue], forState: state) self.setBackgroundImage(backgroundImages[state.rawValue], forState: state) self.setAttributedTitle(attributedTitles[state.rawValue], forState: state) } } // MARK: - SymbiOSis-provided base classes and helpers // A binding superclass to correctly autosize an image view in a self-sizing tableviewcell, etc. ahead of time, so it doesn't have the wrong layout after the image asynchronously loads or "jump" to a new size after scrolling off and on screen. class DynamicImageBinding : Binding { static private let PhotoCache:NSCache = NSCache() @IBOutlet var views:[UIImageView]! var timestamp = NSDate.timeIntervalSinceReferenceDate() func setImage(imageView: UIImageView, fromURL url:NSURL, withSize size:CGSize) { let calculatedSize = CGSizeMake(size.width > 0 ? size.width: imageView.frame.size.width, size.height > 0 ? size.height: imageView.frame.size.height) UIGraphicsBeginImageContextWithOptions(calculatedSize, false, UIScreen.mainScreen().nativeScale) imageView.image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() guard let cachedImage = DynamicImageBinding.PhotoCache.objectForKey(url.absoluteString + NSStringFromCGSize(calculatedSize)) as? UIImage else { let task = NSURLSession.sharedSession().dataTaskWithURL(url) { [requestStamp = timestamp](data, response, error) in if let imageData = data { dispatch_async(dispatch_get_main_queue(), { () -> Void in if let image = UIImage(data:imageData) { UIGraphicsBeginImageContextWithOptions(calculatedSize, false, 0.0) image.drawInRect(CGRectMake(0, 0, calculatedSize.width, calculatedSize.height)) let newImage = UIGraphicsGetImageFromCurrentImageContext() DynamicImageBinding.PhotoCache.setObject(newImage, forKey: url.absoluteString + NSStringFromCGSize(calculatedSize)) if requestStamp == self.timestamp { imageView.image = newImage } } }) } } task.resume() return } imageView.image = cachedImage } override func reset() { timestamp = NSDate.timeIntervalSinceReferenceDate() super.reset() } } class ImageBinding : Binding { static private let PhotoCache:NSCache = NSCache() @IBOutlet var views:[UIImageView]! func setImage(imageView:UIImageView, fromURL:NSURL) { if let cached = ImageBinding.PhotoCache.objectForKey(fromURL.absoluteString) as? UIImage { imageView.image = cached return } let task = NSURLSession.sharedSession().dataTaskWithURL(fromURL) {(data, response, error) in dispatch_async(dispatch_get_main_queue(), { () -> Void in if let imageData = data, let image = UIImage(data:imageData) { ImageBinding.PhotoCache.setObject(image, forKey: fromURL.absoluteString) imageView.image = image } }) } task.resume() } } // A base class or dumb container for NSURL data class NSURLDataSource : DataSource, DataSourceProtocol { let data = Data<(NSURL)>() } // A general DataSource that observes any NSURL-based DataSource for updates, and when the observed DataSource is updated, gets the first URL in the DataSource and retrieves a JSON dictionary from that DataSource class JSONFromNSURLDataSource : DataSource, DataSourceProtocol, DataObserver, Initializable { let data = Data<[NSObject: AnyObject]>() @IBOutlet var urlDataSource:NSURLDataSource! func initialize() { if let dataSourceToObserve = urlDataSource { dataSourceToObserve.data.add(self) } } func updateWith(data: Data<NSURL>) { if let url = data.first { let task = NSURLSession.sharedSession().dataTaskWithURL(url) {(responseData, response, error) in if let jsonData = responseData, let json = (try? NSJSONSerialization.JSONObjectWithData(jsonData, options: NSJSONReadingOptions.MutableContainers)) as? [NSObject: AnyObject] { dispatch_async(dispatch_get_main_queue(), { () -> Void in self.data.set(json) }) } } task.resume() } } }
mit
a02eb4a5d523604946a3385744d1bc05
38.829309
416
0.670283
5.308512
false
false
false
false
nathawes/swift
stdlib/public/Differentiation/Differentiable.swift
7
3529
//===--- Differentiable.swift ---------------------------------*- swift -*-===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2019 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 file defines the Differentiable protocol, used by the experimental // differentiable programming project. This API is not stable and subject to // change. // // Please see forum discussion for more information about the differentiable // programming project: // https://forums.swift.org/t/differentiable-programming-mega-proposal/28547 // //===----------------------------------------------------------------------===// import Swift /// A type that mathematically represents a differentiable manifold whose /// tangent spaces are finite-dimensional. public protocol Differentiable { /// A type representing a differentiable value's derivatives. /// /// Mathematically, this is equivalent to the tangent bundle of the /// differentiable manifold represented by the differentiable type. associatedtype TangentVector: Differentiable & AdditiveArithmetic where TangentVector.TangentVector == TangentVector /// Moves `self` along the given direction. In Riemannian geometry, this is /// equivalent to exponential map, which moves `self` on the geodesic surface /// along the given tangent vector. mutating func move(along direction: TangentVector) /// A closure that produces a zero tangent vector, capturing minimal /// necessary information from `self`. /// /// `move(along: zeroTangentVectorInitializer())` should not modify /// `self`. /// /// In some cases, the zero tangent vector of `self` is equal to /// `TangentVector.zero`. In other cases, the zero tangent vector depends on /// information in `self`, such as shape for an n-dimensional array type. /// For differentiable programming, it is more memory-efficient to define a /// custom `zeroTangentVectorInitializer` property which returns a closure /// that captures and uses only the necessary information to create a zero /// tangent vector. For example: /// /// struct Vector { /// var scalars: [Float] /// var count: Int { scalars.count } /// init(scalars: [Float]) { ... } /// init(repeating repeatedElement: Float, count: Int) { ... } /// } /// /// extension Vector: AdditiveArithmetic { ... } /// /// extension Vector: Differentiable { /// typealias TangentVector = Vector /// /// @noDerivative /// var zeroTangentVectorInitializer: () -> TangentVector { /// let count = self.count /// return { TangentVector(repeating: 0, count: count) } /// } /// } var zeroTangentVectorInitializer: () -> TangentVector { get } } public extension Differentiable where TangentVector == Self { @_alwaysEmitIntoClient mutating func move(along direction: TangentVector) { self += direction } } public extension Differentiable { /// A tangent vector initialized using `zeroTangentVectorInitializer`. /// `move(along: zeroTangentVector)` should not modify `self`. var zeroTangentVector: TangentVector { zeroTangentVectorInitializer() } }
apache-2.0
eea5bcdb9b7d17ab1c402c457f1f3302
40.034884
80
0.657127
5.027066
false
false
false
false
mo3bius/My-Simple-Instagram
My-Simple-Instagram/Configurations/Config.swift
1
1752
// // Config.swift // My-Simple-Instagram // // Created by Luigi Aiello on 30/10/17. // Copyright © 2017 Luigi Aiello. All rights reserved. // import Foundation /** This class is used to access the local configuration of the app. */ class Config { // MARK: - Constants fileprivate static let kToken = "kToken" fileprivate static let kMyId = "kMyId" // MARK: - Token management /** Stores a user token in user defaults. - parameter token: the token that should be stored */ class func store(token: String) { let defaults = UserDefaults.standard defaults.setValue(token, forKey: kToken) let _ = defaults.synchronize() } /** Returns the user token currently stored in user defaults. - returns: the token currently stored in the user defaults or `nil` if no token can be found */ class func token() -> String? { guard let token = UserDefaults.standard.value(forKey: kToken) as? String else { return nil } return token } /** Stores my id in user defaults. - parameter id: the token that should be stored */ class func store(id: String) { let defaults = UserDefaults.standard defaults.setValue(id, forKey: kMyId) let _ = defaults.synchronize() } /** Returns the user id currently stored in user defaults. - returns: the id currently stored in the user defaults or `nil` if no token can be found */ class func id() -> String? { guard let token = UserDefaults.standard.value(forKey: kMyId) as? String else { return nil } return token } }
mit
492f111fa6c4a269a2be0b200f8f69c3
25.530303
101
0.598515
4.444162
false
false
false
false
edragoev1/pdfjet
Sources/Example_49/main.swift
1
2290
import Foundation import PDFjet /** * Example_49.swift * */ public class Example_49 { public init() throws { let stream = OutputStream(toFileAtPath: "Example_49.pdf", append: false) let pdf = PDF(stream!) let f1 = try Font( pdf, InputStream(fileAtPath: "fonts/Droid/DroidSerif-Regular.ttf")!) let f2 = try Font( pdf, InputStream(fileAtPath: "fonts/Droid/DroidSerif-Italic.ttf")!) f1.setSize(14.0) f2.setSize(16.0) let page = Page(pdf, Letter.PORTRAIT) let paragraph1 = Paragraph() .add(TextLine(f1, "Hello")) .add(TextLine(f1, "W").setColor(Color.black).setTrailingSpace(false)) .add(TextLine(f1, "o").setColor(Color.red).setTrailingSpace(false)) .add(TextLine(f1, "r").setColor(Color.green).setTrailingSpace(false)) .add(TextLine(f1, "l").setColor(Color.blue).setTrailingSpace(false)) .add(TextLine(f1, "d").setColor(Color.black)) .add(TextLine(f1, "$").setTrailingSpace(false) .setVerticalOffset(f1.getAscent() - f2.getAscent())) .add(TextLine(f2, "29.95").setColor(Color.blue)) .setAlignment(Align.RIGHT) let paragraph2 = Paragraph() .add(TextLine(f1, "Hello")) .add(TextLine(f1, "World")) .add(TextLine(f1, "$")) .add(TextLine(f2, "29.95").setColor(Color.blue)) .setAlignment(Align.RIGHT) let column = TextColumn() column.addParagraph(paragraph1) column.addParagraph(paragraph2) column.setLocation(70.0, 150.0) column.setWidth(500.0) column.drawOn(page) var paragraphs = [Paragraph]() paragraphs.append(paragraph1) paragraphs.append(paragraph2) let text = Text(paragraphs) text.setLocation(70.0, 200.0) text.setWidth(500.0) text.drawOn(page) pdf.complete() } } // End of Example_49.swift let time0 = Int64(Date().timeIntervalSince1970 * 1000) _ = try Example_49() let time1 = Int64(Date().timeIntervalSince1970 * 1000) print("Example_49 => \(time1 - time0)")
mit
a8446247179b4d6ccb0e6a1b34d16520
30.369863
85
0.567249
3.747954
false
false
false
false
silt-lang/silt
Sources/InnerCore/IRGenStrategy.swift
1
31071
/// IRGenStrategy.swift /// /// Copyright 2019, The Silt Language Project. /// /// This project is released under the MIT license, a copy of which is /// available in the repository. import LLVM import Seismography import OuterCore import Mantle extension IRGenModule { /// Computes the strategy to implement a particular /// /// - Parameters: /// - TC: A type converter. /// - type: The GIR data type to strategize about. /// - llvmType: The LLVM type declaration for this layout. /// - Returns: The strategy used to implement values of this data type. func strategize(_ TC: TypeConverter, _ type: DataType, _ llvmType: StructType) -> DataTypeStrategy { let numElements = type.constructors.count var tik = DataTypeLayoutPlanner.TypeInfoKind.loadable if let strat = self.getAsNatural(TC.IGM, type, llvmType) { return strat } var elementsWithPayload = [DataTypeLayoutPlanner.Element]() var elementsWithNoPayload = [DataTypeLayoutPlanner.Element]() for constr in type.constructors { guard let origArgType = constr.payload else { elementsWithNoPayload.append(.dynamic(constr.name)) continue } if origArgType is BoxType { let managedTI = ManagedObjectTypeInfo(self.refCountedPtrTy, self.getPointerSize(), self.getPointerAlignment()) elementsWithPayload.append(.fixed(constr.name, managedTI)) continue } if let constrTI = TC.getCompleteTypeInfo(origArgType) as? FixedTypeInfo { elementsWithPayload.append(.fixed(constr.name, constrTI)) if !(constrTI is LoadableTypeInfo) && tik == .loadable { tik = .fixed } } else { elementsWithPayload.append(.dynamic(constr.name)) tik = .dynamic } } let planner = DataTypeLayoutPlanner(IGM: TC.IGM, girType: type, storageType: llvmType, typeInfoKind: tik, withPayload: elementsWithPayload, withoutPayload: elementsWithNoPayload) if numElements <= 1 { return NewTypeDataTypeStrategy(planner) } if elementsWithPayload.count > 1 { // return MultiPayloadDataTypeStrategy(planner) fatalError("Unimplemented!") } if elementsWithPayload.count == 1 { return SinglePayloadDataTypeStrategy(planner) } if elementsWithNoPayload.count <= 2 { return SingleBitDataTypeStrategy(planner) } assert(elementsWithPayload.isEmpty) return NoPayloadDataTypeStrategy(planner) } private func getAsNatural(_ IGM: IRGenModule, _ type: DataType, _ llvmType: StructType ) -> DataTypeStrategy? { guard type.constructors.count == 2 else { return nil } let oneCon = type.constructors[0] let twoCon = type.constructors[1] guard (oneCon.payload == nil) != (twoCon.payload == nil) else { return nil } let planner = DataTypeLayoutPlanner(IGM: IGM, girType: type, storageType: llvmType, typeInfoKind: .fixed, withPayload: [], withoutPayload: []) if let succ = oneCon.payload as? TupleType { guard succ.elements.count == 1 else { return nil } guard let dataSucc = succ.elements[0] as? DataType else { return nil } guard dataSucc === type else { return nil } return NaturalDataTypeStrategy(twoCon.name, planner) } else if let succ = twoCon.payload as? TupleType { guard succ.elements.count == 1 else { return nil } guard let dataSucc = succ.elements[0] as? DataType else { return nil } guard dataSucc === type else { return nil } return NaturalDataTypeStrategy(oneCon.name, planner) } else { return nil } } } /// Implements a data type strategy for a type with exactly one case /// which can optionally carry a payload value. /// /// The precise layout of the value can take one of two forms: /// /// - Without Payload: /// - Layout: empty. /// - To construct: No-op. /// - To discriminate: No-op. /// - To destruct: No-op. /// /// - With Payload: /// - Layout: Payload's layout. /// - To construct: Construct the payload by re-explosion. /// - To discriminate: No-op. /// - To destruct: Extract the payload value by re-explosion. /// /// In either case, there is no value to discriminate, and all `switch_constr` /// instructions are resolved to direct branches. final class NewTypeDataTypeStrategy: DataTypeStrategy { let planner: DataTypeLayoutPlanner init(_ planner: DataTypeLayoutPlanner) { self.planner = planner self.planner.fulfill { (planner) -> TypeInfo in guard !planner.payloadElements.isEmpty else { planner.llvmType.setBody([], isPacked: true) return LoadableDataTypeTypeInfo(self, planner.llvmType, .zero, .one) } guard case let .some(.fixed(_, eltTI)) = planner.payloadElements.first else { fatalError() } switch planner.optimalTypeInfoKind { case .dynamic: let alignment = eltTI.alignment planner.llvmType.setBody([], isPacked: true) return DynamicDataTypeTypeInfo(self, planner.llvmType, alignment) case .loadable: let alignment = eltTI.alignment planner.llvmType.setBody([ eltTI.llvmType ], isPacked: true) return LoadableDataTypeTypeInfo(self, planner.llvmType, eltTI.fixedSize, alignment) case .fixed: let alignment = eltTI.alignment planner.llvmType.setBody([ eltTI.llvmType ], isPacked: true) return FixedDataTypeTypeInfo(self, planner.llvmType, eltTI.fixedSize, alignment) } } } private func getSingleton() -> TypeInfo? { switch self.planner.payloadElements[0] { case .dynamic(_): return nil case let .fixed(_, ti): return ti } } private func getLoadableSingleton() -> LoadableTypeInfo? { switch self.planner.payloadElements[0] { case .dynamic(_): return nil case let .fixed(_, ti): return ti as? LoadableTypeInfo } } func initialize(_ IGF: IRGenFunction, _ from: Explosion, _ addr: Address) { if let singleton = getLoadableSingleton() { let ptrTy = PointerType(pointee: singleton.llvmType) let ptr = IGF.B.createPointerBitCast(of: addr, to: ptrTy) singleton.initialize(IGF, from, ptr) } } func reexplode(_ IGF: IRGenFunction, _ src: Explosion, _ dest: Explosion) { getLoadableSingleton()?.reexplode(IGF, src, dest) } func loadAsTake(_ IGF: IRGenFunction, _ addr: Address, _ out: Explosion) { if let singleton = getLoadableSingleton() { let ptrTy = PointerType(pointee: singleton.llvmType) let ptr = IGF.B.createPointerBitCast(of: addr, to: ptrTy) singleton.loadAsTake(IGF, ptr, out) } } func loadAsCopy(_ IGF: IRGenFunction, _ addr: Address, _ out: Explosion) { if let singleton = getLoadableSingleton() { let ptrTy = PointerType(pointee: singleton.llvmType) let ptr = IGF.B.createPointerBitCast(of: addr, to: ptrTy) singleton.loadAsCopy(IGF, ptr, out) } } func emitSwitch(_ IGF: IRGenFunction, _ value: Explosion, _ dests: [(String, BasicBlock)], _ def: BasicBlock?) { _ = value.claimSingle() guard let dest = dests.count == 1 ? dests[0].1 : def else { fatalError() } IGF.B.buildBr(dest) } func emitDataInjection(_ IGF: IRGenFunction, _ : String, _ data: Explosion, _ out: Explosion) { getLoadableSingleton()?.reexplode(IGF, data, out) } func emitDataProjection(_ IGF: IRGenFunction, _ : String, _ value: Explosion, _ projected: Explosion) { getLoadableSingleton()?.reexplode(IGF, value, projected) } func buildExplosionSchema(_ builder: Explosion.Schema.Builder) { guard let singleton = getSingleton() else { return } if self.planner.optimalTypeInfoKind == .loadable { return singleton.buildExplosionSchema(builder) } // Otherwise, use an indirect aggregate schema with our storage type. builder.append(.aggregate(singleton.llvmType, singleton.alignment)) } func buildAggregateLowering(_ IGM: IRGenModule, _ builder: AggregateLowering.Builder, _ offset: Size) { getLoadableSingleton()?.buildAggregateLowering(IGM, builder, offset) } func copy(_ IGF: IRGenFunction, _ src: Explosion, _ dest: Explosion) { getLoadableSingleton()?.copy(IGF, src, dest) } func explosionSize() -> Int { return getLoadableSingleton()?.explosionSize() ?? 0 } func consume(_ IGF: IRGenFunction, _ explosion: Explosion) { getLoadableSingleton()?.consume(IGF, explosion) } func packIntoPayload(_ IGF: IRGenFunction, _ payload: Payload, _ source: Explosion, _ offset: Size) { getLoadableSingleton()?.packIntoPayload(IGF, payload, source, offset) } func unpackFromPayload(_ IGF: IRGenFunction, _ payload: Payload, _ destination: Explosion, _ offset: Size) { getLoadableSingleton()?.unpackFromPayload(IGF, payload, destination, offset) } func destroy(_ IGF: IRGenFunction, _ addr: Address, _ type: GIRType) { if getLoadableSingleton() != nil { IGF.GR.emitDestroyCall(type, addr) } } func assign(_ IGF: IRGenFunction, _ src: Explosion, _ dest: Address) { getLoadableSingleton()?.assign(IGF, src, dest) } func assignWithCopy(_ IGF: IRGenFunction, _ dest: Address, _ src: Address, _ type: GIRType) { if getLoadableSingleton() != nil { IGF.GR.emitAssignWithCopyCall(type, dest, src) } } } /// Implements a data type strategy for a type with exactly two cases with no /// payload. The underlying LLVM type is an `i1`, and discrimination is done /// by conditional branch. final class SingleBitDataTypeStrategy: NoPayloadStrategy { let planner: DataTypeLayoutPlanner init(_ planner: DataTypeLayoutPlanner) { self.planner = planner self.planner.fulfill { (planner) -> TypeInfo in if planner.noPayloadElements.count == 2 { planner.llvmType.setBody([ IntType.int1 ], isPacked: true) } else { planner.llvmType.setBody([], isPacked: true) } let size = Size(planner.noPayloadElements.count == 2 ? 1 : 0) return LoadableDataTypeTypeInfo(self, planner.llvmType, size, .one) } } func buildExplosionSchema(_ schema: Explosion.Schema.Builder) { guard self.planner.noPayloadElements.count == 2 else { return } schema.append(.scalar(IntType.int1)) } func buildAggregateLowering(_ IGM: IRGenModule, _ builder: AggregateLowering.Builder, _ offset: Size) { guard self.planner.noPayloadElements.count == 2 else { return } builder.append(.opaque(begin: offset, end: offset + Size(1))) } func emitDataInjection(_ IGF: IRGenFunction, _ target: String, _ data: Explosion, _ out: Explosion) { guard self.planner.noPayloadElements.count == 2 else { return } out.append(self.planner.noPayloadElements.firstIndex(where: { $0.selector == target }) ?? 0) } func initialize(_ IGF: IRGenFunction, _ from: Explosion, _ addr: Address) { let addr = IGF.B.createStructGEP(addr, 0, .zero, "") IGF.B.buildStore(from.claimSingle(), to: addr.address) } func copy(_ IGF: IRGenFunction, _ src: Explosion, _ dest: Explosion) { dest.append(src.claimSingle()) } func reexplode(_ IGF: IRGenFunction, _ src: Explosion, _ dest: Explosion) { src.transfer(into: dest, self.explosionSize()) } func loadAsCopy(_ IGF: IRGenFunction, _ addr: Address, _ explosion: Explosion) { let addr = IGF.B.createStructGEP(addr, 0, .zero, "") explosion.append(IGF.B.createLoad(addr)) } func loadAsTake(_ IGF: IRGenFunction, _ addr: Address, _ explosion: Explosion) { let addr = IGF.B.createStructGEP(addr, 0, .zero, "") explosion.append(IGF.B.createLoad(addr)) } func emitDataProjection(_ IGF: IRGenFunction, _ : String, _ value: Explosion, _ projected: Explosion) { _ = value.claim(next: self.explosionSize()) } func consume(_ IGF: IRGenFunction, _ explosion: Explosion) { _ = explosion.claimSingle() } func packIntoPayload(_ IGF: IRGenFunction, _ payload: Payload, _ source: Explosion, _ offset: Size) { payload.insertValue(IGF, source.claimSingle(), offset) } func unpackFromPayload(_ IGF: IRGenFunction, _ payload: Payload, _ destination: Explosion, _ offset: Size) { destination.append(payload.extractValue(IGF, self.typeInfo().llvmType, offset)) } func destroy(_ IGF: IRGenFunction, _ addr: Address, _ type: GIRType) { } func assign(_ IGF: IRGenFunction, _ src: Explosion, _ dest: Address) { let newValue = src.claimSingle() IGF.B.buildStore(newValue, to: dest.address) } func assignWithCopy(_ IGF: IRGenFunction, _ dest: Address, _ src: Address, _ : GIRType) { let temp = Explosion() self.loadAsTake(IGF, src, temp) self.initialize(IGF, temp, dest) } } /// Implements a data type strategy for a type where no case has a payload /// value. The underlying LLVM type is the least power-of-two-width integral /// type needed to store the discriminator. final class NoPayloadDataTypeStrategy: NoPayloadStrategy { let planner: DataTypeLayoutPlanner init(_ planner: DataTypeLayoutPlanner) { self.planner = planner self.planner.fulfill { (planner) -> TypeInfo in // Since there are no payloads, we need just enough bits to hold a // discriminator. let usedTagBits = log2(UInt64(planner.noPayloadElements.count - 1)) + 1 let (tagSize, tagTy) = computeTagLayout(planner.IGM, usedTagBits) planner.llvmType.setBody([ tagTy ], isPacked: true) let alignment = Alignment(UInt32(tagSize.rawValue)) return LoadableDataTypeTypeInfo(self, planner.llvmType, tagSize, alignment) } } func buildExplosionSchema(_ schema: Explosion.Schema.Builder) { schema.append(.scalar(getDiscriminatorType())) } func fixedSize() -> Size { return Size(UInt64(self.getDiscriminatorType().width + 7) / 8) } func buildAggregateLowering(_ IGM: IRGenModule, _ builder: AggregateLowering.Builder, _ offset: Size) { builder.append(.opaque(begin: offset, end: offset + self.fixedSize())) } func emitDataInjection(_ IGF: IRGenFunction, _ selector: String, _ data: Explosion, _ out: Explosion) { out.append(discriminatorIndex(for: selector)) } func reexplode(_ IGF: IRGenFunction, _ src: Explosion, _ dest: Explosion) { src.transfer(into: dest, 1) } func initialize(_ IGF: IRGenFunction, _ src: Explosion, _ addr: Address) { IGF.B.buildStore(src.claimSingle(), to: addr.address) } func loadAsTake(_ IGF: IRGenFunction, _ addr: Address, _ explosion: Explosion) { explosion.append(IGF.B.createLoad(addr)) } func loadAsCopy(_ IGF: IRGenFunction, _ addr: Address, _ explosion: Explosion) { let value = IGF.B.createLoad(addr) self.emitScalarRelease(IGF, value) explosion.append(value) } func copy(_ IGF: IRGenFunction, _ src: Explosion, _ dest: Explosion) { dest.append(src.claimSingle()) } func emitDataProjection(_ IGF: IRGenFunction, _ : String, _ value: Explosion, _ projected: Explosion) { _ = value.claim(next: explosionSize()) } func consume(_ IGF: IRGenFunction, _ explosion: Explosion) { _ = explosion.claimSingle() } func packIntoPayload(_ IGF: IRGenFunction, _ payload: Payload, _ source: Explosion, _ offset: Size) { payload.insertValue(IGF, source.claimSingle(), offset) } func unpackFromPayload(_ IGF: IRGenFunction, _ payload: Payload, _ destination: Explosion, _ offset: Size) { let value = payload.extractValue(IGF, self.getDiscriminatorType(), offset) destination.append(value) } func destroy(_ IGF: IRGenFunction, _ addr: Address, _ type: GIRType) { } func assignWithCopy(_ IGF: IRGenFunction, _ dest: Address, _ source: Address, _ : GIRType) { let addr = IGF.B.createStructGEP(source, 0, .zero, "") let value = IGF.B.createLoad(addr) IGF.B.buildStore(value, to: dest.address) } } /// Implements a strategy for a datatype where exactly one case contains a /// payload value, and all other cases do not. /// /// The resulting layout depends mostly on the layout of that payload. In the /// simple case, we know nothing about the payload's layout and so must /// manipulate these values indirectly. In the case where we know the layout /// of the payload, we lay the bits out as follows: /// /// |-8-bits-|-8-bits-|-8-bits-| .... |-8-bits-|-8-bits-|-8-bits-| .... /// •---------------------------------------------------------------------- /// | | | | | | | | /// | | | | | | | | /// | Payload Layout | .... | Discriminator Bits | .... /// | | | | | | | | /// | | | | | | | | /// •---------------------------------------------------------------------- /// /// In the future, we will attempt to compute the spare bits available in the /// layout of the payload and use the unused bitpatterns to reduce the size of /// the discriminator bit region. /// /// The payload and discriminator regions are laid out as packed multiples of /// 8-bit arrays rather than as arbitrary-precision integers to avoid computing /// bizarre integral types as these can cause FastISel to have some indigestion. final class SinglePayloadDataTypeStrategy: PayloadStrategy { let planner: DataTypeLayoutPlanner let payloadSchema: Payload.Schema let payloadElementCount: Int init(_ planner: DataTypeLayoutPlanner) { self.planner = planner var payloadBitCount = 0 switch planner.payloadElements[0] { case let .fixed(_, fixedTI): self.payloadSchema = .bits(fixedTI.fixedSize.valueInBits()) var elementCount = 0 self.payloadSchema.forEachType(planner.IGM) { t in elementCount += 1 payloadBitCount += planner.IGM.dataLayout.sizeOfTypeInBits(t) } self.payloadElementCount = elementCount default: self.payloadSchema = .dynamic self.payloadElementCount = 0 payloadBitCount = -1 } let tagLayout = computeTagLayout(planner.IGM, UInt64(planner.noPayloadElements.count)) let numTagBits = Int(tagLayout.0.rawValue) switch self.planner.optimalTypeInfoKind { case .fixed: self.planner.fulfill { (planner) -> TypeInfo in guard case let .fixed(_, payloadTI) = planner.payloadElements[0] else { fatalError() } assert(payloadBitCount > 0) planner.llvmType.setBody([ ArrayType(elementType: IntType.int8, count: (payloadBitCount+7)/8), ArrayType(elementType: IntType.int8, count: numTagBits), ], isPacked: true) let tagSize = Size((numTagBits+7)/8) return FixedDataTypeTypeInfo(self, planner.llvmType, payloadTI.fixedSize + tagSize, payloadTI.alignment) } case .loadable: self.planner.fulfill { (planner) -> TypeInfo in guard case let .fixed(_, payloadTI) = planner.payloadElements[0] else { fatalError() } assert(payloadBitCount > 0) planner.llvmType.setBody([ ArrayType(elementType: IntType.int8, count: (payloadBitCount+7)/8), ArrayType(elementType: IntType.int8, count: numTagBits), ], isPacked: true) let tagSize = Size((numTagBits+7)/8) return LoadableDataTypeTypeInfo(self, planner.llvmType, payloadTI.fixedSize + tagSize, payloadTI.alignment) } case .dynamic: self.planner.fulfill { (planner) -> TypeInfo in // The body is runtime-dependent, so we can't put anything useful here // statically. planner.llvmType.setBody([], isPacked: true) guard case let .fixed(_, ti) = planner.payloadElements[0] else { fatalError() } return DynamicDataTypeTypeInfo(self, planner.llvmType, ti.alignment) } } } func emitSwitch(_ IGF: IRGenFunction, _ value: Explosion, _ dests: [(String, BasicBlock)], _ def: BasicBlock?) { fatalError("Unimplemented") } func emitDataInjection(_ IGF: IRGenFunction, _ target: String, _ params: Explosion, _ out: Explosion) { guard target != self.planner.payloadElements[0].selector else { // Compute an empty bitpattern and pack the given value into it. let payload = Payload.zero(IGF.IGM, self.payloadSchema) getLoadablePayloadTypeInfo().packIntoPayload(IGF, payload, params, 0) payload.explode(IGF.IGM, out) return } /// Compute the bitpattern for the discriminator and pack it as our /// payload value. let tagIdx = self.indexOf(selector: target) let bitWidth = getFixedPayloadTypeInfo().fixedSize.valueInBits() let pattern = APInt(width: Int(bitWidth), value: tagIdx) let payload = Payload.fromBitPattern(IGF.IGM, pattern, self.payloadSchema) payload.explode(IGF.IGM, out) } func initialize(_ IGF: IRGenFunction, _ from: Explosion, _ addr: Address) { let payload = Payload.fromExplosion(planner.IGM, from, self.payloadSchema) payload.store(IGF, addr) } func destroy(_ IGF: IRGenFunction, _ addr: Address, _ type: GIRType) { let ptrTy = PointerType(pointee: IGF.IGM.refCountedPtrTy) let addr = IGF.B.createPointerBitCast(of: addr, to: ptrTy) let ptr = IGF.B.createLoad(addr) IGF.GR.emitRelease(ptr) } func consume(_ IGF: IRGenFunction, _ explosion: Explosion) { let val = explosion.claimSingle() let ptr = IGF.B.createBitOrPointerCast(val, to: IGF.IGM.refCountedPtrTy) IGF.GR.emitRelease(ptr) } func loadAsTake(_ IGF: IRGenFunction, _ addr: Address, _ explosion: Explosion) { let payload = Payload.load(IGF, addr, self.payloadSchema) payload.explode(IGF.IGM, explosion) } func emitDataProjection(_ IGF: IRGenFunction, _ selector: String, _ value: Explosion, _ projected: Explosion) { guard selector == self.planner.payloadElements[0].selector else { value.markClaimed(self.explosionSize()) return } let payload = Payload.fromExplosion(IGF.IGM, value, self.payloadSchema) getLoadablePayloadTypeInfo().unpackFromPayload(IGF, payload, projected, 0) } func packIntoPayload(_ IGF: IRGenFunction, _ payload: Payload, _ source: Explosion, _ offset: Size) { let payload = Payload.fromExplosion(IGF.IGM, source, self.payloadSchema) payload.packIntoEnumPayload(IGF, payload, offset) } func unpackFromPayload(_ IGF: IRGenFunction, _ payload: Payload, _ destination: Explosion, _ offset: Size) { let payload = Payload.unpackFromPayload(IGF, payload, offset, self.payloadSchema) payload.explode(IGF.IGM, destination) } func assignWithCopy(_ IGF: IRGenFunction, _ dest: Address, _ src: Address, _ type: GIRType) { IGF.GR.emitAssignWithCopyCall(type, dest, src) } } final class NaturalDataTypeStrategy: NoPayloadStrategy { let planner: DataTypeLayoutPlanner let fixedSize: Size let fixedAlignment: Alignment let zeroName: String init(_ zero: String, _ planner: DataTypeLayoutPlanner) { self.zeroName = zero self.planner = planner self.fixedSize = Size(bits: UInt64(planner.IGM.dataLayout.intPointerType().width)) self.fixedAlignment = .one self.planner.fulfill { (planner) -> TypeInfo in // HACK: Use the platform's int type. [32/64] bits ought to be enough for // anybody... let intTy = planner.IGM.dataLayout.intPointerType() planner.llvmType.setBody([ intTy ], isPacked: true) let tagSize = Size(bits: UInt64(intTy.width)) let alignment: Alignment = planner.IGM.dataLayout.abiAlignment(of: intTy) return LoadableDataTypeTypeInfo(self, planner.llvmType, tagSize, alignment) } } func scalarType() -> IntType { return planner.IGM.dataLayout.intPointerType() } func discriminatorIndex(for target: String) -> Constant<Signed> { return self.scalarType().constant(0) } func emitDataProjection(_ IGF: IRGenFunction, _ selector: String, _ value: Explosion, _ projected: Explosion) { let val = value.claimSingle() guard selector != self.zeroName else { return } projected.append(IGF.B.buildSub(val, self.scalarType().constant(1))) } func emitSwitch(_ IGF: IRGenFunction, _ value: Explosion, _ dests: [(String, BasicBlock)], _ def: BasicBlock?) { let discriminator = value.peek() let defaultDest = def ?? { let defaultDest = IGF.function.appendBasicBlock(named: "") let pos = IGF.B.insertBlock! IGF.B.positionAtEnd(of: defaultDest) IGF.B.buildUnreachable() IGF.B.positionAtEnd(of: pos) return defaultDest }() switch dests.count { case 0: guard def != nil else { IGF.B.buildUnreachable() return } IGF.B.buildBr(defaultDest) case 1: let cmp = IGF.B.buildICmp(discriminator, self.scalarType().zero(), .notEqual) IGF.B.buildCondBr(condition: cmp, then: dests[0].1, else: defaultDest) case 2 where def == nil: let firstDest = dests[0] let nextDest = dests[1] let caseTag = discriminatorIndex(for: firstDest.0) let cmp = IGF.B.buildICmp(discriminator, caseTag, .equal) IGF.B.buildCondBr(condition: cmp, then: firstDest.1, else: nextDest.1) defaultDest.removeFromParent() default: let switchInst = IGF.B.buildSwitch(discriminator, else: defaultDest, caseCount: dests.count) for (name, dest) in dests { switchInst.addCase(discriminatorIndex(for: name), dest) } } } func buildExplosionSchema(_ schema: Explosion.Schema.Builder) { schema.append(.scalar(scalarType())) } func buildAggregateLowering(_ IGM: IRGenModule, _ builder: AggregateLowering.Builder, _ offset: Size) { builder.append(.opaque(begin: offset, end: offset + self.fixedSize)) } func emitDataInjection(_ IGF: IRGenFunction, _ : String, _ data: Explosion, _ out: Explosion) { if data.count == 0 { out.append(self.scalarType().constant(0)) } else { let curValue = data.claimSingle() out.append(IGF.B.buildAdd(curValue, self.scalarType().constant(1))) } } func reexplode(_ IGF: IRGenFunction, _ src: Explosion, _ dest: Explosion) { src.transfer(into: dest, self.explosionSize()) } func initialize(_ IGF: IRGenFunction, _ src: Explosion, _ addr: Address) { IGF.B.buildStore(src.claimSingle(), to: addr.address) } func loadAsTake(_ IGF: IRGenFunction, _ addr: Address, _ explosion: Explosion) { explosion.append(IGF.B.createLoad(addr)) } func loadAsCopy(_ IGF: IRGenFunction, _ addr: Address, _ explosion: Explosion) { explosion.append(IGF.B.createLoad(addr)) } func copy(_ IGF: IRGenFunction, _ src: Explosion, _ dest: Explosion) { let value = src.claimSingle() dest.append(value) } func packIntoPayload(_ IGF: IRGenFunction, _ payload: Payload, _ source: Explosion, _ offset: Size) { payload.insertValue(IGF, source.claimSingle(), offset) } func unpackFromPayload(_ IGF: IRGenFunction, _ payload: Payload, _ destination: Explosion, _ offset: Size) { destination.append(payload.extractValue(IGF, self.scalarType(), offset)) } func consume(_ IGF: IRGenFunction, _ explosion: Explosion) { } func destroy(_ IGF: IRGenFunction, _ addr: Address, _ type: GIRType) { } func assign(_ IGF: IRGenFunction, _ src: Explosion, _ dest: Address) { let newValue = src.claimSingle() IGF.B.buildStore(newValue, to: dest.address) } func assignWithCopy(_ IGF: IRGenFunction, _ dest: Address, _ src: Address, _ : GIRType) { let temp = Explosion() self.loadAsTake(IGF, src, temp) self.initialize(IGF, temp, dest) } } private func isPowerOf2(_ Value: UInt64) -> Bool { return (Value != 0) && ((Value & (Value - 1)) == 0) } private func nextPowerOfTwo(_ v: UInt64) -> UInt64 { var v = v v -= 1 v |= v >> 1 v |= v >> 2 v |= v >> 4 v |= v >> 8 v |= v >> 16 v |= v >> 32 v += 1 return v } private func log2(_ val: UInt64) -> UInt64 { return 63 - UInt64(val.leadingZeroBitCount) } // Use the best fitting "normal" integer size for the enum. Though LLVM // theoretically supports integer types of arbitrary bit width, in practice, // types other than i1 or power-of-two-byte sizes like i8, i16, etc. inhibit // FastISel and expose backend bugs. func integerBitSize(for tagBits: UInt64) -> UInt64 { // i1 is used to represent bool in C so is fairly well supported. if tagBits == 1 { return 1 } // Otherwise, round the physical size in bytes up to the next power of two. var tagBytes = (tagBits + 7)/8 if !isPowerOf2(tagBytes) { tagBytes = nextPowerOfTwo(tagBytes) } return Size(tagBytes).valueInBits() } private func computeTagLayout(_ IGM: IRGenModule, _ tagBits: UInt64) -> (Size, IntType) { let typeBits = integerBitSize(for: tagBits) let typeSize = Size(bits: typeBits) return (typeSize, IntType(width: Int(typeBits), in: IGM.module.context)) }
mit
06c040a497f6ab687e376e37f782ddde
33.711732
80
0.620337
4.123026
false
false
false
false
xedin/swift
test/SILGen/lying_about_optional_return_objc.swift
12
4175
// RUN: %target-swift-emit-silgen(mock-sdk: %clang-importer-sdk) -enable-objc-interop -import-objc-header %S/Inputs/block_property_in_objc_class.h %s | %FileCheck %s // CHECK-LABEL: sil hidden [ossa] @$s32lying_about_optional_return_objc0C37ChainingForeignFunctionTypeProperties{{[_0-9a-zA-Z]*}}F func optionalChainingForeignFunctionTypeProperties(b: BlockProperty?) { // CHECK: enum $Optional<()>, #Optional.some!enumelt.1, {{%.*}} : $() b?.readWriteBlock() // CHECK: enum $Optional _ = b?.readWriteBlock // CHECK: enum $Optional<()>, #Optional.some!enumelt.1, {{%.*}} : $() b?.readOnlyBlock() // CHECK: enum $Optional _ = b?.readOnlyBlock // CHECK: unchecked_trivial_bit_cast _ = b?.selector // CHECK: enum $Optional<()>, #Optional.some!enumelt.1, {{%.*}} : $() _ = b?.voidReturning() // CHECK: unchecked_trivial_bit_cast _ = b?.voidPointerReturning() // CHECK: unchecked_trivial_bit_cast _ = b?.opaquePointerReturning() // CHECK: unchecked_trivial_bit_cast _ = b?.pointerReturning() // CHECK: unchecked_trivial_bit_cast _ = b?.constPointerReturning() // CHECK: unchecked_trivial_bit_cast _ = b?.selectorReturning() // CHECK: unchecked_ref_cast _ = b?.objectReturning() // CHECK: enum $Optional<{{.*}} -> {{.*}}> _ = b?.voidReturning // CHECK: enum $Optional<{{.*}} -> {{.*}}> _ = b?.voidPointerReturning // CHECK: enum $Optional<{{.*}} -> {{.*}}> _ = b?.opaquePointerReturning // CHECK: enum $Optional<{{.*}} -> {{.*}}> _ = b?.pointerReturning // CHECK: enum $Optional<{{.*}} -> {{.*}}> _ = b?.constPointerReturning // CHECK: enum $Optional<{{.*}} -> {{.*}}> _ = b?.selectorReturning // CHECK: enum $Optional<{{.*}} -> {{.*}}> _ = b?.objectReturning // CHECK-LABEL: debug_value {{.*}} name "dynamic" let dynamic: AnyObject? = b! // CHECK: enum $Optional<()>, #Optional.some!enumelt.1, {{%.*}} : $() _ = dynamic?.voidReturning() // CHECK: unchecked_trivial_bit_cast {{.*}} $UnsafeMutableRawPointer to $Optional _ = dynamic?.voidPointerReturning() // CHECK: unchecked_trivial_bit_cast {{.*}} $OpaquePointer to $Optional _ = dynamic?.opaquePointerReturning() // CHECK: unchecked_trivial_bit_cast {{.*}} $UnsafeMutablePointer{{.*}} to $Optional _ = dynamic?.pointerReturning() // CHECK: unchecked_trivial_bit_cast {{.*}} $UnsafePointer{{.*}} to $Optional _ = dynamic?.constPointerReturning() // CHECK: unchecked_trivial_bit_cast {{.*}} $Selector to $Optional _ = dynamic?.selectorReturning() // CHECK: unchecked_ref_cast {{.*}} $BlockProperty to $Optional _ = dynamic?.objectReturning() // FIXME: Doesn't opaquely cast the selector result! // C/HECK: unchecked_trivial_bit_cast {{.*}} $Selector to $Optional _ = dynamic?.selector // CHECK: inject_enum_addr {{%.*}} : $*Optional<{{.*}} -> ()>, #Optional.some _ = dynamic?.voidReturning // CHECK: inject_enum_addr {{%.*}} : $*Optional<{{.*}} -> UnsafeMutableRawPointer>, #Optional.some _ = dynamic?.voidPointerReturning // CHECK: inject_enum_addr {{%.*}} : $*Optional<{{.*}} -> OpaquePointer>, #Optional.some _ = dynamic?.opaquePointerReturning // CHECK: inject_enum_addr {{%.*}} : $*Optional<{{.*}} -> UnsafeMutablePointer{{.*}}>, #Optional.some _ = dynamic?.pointerReturning // CHECK: inject_enum_addr {{%.*}} : $*Optional<{{.*}} -> UnsafePointer{{.*}}>, #Optional.some _ = dynamic?.constPointerReturning // CHECK: inject_enum_addr {{%.*}} : $*Optional<{{.*}} -> Selector>, #Optional.some _ = dynamic?.selectorReturning // CHECK: inject_enum_addr {{%.*}} : $*Optional<{{.*}} -> @owned BlockProperty>, #Optional.some _ = dynamic?.objectReturning // CHECK: enum $Optional<()>, #Optional.some!enumelt.1, {{%.*}} : $() _ = dynamic?.voidReturning?() // CHECK: unchecked_trivial_bit_cast _ = dynamic?.voidPointerReturning?() // CHECK: unchecked_trivial_bit_cast _ = dynamic?.opaquePointerReturning?() // CHECK: unchecked_trivial_bit_cast _ = dynamic?.pointerReturning?() // CHECK: unchecked_trivial_bit_cast _ = dynamic?.constPointerReturning?() // CHECK: unchecked_trivial_bit_cast _ = dynamic?.selectorReturning?() _ = dynamic?.objectReturning?() }
apache-2.0
845d9c6b089c6826ced59a102a74be12
40.336634
165
0.630898
4.141865
false
false
false
false
Alterplay/APKenBurnsView
Pod/Classes/Private/AnimationDataSources/FaceAnimationDataSource.swift
1
4597
// // Created by Nickolay Sheika on 6/8/16. // import Foundation import UIKit import QuartzCore enum FaceRecognitionMode { case Biggest case Group init(mode: APKenBurnsViewFaceRecognitionMode) { switch mode { case .None: fatalError("Unsupported mode!") case .Biggest: self = .Biggest case .Group: self = .Group } } } class FaceAnimationDataSource: AnimationDataSource { // MARK: - Variables let animationCalculator: ImageAnimationCalculatorProtocol // will be used for animation if no faces found let backupAnimationDataSource: AnimationDataSource let faceRecognitionMode: FaceRecognitionMode // MARK: - Init init(faceRecognitionMode: FaceRecognitionMode, animationCalculator: ImageAnimationCalculatorProtocol, backupAnimationDataSource: AnimationDataSource) { self.faceRecognitionMode = faceRecognitionMode self.animationCalculator = animationCalculator self.backupAnimationDataSource = backupAnimationDataSource } convenience init(faceRecognitionMode: FaceRecognitionMode, animationDependencies: ImageAnimationDependencies, backupAnimationDataSource: AnimationDataSource) { self.init(faceRecognitionMode: faceRecognitionMode, animationCalculator: ImageAnimationCalculator(animationDependencies: animationDependencies), backupAnimationDataSource: backupAnimationDataSource) } // MARK: - Public func buildAnimationForImage(image: UIImage, forViewPortSize viewPortSize: CGSize) -> ImageAnimation { guard let faceRect = findFaceRect(image: image) else { return backupAnimationDataSource.buildAnimationForImage(image: image, forViewPortSize: viewPortSize) } let imageSize = image.size let startScale: CGFloat = animationCalculator.buildRandomScale(imageSize: imageSize, viewPortSize: viewPortSize) let endScale: CGFloat = animationCalculator.buildRandomScale(imageSize: imageSize, viewPortSize: viewPortSize) let scaledStartImageSize = imageSize.scaledSize(scale: startScale) let scaledEndImageSize = imageSize.scaledSize(scale: endScale) let startFromFace = Bool.random() var imageStartPosition: CGPoint = CGPoint.zero if startFromFace { let faceRectScaled = faceRect.applying(CGAffineTransform(scaleX: startScale, y: startScale)) imageStartPosition = animationCalculator.buildFacePosition(faceRect: faceRectScaled, imageSize: scaledStartImageSize, viewPortSize: viewPortSize) } else { imageStartPosition = animationCalculator.buildPinnedToEdgesPosition(imageSize: scaledStartImageSize, viewPortSize: viewPortSize) } var imageEndPosition: CGPoint = CGPoint.zero if !startFromFace { let faceRectScaled = faceRect.applying(CGAffineTransform(scaleX: endScale, y: endScale)) imageEndPosition = animationCalculator.buildFacePosition(faceRect: faceRectScaled, imageSize: scaledEndImageSize, viewPortSize: viewPortSize) } else { imageEndPosition = animationCalculator.buildOppositeAnglePosition(startPosition: imageStartPosition, imageSize: scaledEndImageSize, viewPortSize: viewPortSize) } let duration = animationCalculator.buildAnimationDuration() let imageStartState = ImageState(scale: startScale, position: imageStartPosition) let imageEndState = ImageState(scale: endScale, position: imageEndPosition) let imageTransition = ImageAnimation(startState: imageStartState, endState: imageEndState, duration: duration) return imageTransition } // MARK: - Private private func findFaceRect(image: UIImage) -> CGRect? { switch faceRecognitionMode { case .Group: return image.groupFacesRect() case .Biggest: return image.biggestFaceRect() } } }
mit
8be2fea63e4508aa3bba8803b37dfe50
38.62931
120
0.627583
5.76788
false
false
false
false
AcroMace/receptionkit
ReceptionKit/View Controllers/Visitor/VisitorViewController.swift
1
2769
// // VisitorViewController.swift // ReceptionKit // // Created by Andy Cho on 2015-04-24. // Copyright (c) 2015 Andy Cho. All rights reserved. // import UIKit class VisitorViewController: ReturnToHomeViewController, StackViewOrientable { // Name of the visitor set by VisitorAskNameViewController var visitorName: String? @IBOutlet weak var stackView: UIStackView! @IBOutlet weak var knowButton: UIButton! @IBOutlet weak var notKnowButton: UIButton! override func viewDidLoad() { super.viewDidLoad() knowButton.setAttributedTitle(ButtonFormatter.getAttributedString(icon: .iKnow, text: .iKnow), for: UIControlState()) knowButton.accessibilityLabel = Text.iKnow.accessibility() knowButton.titleLabel?.textAlignment = NSTextAlignment.center knowButton.titleEdgeInsets = UIEdgeInsets(top: 8, left: 16, bottom: 8, right: 16) notKnowButton.setAttributedTitle(ButtonFormatter.getAttributedString(icon: .iDontKnow, text: .iDontKnow), for: UIControlState()) notKnowButton.accessibilityLabel = Text.iDontKnow.accessibility() notKnowButton.titleLabel?.textAlignment = NSTextAlignment.center notKnowButton.titleEdgeInsets = UIEdgeInsets(top: 8, left: 16, bottom: 8, right: 16) setButtonVerticalAlignment(withDeviceDimensions: view.bounds.size) } // Reset the alignment of the text on rotation override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { setButtonVerticalAlignment(withDeviceDimensions: size) } // MARK: - Navigation // Should post message if the visitor does not know who they are looking for override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if let waitingViewController = segue.destination as? WaitingViewController { // Configure the view model let waitingViewModel = WaitingViewModel(shouldAskToWait: true) waitingViewController.configure(waitingViewModel) // We don't know the name of the person who just checked in guard let visitorName = visitorName, !visitorName.isEmpty else { messageSender.send(message: .unknownVisitorUnknownVisitee()) doorbell.play() return } // We know the visitor's name but they don't know the person they're looking for messageSender.send(message: .knownVisitorUnknownVisitee(visitorName: visitorName)) doorbell.play() } else if let visitorSearchViewController = segue.destination as? VisitorSearchViewController { visitorSearchViewController.configure(VisitorSearchViewModel(visitorName: visitorName)) } } }
mit
0b2b0cd68ea03ebf27f9594e02dde2e3
41.6
136
0.711087
4.980216
false
false
false
false
overtake/TelegramSwift
Telegram-Mac/EmojiesController.swift
1
71138
// // EmojiesController.swift // Telegram // // Created by Mike Renoir on 30.05.2022. // Copyright © 2022 Telegram. All rights reserved. // import Foundation import TGUIKit import SwiftSignalKit import TelegramCore import InAppSettings import Postbox //private final class WarpView: View { // private final class WarpPartView: View { // let cloneView: PortalView // // init?(contentView: PortalSourceView) { // guard let cloneView = PortalView(matchPosition: false) else { // return nil // } // self.cloneView = cloneView // // super.init(frame: CGRect()) // // self.layer.anchorPoint = CGPoint(x: 0.5, y: 0.0) // // self.clipsToBounds = true // self.addSubview(cloneView.view) // contentView.addPortal(view: cloneView) // } // // required init?(coder: NSCoder) { // fatalError("init(coder:) has not been implemented") // } // // func update(containerSize: CGSize, rect: CGRect, transition: Transition) { // transition.setFrame(view: self.cloneView.view, frame: CGRect(origin: CGPoint(x: -rect.minX, y: -rect.minY), size: CGSize(width: containerSize.width, height: containerSize.height))) // } // } // // let contentView: PortalSourceView // // private let clippingView: UIView // private let overlayView: UIView // // private var warpViews: [WarpPartView] = [] // // override init(frame: CGRect) { // self.contentView = PortalSourceView() // self.clippingView = UIView() // self.overlayView = UIView() // // super.init(frame: frame) // // self.clippingView.addSubview(self.contentView) // // self.clippingView.clipsToBounds = false // self.addSubview(self.clippingView) // // self.addSubview(self.overlayView) // // for _ in 0 ..< 8 { // if let warpView = WarpPartView(contentView: self.contentView) { // self.warpViews.append(warpView) // self.addSubview(warpView) // } // } // } // // required init?(coder: NSCoder) { // fatalError("init(coder:) has not been implemented") // } // // func update(size: CGSize, topInset: CGFloat, warpHeight: CGFloat, theme: PresentationTheme, transition: Transition) { // transition.setFrame(view: self.contentView, frame: CGRect(origin: CGPoint(), size: size)) // // let frame = CGRect(origin: CGPoint(x: 0.0, y: -topInset), size: CGSize(width: size.width, height: size.height + topInset - warpHeight)) // transition.setPosition(view: self.clippingView, position: frame.center) // transition.setBounds(view: self.clippingView, bounds: CGRect(origin: CGPoint(x: 0.0, y: -topInset + (topInset - warpHeight) * 0.5), size: size)) // // let allItemsHeight = warpHeight * 0.5 // for i in 0 ..< self.warpViews.count { // let itemHeight = warpHeight / CGFloat(self.warpViews.count) // let itemFraction = CGFloat(i + 1) / CGFloat(self.warpViews.count) // let _ = itemHeight // // let da = CGFloat.pi * 0.5 / CGFloat(self.warpViews.count) // let alpha = CGFloat.pi * 0.5 - itemFraction * CGFloat.pi * 0.5 // let endPoint = CGPoint(x: cos(alpha), y: sin(alpha)) // let prevAngle = alpha + da // let prevPt = CGPoint(x: cos(prevAngle), y: sin(prevAngle)) // var angle: CGFloat // angle = -atan2(endPoint.y - prevPt.y, endPoint.x - prevPt.x) // // let itemLengthVector = CGPoint(x: endPoint.x - prevPt.x, y: endPoint.y - prevPt.y) // let itemLength = sqrt(itemLengthVector.x * itemLengthVector.x + itemLengthVector.y * itemLengthVector.y) * warpHeight * 0.5 // let _ = itemLength // // var transform: CATransform3D // transform = CATransform3DIdentity // transform.m34 = 1.0 / 240.0 // // transform = CATransform3DTranslate(transform, 0.0, prevPt.x * allItemsHeight, (1.0 - prevPt.y) * allItemsHeight) // transform = CATransform3DRotate(transform, angle, 1.0, 0.0, 0.0) // // //self.warpViews[i].backgroundColor = UIColor(red: 0.0, green: 0.0, blue: CGFloat(i) / CGFloat(self.warpViews.count - 1), alpha: 1.0) // //self.warpViews[i].backgroundColor = UIColor(white: 0.0, alpha: 0.5) // //self.warpViews[i].backgroundColor = theme.list.plainBackgroundColor // // let positionY = size.height - allItemsHeight + 4.0 + /*warpHeight * cos(alpha)*/ CGFloat(i) * itemLength // let rect = CGRect(origin: CGPoint(x: 0.0, y: positionY), size: CGSize(width: size.width, height: itemLength)) // transition.setPosition(view: self.warpViews[i], position: CGPoint(x: rect.midX, y: size.height - allItemsHeight + 4.0)) // transition.setBounds(view: self.warpViews[i], bounds: CGRect(origin: CGPoint(), size: CGSize(width: size.width, height: itemLength))) // transition.setTransform(view: self.warpViews[i], transform: transform) // self.warpViews[i].update(containerSize: size, rect: rect, transition: transition) // } // // self.overlayView.backgroundColor = theme.list.plainBackgroundColor // transition.setFrame(view: self.overlayView, frame: CGRect(origin: CGPoint(x: 0.0, y: size.height - allItemsHeight + 4.0), size: CGSize(width: size.width, height: allItemsHeight))) // } // // override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? { // return self.contentView.hitTest(point, with: event) // } //} private extension RecentReactionItem.Content { var reaction: MessageReaction.Reaction { switch self { case let .custom(file): return .custom(file.fileId.id) case let .builtin(emoji): return .builtin(emoji) } } } enum EmojiSegment : Int64, Comparable { case RecentAnimated = 100 case Recent = 0 case People = 1 case AnimalsAndNature = 2 case FoodAndDrink = 3 case ActivityAndSport = 4 case TravelAndPlaces = 5 case Objects = 6 case Symbols = 7 case Flags = 8 var localizedString: String { switch self { case .RecentAnimated: return strings().emojiRecent case .Recent: return strings().emojiRecentNew case .People: return strings().emojiSmilesAndPeople case .AnimalsAndNature: return strings().emojiAnimalsAndNature case .FoodAndDrink: return strings().emojiFoodAndDrink case .ActivityAndSport: return strings().emojiActivityAndSport case .TravelAndPlaces: return strings().emojiTravelAndPlaces case .Objects: return strings().emojiObjects case .Symbols: return strings().emojiSymbols case .Flags: return strings().emojiFlags } } static var all: [EmojiSegment] { return [.People, .AnimalsAndNature, .FoodAndDrink, .ActivityAndSport, .TravelAndPlaces, .Objects, .Symbols, .Flags] } var hashValue:Int { return Int(self.rawValue) } } func ==(lhs:EmojiSegment, rhs:EmojiSegment) -> Bool { return lhs.rawValue == rhs.rawValue } func <(lhs:EmojiSegment, rhs:EmojiSegment) -> Bool { return lhs.rawValue < rhs.rawValue } let emojiesInstance:[EmojiSegment:[String]] = { assertNotOnMainThread() var local:[EmojiSegment:[String]] = [EmojiSegment:[String]]() let resource:URL? if #available(OSX 11.1, *) { resource = Bundle.main.url(forResource:"emoji1016", withExtension:"txt") } else if #available(OSX 10.14.1, *) { resource = Bundle.main.url(forResource:"emoji1014-1", withExtension:"txt") } else if #available(OSX 10.12, *) { resource = Bundle.main.url(forResource:"emoji", withExtension:"txt") } else { resource = Bundle.main.url(forResource:"emoji11", withExtension:"txt") } if let resource = resource { var file:String = "" do { file = try String(contentsOf: resource) } catch { print("emoji file not loaded") } let segments = file.components(separatedBy: "\n\n") for segment in segments { let list = segment.components(separatedBy: " ") if let value = EmojiSegment(rawValue: Int64(local.count + 1)) { local[value] = list } } } return local }() private func segments(_ emoji: [EmojiSegment : [String]], skinModifiers: [EmojiSkinModifier]) -> [EmojiSegment:[[NSAttributedString]]] { var segments:[EmojiSegment:[[NSAttributedString]]] = [:] for (key,list) in emoji { var line:[NSAttributedString] = [] var lines:[[NSAttributedString]] = [] var i = 0 for emoji in list { var e:String = emoji.emojiUnmodified for modifier in skinModifiers { if e == modifier.emoji { if e.length == 5 { let mutable = NSMutableString() mutable.insert(e, at: 0) mutable.insert(modifier.modifier, at: 2) e = mutable as String } else { e = e + modifier.modifier } } } if !line.contains(where: {$0.string == String(e.first!) }), let first = e.first { if String(first).length > 1 { line.append(.initialize(string: String(first), font: .normal(26.0))) i += 1 } } if i == 8 { lines.append(line) line.removeAll() i = 0 } } if line.count > 0 { lines.append(line) } if lines.count > 0 { segments[key] = lines } } return segments } private final class Arguments { let context: AccountContext let mode: EmojiesController.Mode let send:(StickerPackItem, StickerPackCollectionInfo?, Int32?, NSRect?)->Void let sendEmoji:(String, NSRect)->Void let selectEmojiSegment:(EmojiSegment)->Void let viewSet:(StickerPackCollectionInfo)->Void let showAllItems:(Int64)->Void let openPremium:()->Void let installPack:(StickerPackCollectionInfo, [StickerPackItem])->Void let clearRecent:()->Void init(context: AccountContext, mode: EmojiesController.Mode, send:@escaping(StickerPackItem, StickerPackCollectionInfo?, Int32?, NSRect?)->Void, sendEmoji:@escaping(String, NSRect)->Void, selectEmojiSegment:@escaping(EmojiSegment)->Void, viewSet:@escaping(StickerPackCollectionInfo)->Void, showAllItems:@escaping(Int64)->Void, openPremium:@escaping()->Void, installPack:@escaping(StickerPackCollectionInfo, [StickerPackItem])->Void, clearRecent:@escaping()->Void) { self.context = context self.send = send self.sendEmoji = sendEmoji self.selectEmojiSegment = selectEmojiSegment self.viewSet = viewSet self.showAllItems = showAllItems self.openPremium = openPremium self.installPack = installPack self.mode = mode self.clearRecent = clearRecent } } private struct State : Equatable { struct EmojiState : Equatable { var selected: EmojiSegment? } struct Section : Equatable { var info: StickerPackCollectionInfo var items:[StickerPackItem] var dict:[MediaId: StickerPackItem] var installed: Bool } var sections:[Section] var peer: PeerEquatable? var emojiState: EmojiState = .init(selected: nil) var revealed:[Int64: Bool] = [:] var search: [String]? = nil var reactions: AvailableReactions? = nil var recentStatusItems: [RecentMediaItem] = [] var forumTopicItems: [StickerPackItem] = [] var featuredStatusItems: [RecentMediaItem] = [] var recentReactionsItems: [RecentReactionItem] = [] var topReactionsItems: [RecentReactionItem] = [] var recent: RecentUsedEmoji = .defaultSettings var reactionSettings: ReactionSettings = .default var iconStatusEmoji: [TelegramMediaFile] = [] var selectedItems: [EmojiesSectionRowItem.SelectedItem] struct ExternalTopic: Equatable { let title: String let iconColor: Int32 } var externalTopic: ExternalTopic = .init(title: "", iconColor: 0) } private func _id_section(_ id:Int64) -> InputDataIdentifier { return .init("_id_section_\(id)") } private func _id_pack(_ id: Int64) -> InputDataIdentifier { return .init("_id_pack_\(id)") } private func _id_emoji_segment(_ segment:Int64) -> InputDataIdentifier { return .init("_id_emoji_segment_\(segment)") } private func _id_aemoji_block(_ segment:Int64) -> InputDataIdentifier { return .init("_id_aemoji_block\(segment)") } private func _id_emoji_block(_ segment: Int64) -> InputDataIdentifier { return .init("_id_emoji_block_\(segment)") } private let _id_segments_pack = InputDataIdentifier("_id_segments_pack") private let _id_recent_pack = InputDataIdentifier("_id_recent_pack") private func packEntries(_ state: State, arguments: Arguments) -> [InputDataEntry] { var entries:[InputDataEntry] = [] var index: Int32 = 0 var sectionId:Int32 = 0 entries.append(.custom(sectionId: sectionId, index: index, value: .none, identifier: .init("left"), equatable: nil, comparable: nil, item: { initialSize, stableId in return GeneralRowItem(initialSize, height: 6, stableId: stableId, backgroundColor: .clear) })) index += 1 let hasRecent: Bool switch arguments.mode { case .status: hasRecent = !state.recentStatusItems.isEmpty || !state.featuredStatusItems.isEmpty case .emoji: hasRecent = true case .reactions: hasRecent = !state.recentReactionsItems.isEmpty || !state.topReactionsItems.isEmpty case .selectAvatar: hasRecent = true case .forumTopic: hasRecent = true } if hasRecent { entries.append(.custom(sectionId: sectionId, index: index, value: .none, identifier: _id_recent_pack, equatable: nil, comparable: nil, item: { initialSize, stableId in return ETabRowItem(initialSize, stableId: stableId, icon: theme.icons.emojiRecentTab, iconSelected: theme.icons.emojiRecentTabActive) })) index += 1 } if arguments.mode == .emoji { entries.append(.custom(sectionId: sectionId, index: index, value: .none, identifier: _id_segments_pack, equatable: InputDataEquatable(state.emojiState), comparable: nil, item: { initialSize, stableId in return EmojiTabsItem(initialSize, stableId: stableId, segments: EmojiSegment.all, selected: state.emojiState.selected, select: arguments.selectEmojiSegment) })) index += 1 } for section in state.sections { let isPremium = section.items.contains(where: { $0.file.isPremiumEmoji }) entries.append(.custom(sectionId: sectionId, index: index, value: .none, identifier: _id_pack(section.info.id.id), equatable: InputDataEquatable(state), comparable: nil, item: { initialSize, stableId in return StickerPackRowItem(initialSize, stableId: stableId, packIndex: 0, isPremium: isPremium, installed: section.installed, context: arguments.context, info: section.info, topItem: section.items.first) })) index += 1 } entries.append(.custom(sectionId: sectionId, index: index, value: .none, identifier: .init("right"), equatable: nil, comparable: nil, item: { initialSize, stableId in return GeneralRowItem(initialSize, height: 6, stableId: stableId, backgroundColor: .clear) })) index += 1 return entries } private func entries(_ state: State, arguments: Arguments) -> [InputDataEntry] { var entries:[InputDataEntry] = [] var sectionId:Int32 = 0 var index: Int32 = 0 // entries.append(.sectionId(sectionId, type: .custom(10))) // sectionId += 1 if arguments.mode != .reactions { entries.append(.custom(sectionId: sectionId, index: index, value: .none, identifier: .init("search"), equatable: nil, comparable: nil, item: { initialSize, stableId in return GeneralRowItem(initialSize, height: 46, stableId: stableId, backgroundColor: .clear) })) index += 1 } else { entries.append(.custom(sectionId: sectionId, index: index, value: .none, identifier: .init("search"), equatable: nil, comparable: nil, item: { initialSize, stableId in return GeneralRowItem(initialSize, height: 10, stableId: stableId, backgroundColor: .clear) })) index += 1 } // entries.append(.sectionId(sectionId, type: .custom(46))) // sectionId += 1 var e = emojiesInstance e[EmojiSegment.Recent] = state.recent.emojies let seg = segments(e, skinModifiers: state.recent.skinModifiers) let seglist = seg.map { (key,_) -> EmojiSegment in return key }.sorted(by: <) let isPremium = state.peer?.peer.isPremium == true let recentDict:[MediaId: StickerPackItem] = state.sections.reduce([:], { current, value in return current + value.dict }) var recentAnimated:[StickerPackItem] = state.recent.animated.compactMap { mediaId in if let item = recentDict[mediaId] { if !item.file.isPremiumEmoji || isPremium { return item } } return nil } if arguments.mode == .forumTopic { let file = ForumUI.makeIconFile(title: state.externalTopic.title, iconColor: state.externalTopic.iconColor) recentAnimated.insert(.init(index: .init(index: 0, id: 0), file: file, indexKeys: []), at: 0) recentAnimated.append(contentsOf: state.forumTopicItems) } struct Tuple : Equatable { let items: [StickerPackItem] let selected: [EmojiesSectionRowItem.SelectedItem] } if let search = state.search { if !search.isEmpty { let lines: [[NSAttributedString]] = search.chunks(8).map { return $0.map { .initialize(string: $0, font: .normal(26.0)) } } if arguments.mode == .emoji { entries.append(.custom(sectionId: sectionId, index: index, value: .none, identifier: .init("search_e_stick"), equatable: InputDataEquatable(search), comparable: nil, item: { initialSize, stableId in return EStickItem(initialSize, stableId: stableId, segmentName: strings().emojiSearchEmoji) })) index += 1 entries.append(.custom(sectionId: sectionId, index: index, value: .none, identifier: .init("search_e"), equatable: InputDataEquatable(search), comparable: nil, item: { initialSize, stableId in return EBlockItem(initialSize, stableId: stableId, attrLines: lines, segment: .Recent, account: arguments.context.account, selectHandler: arguments.sendEmoji) })) index += 1 } var animatedEmoji:[StickerPackItem] = state.sections.reduce([], { current, value in return current + value.items.filter { item in for key in item.getStringRepresentationsOfIndexKeys() { if search.contains(key) { return true } } return false } }) let statuses = state.iconStatusEmoji + state.recentStatusItems.map { $0.media } + state.featuredStatusItems.map { $0.media } var contains:Set<MediaId> = Set() let normalized:[StickerPackItem] = statuses.filter { item in let text = item.customEmojiText ?? item.stickerText ?? "" if !contains.contains(item.fileId), search.contains(text) { contains.insert(item.fileId) return true } return false }.map { value in return StickerPackItem(index: .init(index: 0, id: 0), file: value, indexKeys: []) } for item in normalized { if !animatedEmoji.contains(where: { $0.file.fileId == item.file.fileId }) { animatedEmoji.append(item) } } if !animatedEmoji.isEmpty { entries.append(.custom(sectionId: sectionId, index: index, value: .none, identifier: .init("search_ae_stick"), equatable: InputDataEquatable(search), comparable: nil, item: { initialSize, stableId in return EStickItem(initialSize, stableId: stableId, segmentName: strings().emojiSearchAnimatedEmoji) })) index += 1 entries.append(.custom(sectionId: sectionId, index: index, value: .none, identifier: .init("search_ae"), equatable: InputDataEquatable(Tuple(items: animatedEmoji, selected: state.selectedItems)), comparable: nil, item: { initialSize, stableId in return EmojiesSectionRowItem(initialSize, stableId: stableId, context: arguments.context, revealed: true, installed: false, info: nil, items: animatedEmoji, mode: arguments.mode.itemMode, selectedItems: state.selectedItems, callback: arguments.send) })) index += 1 } else if arguments.mode == .status { entries.append(.custom(sectionId: sectionId, index: index, value: .none, identifier: .init("search_empty"), equatable: InputDataEquatable(state), comparable: nil, item: { initialSize, stableId in return SearchEmptyRowItem.init(initialSize, stableId: stableId) })) index += 1 } } else { entries.append(.custom(sectionId: sectionId, index: index, value: .none, identifier: .init("search_empty"), equatable: InputDataEquatable(state), comparable: nil, item: { initialSize, stableId in return SearchEmptyRowItem.init(initialSize, stableId: stableId) })) index += 1 } } else { for key in seglist { if key == .Recent, arguments.mode == .reactions { var reactionsRecent:[StickerPackItem] = [] var reactionsPopular:[StickerPackItem] = [] var recent:[RecentReactionItem] = [] var popular:[RecentReactionItem] = [] let perline: Int = 8 // if arguments.context.isPremium { let top = state.topReactionsItems.filter { value in if arguments.context.isPremium { return true } else { return !value.content.reaction.string.isEmpty } } popular = Array(top.prefix(perline * 2)) recent = state.recentReactionsItems for item in state.topReactionsItems { let recentContains = recent.contains(where: { $0.id.id == item.id.id }) let popularContains = popular.contains(where: { $0.id.id == item.id.id }) if !recentContains && !popularContains { if state.recentReactionsItems.isEmpty { switch item.content { case .builtin: recent.append(item) default: break } } else { recent.append(item) } } } if let reactions = state.reactions?.enabled { for reaction in reactions { let recentContains = recent.contains(where: { $0.content.reaction == reaction.value }) let popularContains = popular.contains(where: { $0.content.reaction == reaction.value }) if !recentContains && !popularContains { switch reaction.value { case let .builtin(emoji): recent.append(.init(.builtin(emoji))) default: break } } } } recent = Array(recent.prefix(perline * 10)) let transform:(RecentReactionItem)->StickerPackItem? = { item in switch item.content { case let .builtin(emoji): let builtin = state.reactions?.enabled.first(where: { $0.value.string == emoji }) if let builtin = builtin { return .init(index: .init(index: 0, id: 0), file: builtin.selectAnimation, indexKeys: []) } case let .custom(file): return .init(index: .init(index: -1, id: 0), file: file, indexKeys: []) } return nil } reactionsPopular.append(contentsOf: popular.compactMap(transform)) reactionsRecent.append(contentsOf: recent.compactMap(transform)) reactionsRecent = reactionsRecent.filter { item in return !reactionsPopular.contains(where: { $0.file.fileId == item.file.fileId }) } entries.append(.custom(sectionId: sectionId, index: index, value: .none, identifier: _id_emoji_block(EmojiSegment.RecentAnimated.rawValue), equatable: InputDataEquatable(Tuple(items: reactionsPopular, selected: state.selectedItems)), comparable: nil, item: { initialSize, stableId in return EmojiesSectionRowItem(initialSize, stableId: stableId, context: arguments.context, revealed: true, installed: true, info: nil, items: reactionsPopular, mode: arguments.mode.itemMode, selectedItems: state.selectedItems, callback: arguments.send) })) index += 1 if !reactionsRecent.isEmpty { let containsCustom = reactionsRecent.contains(where: { $0.index.index == -1 }) if containsCustom { let text = strings().reactionsRecentlyUsed entries.append(.custom(sectionId: sectionId, index: index, value: .none, identifier: _id_emoji_segment(-1), equatable: InputDataEquatable(text), comparable: nil, item: { initialSize, stableId in return EStickItem(initialSize, stableId: stableId, segmentName: text, clearCallback: arguments.clearRecent) })) index += 1 } else { let text = strings().reactionsPopular entries.append(.custom(sectionId: sectionId, index: index, value: .none, identifier: _id_emoji_segment(-1), equatable: InputDataEquatable(text), comparable: nil, item: { initialSize, stableId in return EStickItem(initialSize, stableId: stableId, segmentName: text ) })) index += 1 } entries.append(.custom(sectionId: sectionId, index: index, value: .none, identifier: _id_emoji_block(-1), equatable: InputDataEquatable(Tuple(items: reactionsRecent, selected: state.selectedItems)), comparable: nil, item: { initialSize, stableId in return EmojiesSectionRowItem(initialSize, stableId: stableId, context: arguments.context, revealed: true, installed: true, info: nil, items: reactionsRecent, mode: arguments.mode.itemMode, selectedItems: state.selectedItems, callback: arguments.send) })) index += 1 } } let statuses = state.recentStatusItems.filter { !isDefaultStatusesPackId($0.media.emojiReference) } + state.featuredStatusItems var contains:Set<MediaId> = Set() var normalized:[StickerPackItem] = statuses.filter { item in if !contains.contains(item.media.fileId) { contains.insert(item.media.fileId) return true } return false }.map { value in return StickerPackItem(index: .init(index: 0, id: 0), file: value.media, indexKeys: []) } if key == .Recent, arguments.mode == .status { let string: String if let expiryDate = state.peer?.peer.emojiStatus?.expirationDate, expiryDate > arguments.context.timestamp { string = strings().customStatusExpires(timeIntervalString(Int(expiryDate - arguments.context.timestamp))) } else { string = strings().customStatusExpiresPromo } entries.append(.custom(sectionId: sectionId, index: index, value: .none, identifier: .init("_id_status_status"), equatable: .init(string), comparable: nil, item: { initialSize, stableId in return EmojiStatusStatusRowItem(initialSize, stableId: stableId, status: string.uppercased(), viewType: .textTopItem) })) index += 1 let def = TelegramMediaFile(fileId: .init(namespace: 0, id: 0), partialReference: nil, resource: LocalBundleResource(name: "Icon_Premium_StickerPack", ext: ""), previewRepresentations: [], videoThumbnails: [], immediateThumbnailData: nil, mimeType: "bundle/jpeg", size: nil, attributes: []) normalized.insert(.init(index: .init(index: 0, id: 0), file: def, indexKeys: []), at: 0) normalized.insert(contentsOf: state.iconStatusEmoji.prefix(7).map { .init(index: .init(index: 0, id: 0), file: $0, indexKeys: []) }, at: 1) struct Tuple : Equatable { let items: [StickerPackItem] let revealed: Bool let selected:[EmojiesSectionRowItem.SelectedItem] } let tuple = Tuple(items: Array(normalized.prefix(13 * 8)), revealed: state.revealed[-1] ?? false, selected: state.selectedItems) entries.append(.custom(sectionId: sectionId, index: index, value: .none, identifier: _id_emoji_block(EmojiSegment.RecentAnimated.rawValue), equatable: InputDataEquatable(tuple), comparable: nil, item: { initialSize, stableId in return EmojiesSectionRowItem(initialSize, stableId: stableId, context: arguments.context, revealed: tuple.revealed, installed: true, info: nil, items: tuple.items, mode: arguments.mode.itemMode, selectedItems: tuple.selected, callback: arguments.send, showAllItems: { arguments.showAllItems(-1) }) })) index += 1 } let hasAnimatedRecent = arguments.mode == .emoji || arguments.mode == .forumTopic || arguments.mode == .selectAvatar if key == .Recent, !recentAnimated.isEmpty, hasAnimatedRecent { entries.append(.custom(sectionId: sectionId, index: index, value: .none, identifier: _id_emoji_block(EmojiSegment.RecentAnimated.rawValue), equatable: InputDataEquatable(Tuple.init(items: recentAnimated, selected: state.selectedItems)), comparable: nil, item: { initialSize, stableId in return EmojiesSectionRowItem(initialSize, stableId: stableId, context: arguments.context, revealed: true, installed: true, info: nil, items: recentAnimated, mode: arguments.mode.itemMode, selectedItems: state.selectedItems, callback: arguments.send) })) index += 1 } if key != .Recent || !recentAnimated.isEmpty, arguments.mode == .emoji { entries.append(.custom(sectionId: sectionId, index: index, value: .none, identifier: _id_emoji_segment(key.rawValue), equatable: InputDataEquatable(key), comparable: nil, item: { initialSize, stableId in return EStickItem(initialSize, stableId: stableId, segmentName:key.localizedString) })) index += 1 } if arguments.mode == .emoji { entries.append(.custom(sectionId: sectionId, index: index, value: .none, identifier: _id_emoji_block(key.rawValue), equatable: InputDataEquatable(key), comparable: nil, item: { initialSize, stableId in return EBlockItem(initialSize, stableId: stableId, attrLines: seg[key]!, segment: key, account: arguments.context.account, selectHandler: arguments.sendEmoji) })) index += 1 } } for section in state.sections { entries.append(.custom(sectionId: sectionId, index: index, value: .none, identifier: _id_aemoji_block(section.info.id.id), equatable: InputDataEquatable(section.info), comparable: nil, item: { initialSize, stableId in return GeneralRowItem(initialSize, height: 10, stableId: stableId, backgroundColor: .clear) })) index += 1 struct Tuple : Equatable { let section: State.Section let isPremium: Bool let revealed: Bool let selectedItems:[EmojiesSectionRowItem.SelectedItem] } let tuple = Tuple(section: section, isPremium: state.peer?.peer.isPremium ?? false, revealed: state.revealed[section.info.id.id] != nil, selectedItems: state.selectedItems) entries.append(.custom(sectionId: sectionId, index: index, value: .none, identifier: _id_section(section.info.id.id), equatable: InputDataEquatable(tuple), comparable: nil, item: { initialSize, stableId in return EmojiesSectionRowItem(initialSize, stableId: stableId, context: arguments.context, revealed: tuple.revealed, installed: section.installed, info: section.info, items: section.items, mode: arguments.mode.itemMode, selectedItems: state.selectedItems, callback: arguments.send, viewSet: { info in arguments.viewSet(info) }, showAllItems: { arguments.showAllItems(section.info.id.id) }, openPremium: arguments.openPremium, installPack: arguments.installPack) })) index += 1 } } entries.append(.custom(sectionId: sectionId, index: index, value: .none, identifier: .init("bottom_section"), equatable: nil, comparable: nil, item: { initialSize, stableId in return GeneralRowItem(initialSize, height: 10, stableId: stableId, backgroundColor: .clear) })) index += 1 entries.append(.custom(sectionId: sectionId, index: index, value: .none, identifier: .init("bottom"), equatable: nil, comparable: nil, item: { initialSize, stableId in return GeneralRowItem(initialSize, height: 46, stableId: stableId, backgroundColor: .clear) })) index += 1 // entries // entries.append(.sectionId(sectionId, type: .normal)) // sectionId += 1 return entries } final class AnimatedEmojiesView : View { let tableView = TableView() let packsView = HorizontalTableView(frame: NSZeroRect) private let borderView = View() private let tabs = View() private let selectionView: View = View(frame: NSMakeRect(0, 0, 36, 36)) let searchView = SearchView(frame: .zero) private let searchContainer = View() private let searchBorder = View() private var mode: EmojiesController.Mode = .emoji required init(frame frameRect: NSRect) { super.init(frame: frameRect) self.packsView.getBackgroundColor = { .clear } self.tableView.getBackgroundColor = { .clear } addSubview(self.tableView) searchContainer.addSubview(searchView) searchContainer.addSubview(searchBorder) addSubview(searchContainer) tabs.addSubview(selectionView) tabs.addSubview(self.packsView) addSubview(self.borderView) addSubview(tabs) self.packsView.addScroll(listener: .init(dispatchWhenVisibleRangeUpdated: false, { [weak self] position in self?.updateSelectionState(animated: false) })) self.tableView.addScroll(listener: .init(dispatchWhenVisibleRangeUpdated: false, { [weak self] position in self?.updateScrollerSearch() })) self.layout() } override func layout() { super.layout() self.updateLayout(self.frame.size, transition: .immediate) } private func updateScrollerSearch() { self.updateLayout(self.frame.size, transition: .immediate) } func updateLayout(_ size: NSSize, transition: ContainedViewLayoutTransition) { let initial: CGFloat = searchState?.state == .Focus ? -46 : 0 transition.updateFrame(view: tabs, frame: NSMakeRect(0, initial, size.width, 46)) transition.updateFrame(view: packsView, frame: tabs.focus(NSMakeSize(size.width, 36))) transition.updateFrame(view: borderView, frame: NSMakeRect(0, tabs.frame.maxY, size.width, .borderSize)) let searchDest = tableView.rectOf(index: 0).minY + (tableView.clipView.destination?.y ?? tableView.documentOffset.y) transition.updateFrame(view: searchContainer, frame: NSMakeRect(0, min(max(tabs.frame.maxY - searchDest, 0), tabs.frame.maxY), size.width, 46)) transition.updateFrame(view: searchView, frame: searchContainer.focus(NSMakeSize(size.width - 16, 30))) transition.updateFrame(view: searchBorder, frame: NSMakeRect(0, searchContainer.frame.height - .borderSize, size.width, .borderSize)) transition.updateFrame(view: tableView, frame: NSMakeRect(0, tabs.frame.maxY, size.width, size.height)) let alpha: CGFloat = searchState?.state == .Focus && tableView.documentOffset.y > 0 ? 1 : 0 transition.updateAlpha(view: searchBorder, alpha: alpha) self.updateSelectionState(animated: transition.isAnimated) } override func viewDidEndLiveResize() { super.viewDidEndLiveResize() tableView.viewDidEndLiveResize() packsView.viewDidEndLiveResize() } override func updateLocalizationAndTheme(theme: PresentationTheme) { super.updateLocalizationAndTheme(theme: theme) self.backgroundColor = mode == .reactions ? .clear : theme.colors.background borderView.backgroundColor = mode == .reactions ? theme.colors.grayIcon.withAlphaComponent(0.1) : theme.colors.border tabs.backgroundColor = mode != .reactions ? theme.colors.background : .clear searchContainer.backgroundColor = theme.colors.background searchBorder.backgroundColor = theme.colors.border self.searchView.updateLocalizationAndTheme(theme: theme) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } private var searchState: SearchState? = nil func updateSearchState(_ searchState: SearchState, animated: Bool) { self.searchState = searchState let transition: ContainedViewLayoutTransition if animated { transition = .animated(duration: 0.2, curve: .easeOut) } else { transition = .immediate } self.updateLayout(self.frame.size, transition: transition) } func update(sections: TableUpdateTransition, packs: TableUpdateTransition, mode: EmojiesController.Mode) { self.mode = mode self.tableView.merge(with: sections) self.packsView.merge(with: packs) searchContainer.isHidden = mode == .reactions tableView.scrollerInsets = mode == .reactions ? .init() : .init(left: 0, right: 0, top: 46, bottom: 50) updateSelectionState(animated: packs.animated) updateLocalizationAndTheme(theme: theme) } func updateSelectionState(animated: Bool) { let transition: ContainedViewLayoutTransition if animated { transition = .animated(duration: 0.2, curve: .easeOut) } else { transition = .immediate } var animated = transition.isAnimated var item = packsView.selectedItem() if item == nil, packsView.count > 1 { item = packsView.item(at: 1) animated = false } guard let item = item else { return } let viewPoint = packsView.rectOf(item: item).origin let point = packsView.clipView.destination ?? packsView.contentOffset let rect = NSMakeRect(viewPoint.y - point.y, 5, item.height, packsView.frame.height) selectionView.layer?.cornerRadius = item.height == item.width && item.index != 1 ? .cornerRadius : item.width / 2 if mode == .reactions { selectionView.background = theme.colors.vibrant.mixedWith(NSColor(0x000000), alpha: 0.1) } else { selectionView.background = theme.colors.grayBackground.withAlphaComponent(item.height == item.width ? 1 : 0.9) } if animated { selectionView.layer?.animateCornerRadius() } transition.updateFrame(view: selectionView, frame: rect) } func scroll(to segment: EmojiSegment, animated: Bool) { // if let item = packsView.item(stableId: InputDataEntryId.custom(_id_segments_pack)) { // _ = self.packsView.select(item: item) // } let stableId = InputDataEntryId.custom(_id_emoji_segment(segment.rawValue)) tableView.scroll(to: .top(id: stableId, innerId: nil, animated: animated, focus: .init(focus: false), inset: 0)) updateSelectionState(animated: animated) } func findSegmentAndScroll(selected: TableRowItem, animated: Bool) -> EmojiSegment? { let stableId = selected.stableId as? InputDataEntryId var segment: EmojiSegment? if let identifier = stableId?.identifier { if identifier == _id_recent_pack { tableView.scroll(to: .up(animated)) } else if identifier == _id_segments_pack { segment = EmojiSegment.People let stableId = InputDataEntryId.custom(_id_emoji_segment(EmojiSegment.People.rawValue)) tableView.scroll(to: .top(id: stableId, innerId: nil, animated: animated, focus: .init(focus: false), inset: 0)) } else if identifier.identifier.hasPrefix("_id_pack_") { let collectionId = identifier.identifier.trimmingCharacters(in: CharacterSet(charactersIn: "1234567890").inverted) if let collectionId = Int64(collectionId) { let stableId = InputDataEntryId.custom(_id_aemoji_block(collectionId)) tableView.scroll(to: .top(id: stableId, innerId: nil, animated: animated, focus: .init(focus: false), inset: 0)) let packStableId = InputDataEntryId.custom(_id_pack(collectionId)) packsView.scroll(to: .center(id: packStableId, innerId: nil, animated: true, focus: .init(focus: false), inset: 0)) } } } updateSelectionState(animated: true) return segment } func selectBestPack() -> EmojiSegment? { guard tableView.count > 1, tableView.visibleRows().location != NSNotFound else { return nil } let stableId = tableView.item(at: max(1, tableView.visibleRows().location)).stableId var _stableId: AnyHashable? var _segment: EmojiSegment? if let stableId = stableId as? InputDataEntryId, let identifier = stableId.identifier { let identifier = identifier.identifier if identifier.hasPrefix("_id_emoji_segment_") || identifier.hasPrefix("_id_emoji_block_") { if let segmentId = Int64(identifier.suffix(1)), let segment = EmojiSegment(rawValue: segmentId) { switch segment { case .Recent, .RecentAnimated: _stableId = InputDataEntryId.custom(_id_recent_pack) default: _stableId = InputDataEntryId.custom(_id_segments_pack) } _segment = segment } } else if identifier.hasPrefix("_id_section_") { let collectionId = identifier.trimmingCharacters(in: CharacterSet(charactersIn: "1234567890").inverted) if let collectionId = Int64(collectionId) { _stableId = InputDataEntryId.custom(_id_pack(collectionId)) } } } if let stableId = _stableId, let item = packsView.item(stableId: stableId) { _ = self.packsView.select(item: item) self.packsView.scroll(to: .center(id: stableId, innerId: nil, animated: true, focus: .init(focus: false), inset: 0)) } updateSelectionState(animated: true) return _segment } func scroll(to info: StickerPackCollectionInfo, animated: Bool) { let item = self.packsView.item(stableId: InputDataEntryId.custom(_id_pack(info.id.id))) if let item = item { _ = self.packsView.select(item: item) self.packsView.scroll(to: .center(id: item.stableId, innerId: nil, animated: animated, focus: .init(focus: false), inset: 0)) self.tableView.scroll(to: .top(id: InputDataEntryId.custom(_id_aemoji_block(info.id.id)), innerId: nil, animated: animated, focus: .init(focus: false), inset: 0)) updateSelectionState(animated: animated) } } } final class EmojiesController : TelegramGenericViewController<AnimatedEmojiesView>, TableViewDelegate { private let disposable = MetaDisposable() private var interactions: EntertainmentInteractions? private weak var chatInteraction: ChatInteraction? private var updateState: (((State) -> State) -> Void)? = nil private var scrollOnAppear:(()->Void)? = nil var makeSearchCommand:((ESearchCommand)->Void)? private let searchValue = ValuePromise<SearchState>(.init(state: .None, request: nil)) private var searchState: SearchState = .init(state: .None, request: nil) { didSet { self.searchValue.set(searchState) } } private func updateSearchState(_ state: SearchState) { self.searchState = state if !state.request.isEmpty { self.makeSearchCommand?(.loading) } if self.isLoaded() == true { self.genericView.updateSearchState(state, animated: true) } } enum Mode { case emoji case status case reactions case selectAvatar case forumTopic var itemMode: EmojiesSectionRowItem.Mode { switch self { case .reactions: return .reactions case .status: return .statuses default: return .panel } } } private let mode: Mode var closeCurrent:(()->Void)? = nil var animateAppearance:(([TableRowItem])->Void)? = nil private let selectedItems: [EmojiesSectionRowItem.SelectedItem] init(_ context: AccountContext, mode: Mode = .emoji, selectedItems: [EmojiesSectionRowItem.SelectedItem] = []) { self.mode = mode self.selectedItems = selectedItems super.init(context) _frameRect = NSMakeRect(0, 0, 350, 300) self.bar = .init(height: 0) } deinit { disposable.dispose() } private func updatePackReorder(_ sections: [State.Section]) { let resortRange: NSRange = NSMakeRange(3, genericView.packsView.count - 4 - sections.filter { !$0.installed }.count) let context = self.context if resortRange.length > 0 { self.genericView.packsView.resortController = TableResortController(resortRange: resortRange, start: { _ in }, resort: { _ in }, complete: { fromIndex, toIndex in if fromIndex == toIndex { return } let fromSection = sections[fromIndex - resortRange.location] let toSection = sections[toIndex - resortRange.location] let referenceId: ItemCollectionId = toSection.info.id let _ = (context.account.postbox.transaction { transaction -> Void in var infos = transaction.getItemCollectionsInfos(namespace: Namespaces.ItemCollection.CloudEmojiPacks) var reorderInfo: ItemCollectionInfo? for i in 0 ..< infos.count { if infos[i].0 == fromSection.info.id { reorderInfo = infos[i].1 infos.remove(at: i) break } } if let reorderInfo = reorderInfo { var inserted = false for i in 0 ..< infos.count { if infos[i].0 == referenceId { if fromIndex < toIndex { infos.insert((fromSection.info.id, reorderInfo), at: i + 1) } else { infos.insert((fromSection.info.id, reorderInfo), at: i) } inserted = true break } } if !inserted { infos.append((fromSection.info.id, reorderInfo)) } addSynchronizeInstalledStickerPacksOperation(transaction: transaction, namespace: Namespaces.ItemCollection.CloudEmojiPacks, content: .sync, noDelay: false) transaction.replaceItemCollectionInfos(namespace: Namespaces.ItemCollection.CloudEmojiPacks, itemCollectionInfos: infos) } } |> deliverOnMainQueue).start(completed: { }) }) } else { self.genericView.packsView.resortController = nil } } override func viewDidLoad() { super.viewDidLoad() genericView.packsView.delegate = self let searchInteractions = SearchInteractions({ [weak self] state, _ in self?.updateSearchState(state) }, { [weak self] state in self?.updateSearchState(state) }) genericView.searchView.searchInteractions = searchInteractions let scrollToOnNextTransaction: Atomic<StickerPackCollectionInfo?> = Atomic(value: nil) let scrollToOnNextAppear: Atomic<StickerPackCollectionInfo?> = Atomic(value: nil) let context = self.context let mode = self.mode let actionsDisposable = DisposableSet() let initialState = State(sections: [], selectedItems: self.selectedItems) let statePromise = ValuePromise<State>(ignoreRepeated: true) let stateValue = Atomic(value: initialState) let updateState: ((State) -> State) -> Void = { f in statePromise.set(stateValue.modify (f)) } self.updateState = { f in updateState(f) } self.scrollOnAppear = { [weak self] in if let info = scrollToOnNextAppear.swap(nil) { self?.genericView.scroll(to: info, animated: false) } } let arguments = Arguments(context: context, mode: self.mode, send: { [weak self] item, info, timeout, rect in switch mode { case .emoji: if !context.isPremium && item.file.isPremiumEmoji, context.peerId != self?.chatInteraction?.peerId { showModalText(for: context.window, text: strings().emojiPackPremiumAlert, callback: { _ in showModal(with: PremiumBoardingController(context: context, source: .premium_stickers), for: context.window) }) } else { self?.interactions?.sendAnimatedEmoji(item, info, nil, rect) } _ = scrollToOnNextAppear.swap(info) case .status: self?.interactions?.sendAnimatedEmoji(item, nil, timeout, rect) default: self?.interactions?.sendAnimatedEmoji(item, nil, nil, rect) } }, sendEmoji: { [weak self] emoji, fromRect in self?.interactions?.sendEmoji(emoji, fromRect) }, selectEmojiSegment: { [weak self] segment in updateState { current in var current = current current.emojiState.selected = segment return current } self?.genericView.scroll(to: segment, animated: true) }, viewSet: { info in showModal(with: StickerPackPreviewModalController(context, peerId: nil, references: [.emoji(.name(info.shortName))]), for: context.window) }, showAllItems: { id in updateState { current in var current = current current.revealed[id] = true return current } }, openPremium: { [weak self] in showModal(with: PremiumBoardingController(context: context, source: .premium_emoji), for: context.window) self?.closeCurrent?() }, installPack: { info, items in _ = scrollToOnNextTransaction.swap(info) let signal = context.engine.stickers.addStickerPackInteractively(info: info, items: items) |> deliverOnMainQueue _ = signal.start() }, clearRecent: { _ = context.engine.stickers.clearRecentlyUsedReactions().start() }) let selectUpdater = { [weak self] in if self?.genericView.tableView.clipView.isAnimateScrolling == true { return } let innerSegment = self?.genericView.selectBestPack() updateState { current in var current = current current.emojiState.selected = innerSegment return current } } genericView.tableView.addScroll(listener: .init(dispatchWhenVisibleRangeUpdated: true, { position in selectUpdater() })) let search = self.searchValue.get() |> distinctUntilChanged(isEqual: { prev, new in return prev.request == new.request }) |> mapToSignal { state -> Signal<[String]?, NoError> in if state.request.isEmpty { return .single(nil) } else { return context.sharedContext.inputSource.searchEmoji(postbox: context.account.postbox, engine: context.engine, sharedContext: context.sharedContext, query: state.request, completeMatch: false, checkPrediction: false) |> map(Optional.init) |> delay(0.2, queue: .concurrentDefaultQueue()) } } let combined = statePromise.get() let signal:Signal<(sections: InputDataSignalValue, packs: InputDataSignalValue, state: State), NoError> = combined |> deliverOnResourceQueue |> map { state in let sections = InputDataSignalValue(entries: entries(state, arguments: arguments)) let packs = InputDataSignalValue(entries: packEntries(state, arguments: arguments)) return (sections: sections, packs: packs, state: state) } let previousSections: Atomic<[AppearanceWrapperEntry<InputDataEntry>]> = Atomic(value: []) let previousPacks: Atomic<[AppearanceWrapperEntry<InputDataEntry>]> = Atomic(value: []) let initialSize = self.atomicSize let onMainQueue: Atomic<Bool> = Atomic(value: false) let inputArguments = InputDataArguments(select: { _, _ in }, dataUpdated: { }) let transition: Signal<(sections: TableUpdateTransition, packs: TableUpdateTransition, state: State), NoError> = combineLatest(queue: .mainQueue(), appearanceSignal, signal) |> mapToQueue { appearance, state in let sectionEntries = state.sections.entries.map({AppearanceWrapperEntry(entry: $0, appearance: appearance)}) let packEntries = state.packs.entries.map({AppearanceWrapperEntry(entry: $0, appearance: appearance)}) let onMain = onMainQueue.swap(false) let sectionsTransition = prepareInputDataTransition(left: previousSections.swap(sectionEntries), right: sectionEntries, animated: state.sections.animated, searchState: state.sections.searchState, initialSize: initialSize.modify{$0}, arguments: inputArguments, onMainQueue: onMain) let packsTransition = prepareInputDataTransition(left: previousPacks.swap(packEntries), right: packEntries, animated: state.packs.animated, searchState: state.packs.searchState, initialSize: initialSize.modify{$0}, arguments: inputArguments, onMainQueue: onMain) return combineLatest(sectionsTransition, packsTransition) |> map { values in return (sections: values.0, packs: values.1, state: state.state) } } |> deliverOnMainQueue disposable.set(transition.start(next: { [weak self] values in self?.genericView.update(sections: values.sections, packs: values.packs, mode: mode) selectUpdater() if let info = scrollToOnNextTransaction.swap(nil) { self?.genericView.scroll(to: info, animated: false) } self?.updatePackReorder(values.state.sections) var visibleItems:[TableRowItem] = [] if self?.didSetReady == false { self?.genericView.packsView.enumerateVisibleItems(with: { item in visibleItems.append(item) return true }) self?.genericView.tableView.enumerateVisibleItems(with: { item in visibleItems.append(item) return true }) } self?.readyOnce() if !visibleItems.isEmpty { self?.animateAppearance?(visibleItems) } })) let updateSearchCommand:()->Void = { [weak self] in self?.makeSearchCommand?(.normal) } /* public static let CloudRecentStatusEmoji: Int32 = 17 public static let CloudFeaturedStatusEmoji: Int32 = 18 */ var orderedItemListCollectionIds: [Int32] = [] var iconStatusEmoji: Signal<[TelegramMediaFile], NoError> = .single([]) if mode == .status { orderedItemListCollectionIds.append(Namespaces.OrderedItemList.CloudFeaturedStatusEmoji) orderedItemListCollectionIds.append(Namespaces.OrderedItemList.CloudRecentStatusEmoji) iconStatusEmoji = context.engine.stickers.loadedStickerPack(reference: .iconStatusEmoji, forceActualized: false) |> map { result -> [TelegramMediaFile] in switch result { case let .result(_, items, _): return items.map(\.file) default: return [] } } |> take(1) } else if mode == .reactions { orderedItemListCollectionIds.append(Namespaces.OrderedItemList.CloudRecentReactions) orderedItemListCollectionIds.append(Namespaces.OrderedItemList.CloudTopReactions) } else if mode == .forumTopic { } let emojies = context.account.postbox.itemCollectionsView(orderedItemListCollectionIds: orderedItemListCollectionIds, namespaces: [Namespaces.ItemCollection.CloudEmojiPacks], aroundIndex: nil, count: 2000000) let forumTopic: Signal<[StickerPackItem], NoError> if mode == .forumTopic { forumTopic = context.engine.stickers.loadedStickerPack(reference: .iconTopicEmoji, forceActualized: false) |> map { result in switch result { case let .result(_, items, _): return items default: return [] } } } else { forumTopic = .single([]) } let reactions = context.reactions.stateValue let reactionSettings = context.account.postbox.preferencesView(keys: [PreferencesKeys.reactionSettings]) |> map { preferencesView -> ReactionSettings in let reactionSettings: ReactionSettings if let entry = preferencesView.values[PreferencesKeys.reactionSettings], let value = entry.get(ReactionSettings.self) { reactionSettings = value } else { reactionSettings = .default } return reactionSettings } actionsDisposable.add(combineLatest(emojies, context.account.viewTracker.featuredEmojiPacks(), context.account.postbox.peerView(id: context.peerId), search, reactions, recentUsedEmoji(postbox: context.account.postbox), reactionSettings, iconStatusEmoji, forumTopic).start(next: { view, featured, peerView, search, reactions, recentEmoji, reactionSettings, iconStatusEmoji, forumTopic in var featuredStatusEmoji: OrderedItemListView? var recentStatusEmoji: OrderedItemListView? var recentReactionsView: OrderedItemListView? var topReactionsView: OrderedItemListView? for orderedView in view.orderedItemListsViews { if orderedView.collectionId == Namespaces.OrderedItemList.CloudFeaturedStatusEmoji { featuredStatusEmoji = orderedView } else if orderedView.collectionId == Namespaces.OrderedItemList.CloudRecentStatusEmoji { recentStatusEmoji = orderedView } else if orderedView.collectionId == Namespaces.OrderedItemList.CloudRecentReactions { recentReactionsView = orderedView } else if orderedView.collectionId == Namespaces.OrderedItemList.CloudTopReactions { topReactionsView = orderedView } } var recentStatusItems:[RecentMediaItem] = [] var featuredStatusItems:[RecentMediaItem] = [] var recentReactionsItems:[RecentReactionItem] = [] var topReactionsItems:[RecentReactionItem] = [] if let recentStatusEmoji = recentStatusEmoji { for item in recentStatusEmoji.items { guard let item = item.contents.get(RecentMediaItem.self) else { continue } recentStatusItems.append(item) } } if let featuredStatusEmoji = featuredStatusEmoji { for item in featuredStatusEmoji.items { guard let item = item.contents.get(RecentMediaItem.self) else { continue } featuredStatusItems.append(item) } } if let recentReactionsView = recentReactionsView { for item in recentReactionsView.items { guard let item = item.contents.get(RecentReactionItem.self) else { continue } recentReactionsItems.append(item) } } if let topReactionsView = topReactionsView { for item in topReactionsView.items { guard let item = item.contents.get(RecentReactionItem.self) else { continue } topReactionsItems.append(item) } } updateState { current in var current = current var sections: [State.Section] = [] for (_, info, _) in view.collectionInfos { var files: [StickerPackItem] = [] var dict: [MediaId: StickerPackItem] = [:] if let info = info as? StickerPackCollectionInfo { let items = view.entries for (i, entry) in items.enumerated() { if entry.index.collectionId == info.id { if let item = view.entries[i].item as? StickerPackItem { files.append(item) dict[item.file.fileId] = item } } } if !files.isEmpty { sections.append(.init(info: info, items: files, dict: dict, installed: true)) } } } for item in featured { let contains = sections.contains(where: { $0.info.id == item.info.id }) if !contains { let dict = item.topItems.toDictionary(with: { $0.file.fileId }) sections.append(.init(info: item.info, items: item.topItems, dict: dict, installed: false)) } } if let peer = peerView.peers[peerView.peerId] { current.peer = .init(peer) } current.featuredStatusItems = featuredStatusItems current.recentStatusItems = recentStatusItems current.forumTopicItems = forumTopic current.sections = sections current.search = search current.reactions = reactions current.recent = recentEmoji current.topReactionsItems = topReactionsItems current.recentReactionsItems = recentReactionsItems current.reactionSettings = reactionSettings current.iconStatusEmoji = iconStatusEmoji return current } DispatchQueue.main.async { updateSearchCommand() } })) self.onDeinit = { actionsDisposable.dispose() _ = previousSections.swap([]) _ = previousPacks.swap([]) } } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.scrollOnAppear?() } func update(with interactions:EntertainmentInteractions?, chatInteraction: ChatInteraction) { self.interactions = interactions self.chatInteraction = chatInteraction } func findGroupStableId(for stableId: AnyHashable) -> AnyHashable? { return nil } func isSelectable(row: Int, item: TableRowItem) -> Bool { return true } func selectionWillChange(row: Int, item: TableRowItem, byClick: Bool) -> Bool { return !(item is GeneralRowItem) } func selectionDidChange(row:Int, item:TableRowItem, byClick:Bool, isNew:Bool) { if byClick { let segment = genericView.findSegmentAndScroll(selected: item, animated: true) updateState? { current in var current = current current.emojiState.selected = segment return current } } } func setExternalForumTitle(_ title: String, iconColor: Int32 = 0, selectedItem: EmojiesSectionRowItem.SelectedItem? = nil) { updateState? { current in var current = current current.externalTopic = .init(title: title, iconColor: iconColor) if let selectedItem = selectedItem { current.selectedItems = [selectedItem] } else { current.selectedItems = [] } return current } } func setSelectedItem(_ selectedItem: EmojiesSectionRowItem.SelectedItem? = nil) { updateState? { current in var current = current if let selectedItem = selectedItem { current.selectedItems = [selectedItem] } else { current.selectedItems = [] } return current } } override func scrollup(force: Bool = false) { genericView.tableView.scroll(to: .up(true)) } override var supportSwipes: Bool { return !genericView.packsView._mouseInside() } }
gpl-2.0
fdfba19a42a6fe1f42819f85faf40f02
43.322118
469
0.579797
4.882765
false
false
false
false
jeden/kocomojo-kit
KocomojoApp/KocomojoApp/ui/controllers/PlansController.swift
1
3004
// // PlansController.swift // KocomojoApp // // Created by Antonio Bello on 1/27/15. // Copyright (c) 2015 Elapsus. All rights reserved. // import UIKit import Foundation import KocomojoKit class PlansController: UITableViewController { private lazy var servicesManager = ServicesManager.instance private var entities: [Plan]! } /// MARK: - Lifecycle extension PlansController { override func viewDidLoad() { super.viewDidLoad() self.title = "generic.plans.label".localized loadEntities() } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { switch segue.identifier { case .Some("show-features"): if let indexPath = self.tableView.indexPathForSelectedRow() { let plan = self.entities[indexPath.row] let vc = segue.destinationViewController as PlanFeaturesController vc.configure(plan.features.sorted(<)) } default: break } } } /// MARK: - UITableViewDelegate extension PlansController : UITableViewDelegate { override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { self.performSegueWithIdentifier("show-features", sender: self) } } /// MARK: - UITableViewDataSource extension PlansController : UITableViewDataSource { override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.entities != nil ? self.entities.count : 0 } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cellIdentifier = "plan-cell" let cell = self.tableView.dequeueReusableCellWithIdentifier(cellIdentifier) as? UITableViewCell ?? UITableViewCell(style: .Subtitle, reuseIdentifier: cellIdentifier) let plan = self.entities[indexPath.row] let price = NSString(format: "%.2f", plan.monthlyFee) cell.textLabel?.text = "\(plan.name) (\(price))" cell.detailTextLabel?.text = "\(plan.description) (\(plan.nickName))" cell.backgroundColor = plan.recommended ? UIColor(red: 0.8, green: 0.96, blue: 0.8, alpha: 1.0) : UIColor.whiteColor() cell.accessoryType = .DisclosureIndicator return cell } } /// MARK: - Internals extension PlansController { private func loadEntities() { self.showProgress() self.servicesManager.getPlans { result in switch(result) { case .Error(let error): println(error.localizedDescription) case .Value(let plans): self.entities = plans() dispatch_async(dispatch_get_main_queue()) { self.tableView.reloadData() } } self.hideProgress() } } }
mit
ad6e6410b5e4765e3cd0f20fa8d16800
30.631579
173
0.645806
4.91653
false
false
false
false
zimcherDev/ios
Zimcher/UIKit Objects/UI Helpers/CustomUIElement/TextFieldWithPlaceholderAlignment.swift
1
1126
import UIKit import Foundation protocol TextFieldWithPlaceholderAlignment: UITextFieldDelegate { var placeholderAlignment: NSTextAlignment {get set} var editingTextAlignment: NSTextAlignment {get set} } extension TextFieldWithPlaceholderAlignment { func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool { let isEmpty = range.length == (textField.text ?? "" as NSString).length && range.location == 0 && (string as NSString).length == 0 textField.textAlignment = isEmpty ? placeholderAlignment : editingTextAlignment return true } } class TextField: UITextField{ var placeholderAlignment: NSTextAlignment = NSTextAlignment.Left //var editingTextAlignment: NSTextAlignment = NSTextAlignment.Right { didSet { textAlignment = placeholderAlignment } } override func drawPlaceholderInRect(rect: CGRect) { let style = NSMutableParagraphStyle() style.alignment = placeholderAlignment style.lineBreakMode = .ByTruncatingTail } }
apache-2.0
6391b1300a976b45c1746fe30491ae8a
36.566667
132
0.720249
5.864583
false
false
false
false
taichisocks/taichiOSX
taichiOSX/swifter/Socket.swift
3
4152
// // Socket.swift // Swifter // Copyright (c) 2014 Damian Kołakowski. All rights reserved. // import Foundation /* Low level routines for POSIX sockets */ struct Socket { static func lastErr(reason: String) -> NSError { let errorCode = errno if let errorText = String.fromCString(UnsafePointer(strerror(errorCode))) { return NSError(domain: "SOCKET", code: Int(errorCode), userInfo: [NSLocalizedFailureReasonErrorKey : reason, NSLocalizedDescriptionKey : errorText]) } return NSError(domain: "SOCKET", code: Int(errorCode), userInfo: nil) } static func tcpForListen(port: in_port_t = 8080, error:NSErrorPointer = nil) -> CInt? { let s = socket(AF_INET, SOCK_STREAM, 0) if ( s == -1 ) { if error != nil { error.memory = lastErr("socket(...) failed.") } return nil } var value: Int32 = 1; if ( setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &value, socklen_t(sizeof(Int32))) == -1 ) { release(s) if error != nil { error.memory = lastErr("setsockopt(...) failed.") } return nil } nosigpipe(s) var addr = sockaddr_in(sin_len: __uint8_t(sizeof(sockaddr_in)), sin_family: sa_family_t(AF_INET), sin_port: port_htons(port), sin_addr: in_addr(s_addr: inet_addr("0.0.0.0")), sin_zero: (0, 0, 0, 0, 0, 0, 0, 0)) var sock_addr = sockaddr(sa_len: 0, sa_family: 0, sa_data: (0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)) memcpy(&sock_addr, &addr, Int(sizeof(sockaddr_in))) if ( bind(s, &sock_addr, socklen_t(sizeof(sockaddr_in))) == -1 ) { release(s) if error != nil { error.memory = lastErr("bind(...) failed.") } return nil } if ( listen(s, 20 /* max pending connection */ ) == -1 ) { release(s) if error != nil { error.memory = lastErr("listen(...) failed.") } return nil } return s } static func writeUTF8(socket: CInt, string: String, error: NSErrorPointer = nil) -> Bool { if let nsdata = string.dataUsingEncoding(NSUTF8StringEncoding) { writeData(socket, data: nsdata, error: error) } return true } static func writeASCII(socket: CInt, string: String, error: NSErrorPointer = nil) -> Bool { if let nsdata = string.dataUsingEncoding(NSASCIIStringEncoding) { writeData(socket, data: nsdata, error: error) } return true } static func writeData(socket: CInt, data: NSData, error:NSErrorPointer = nil) -> Bool { var sent = 0 let unsafePointer = UnsafePointer<UInt8>(data.bytes) while ( sent < data.length ) { let s = write(socket, unsafePointer + sent, Int(data.length - sent)) if ( s <= 0 ) { if error != nil { error.memory = lastErr("write(...) failed.") } return false } sent += s } return true } static func acceptClientSocket(socket: CInt, error:NSErrorPointer = nil) -> CInt? { var addr = sockaddr(sa_len: 0, sa_family: 0, sa_data: (0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)), len: socklen_t = 0 let clientSocket = accept(socket, &addr, &len) if ( clientSocket != -1 ) { Socket.nosigpipe(clientSocket) return clientSocket } if error != nil { error.memory = lastErr("accept(...) failed.") } return nil } static func nosigpipe(socket: CInt) { // prevents crashes when blocking calls are pending and the app is paused ( via Home button ) var no_sig_pipe: Int32 = 1; setsockopt(socket, SOL_SOCKET, SO_NOSIGPIPE, &no_sig_pipe, socklen_t(sizeof(Int32))); } static func port_htons(port: in_port_t) -> in_port_t { let isLittleEndian = Int(OSHostByteOrder()) == OSLittleEndian return isLittleEndian ? _OSSwapInt16(port) : port } static func release(socket: CInt) { shutdown(socket, SHUT_RDWR) close(socket) } }
apache-2.0
4dd1eeadedcccbab497a692abf689667
38.160377
160
0.562997
3.847081
false
false
false
false
ps2/rileylink_ios
OmniKit/OmnipodCommon/FaultEventCode.swift
1
21608
// // FaultEventCode.swift // OmniKit // // Created by Pete Schwamb on 9/28/18. // Copyright © 2018 Pete Schwamb. All rights reserved. // import Foundation public struct FaultEventCode: CustomStringConvertible, Equatable { public let rawValue: UInt8 public enum FaultEventType: UInt8 { case noFaults = 0x00 case failedFlashErase = 0x01 case failedFlashStore = 0x02 case tableCorruptionBasalSubcommand = 0x03 case corruptionByte720 = 0x05 case dataCorruptionInTestRTCInterrupt = 0x06 case rtcInterruptHandlerInconsistentState = 0x07 case valueGreaterThan8 = 0x08 case bf0notEqualToBF1 = 0x0A case tableCorruptionTempBasalSubcommand = 0x0B case resetDueToCOP = 0x0D case resetDueToIllegalOpcode = 0x0E case resetDueToIllegalAddress = 0x0F case resetDueToSAWCOP = 0x10 case corruptionInByte_866 = 0x11 case resetDueToLVD = 0x12 case messageLengthTooLong = 0x13 case occluded = 0x14 case corruptionInWord129 = 0x15 case corruptionInByte868 = 0x16 case corruptionInAValidatedTable = 0x17 case reservoirEmpty = 0x18 case badPowerSwitchArrayValue1 = 0x19 case badPowerSwitchArrayValue2 = 0x1A case badLoadCnthValue = 0x1B case exceededMaximumPodLife80Hrs = 0x1C case badStateCommand1AScheduleParse = 0x1D case unexpectedStateInRegisterUponReset = 0x1E case wrongSummaryForTable129 = 0x1F case validateCountErrorWhenBolusing = 0x20 case badTimerVariableState = 0x21 case unexpectedRTCModuleValueDuringReset = 0x22 case problemCalibrateTimer = 0x23 case rtcInterruptHandlerUnexpectedCall = 0x26 case missing2hourAlertToFillTank = 0x27 case faultEventSetupPod = 0x28 case errorMainLoopHelper0 = 0x29 case errorMainLoopHelper1 = 0x2A case errorMainLoopHelper2 = 0x2B case errorMainLoopHelper3 = 0x2C case errorMainLoopHelper4 = 0x2D case errorMainLoopHelper5 = 0x2E case errorMainLoopHelper6 = 0x2F case errorMainLoopHelper7 = 0x30 case insulinDeliveryCommandError = 0x31 case badValueStartupTest = 0x32 case connectedPodCommandTimeout = 0x33 case resetFromUnknownCause = 0x34 case errorFlashInitialization = 0x36 case badPiezoValue = 0x37 case unexpectedValueByte358 = 0x38 case problemWithLoad1and2 = 0x39 case aGreaterThan7inMessage = 0x3A case failedTestSawReset = 0x3B case testInProgress = 0x3C case problemWithPumpAnchor = 0x3D case errorFlashWrite = 0x3E case encoderCountTooHigh = 0x40 case encoderCountExcessiveVariance = 0x41 case encoderCountTooLow = 0x42 case encoderCountProblem = 0x43 case checkVoltageOpenWire1 = 0x44 case checkVoltageOpenWire2 = 0x45 case problemWithLoad1and2type46 = 0x46 case problemWithLoad1and2type47 = 0x47 case badTimerCalibration = 0x48 case badTimerRatios = 0x49 case badTimerValues = 0x4A case trimICSTooCloseTo0x1FF = 0x4B case problemFindingBestTrimValue = 0x4C case badSetTPM1MultiCasesValue = 0x4D case unexpectedRFErrorFlagDuringReset = 0x4F case badCheckSdrhAndByte11FState = 0x51 case issueTXOKprocessInputBuffer = 0x52 case wrongValueWord_107 = 0x53 case packetFrameLengthTooLong = 0x54 case unexpectedIRQHighinTimerTick = 0x55 case unexpectedIRQLowinTimerTick = 0x56 case badArgToGetEntry = 0x57 case badArgToUpdate37ATable = 0x58 case errorUpdating37ATable = 0x59 case occlusionCheckValueTooHigh = 0x5A case loadTableCorruption = 0x5B case primeOpenCountTooLow = 0x5C case badValueByte109 = 0x5D case disableFlashSecurityFailed = 0x5E case checkVoltageFailure = 0x5F case occlusionCheckStartup1 = 0x60 case occlusionCheckStartup2 = 0x61 case occlusionCheckTimeouts1 = 0x62 case occlusionCheckTimeouts2 = 0x66 case occlusionCheckTimeouts3 = 0x67 case occlusionCheckPulseIssue = 0x68 case occlusionCheckBolusProblem = 0x69 case occlusionCheckAboveThreshold = 0x6A case basalUnderInfusion = 0x80 case basalOverInfusion = 0x81 case tempBasalUnderInfusion = 0x82 case tempBasalOverInfusion = 0x83 case bolusUnderInfusion = 0x84 case bolusOverInfusion = 0x85 case basalOverInfusionPulse = 0x86 case tempBasalOverInfusionPulse = 0x87 case bolusOverInfusionPulse = 0x88 case immediateBolusOverInfusionPulse = 0x89 case extendedBolusOverInfusionPulse = 0x8A case corruptionOfTables = 0x8B case badInputToVerifyAndStartPump = 0x8D case badPumpReq5State = 0x8E case command1AParseUnexpectedFailed = 0x8F case badValueForTables = 0x90 case badPumpReq1State = 0x91 case badPumpReq2State = 0x92 case badPumpReq3State = 0x93 case badValueField6in0x1A = 0x95 case badStateInClearBolusIST2AndVars = 0x96 case badStateInMaybeInc33D = 0x97 case valuesDoNotMatchOrAreGreaterThan0x97 = 0x98 } public var faultType: FaultEventType? { return FaultEventType(rawValue: rawValue) } public init(rawValue: UInt8) { self.rawValue = rawValue } public var description: String { let faultDescription: String if let faultType = faultType { faultDescription = { switch faultType { case .noFaults: return "No fault" case .failedFlashErase: return "Flash erase failed" case .failedFlashStore: return "Flash store failed" case .tableCorruptionBasalSubcommand: return "Basal subcommand table corruption" case .corruptionByte720: return "Corruption in byte_720" case .dataCorruptionInTestRTCInterrupt: return "Data corruption error in test_RTC_interrupt" case .rtcInterruptHandlerInconsistentState: return "RTC interrupt handler called with inconstent state" case .valueGreaterThan8: return "Value > 8" case .bf0notEqualToBF1: return "Corruption in byte_BF0" case .tableCorruptionTempBasalSubcommand: return "Temp basal subcommand table corruption" case .resetDueToCOP: return "Reset due to COP" case .resetDueToIllegalOpcode: return "Reset due to illegal opcode" case .resetDueToIllegalAddress: return "Reset due to illegal address" case .resetDueToSAWCOP: return "Reset due to SAWCOP" case .corruptionInByte_866: return "Corruption in byte_866" case .resetDueToLVD: return "Reset due to LVD" case .messageLengthTooLong: return "Message length too long" case .occluded: return "Occluded" case .corruptionInWord129: return "Corruption in word_129 table/word_86A/dword_86E" case .corruptionInByte868: return "Corruption in byte_868" case .corruptionInAValidatedTable: return "Corruption in a validated table" case .reservoirEmpty: return "Reservoir empty or exceeded maximum pulse delivery" case .badPowerSwitchArrayValue1: return "Bad Power Switch Array Status and Control Register value 1 before starting pump" case .badPowerSwitchArrayValue2: return "Bad Power Switch Array Status and Control Register value 2 before starting pump" case .badLoadCnthValue: return "Bad LOADCNTH value when running pump" case .exceededMaximumPodLife80Hrs: return "Exceeded maximum Pod life of 80 hours" case .badStateCommand1AScheduleParse: return "Unexpected internal state in command_1A_schedule_parse_routine_wrapper" case .unexpectedStateInRegisterUponReset: return "Unexpected commissioned state in status and control register upon reset" case .wrongSummaryForTable129: return "Sum mismatch for word_129 table" case .validateCountErrorWhenBolusing: return "Validate encoder count error when bolusing" case .badTimerVariableState: return "Bad timer variable state" case .unexpectedRTCModuleValueDuringReset: return "Unexpected RTC Modulo Register value during reset" case .problemCalibrateTimer: return "Problem in calibrate_timer_case_3" case .rtcInterruptHandlerUnexpectedCall: return "RTC interrupt handler unexpectedly called" case .missing2hourAlertToFillTank: return "Failed to set up 2 hour alert for tank fill operation" case .faultEventSetupPod: return "Bad arg or state in update_insulin_variables, verify_and_start_pump or main_loop_control_pump" case .errorMainLoopHelper0: return "Alert #0 auto-off timeout" case .errorMainLoopHelper1: return "Alert #1 auto-off timeout" case .errorMainLoopHelper2: return "Alert #2 auto-off timeout" case .errorMainLoopHelper3: return "Alert #3 auto-off timeout" case .errorMainLoopHelper4: return "Alert #4 auto-off timeout" case .errorMainLoopHelper5: return "Alert #5 auto-off timeout" case .errorMainLoopHelper6: return "Alert #6 auto-off timeout" case .errorMainLoopHelper7: return "Alert #7 auto-off timeout" case .insulinDeliveryCommandError: return "Incorrect pod state for command or error during insulin command setup" case .badValueStartupTest: return "Bad value during startup testing" case .connectedPodCommandTimeout: return "Connected Pod command timeout" case .resetFromUnknownCause: return "Reset from unknown cause" case .errorFlashInitialization: return "Flash initialization error" case .badPiezoValue: return "Bad piezo value" case .unexpectedValueByte358: return "Unexpected byte_358 value" case .problemWithLoad1and2: return "Problem with LOAD1/LOAD2" case .aGreaterThan7inMessage: return "A > 7 in message processing" case .failedTestSawReset: return "SAW reset testing fail" case .testInProgress: return "402D is 'Z' - test in progress" case .problemWithPumpAnchor: return "Problem with pump anchor" case .errorFlashWrite: return "Flash initialization or write error" case .encoderCountTooHigh: return "Encoder count too high" case .encoderCountExcessiveVariance: return "Encoder count excessive variance" case .encoderCountTooLow: return "Encoder count too low" case .encoderCountProblem: return "Encoder count problem" case .checkVoltageOpenWire1: return "Check voltage open wire 1 problem" case .checkVoltageOpenWire2: return "Check voltage open wire 2 problem" case .problemWithLoad1and2type46: return "Problem with LOAD1/LOAD2" case .problemWithLoad1and2type47: return "Problem with LOAD1/LOAD2" case .badTimerCalibration: return "Bad timer calibration" case .badTimerRatios: return "Bad timer values: COP timer ratio bad" case .badTimerValues: return "Bad timer values" case .trimICSTooCloseTo0x1FF: return "ICS trim too close to 0x1FF" case .problemFindingBestTrimValue: return "find_best_trim_value problem" case .badSetTPM1MultiCasesValue: return "Bad set_TPM1_multi_cases value" case .unexpectedRFErrorFlagDuringReset: return "Unexpected TXSCR2 RF Tranmission Error Flag set during reset" case .badCheckSdrhAndByte11FState: return "Bad check_SDIRH and byte_11F state before starting pump" case .issueTXOKprocessInputBuffer: return "TXOK issue in process_input_buffer" case .wrongValueWord_107: return "Wrong word_107 value during input message processing" case .packetFrameLengthTooLong: return "Packet frame length too long" case .unexpectedIRQHighinTimerTick: return "Unexpected IRQ high in timer_tick" case .unexpectedIRQLowinTimerTick: return "Unexpected IRQ low in timer_tick" case .badArgToGetEntry: return "Corrupt constants table at byte_37A[] or flash byte_4036[]" case .badArgToUpdate37ATable: return "Bad argument to update_37A_table" case .errorUpdating37ATable: return "Error updating constants byte_37A table" case .occlusionCheckValueTooHigh: return "Occlusion check value too high for detection" case .loadTableCorruption: return "Load table corruption" case .primeOpenCountTooLow: return "Prime open count too low" case .badValueByte109: return "Bad byte_109 value" case .disableFlashSecurityFailed: return "Write flash byte to disable flash security failed" case .checkVoltageFailure: return "Two check voltage failures before starting pump" case .occlusionCheckStartup1: return "Occlusion check startup problem 1" case .occlusionCheckStartup2: return "Occlusion check startup problem 2" case .occlusionCheckTimeouts1: return "Occlusion check excess timeouts 1" case .occlusionCheckTimeouts2: return "Occlusion check excess timeouts 2" case .occlusionCheckTimeouts3: return "Occlusion check excess timeouts 3" case .occlusionCheckPulseIssue: return "Occlusion check pulse issue" case .occlusionCheckBolusProblem: return "Occlusion check bolus problem" case .occlusionCheckAboveThreshold: return "Occlusion check above threshold" case .basalUnderInfusion: return "Basal under infusion" case .basalOverInfusion: return "Basal over infusion" case .tempBasalUnderInfusion: return "Temp basal under infusion" case .tempBasalOverInfusion: return "Temp basal over infusion" case .bolusUnderInfusion: return "Bolus under infusion" case .bolusOverInfusion: return "Bolus over infusion" case .basalOverInfusionPulse: return "Basal over infusion pulse" case .tempBasalOverInfusionPulse: return "Temp basal over infusion pulse" case .bolusOverInfusionPulse: return "Bolus over infusion pulse" case .immediateBolusOverInfusionPulse: return "Immediate bolus under infusion pulse" case .extendedBolusOverInfusionPulse: return "Extended bolus over infusion pulse" case .corruptionOfTables: return "Corruption of $283/$2E3/$315 tables" case .badInputToVerifyAndStartPump: return "Bad input value to verify_and_start_pump" case .badPumpReq5State: return "Pump req 5 with basal IST not set or temp basal IST set" case .command1AParseUnexpectedFailed: return "Command 1A parse routine unexpected failed" case .badValueForTables: return "Bad value for $283/$2E3/$315 table specification" case .badPumpReq1State: return "Pump request 1 with temp basal IST not set" case .badPumpReq2State: return "Pump request 2 with temp basal IST not set" case .badPumpReq3State: return "Pump request 3 and bolus IST not set when about to pulse" case .badValueField6in0x1A: return "Bad table specifier field6 in 1A command" case .badStateInClearBolusIST2AndVars: return "Bad variable state in clear_Bolus_IST2_and_vars" case .badStateInMaybeInc33D: return "Bad variable state in maybe_inc_33D" case .valuesDoNotMatchOrAreGreaterThan0x97: return "Unknown fault code" } }() } else { faultDescription = "Unknown Fault" } return String(format: "Fault Event Code 0x%02x: %@", rawValue, faultDescription) } public var localizedDescription: String { if let faultType = faultType { switch faultType { case .noFaults: return LocalizedString("No faults", comment: "Description for Fault Event Code .noFaults") case .reservoirEmpty: return LocalizedString("Empty reservoir", comment: "Description for Empty reservoir pod fault") case .exceededMaximumPodLife80Hrs: return LocalizedString("Pod expired", comment: "Description for Pod expired pod fault") case .occluded: return LocalizedString("Occlusion detected", comment: "Description for Occlusion detected pod fault") default: return String(format: LocalizedString("Internal pod fault %1$03d", comment: "The format string for Internal pod fault (1: The fault code value)"), rawValue) } } else { return String(format: LocalizedString("Unknown pod fault %1$03d", comment: "The format string for Unknown pod fault (1: The fault code value)"), rawValue) } } }
mit
da28e7293eaf105c7439b351cd24614b
51.444175
172
0.54922
5.196489
false
false
false
false
headione/criticalmaps-ios
CriticalMapsKit/Tests/HelperTests/CodableExtensionsTests.swift
1
600
@testable import Helpers import XCTest class CodableExtensionsTests: XCTestCase { let testModel = [1, 2, 3] func testencodedHelperFunctionShouldEncode() throws { let testModelEncoded = try testModel.encoded() let testData = try JSONEncoder().encode(testModel) XCTAssertEqual(testModelEncoded, testData) } func testDecodedHelperFunctionShouldDecode() throws { let encodedTestModel = try JSONEncoder().encode(testModel) let decodedTestModed: [Int] = try encodedTestModel.decoded() XCTAssertEqual(decodedTestModed, testModel) } }
mit
9118cf762631c91d8a9f49554ab0a549
29
68
0.716667
4.958678
false
true
false
false
cubixlabs/SocialGIST
Pods/GISTFramework/GISTFramework/Classes/BaseClasses/BaseUIBarButtonItem.swift
1
3343
// // BaseUIBarButtonItem.swift // GISTFramework // // Created by Shoaib Abdul on 04/12/2016. // Copyright © 2016 Social Cubix. All rights reserved. // import UIKit open class BaseUIBarButtonItem: UIBarButtonItem, BaseView { //MARK: - Properties /// Flag for whether to resize the values for iPad. @IBInspectable open var sizeForIPad:Bool = GIST_CONFIG.sizeForIPad; /// Font name key from Sync Engine. @IBInspectable open var fontName:String = GIST_CONFIG.fontName { didSet { self.font = UIFont.font(fontName, fontStyle: fontStyle, sizedForIPad: self.sizeForIPad); } } /// Font size/style key from Sync Engine. @IBInspectable open var fontStyle:String = GIST_CONFIG.fontStyle { didSet { self.font = UIFont.font(fontName, fontStyle: fontStyle, sizedForIPad: self.sizeForIPad); } } @IBInspectable open var respectRTL:Bool = GIST_CONFIG.respectRTL { didSet { if (respectRTL != oldValue && self.respectRTL && GISTUtility.isRTL) { super.image = self.image?.mirrored(); } } } //P.E. /// Extended proprty font for Segmented Controler Items open var font:UIFont? = nil { didSet { self.setTitleTextAttributes([NSFontAttributeName:self.font!], for: UIControlState()); } } private var _titleKey:String?; open override var title: String? { set { if let key:String = newValue , key.hasPrefix("#") == true{ _titleKey = key; // holding key for using later super.title = SyncedText.text(forKey: key); } else { super.title = newValue; } } get { return super.title; } } open override var image: UIImage? { set { if (self.respectRTL && GISTUtility.isRTL) { super.image = newValue?.mirrored(); } else { super.image = newValue; } } get { return super.image; } } /// Overridden method to setup/ initialize components. override open func awakeFromNib() { super.awakeFromNib(); self.commontInit(); } //F.E. /// Common initazier for setting up items. private func commontInit() { self.font = UIFont.font(fontName, fontStyle: fontStyle, sizedForIPad: self.sizeForIPad); //Updating text with synced data if let txt:String = self.title , txt.hasPrefix("#") == true { self.title = txt; // Assigning again to set value from synced data } else if _titleKey != nil { self.title = _titleKey } if (self.respectRTL && GISTUtility.isRTL) { super.image = self.image?.mirrored(); } } //F.E. /// Updates layout and contents from SyncEngine. this is a protocol method BaseView that is called when the view is refreshed. func updateView(){ self.font = UIFont.font(fontName, fontStyle: fontStyle, sizedForIPad: self.sizeForIPad); if let txtKey:String = _titleKey { self.title = txtKey } } //F.E. } //CLS END
gpl-3.0
d43c8f0fb6a86fe062e942277fe28fbc
29.108108
130
0.561041
4.707042
false
false
false
false
pidjay/SideMenu
Example/SideMenu/SideMenuTableView.swift
1
790
// // SideMenuTableView.swift // SideMenu // // Created by Jon Kent on 4/5/16. // Copyright © 2016 CocoaPods. All rights reserved. // import Foundation import SideMenu class SideMenuTableView: UITableViewController { override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) // this will be non-nil if a blur effect is applied guard tableView.backgroundView == nil else { return } // Set up a cool background image for demo purposes let imageView = UIImageView(image: UIImage(named: "saturn")) imageView.contentMode = .scaleAspectFit imageView.backgroundColor = UIColor.black.withAlphaComponent(0.2) tableView.backgroundView = imageView } }
mit
894c44b51d577a22cfb63a5053ab44b2
26.206897
73
0.653992
4.900621
false
false
false
false
yuandiLiao/YDModel
YDModelTest/YDModelTest/ViewController.swift
1
4161
// // ViewController.swift // YDModelTest // // Created by 廖源迪 on 2017/8/22. // Copyright © 2017年 yuandiLiao. All rights reserved. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. fun1() fun2() fun3() fun4() } //基本的字典转model func fun1(){ let dic = ["intValue":222, "name":"哟哟", "url":"http://baidu.com", "age":"22222", "boolValue":222, "nsinter":222, "doubleValue":222, "floatValue":222, "floatValue1":222, "floatValue2":222, "numberValue":222, "dic":["hah":"哈哈"], "arr":[1,2,3,4,5], "str":["name":"嘻嘻","age":40], "arrModel":[ ["name":"嘻嘻1","age":401], ["name":"嘻嘻2","age":403], ["name":"嘻嘻3","age":404]]] as [String : Any] let use = Use.modelWithDic(dic: dic as Dictionary<String, AnyObject>) as! Use print(use) } //内嵌模型和内嵌数组模型字典转model func fun2(){ let dic = ["schoolName":"深圳大学", "place":"深圳", "schoolAge":"32", "student":["name":"嘻嘻","age":40], "arrModel":[ ["name":"嘻嘻1","age":401], ["name":"嘻嘻2","age":403], ["name":"嘻嘻3","age":404]]] as [String : Any] let school = School.modelWithDic(dic: dic as Dictionary<String, AnyObject>) as! School print(school) } //映射 func fun3(){ let dic = ["string":"mapperString", "int":"1111", "student":["name":"嘻嘻","age":40], "arrModel":[ ["schoolName":"深圳大学", "place":"深圳", "schoolAge":"32", "student":["name":"嘻嘻","age":40], "arrModel":[ ["name":"嘻嘻1","age":401], ["name":"嘻嘻2","age":403], ["name":"嘻嘻3","age":404]]], ["schoolName":"深圳大学", "place":"深圳", "schoolAge":"32", "student":["name":"嘻嘻","age":40], "arrModel":[ ["name":"嘻嘻1","age":401], ["name":"嘻嘻2","age":403], ["name":"嘻嘻3","age":404]]], ["schoolName":"深圳大学", "place":"深圳", "schoolAge":"32", "student":["name":"嘻嘻","age":40], "arrModel":[ ["name":"嘻嘻1","age":401], ["name":"嘻嘻2","age":403], ["name":"嘻嘻3","age":404]]]]] as [String : Any] let mapper = Mapper.modelWithDic(dic: dic as Dictionary<String, AnyObject>) print(mapper) } //数组模型 func fun4(){ let array = [ ["name":4444,"age":401], ["name":"嘻嘻2","age":403], ["name":"嘻嘻3","age":404], ["name":"嘻嘻1","age":401], ["name":"嘻嘻2","age":403], ["name":"嘻嘻3","age":404], ["name":"嘻嘻1","age":401], ["name":"嘻嘻2","age":403], ["name":"嘻嘻3","age":404]] let modelArray = Student.modelWithArray(array: array as Array<AnyObject>) as! Array<Student> for item in modelArray { print(item) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
654715ac2bdbf8f055bbeac1818f7d88
32.288136
101
0.397658
3.95569
false
false
false
false
JGiola/swift-package-manager
Sources/SourceControl/Repository.swift
1
9026
/* This source file is part of the Swift.org open source project Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for Swift project authors */ import Basic /// Specifies a repository address. public struct RepositorySpecifier: Hashable { /// The URL of the repository. public let url: String /// Create a specifier. public init(url: String) { self.url = url } /// A unique identifier for this specifier. /// /// This identifier is suitable for use in a file system path, and /// unique for each repository. public var fileSystemIdentifier: String { // Use first 8 chars of a stable hash. let hash = SHA256(url).digestString() let suffix = hash.dropLast(hash.count - 8) return basename + "-" + suffix } /// Returns the cleaned basename for the specifier. public var basename: String { var basename = url.components(separatedBy: "/").last! if basename.hasSuffix(".git") { basename = String(basename.dropLast(4)) } return basename } } extension RepositorySpecifier: CustomStringConvertible { public var description: String { return url } } extension RepositorySpecifier: JSONMappable, JSONSerializable { public init(json: JSON) throws { guard case .string(let url) = json else { throw JSON.MapError.custom(key: nil, message: "expected string, got \(json)") } self.url = url } public func toJSON() -> JSON { return .string(url) } } /// A repository provider. /// /// This protocol defines the lower level interface used to to access /// repositories. High-level clients should access repositories via a /// `RepositoryManager`. public protocol RepositoryProvider { /// Fetch the complete repository at the given location to `path`. /// /// - Throws: If there is an error fetching the repository. func fetch(repository: RepositorySpecifier, to path: AbsolutePath) throws /// Open the given repository. /// /// - Parameters: /// - repository: The specifier for the repository. /// - path: The location of the repository on disk, at which the /// repository has previously been created via `fetch`. /// - Throws: If the repository is unable to be opened. func open(repository: RepositorySpecifier, at path: AbsolutePath) throws -> Repository /// Clone a managed repository into a working copy at on the local file system. /// /// Once complete, the repository can be opened using `openCheckout`. /// /// - Parameters: /// - sourcePath: The location of the repository on disk, at which the /// repository has previously been created via `fetch`. /// - destinationPath: The path at which to create the working copy; it is /// expected to be non-existent when called. /// - editable: The checkout is expected to be edited by users. func cloneCheckout( repository: RepositorySpecifier, at sourcePath: AbsolutePath, to destinationPath: AbsolutePath, editable: Bool) throws /// Returns true if a working repository exists at `path` func checkoutExists(at path: AbsolutePath) throws -> Bool /// Open a working repository copy. /// /// - Parameters: /// - path: The location of the repository on disk, at which the /// repository has previously been created via `cloneCheckout`. func openCheckout(at path: AbsolutePath) throws -> WorkingCheckout } extension RepositoryProvider { public func checkoutExists(at path: AbsolutePath) throws -> Bool { fatalError("Unimplemented") } } /// Abstract repository operations. /// /// This interface provides access to an abstracted representation of a /// repository which is ultimately owned by a `RepositoryManager`. This interface /// is designed in such a way as to provide the minimal facilities required by /// the package manager to gather basic information about a repository, but it /// does not aim to provide all of the interfaces one might want for working /// with an editable checkout of a repository on disk. /// /// The goal of this design is to allow the `RepositoryManager` a large degree of /// flexibility in the storage and maintenance of its underlying repositories. /// /// This protocol is designed under the assumption that the repository can only /// be mutated via the functions provided here; thus, e.g., `tags` is expected /// to be unchanged through the lifetime of an instance except as otherwise /// documented. The behavior when this assumption is violated is undefined, /// although the expectation is that implementations should throw or crash when /// an inconsistency can be detected. public protocol Repository { /// Get the list of tags in the repository. var tags: [String] { get } /// Resolve the revision for a specific tag. /// /// - Precondition: The `tag` should be a member of `tags`. /// - Throws: If a error occurs accessing the named tag. func resolveRevision(tag: String) throws -> Revision /// Resolve the revision for an identifier. /// /// The identifier can be a branch name or a revision identifier. /// /// - Throws: If the identifier can not be resolved. func resolveRevision(identifier: String) throws -> Revision /// Fetch and update the repository from its remote. /// /// - Throws: If an error occurs while performing the fetch operation. func fetch() throws /// Returns true if the given revision exists. func exists(revision: Revision) -> Bool /// Open an immutable file system view for a particular revision. /// /// This view exposes the contents of the repository at the given revision /// as a file system rooted inside the repository. The repository must /// support opening multiple views concurrently, but the expectation is that /// clients should be prepared for this to be inefficient when performing /// interleaved accesses across separate views (i.e., the repository may /// back the view by an actual file system representation of the /// repository). /// /// It is expected behavior that attempts to mutate the given FileSystem /// will fail or crash. /// /// - Throws: If a error occurs accessing the revision. func openFileView(revision: Revision) throws -> FileSystem } /// An editable checkout of a repository (i.e. a working copy) on the local file /// system. public protocol WorkingCheckout { /// Get the list of tags in the repository. var tags: [String] { get } /// Get the current revision. func getCurrentRevision() throws -> Revision /// Fetch and update the repository from its remote. /// /// - Throws: If an error occurs while performing the fetch operation. func fetch() throws /// Query whether the checkout has any commits which are not pushed to its remote. func hasUnpushedCommits() throws -> Bool /// This check for any modified state of the repository and returns true /// if there are uncommited changes. func hasUncommittedChanges() -> Bool /// Check out the given tag. func checkout(tag: String) throws /// Check out the given revision. func checkout(revision: Revision) throws /// Returns true if the given revision exists. func exists(revision: Revision) -> Bool /// Create a new branch and checkout HEAD to it. /// /// Note: It is an error to provide a branch name which already exists. func checkout(newBranch: String) throws /// Returns true if there is an alternative store in the checkout and it is valid. func isAlternateObjectStoreValid() -> Bool /// Returns true if the file at `path` is ignored by `git` func areIgnored(_ paths: [AbsolutePath]) throws -> [Bool] } extension WorkingCheckout { public func areIgnored(_ paths: [AbsolutePath]) throws -> [Bool] { fatalError("Unimplemented") } } /// A single repository revision. public struct Revision: Hashable { /// A precise identifier for a single repository revision, in a repository-specified manner. /// /// This string is intended to be opaque to the client, but understandable /// by a user. For example, a Git repository might supply the SHA1 of a /// commit, or an SVN repository might supply a string such as 'r123'. public let identifier: String public init(identifier: String) { self.identifier = identifier } } extension Revision: JSONMappable { public init(json: JSON) throws { guard case .string(let identifier) = json else { throw JSON.MapError.custom(key: nil, message: "expected string, got \(json)") } self.init(identifier: identifier) } }
apache-2.0
206154dd56c0c4415c8ed062704efb39
35.691057
96
0.68203
4.775661
false
false
false
false
MukeshKumarS/Swift
stdlib/public/core/AssertCommon.swift
1
7032
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // Implementation Note: this file intentionally uses very LOW-LEVEL // CONSTRUCTS, so that assert and fatal may be used liberally in // building library abstractions without fear of infinite recursion. // // FIXME: We could go farther with this simplification, e.g. avoiding // UnsafeMutablePointer @_transparent @warn_unused_result public // @testable func _isDebugAssertConfiguration() -> Bool { // The values for the assert_configuration call are: // 0: Debug // 1: Release // 2: Fast return Int32(Builtin.assert_configuration()) == 0 } @_transparent @warn_unused_result internal func _isReleaseAssertConfiguration() -> Bool { // The values for the assert_configuration call are: // 0: Debug // 1: Release // 2: Fast return Int32(Builtin.assert_configuration()) == 1 } @_transparent @warn_unused_result public // @testable func _isFastAssertConfiguration() -> Bool { // The values for the assert_configuration call are: // 0: Debug // 1: Release // 2: Fast return Int32(Builtin.assert_configuration()) == 2 } @_transparent @warn_unused_result public // @testable func _isStdlibInternalChecksEnabled() -> Bool { #if INTERNAL_CHECKS_ENABLED return true #else return false #endif } @_silgen_name("swift_reportFatalErrorInFile") func _reportFatalErrorInFile( prefix: UnsafePointer<UInt8>, _ prefixLength: UInt, _ message: UnsafePointer<UInt8>, _ messageLength: UInt, _ file: UnsafePointer<UInt8>, _ fileLength: UInt, _ line: UInt) @_silgen_name("swift_reportFatalError") func _reportFatalError( prefix: UnsafePointer<UInt8>, _ prefixLength: UInt, _ message: UnsafePointer<UInt8>, _ messageLength: UInt) @_silgen_name("swift_reportUnimplementedInitializerInFile") func _reportUnimplementedInitializerInFile( className: UnsafePointer<UInt8>, _ classNameLength: UInt, _ initName: UnsafePointer<UInt8>, _ initNameLength: UInt, _ file: UnsafePointer<UInt8>, _ fileLength: UInt, _ line: UInt, _ column: UInt) @_silgen_name("swift_reportUnimplementedInitializer") func _reportUnimplementedInitializer( className: UnsafePointer<UInt8>, _ classNameLength: UInt, _ initName: UnsafePointer<UInt8>, _ initNameLength: UInt) /// This function should be used only in the implementation of user-level /// assertions. /// /// This function should not be inlined because it is cold and it inlining just /// bloats code. @noreturn @inline(never) @_semantics("stdlib_binary_only") func _assertionFailed( prefix: StaticString, _ message: StaticString, _ file: StaticString, _ line: UInt ) { prefix.withUTF8Buffer { (prefix) -> Void in message.withUTF8Buffer { (message) -> Void in file.withUTF8Buffer { (file) -> Void in _reportFatalErrorInFile( prefix.baseAddress, UInt(prefix.count), message.baseAddress, UInt(message.count), file.baseAddress, UInt(file.count), line) Builtin.int_trap() } } } Builtin.int_trap() } /// This function should be used only in the implementation of user-level /// assertions. /// /// This function should not be inlined because it is cold and it inlining just /// bloats code. @noreturn @inline(never) @_semantics("stdlib_binary_only") func _assertionFailed( prefix: StaticString, _ message: String, _ file: StaticString, _ line: UInt ) { prefix.withUTF8Buffer { (prefix) -> Void in let messageUTF8 = message.nulTerminatedUTF8 messageUTF8.withUnsafeBufferPointer { (messageUTF8) -> Void in file.withUTF8Buffer { (file) -> Void in _reportFatalErrorInFile( prefix.baseAddress, UInt(prefix.count), messageUTF8.baseAddress, UInt(messageUTF8.count), file.baseAddress, UInt(file.count), line) } } } Builtin.int_trap() } /// This function should be used only in the implementation of stdlib /// assertions. /// /// This function should not be inlined because it is cold and it inlining just /// bloats code. @noreturn @inline(never) @_semantics("stdlib_binary_only") func _fatalErrorMessage(prefix: StaticString, _ message: StaticString, _ file: StaticString, _ line: UInt) { #if INTERNAL_CHECKS_ENABLED prefix.withUTF8Buffer { (prefix) in message.withUTF8Buffer { (message) in file.withUTF8Buffer { (file) in _reportFatalErrorInFile( prefix.baseAddress, UInt(prefix.count), message.baseAddress, UInt(message.count), file.baseAddress, UInt(file.count), line) } } } #else prefix.withUTF8Buffer { (prefix) in message.withUTF8Buffer { (message) in _reportFatalError( prefix.baseAddress, UInt(prefix.count), message.baseAddress, UInt(message.count)) } } #endif Builtin.int_trap() } /// Prints a fatal error message when a unimplemented initializer gets /// called by the Objective-C runtime. @_transparent @noreturn public // COMPILER_INTRINSIC func _unimplemented_initializer(className: StaticString, initName: StaticString = __FUNCTION__, file: StaticString = __FILE__, line: UInt = __LINE__, column: UInt = __COLUMN__) { // This function is marked @_transparent so that it is inlined into the caller // (the initializer stub), and, depending on the build configuration, // redundant parameter values (__FILE__ etc.) are eliminated, and don't leak // information about the user's source. if _isDebugAssertConfiguration() { className.withUTF8Buffer { (className) in initName.withUTF8Buffer { (initName) in file.withUTF8Buffer { (file) in _reportUnimplementedInitializerInFile( className.baseAddress, UInt(className.count), initName.baseAddress, UInt(initName.count), file.baseAddress, UInt(file.count), line, column) } } } } else { className.withUTF8Buffer { (className) in initName.withUTF8Buffer { (initName) in _reportUnimplementedInitializer( className.baseAddress, UInt(className.count), initName.baseAddress, UInt(initName.count)) } } } Builtin.int_trap() } @noreturn public // COMPILER_INTRINSIC func _undefined<T>( @autoclosure message: () -> String = String(), file: StaticString = __FILE__, line: UInt = __LINE__ ) -> T { _assertionFailed("fatal error", message(), file, line) }
apache-2.0
814b69f606f1eb49d34d3604ee5e8cdb
29.310345
80
0.658276
4.346106
false
false
false
false
firebase/firebase-ios-sdk
FirebaseCombineSwift/Tests/Unit/Credentials.swift
2
967
// Copyright 2020 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import Foundation enum Credentials { static let googleAppID = "1:1085102361755:ios:f790a919483d5bdf" static let gcmSenderID = "217397612173" static let apiKey = "FAKE_API_KEY" static let clientID = "123456.apps.googleusercontent.com" static let bundleID = "org.cocoapods-generate.App-iOS" static let projectID = "fir-combinesample" static let bucket = "bucket" }
apache-2.0
7e16e04a7061ddb218eb151676696e5f
37.68
75
0.748707
3.868
false
false
false
false
gregomni/swift
tools/swift-inspect/Sources/swift-inspect/Operations/DumpCacheNodes.swift
9
1383
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2020 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// import ArgumentParser import SwiftRemoteMirror internal struct DumpCacheNodes: ParsableCommand { static let configuration = CommandConfiguration( abstract: "Print the target's metadata cache nodes.") @OptionGroup() var options: UniversalOptions func run() throws { try inspect(options: options) { process in print("Address", "Tag", "Tag Name", "Size", "Left", "Right", separator: "\t") try process.context.allocations.forEach { var node: swift_metadata_cache_node_t = swift_metadata_cache_node_t() if swift_reflection_metadataAllocationCacheNode(process.context, $0, &node) == 0 { return } let name: String = process.context.name(allocation: $0.tag) ?? "<unknown>" print("\(hex: $0.ptr)\t\($0.tag)\t\(name)\t\($0.size)\t\(hex: node.Left)\t\(hex: node.Right)") } } } }
apache-2.0
8b18c202e7422076798407837cabde64
36.378378
102
0.597252
4.335423
false
true
false
false
gregomni/swift
test/Generics/sr14580.swift
3
1639
// RUN: %target-typecheck-verify-swift -requirement-machine-protocol-signatures=on // RUN: %target-swift-frontend -typecheck -debug-generic-signatures -requirement-machine-protocol-signatures=on %s 2>&1 | %FileCheck %s public protocol ScalarProtocol: ScalarMultiplicative where Self == Scalar { } public protocol ScalarMultiplicative { associatedtype Scalar: ScalarProtocol } public protocol MapReduceArithmetic: ScalarMultiplicative, Collection where Element: ScalarMultiplicative {} public protocol Tensor: MapReduceArithmetic where Element == Scalar { } // CHECK-LABEL: sr14580.(file).ColorModel@ // CHECK-LABEL: Requirement signature: <Self where Self : Tensor, Self == Self.[ColorModel]Float16Components.[ColorComponents]Model, Self.[Sequence]Element == Double, Self.[ColorModel]Float16Components : ColorComponents, Self.[ColorModel]Float32Components : ColorComponents, Self.[ColorModel]Float16Components.[Sequence]Element == Double, Self.[ColorModel]Float16Components.[ColorComponents]Model == Self.[ColorModel]Float32Components.[ColorComponents]Model, Self.[ColorModel]Float32Components.[Sequence]Element == Double> public protocol ColorModel: Tensor where Scalar == Double { associatedtype Float16Components: ColorComponents where Float16Components.Model == Self, Float16Components.Scalar == Double associatedtype Float32Components: ColorComponents where Float32Components.Model == Self, Float32Components.Scalar == Double } public protocol ColorComponents: Tensor { associatedtype Model: ColorModel } extension Double : ScalarMultiplicative {} extension Double : ScalarProtocol { public typealias Scalar = Self }
apache-2.0
70b429c08e79255fadd86f1c48c5fc9d
53.633333
522
0.80781
4.820588
false
false
false
false
jkusnier/WorkoutMerge
Pods/p2.OAuth2/OAuth2/OAuth2PasswordGrant.swift
1
4629
// // OAuth2PasswordGrant.swift // OAuth2 // // Created by Tim Sneed on 6/5/15. // Copyright (c) 2015 Pascal Pfiffner. 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 /** A class to handle authorization for clients via password grant. */ public class OAuth2PasswordGrant: OAuth2 { /// Username to use during authentication. public var username: String /// The user's password. public var password: String /** Adds support for the "password" & "username" setting. */ public override init(settings: OAuth2JSON) { username = settings["username"] as? String ?? "" password = settings["password"] as? String ?? "" super.init(settings: settings) } public override func authorize(params params: [String : String]?, autoDismiss: Bool) { if hasUnexpiredAccessToken() { self.didAuthorize([String: String]()) } else { logIfVerbose("No access token, requesting a new one") obtainAccessToken() { error in if let error = error { self.didFail(error) } else { self.didAuthorize([String: String]()) } } } } /** If there is a refresh token, use it to receive a fresh access token. - parameter callback: The callback to call after the refresh token exchange has finished */ func obtainAccessToken(callback: ((error: NSError?) -> Void)) { do { let post = try tokenRequest() logIfVerbose("Requesting new access token from \(post.URL?.description)") performRequest(post) { data, status, error in if let data = data { do { let json = try self.parseAccessTokenResponse(data) if status < 400 && nil == json["error"] { self.logIfVerbose("Did get access token [\(nil != self.accessToken)]") callback(error: nil) } else { callback(error: self.errorForErrorResponse(json, fallback: "The username or password is incorrect")) } } catch let err { self.logIfVerbose("Error parsing response: \((err as NSError).localizedDescription)") callback(error: err as NSError) } } else { callback(error: error ?? genOAuth2Error("Error checking username and password: no data received")) } } } catch let err { callback(error: err as NSError) } } /** Creates a POST request with x-www-form-urlencoded body created from the supplied URL's query part. */ func tokenRequest() throws -> NSMutableURLRequest { if username.isEmpty{ throw OAuth2IncompleteSetup.NoUsername } if password.isEmpty{ throw OAuth2IncompleteSetup.NoPassword } if clientId.isEmpty { throw OAuth2IncompleteSetup.NoClientId } if nil == clientSecret { throw OAuth2IncompleteSetup.NoClientSecret } let req = NSMutableURLRequest(URL: authURL) req.HTTPMethod = "POST" req.setValue("application/x-www-form-urlencoded; charset=utf-8", forHTTPHeaderField: "Content-Type") req.setValue("application/json", forHTTPHeaderField: "Accept") // create body string var body = "grant_type=password&username=\(username.wwwFormURLEncodedString)&password=\(password.wwwFormURLEncodedString)" if let scope = scope { body += "&scope=\(scope.wwwFormURLEncodedString)" } req.HTTPBody = body.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true) // add Authorization header logIfVerbose("Adding “Authorization” header as “Basic client-key:client-secret”") let pw = "\(clientId.wwwFormURLEncodedString):\(clientSecret!.wwwFormURLEncodedString)" if let utf8 = pw.dataUsingEncoding(NSUTF8StringEncoding) { req.setValue("Basic \(utf8.base64EncodedStringWithOptions([]))", forHTTPHeaderField: "Authorization") } else { logIfVerbose("ERROR: for some reason failed to base-64 encode the client-key:client-secret combo") } return req } override func parseAccessTokenResponse(data: NSData) throws -> OAuth2JSON { let json = try super.parseAccessTokenResponse(data) if let type = json["token_type"] as? String where "bearer" != type { logIfVerbose("WARNING: expecting “bearer” token type but got “\(type)”") } return json } }
mit
b082621932e8f859242c0d154ab00aa6
30.168919
124
0.700412
3.860251
false
false
false
false
hyperoslo/CalendarKit
Source/Timeline/TimelineContainer.swift
1
2031
import UIKit public final class TimelineContainer: UIScrollView { public let timeline: TimelineView public init(_ timeline: TimelineView) { self.timeline = timeline super.init(frame: .zero) } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override public func layoutSubviews() { super.layoutSubviews() timeline.frame = CGRect(x: 0, y: 0, width: bounds.width, height: timeline.fullHeight) timeline.offsetAllDayView(by: contentOffset.y) //adjust the scroll insets let allDayViewHeight = timeline.allDayViewHeight let bottomSafeInset: CGFloat if #available(iOS 11.0, *) { bottomSafeInset = window?.safeAreaInsets.bottom ?? 0 } else { bottomSafeInset = 0 } scrollIndicatorInsets = UIEdgeInsets(top: allDayViewHeight, left: 0, bottom: bottomSafeInset, right: 0) contentInset = UIEdgeInsets(top: allDayViewHeight, left: 0, bottom: bottomSafeInset, right: 0) } public func prepareForReuse() { timeline.prepareForReuse() } public func scrollToFirstEvent(animated: Bool) { let allDayViewHeight = timeline.allDayViewHeight let padding = allDayViewHeight + 8 if let yToScroll = timeline.firstEventYPosition { setTimelineOffset(CGPoint(x: contentOffset.x, y: yToScroll - padding), animated: animated) } } public func scrollTo(hour24: Float, animated: Bool = true) { let percentToScroll = CGFloat(hour24 / 24) let yToScroll = contentSize.height * percentToScroll let padding: CGFloat = 8 setTimelineOffset(CGPoint(x: contentOffset.x, y: yToScroll - padding), animated: animated) } private func setTimelineOffset(_ offset: CGPoint, animated: Bool) { let yToScroll = offset.y let bottomOfScrollView = contentSize.height - bounds.size.height let newContentY = (yToScroll < bottomOfScrollView) ? yToScroll : bottomOfScrollView setContentOffset(CGPoint(x: offset.x, y: newContentY), animated: animated) } }
mit
8a002f842538c27c026c46746343d280
34.017241
107
0.712949
4.33049
false
false
false
false
therealglazou/quaxe-for-swift
quaxe/core/DOMImplementation.swift
1
2946
/** * Quaxe for Swift * * Copyright 2016-2017 Disruptive Innovations * * Original author: * Daniel Glazman <[email protected]> * * Contributors: * */ /** * https://dom.spec.whatwg.org/#interface-domimplementation * * status: done */ public class DOMImplementation: pDOMImplementation { /** * https://dom.spec.whatwg.org/#dom-domimplementation-createdocumenttype */ public func createDocumentType(_ qualifiedName: DOMString, _ publicId: DOMString, _ systemId: DOMString) throws -> pDocumentType { //Step 1 try Namespaces.validateQualifiedName(qualifiedName) // Step 2 return DocumentType(qualifiedName, publicId, systemId) } /** * https://dom.spec.whatwg.org/#dom-domimplementation-createdocument */ public func createDocument(_ namespace: DOMString?, _ qualifiedName: DOMString?, _ doctype: pDocumentType? = nil) throws -> pXMLDocument { // Step 1 let doc = Document() // Step 2 var element: pElement? = nil // Step 3 if nil != qualifiedName && !qualifiedName!.isEmpty { element = try doc.createElementNS(namespace, qualifiedName!) } // Step 4 if nil != doctype { try MutationAlgorithms.append(doctype as! Node, doc) } // Step 5 if nil != element { try MutationAlgorithms.append(element as! Node, doc) } // Step 6 // Explicitely not implemented here // Step 7 return doc } /** * https://dom.spec.whatwg.org/#dom-domimplementation-createhtmldocument */ public func createHTMLDocument(_ title: DOMString? = nil) throws -> pDocument { // Step 1 let doc = Document() doc.type = "html" // Step 2 doc.mContentType = "text/html" // Step 3 let dt = try createDocumentType("html", "", "") try MutationAlgorithms.append(dt as! Node, doc) // Step 4 let htmlElement = try doc.createElementNS(Namespaces.HTML_NAMESPACE, "html") try MutationAlgorithms.append(htmlElement as! Node, doc) // Step 5 let headElement = try doc.createElementNS(Namespaces.HTML_NAMESPACE, "head") try MutationAlgorithms.append(headElement as! Node, htmlElement as! Node) // Step 6 if let t = title { // Step 6.1 let titleElement = try doc.createElementNS(Namespaces.HTML_NAMESPACE, "title") try MutationAlgorithms.append(titleElement as! Node, headElement as! Node) let textNode = doc.createTextNode(t) try MutationAlgorithms.append(textNode as! Node, titleElement as! Node) } // Step 7 let bodyElement = try doc.createElementNS(Namespaces.HTML_NAMESPACE, "head") try MutationAlgorithms.append(bodyElement as! Node, htmlElement as! Node) // Step 8 // explicitely not implemented by Quaxe // Step 9 return doc } /** * https://dom.spec.whatwg.org/#dom-domimplementation-hasfeature */ public func hasFeatures() -> Bool {return true} init() {} }
mpl-2.0
98f5180189d8d2e2202f149cf64f8589
25.070796
140
0.664969
4.0191
false
false
false
false
thongtran715/Find-Friends
MapKitTutorial/FriendSearchViewController.swift
1
4148
// // FriendSearchViewController.swift // MapKitTutorial // // Created by Thong Tran on 7/8/16. // Copyright © 2016 Thorn Technologies. All rights reserved. // import UIKit import Parse protocol FriendSearchTableViewCellDelegate: class { func cell(cell: FriendSearchTableViewCell, didSelectFollowUser user: PFUser) func cell(cell: FriendSearchTableViewCell, didSelectUnfollowUser user: PFUser) } class FriendSearchViewController: UIViewController { var stringName = [PFUser]() @IBOutlet var searchBar: UISearchBar! @IBOutlet var tableView: UITableView! var post: Post? override func viewDidLoad() { super.viewDidLoad() } var users: [PFUser]? // the current parse query var query: PFQuery? { didSet { // whenever we assign a new query, cancel any previous requests // you can use oldValue to access the previous value of the property oldValue?.cancel() } } // this view can be in two different states enum State { case DefaultMode case SearchMode } // whenever the state changes, perform one of the two queries and update the list var state: State = .DefaultMode { didSet { switch (state) { case .DefaultMode: query = ParseHelper.getAllUsers(updateList) case .SearchMode: let searchText = searchBar?.text ?? "" query = ParseHelper.searchUsers(searchText, completionBlock:updateList) } } } func updateList(results: [PFObject]?, error: NSError?) { self.users = results as? [PFUser] ?? [] self.tableView.reloadData() } override func viewWillAppear(animated: Bool) { super.viewWillAppear(true) state = .DefaultMode } } extension FriendSearchViewController : UITableViewDataSource { func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.users?.count ?? 0 } func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("userCell") as! FriendSearchTableViewCell let user = users![indexPath.row] cell.user = user cell.delegate = self return cell } } extension FriendSearchViewController: UISearchBarDelegate { func searchBarTextDidBeginEditing(searchBar: UISearchBar) { searchBar.setShowsCancelButton(true, animated: true) state = .SearchMode } func searchBarCancelButtonClicked(searchBar: UISearchBar) { searchBar.resignFirstResponder() searchBar.text = "" searchBar.setShowsCancelButton(false, animated: true) state = .DefaultMode } func searchBar(searchBar: UISearchBar, textDidChange searchText: String) { ParseHelper.searchUsers(searchText, completionBlock:updateList) } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "Back" { var array = [String]() for user in stringName { array.append(user.username!) } let name = array.joinWithSeparator(", ") if let viewCol = segue.destinationViewController as? AddViewController { viewCol.nameOfUsers.text = name viewCol.arrayOfUsers = stringName } } } } extension FriendSearchViewController: FriendSearchTableViewCellDelegate { func cell(cell: FriendSearchTableViewCell, didSelectFollowUser user: PFUser) { //ParseHelper.setParseRelationshipBetweenUsers(post!, userShare: user) stringName.append(user) } func cell(cell: FriendSearchTableViewCell, didSelectUnfollowUser user: PFUser) { stringName.removeLast() } }
mit
79d49e5d2fad8890c226f9e05d6ac95d
28.621429
109
0.634917
5.276081
false
false
false
false
OscarSwanros/swift
test/SILGen/objc_dealloc.swift
2
5277
// RUN: %target-swift-frontend -sdk %S/Inputs -I %S/Inputs -enable-source-import %s -emit-silgen -enable-sil-ownership | %FileCheck %s // REQUIRES: objc_interop import gizmo class X { } func onDestruct() { } @requires_stored_property_inits class SwiftGizmo : Gizmo { var x = X() // CHECK-LABEL: sil hidden [transparent] @_T012objc_dealloc10SwiftGizmoC1xAA1XCvpfi : $@convention(thin) () -> @owned X // CHECK: [[FN:%.*]] = function_ref @_T012objc_dealloc1XCACycfC : $@convention(method) (@thick X.Type) -> @owned X // CHECK-NEXT: [[METATYPE:%.*]] = metatype $@thick X.Type // CHECK-NEXT: [[RESULT:%.*]] = apply [[FN]]([[METATYPE]]) : $@convention(method) (@thick X.Type) -> @owned X // CHECK-NEXT: return [[RESULT]] : $X // CHECK-LABEL: sil hidden @_T012objc_dealloc10SwiftGizmoC{{[_0-9a-zA-Z]*}}fc // CHECK: bb0([[SELF_PARAM:%[0-9]+]] : @owned $SwiftGizmo): override init() { // CHECK: [[SELF_BOX:%.*]] = alloc_box ${ var SwiftGizmo }, let, name "self" // CHECK: [[SELF_UNINIT:%.*]] = mark_uninitialized [derivedselfonly] [[SELF_BOX]] : ${ var SwiftGizmo } // CHECK: [[SELF_ADDR:%.*]] = project_box [[SELF_UNINIT]] // CHECK-NOT: ref_element_addr // CHECK: [[SELF:%.*]] = load [take] [[SELF_ADDR]] // CHECK-NEXT: [[UPCAST_SELF:%.*]] = upcast [[SELF]] : $SwiftGizmo to $Gizmo // CHECK-NEXT: [[BORROWED_UPCAST_SELF:%.*]] = begin_borrow [[UPCAST_SELF]] // CHECK-NEXT: [[DOWNCAST_BORROWED_UPCAST_SELF:%.*]] = unchecked_ref_cast [[BORROWED_UPCAST_SELF]] : $Gizmo to $SwiftGizmo // CHECK-NEXT: objc_super_method [[DOWNCAST_BORROWED_UPCAST_SELF]] : $SwiftGizmo // CHECK-NEXT: end_borrow [[BORROWED_UPCAST_SELF]] from [[UPCAST_SELF]] // CHECK: return super.init() } // CHECK-LABEL: sil hidden @_T012objc_dealloc10SwiftGizmoCfD : $@convention(method) (@owned SwiftGizmo) -> () deinit { // CHECK: bb0([[SELF:%[0-9]+]] : @owned $SwiftGizmo): // Call onDestruct() // CHECK: [[ONDESTRUCT_REF:%[0-9]+]] = function_ref @_T012objc_dealloc10onDestructyyF : $@convention(thin) () -> () // CHECK: [[ONDESTRUCT_RESULT:%[0-9]+]] = apply [[ONDESTRUCT_REF]]() : $@convention(thin) () -> () onDestruct() // Note: don't destroy instance variables // CHECK-NOT: ref_element_addr // Call super -dealloc. // CHECK: [[SUPER_DEALLOC:%[0-9]+]] = objc_super_method [[SELF]] : $SwiftGizmo, #Gizmo.deinit!deallocator.foreign : (Gizmo) -> () -> (), $@convention(objc_method) (Gizmo) -> () // CHECK: [[SUPER:%[0-9]+]] = upcast [[SELF]] : $SwiftGizmo to $Gizmo // CHECK: [[SUPER_DEALLOC_RESULT:%[0-9]+]] = apply [[SUPER_DEALLOC]]([[SUPER]]) : $@convention(objc_method) (Gizmo) -> () // CHECK: end_lifetime [[SUPER]] // CHECK: [[RESULT:%[0-9]+]] = tuple () // CHECK: return [[RESULT]] : $() } // Objective-C deallocation deinit thunk (i.e., -dealloc). // CHECK-LABEL: sil hidden [thunk] @_T012objc_dealloc10SwiftGizmoCfDTo : $@convention(objc_method) (SwiftGizmo) -> () // CHECK: bb0([[SELF:%[0-9]+]] : @unowned $SwiftGizmo): // CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]] // CHECK: [[GIZMO_DTOR:%[0-9]+]] = function_ref @_T012objc_dealloc10SwiftGizmoCfD : $@convention(method) (@owned SwiftGizmo) -> () // CHECK: [[RESULT:%[0-9]+]] = apply [[GIZMO_DTOR]]([[SELF_COPY]]) : $@convention(method) (@owned SwiftGizmo) -> () // CHECK: return [[RESULT]] : $() // Objective-C IVar initializer (i.e., -.cxx_construct) // CHECK-LABEL: sil hidden @_T012objc_dealloc10SwiftGizmoCfeTo : $@convention(objc_method) (@owned SwiftGizmo) -> @owned SwiftGizmo // CHECK: bb0([[SELF_PARAM:%[0-9]+]] : @owned $SwiftGizmo): // CHECK-NEXT: debug_value [[SELF_PARAM]] : $SwiftGizmo, let, name "self" // CHECK-NEXT: [[SELF:%[0-9]+]] = mark_uninitialized [rootself] [[SELF_PARAM]] : $SwiftGizmo // CHECK: [[XINIT:%[0-9]+]] = function_ref @_T012objc_dealloc10SwiftGizmoC1xAA1XCvpfi // CHECK-NEXT: [[XOBJ:%[0-9]+]] = apply [[XINIT]]() : $@convention(thin) () -> @owned X // CHECK-NEXT: [[BORROWED_SELF:%.*]] = begin_borrow [[SELF]] // CHECK-NEXT: [[X:%[0-9]+]] = ref_element_addr [[BORROWED_SELF]] : $SwiftGizmo, #SwiftGizmo.x // CHECK-NEXT: [[WRITE:%.*]] = begin_access [modify] [dynamic] [[X]] : $*X // CHECK-NEXT: assign [[XOBJ]] to [[WRITE]] : $*X // CHECK-NEXT: end_access [[WRITE]] : $*X // CHECK-NEXT: end_borrow [[BORROWED_SELF]] from [[SELF]] // CHECK-NEXT: return [[SELF]] : $SwiftGizmo // Objective-C IVar destroyer (i.e., -.cxx_destruct) // CHECK-LABEL: sil hidden @_T012objc_dealloc10SwiftGizmoCfETo : $@convention(objc_method) (SwiftGizmo) -> () // CHECK: bb0([[SELF:%[0-9]+]] : @unowned $SwiftGizmo): // CHECK-NEXT: debug_value [[SELF]] : $SwiftGizmo, let, name "self" // CHECK-NEXT: [[SELF_BORROW:%.*]] = begin_borrow [[SELF]] // CHECK-NEXT: [[X:%[0-9]+]] = ref_element_addr [[SELF_BORROW]] : $SwiftGizmo, #SwiftGizmo.x // CHECK-NEXT: destroy_addr [[X]] : $*X // CHECK-NEXT: end_borrow [[SELF_BORROW]] from [[SELF]] // CHECK-NEXT: [[RESULT:%[0-9]+]] = tuple () // CHECK-NEXT: return [[RESULT]] : $() } // CHECK-NOT: sil hidden [thunk] @_T0So11SwiftGizmo2CfETo : $@convention(objc_method) (SwiftGizmo2) -> () class SwiftGizmo2 : Gizmo { }
apache-2.0
d91897e3226eb8844f30a60ae6e9ef52
54.547368
182
0.601478
3.34835
false
false
false
false
oguntli/swift-grant-o-meter
Resources/bootstrap.swift
2
6838
#!/usr/bin/env xcrun swift // Copyright (c) 2016 ikiApps 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 /** Create a Derived Data RAM disk for use by Xcode. The regex matching is designed for English language systems. Tested with OS X 10.11.6 (El Capitan) and Swift 3.0. The disk is mounted into the default path for Xcode's Derived Data path and will be used automatically by Xcode if the path is correct for the one set in Xcode's preferences. This script can be added as a startup agent inside ~/Library/LaunchAgents. ** BE SURE TO CHANGE USERNAME BELOW TO MATCH YOUR USERNAME. ** The path below refers to a bin directory contained in your home directory. This folder needs to be created if it does not already exist. This script copied into that directory will need to have execute (+x) permissions. The property list inside LaunchAgents only requires read (+r) permissions to work. It is sufficient to simply copy the property list into the LaunchAgents directory. The directory itself will have to be created if it does not already exist. Here is the content of an example plist (property list) that will have the RAM disk created at startup. filename: com.ikiapps.setupXcodeDerivedDataRamDisk.plist ------------------------------------------------------------------- <?xml version=1.0 encoding=UTF-8?> <!DOCTYPE plist PUBLIC -//Apple//DTD PLIST 1.0//EN http://www.apple.com/DTDs/PropertyList-1.0.dtd> <plist version=1.0> <dict> <key>Label</key> <string>com.ikiapps.setupXcodeDerivedDataRamDisk.plist</string> <key>ProgramArguments</key> <array> <string>/usr/bin/xcrun</string> <string>/Users/USERNAME/bin/setupXcodeDerivedDataRAMDisk.swift</string> </array> <key>RunAtLoad</key> <true/> <key>LaunchOnlyOnce</key> <true/> </dict> </plist> ------------------------------------------------------------------- The launch agent can be tested with: launchctl load com.ikiapps.setupXcodeDerivedDataRamDisk.plist */ /// Constants: let RAMDISK_GB = 2 // Set the number of gigabytes for the RAM disk here! let home = NSHomeDirectory() let derivedDataPath = "\(home)/Library/Developer/Xcode/DerivedData" /** - returns: Bool true if the ram disk already exists. */ func ramDiskExists() -> Bool { let output = runTask(launchPath: "/sbin/mount", arguments: []) let regex: NSRegularExpression? do { regex = try NSRegularExpression(pattern: "/dev/disk.*Library/Developer/Xcode/DerivedData.*mounted", options: NSRegularExpression.Options.caseInsensitive) let numberOfMatches = regex!.numberOfMatches(in: output, options: [], range: NSMakeRange(0, output.characters.count)) if numberOfMatches == 1 { print("RAM disk is already mounted.\n") print(output) return true } } catch let error as NSError { print("error: \(error.localizedDescription)") assert (false) } return false } /** - parameter Int for number of blocks to use for the ram disk. - returns: Bool true if the creation of the ram disk is successful. */ func createRamDisk(blocks: Int) -> Bool { let output = runTask(launchPath: "/usr/bin/hdid", arguments: ["-nomount", "ram://\(blocks)"]) let allOutput = NSMakeRange(0, output.characters.count) let regex: NSRegularExpression? do { regex = try NSRegularExpression(pattern: "/dev/disk(\\d+)", options: NSRegularExpression.Options.caseInsensitive) let numberOfMatches = regex!.numberOfMatches(in: output, options: [], range: allOutput) print("output \(output)") if numberOfMatches == 1 { let matches = regex?.matches(in: output, options: [], range: allOutput) for match in matches! { let matchRange: NSRange = match.rangeAt(1) let disk = output.substring(with: output.index(output.startIndex, offsetBy: matchRange.location) ..< output.index(output.startIndex, offsetBy: (matchRange.location + matchRange.length))) makeFilesystemOn(disk: disk) addRamDiskToSpotlight() } } else { return false } } catch let error as NSError { print("error: \(error.localizedDescription)") assert (false) } return true } func makeFilesystemOn(disk: String) { let drive = "/dev/rdisk\(disk)" let output = runTask(launchPath: "/sbin/newfs_hfs", arguments: ["-v", "DerivedData", drive]) print(output) mountRamDisk(drive: drive) } func mountRamDisk(drive: String) { let output = runTask(launchPath: "/usr/sbin/diskutil", arguments: ["mount", "-mountPoint", derivedDataPath, drive]) print(output) } /// Add to Spotlight so that Instruments can find symbols. func addRamDiskToSpotlight() { let output = runTask(launchPath: "/usr/bin/mdutil", arguments: [derivedDataPath, "-i", "on"]) print(output) } func runTask(launchPath: String, arguments: [String]) -> String { let task = Process() task.launchPath = launchPath task.arguments = arguments let pipe = Pipe() task.standardOutput = pipe task.launch() let data = pipe.fileHandleForReading.readDataToEndOfFile() return NSString(data: data, encoding: String.Encoding.utf8.rawValue) as! String } print("Setting up RAM disk for Xcode.\n") if !ramDiskExists() { let result = createRamDisk(blocks: RAMDISK_GB * 1024 * 2048) if result { print("Created RAM disk.") } else { print("Unable to create RAM disk.") } } else { print("RAM disk for Derived Data already exists.") }
mpl-2.0
3d6367d330c6adfd9b7d2557d69d66d9
33.19
121
0.664814
4.271081
false
false
false
false
aceisScope/CustomSearchSwift
CustomSearchSwift/CustomSearchSwift/HotKeywordsView.swift
1
3395
// // HotKeywordsView.swift // CustomSearchSwift // // Created by bhliu on 14-6-16. // Copyright (c) 2014 Katze. All rights reserved. // import UIKit protocol KeyWordDelegate { func selectOnKeyWord(word:NSString) } class HotKeywordsView: UIView { let TOPMARGIN = 44 let MARGIN = 10 var delegate:KeyWordDelegate? var titleLabel:UILabel! init(frame: CGRect) { super.init(frame: frame) // Initialization code self.backgroundColor = UIColor(red: 240.0/256, green: 240.0/256, blue: 240.0/256, alpha: 1.0) self.titleLabel = UILabel(frame: CGRectMake(15, 10, 200, 20)) self.titleLabel.backgroundColor = UIColor.clearColor() self.titleLabel.text = "Popular searches"; self.titleLabel.textColor = UIColor(red: 90.0/256, green: 90.0/256, blue: 90.0/256, alpha: 1) self.titleLabel.font = UIFont(name: "Arial", size: 15) self.titleLabel.shadowColor = UIColor.whiteColor() self.titleLabel.shadowOffset = CGSizeMake(0, 1) self.addSubview(self.titleLabel) } func setWords(words:NSArray) { var i:Int = 0 var frameOfLastButton:CGRect = CGRectZero for dict:AnyObject in words { let tmp:NSDictionary = (dict as? NSDictionary)! let label: UILabel = UILabel(frame: CGRectMake(10, TOPMARGIN+i*25 , 70, 20)) label.font = UIFont(name: "GillSans", size: 16) label.text = tmp["name"] as NSString label.textColor = UIColor(red: 149.0/256, green: 149.0/256, blue: 149.0/256, alpha: 1) label.shadowColor = UIColor.whiteColor() label.shadowOffset = CGSizeMake(0, 1) self.addSubview(label) var j:Int = 0 for keyword:AnyObject in (tmp["words"] as NSArray){ let button:UIButton = UIButton.buttonWithType(UIButtonType.Custom) as UIButton button.setTitle(keyword as NSString, forState: UIControlState.Normal) button.setTitleColor(UIColor(red: 66.0/256, green: 66.0/256, blue: 66.0/256, alpha: 1),forState: UIControlState.Normal) button.titleLabel.font = UIFont(name: "GillSans", size: 14) button.setTitleShadowColor(UIColor.whiteColor(), forState: UIControlState.Normal) button.titleShadowOffset = CGSizeMake(0, 1) let size:CGSize = (keyword as NSString).sizeWithFont(UIFont.systemFontOfSize(14)) if j != 0 { button.frame = CGRectMake(frameOfLastButton.origin.x + frameOfLastButton.size.width + MARGIN, TOPMARGIN+i*25 , size.width, size.height) } else { button.frame = CGRectMake(70, TOPMARGIN+i*25, size.width, size.height); } self.addSubview(button) button.addTarget(self, action: "buttonPress:", forControlEvents: UIControlEvents.TouchUpInside) j++ frameOfLastButton = button.frame } i++; frameOfLastButton = CGRectZero } } func buttonPress(sender: UIButton!) { delegate?.selectOnKeyWord(sender.titleLabel.text) } }
mit
e664f2525e2593589d90d938ba566138
36.307692
155
0.579971
4.380645
false
false
false
false
SASAbus/SASAbus-ios
SASAbus/Beacon/AbsBeacon.swift
1
830
// // Created by Alex Lardschneider on 03/04/2017. // Copyright (c) 2017 SASA AG. All rights reserved. // import Foundation import CoreLocation import ObjectMapper class AbsBeacon: Mappable { var id: Int = -1 var startDate = Date() var seenSeconds: Int64 = 0 var lastSeen: Int64 = 0 var distance: CLProximity = .unknown init(id: Int) { self.id = id seen() } required init?(map: Map) { } func mapping(map: Map) { id <- map["id"] startDate <- (map["startDate"], DateTransform()) seenSeconds <- map["seenSeconds"] lastSeen <- map["lastSeen"] distance <- map["distance"] } func seen() { let millis = Date().millis() seenSeconds = (millis - startDate.millis()) / 1000 lastSeen = millis } }
gpl-3.0
9ac7d74603165f8bc826f42ced62d9b7
17.444444
58
0.572289
3.990385
false
false
false
false
BrijeshShiroya/SwiftyTextField
SwiftyTextField/Classes/SwiftyTextField.swift
1
7965
// // SwiftyTextField.swift // Pods // // Created by Shiroya&Bros on 10/06/17. // // import Foundation import UIKit public enum SwiftyTextFieldType: String{ case None = "none" case Email = "email" case Mobile = "mobile" case Password = "password" case DateOfBirth = "dateofbirth" case PostalCode = "postalcode" } @objc public protocol SwiftyTextFieldDelegate : class { @objc optional func textField(_ textField: SwiftyTextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool @objc optional func textFieldShouldEndEditing(_ textField: SwiftyTextField) -> Bool @objc optional func textFieldDidEndEditing(_ textField: SwiftyTextField) @objc optional func textFieldDidBeginEditing(_ textField: SwiftyTextField) @objc optional func textFieldShouldReturn(_ textField: SwiftyTextField) -> Bool } @IBDesignable public class SwiftyTextField:UITextField{ //MARK: - Variables - public var maximumTextLength:Int = 255 public var currentTextFieldType:String = SwiftyTextFieldType.None.rawValue var delegateObj:SwiftyTextFieldDelegate? //MARK: - Initialization - override public init(frame: CGRect) { super.init(frame: frame) self.delegate = self } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.delegate = self DispatchQueue.main.asyncAfter(deadline: .now() + 0.50) { self.configSwiftyTextField() } } //MARK: - IBInspactable - /* This property set corner radius of textfield . If user not give any valur to this property then default valur is 0.0 .If user set value then apply on it. */ @IBInspectable public var CornerRadius:CGFloat = 0.0{ didSet{ self.layer.cornerRadius = CornerRadius self.layer.masksToBounds = true } } /* LeftPadding set left space of textfield that means front space is set and when user start writing into textfield, writing is start after leftspace into textfield. */ @IBInspectable public var LeftPadding:CGFloat = 0.0{ didSet{ } } /* RightPadding set right space of textfield that means rear space is set and when user start writing into textfield, writing is start after rightspace into textfield. */ @IBInspectable public var RightPadding:CGFloat = 0.0{ didSet{ } } /* MaxLength is set limitation of user input.when user wants set limitation of input in textfield that time user set this value */ @IBInspectable public var MaxLength:Int = 255{ didSet{ if (MaxLength != 0){ self.maximumTextLength = MaxLength } } } /* set textfield type like none, email, mobile, password, dateofbirth, postalcode */ @IBInspectable public var TextFieldType:String?{ didSet{ if let textFieldType = SwiftyTextFieldType.init(rawValue: TextFieldType?.lowercased() ?? ""){ self.currentTextFieldType = textFieldType.rawValue } } } //MARK: - Other functions - /* set keyboardtype based on textfield type, if textfieldtype is dateofbirth then open datepicker */ public func configSwiftyTextField(){ if(self.currentTextFieldType.lowercased() == SwiftyTextFieldType.DateOfBirth.rawValue){ let datePicker = UIDatePicker() datePicker.datePickerMode = .date datePicker.maximumDate = Date() self.inputView = datePicker datePicker.addTarget(self, action: #selector(SwiftyTextField.changeDatePickerValue(_:)), for: .valueChanged) }else if(self.currentTextFieldType.lowercased() == SwiftyTextFieldType.PostalCode.rawValue){ self.keyboardType = .numberPad }else if(self.currentTextFieldType.lowercased() == SwiftyTextFieldType.Mobile.rawValue){ self.keyboardType = .phonePad }else if (self.currentTextFieldType.lowercased() == SwiftyTextFieldType.Password.rawValue){ self.isSecureTextEntry = true }else if (self.currentTextFieldType.lowercased() == SwiftyTextFieldType.Email.rawValue){ self.keyboardType = .emailAddress } } //Action for change datepicker-when textfield type is date of birth func changeDatePickerValue(_ sender:UIDatePicker) { let dateFormatter = DateFormatter() dateFormatter.dateFormat = "dd-MMM-yyyy" dateFormatter.dateFormat = "dd-MMM-yyyy" self.text = dateFormatter.string(from: sender.date) } //MARK: - Email Validation - //check email validation if valid email id then return true otherwise return false func isValidEmail(email:String) -> Bool { let emailRegEx = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}" let emailTest = NSPredicate(format:"SELF MATCHES %@", emailRegEx) return emailTest.evaluate(with: email) } //MARK: - Mobile Validation - //check mobile/phone validation if valid Phone/mobile then return true otherwise return false func isValidMobile(lengthNumber:Int) -> Bool{ let PHONE_REGEX = "^\\d{\(lengthNumber)}$" let phoneTest = NSPredicate(format: "SELF MATCHES %@", PHONE_REGEX) let result = phoneTest.evaluate(with: self) return result } //MARK: - Textfield methods - /* set left,right,bottom and top space into textfield. Set four side space when user editing or after editing or before editing. */ override public func textRect(forBounds bounds: CGRect) -> CGRect { return UIEdgeInsetsInsetRect(bounds, UIEdgeInsets.init(top: 0, left: self.LeftPadding, bottom: 0.0, right: self.RightPadding)) } override public func placeholderRect(forBounds bounds: CGRect) -> CGRect { return UIEdgeInsetsInsetRect(bounds, UIEdgeInsets.init(top: 0, left: self.LeftPadding, bottom: 0.0, right: self.RightPadding)) } override public func editingRect(forBounds bounds: CGRect) -> CGRect { return UIEdgeInsetsInsetRect(bounds, UIEdgeInsets.init(top: 0, left: self.LeftPadding, bottom: 0.0, right: self.RightPadding)) } } //MARK: - Textfield Delegates - extension SwiftyTextField:UITextFieldDelegate{ public func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { var isValidTextField:Bool = true let newString = NSString(string: textField.text!).replacingCharacters(in: range, with: string) let strTrimmed = (NSString(string:newString)).trimmingCharacters(in: CharacterSet.whitespaces)//remove white space isValidTextField = strTrimmed.characters.count <= self.maximumTextLength if(self.currentTextFieldType == SwiftyTextFieldType.PostalCode.rawValue || self.currentTextFieldType == SwiftyTextFieldType.Mobile.rawValue){ if isValidTextField{ let aSet = NSCharacterSet(charactersIn:"0123456789").inverted let compSepByCharInSet = string.components(separatedBy: aSet) let numberFiltered = compSepByCharInSet.joined(separator: "") isValidTextField = (string == numberFiltered) } } if isValidTextField{ if delegate != nil{ isValidTextField = (delegate?.textField!(textField as! SwiftyTextField, shouldChangeCharactersIn: range, replacementString: string))! } } return isValidTextField } public func textFieldShouldEndEditing(_ textField: UITextField) -> Bool { if (delegateObj != nil){ delegateObj?.textFieldShouldEndEditing!(textField as! SwiftyTextField) } return true } public func textFieldDidEndEditing(_ textField: UITextField) { if (delegateObj != nil){ delegateObj?.textFieldDidEndEditing!(textField as! SwiftyTextField) } } public func textFieldDidBeginEditing(_ textField: UITextField) { if (delegateObj != nil){ delegateObj?.textFieldDidBeginEditing!(textField as! SwiftyTextField) } } public func textFieldShouldReturn(_ textField: UITextField) -> Bool { textField.resignFirstResponder() if (delegateObj != nil){ return (delegateObj?.textFieldShouldReturn!(textField as! SwiftyTextField))! } return true } }
mit
8e44ba5f3b71ab073c29445b272e1e75
35.040724
167
0.71651
4.609375
false
false
false
false
TangentW/PhotosSheet
PhotosSheet/PhotosSheet/Classes/PhotosDisplayController.swift
1
6489
// // PhotosDisplayController.swift // PhotosSheet // // Created by Tan on 2017/8/14. // import UIKit import Photos // MARK: - PhotosDisplayController extension PhotosSheet { final class PhotosDisplayController: UIViewController { init() { super.init(nibName: nil, bundle: nil) } override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } fileprivate(set) lazy var photosDisplayView: UICollectionView = { let view = UICollectionView(frame: .zero, collectionViewLayout: self._photosDisplayLayout) view.showsHorizontalScrollIndicator = false view.backgroundColor = UIColor.white.withAlphaComponent(0.9) return view }() fileprivate lazy var _photosDisplayLayout: UICollectionViewLayout = { let layout = UICollectionViewFlowLayout() layout.scrollDirection = .horizontal layout.minimumInteritemSpacing = 5 layout.minimumLineSpacing = 0 return layout }() } } extension PhotosSheet.PhotosDisplayController { override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = UIColor.clear view.addSubview(photosDisplayView) } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() photosDisplayView.frame = view.bounds } } // MARK: - PhotoItemView extension PhotosSheet.PhotosDisplayController { final class PhotoItemView: UICollectionViewCell { fileprivate var _preRequestId: PHImageRequestID? fileprivate var _hideCheckbox = false lazy private(set) var hideCheckbox: (Bool) -> () = { return { [weak self] hide in self?._hideCheckbox = hide if let model = self?.model, model.didSelected { return } self?._checkbox.isHidden = hide } }() override init(frame: CGRect) { super.init(frame: frame) backgroundColor = UIColor.clear contentView.addSubview(_contentView) contentView.addSubview(_checkbox) contentView.addSubview(_videoMarkView) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } var model: PhotosSheet.Model? { didSet { guard let model = model, oldValue != model else { return } // Loading thumbnail _preRequestId = PhotosSheet.PhotosManager.shared.fetchPhoto(with: model.asset, type: .thumbnail(height: PhotosSheet.photoItemHeight), completionHandler: { [weak self] image in // Called twice. // First callback low quality thumbnail, second callback high quality thumbnail. self?._contentView.image = image }) _setupCheckbox(isModelSelected: model.didSelected) _videoMarkView.isHidden = model.asset.mediaType != .video model.didChangedSelected = { [weak self] didSelected in self?._setupCheckbox(isModelSelected: didSelected) } _checkbox.isHidden = !model.didSelected && _hideCheckbox } } fileprivate func _setupCheckbox(isModelSelected: Bool) { let checkboxImage = isModelSelected ? UIImage(named: "selection-mark-selected", in: Bundle.myBundle, compatibleWith: nil) : UIImage(named: "selection-mark-normal", in: Bundle.myBundle, compatibleWith: nil) _checkbox.image = checkboxImage } override func prepareForReuse() { super.prepareForReuse() if let preRequestId = _preRequestId { PHImageManager.default().cancelImageRequest(preRequestId) } } deinit { if let preRequestId = _preRequestId { PHImageManager.default().cancelImageRequest(preRequestId) } } override func layoutSubviews() { super.layoutSubviews() _contentView.frame = bounds _checkbox.sizeToFit() _checkbox.frame.origin = CGPoint(x: bounds.width - _checkbox.bounds.width - PhotosSheet.photoItemCheckboxRightMargin, y: bounds.height - _checkbox.bounds.height - PhotosSheet.photoItemCheckboxBottomMargin) _videoMarkView.sizeToFit() _videoMarkView.frame.origin = CGPoint(x: PhotosSheet.photoItemVideoMarkerViewLeftMargin, y: bounds.height - _videoMarkView.bounds.height - PhotosSheet.photoItemVideoMarkerViewBottomMargin) } fileprivate lazy var _contentView: UIImageView = { let imageView = UIImageView() imageView.contentMode = .scaleAspectFill imageView.layer.masksToBounds = true return imageView }() fileprivate lazy var _checkbox: UIImageView = { let view = UIImageView() view.image = UIImage(named: "selection-mark-normal", in: Bundle.myBundle, compatibleWith: nil) return view }() fileprivate lazy var _videoMarkView: UIImageView = { let view = UIImageView() view.tintColor = .white view.image = UIImage(named: "file-cate-list-video", in: Bundle.myBundle, compatibleWith: nil)?.withRenderingMode(.alwaysTemplate) view.layer.shadowColor = UIColor.black.cgColor view.layer.shadowOffset = CGSize(width: 1, height: 1) view.layer.shadowRadius = 1 view.layer.shadowOpacity = 0.5 return view }() } } extension PhotosSheet.PhotosDisplayController.PhotoItemView: PhotosDisplayViewContentOffsetObserver { func displayView(_ displayView: UICollectionView, onContentOffsetChange contentOffset: CGPoint) { let displayViewWidth = displayView.bounds.width let x = min(max(displayViewWidth - (frame.origin.x - contentOffset.x) - _checkbox.bounds.width - PhotosSheet.photoItemCheckboxRightMargin, PhotosSheet.photoItemCheckboxRightMargin), bounds.width - _checkbox.bounds.width - PhotosSheet.photoItemCheckboxBottomMargin) _checkbox.frame.origin.x = x } }
mit
fdf0632cc26fe16e25b7cce9282bcf63
39.304348
272
0.630452
5.1912
false
false
false
false
navrit/dosenet-apps
iOS/DoseNet/DoseNet/DosimeterViewController.swift
1
8458
// // DosimeterViewController.swift // DoseNet // // Created by Navrit Bal on 30/12/2015. // Copyright © 2015 navrit. All rights reserved. // import UIKit import Alamofire import SwiftSpinner import JLToast import CoreLocation let url:String! = "https://radwatch.berkeley.edu/sites/default/files/output.geojson?" + randomAlphaNumericString(32) var userLoc:CLLocationCoordinate2D! var numberOfDosimeters:Int! = 0 var dosimeters : [Dosimeter] = [] var selectedDosimeter:String! func randomAlphaNumericString(length: Int) -> String { let allowedChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" let allowedCharsCount = UInt32(allowedChars.characters.count) var randomString = "" for _ in (0..<length) { let randomNum = Int(arc4random_uniform(allowedCharsCount)) let newCharacter = allowedChars[allowedChars.startIndex.advancedBy(randomNum)] randomString += String(newCharacter) } return randomString } class DosimeterViewController: UITableViewController, CLLocationManagerDelegate { @IBAction func cancelToDosimeterViewController(segue: UIStoryboardSegue){} var items = [String]() var itemsDistances = [Double]() var newitem: String = "" let locationManager = CLLocationManager() func main() { SwiftSpinner.show("Loading...", animated: true) initCLLocationManager() } func networkRequest() { Alamofire.request(.GET, url).responseJSON { response in switch response.result { case .Success: if let value = response.result.value { let features:JSON = JSON(value)["features"] var lastDistance = CLLocationDistance(20037500) numberOfDosimeters = features.count for i in 0..<numberOfDosimeters { let this:JSON = features[i] let prop:JSON = this["properties"] let name:JSON = prop["Name"] let dose_uSv:JSON = prop["Latest dose (&microSv/hr)"] let dose_mRem:JSON = prop["Latest dose (mREM/hr)"] let time:JSON = prop["Latest measurement"] let lon = this["geometry"]["coordinates"][0] let lat = this["geometry"]["coordinates"][1] let CLlon = CLLocationDegrees(lon.double!) let CLlat = CLLocationDegrees(lat.double!) let fromLoc = CLLocation(latitude: CLlat, longitude: CLlon) let toLoc = CLLocation(latitude: userLoc.latitude, longitude: userLoc.longitude) let distance = fromLoc.distanceFromLocation(toLoc) if (distance < lastDistance) { lastDistance = distance closestDosimeter = name.string } let d = Dosimeter(name: name.string!, lastDose_uSv: dose_uSv.double!, lastDose_mRem: dose_mRem.double!, lastTime: time.string!, distance: (distance/1000)) // m --> km dosimeters.append(d) } let tabItem = self.tabBarController?.tabBar.items![1] tabItem!.badgeValue = String(numberOfDosimeters) dosimeters.sortInPlace({ $0.distance < $1.distance }) dispatch_async(dispatch_get_main_queue()) { self.tableView.reloadData() } SwiftSpinner.hide() } case .Failure(let error): SwiftSpinner.hide() SwiftSpinner.show("Failed update...").addTapHandler({ SwiftSpinner.hide() }, subtitle: "Tap to hide, try again later!") print(error) } } } func initCLLocationManager(){ // Ask for Authorisation from the User. self.locationManager.requestAlwaysAuthorization() // For use in foreground self.locationManager.requestWhenInUseAuthorization() if CLLocationManager.locationServicesEnabled() { locationManager.delegate = self locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters locationManager.startUpdatingLocation() } } func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { userLoc = manager.location!.coordinate print("locations = \(userLoc.latitude) \(userLoc.longitude)") networkRequest() locationManager.stopUpdatingLocation() } override func numberOfSectionsInTableView(tableView: UITableView) -> Int { // 1 return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // 2 return dosimeters.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { // 3 let cell = tableView.dequeueReusableCellWithIdentifier("DosimeterCell", forIndexPath: indexPath) as! DosimeterCell let dosimeter = dosimeters[indexPath.row] as Dosimeter cell.dosimeter = dosimeter //let destination = DosimeterGraphsViewController() //destination.performSegueWithIdentifier("graphSegue", sender: self) /*if let titleLabel = cell.viewWithTag(100) as? UILabel { //4 titleLabel.text = dosimeters[indexPath.row].name } if let subtitleLabel = cell.viewWithTag(101) as? UILabel { //5 let km = dosimeters[indexPath.row].distance let detailText = String(format:"%.0f", km!*0.621371) + " mi / " + String(format:"%.0f", km!) + " km" subtitleLabel.text = detailText }*/ return cell } // Get long name to the graph controller /* override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) { // Create a variable that you want to send var longName = dosimeters // Create a new variable to store the instance let destinationVC = segue.destinationViewController destinationVC.programVar = newProgramVar } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { // Create a variable that you want to send based on the destination view controller // You can get a reference to the data by using indexPath shown below let selectedProgram = programy[indexPath.row] // Create an instance of PlayerTableViewController and pass the variable let destinationVC = PlayerTableViewController() destinationVC.programVar = selectedProgram // Let's assume that the segue name is called playerSegue // This will perform the segue and pre-load the variable for you to use destinationVC.performSegueWithIdentifier("playerSegue", sender: self) } */ override func viewDidLoad() { super.viewDidLoad() main() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } class DosimeterCell: UITableViewCell { //http://www.raywenderlich.com/113388/storyboards-tutorial-in-ios-9-part-1 @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var subtitleLabel: UILabel! var dosimeter : Dosimeter! { didSet { let km = dosimeter.distance let detailText = String(format:"%.0f", km!*0.621371) + " mi / " + String(format:"%.0f", km!) + " km" titleLabel.text = dosimeter.name subtitleLabel.text = detailText } } }
mit
434bc6a712fc6985643734cf89c0a083
36.096491
122
0.574317
5.505859
false
false
false
false
lyft/SwiftLint
Source/SwiftLintFramework/Rules/ForWhereRule.swift
1
5654
import Foundation import SourceKittenFramework public struct ForWhereRule: ASTRule, ConfigurationProviderRule { public var configuration = SeverityConfiguration(.warning) public init() {} public static let description = RuleDescription( identifier: "for_where", name: "For Where", description: "`where` clauses are preferred over a single `if` inside a `for`.", kind: .idiomatic, nonTriggeringExamples: [ "for user in users where user.id == 1 { }\n", // if let "for user in users {\n" + " if let id = user.id { }\n" + "}\n", // if var "for user in users {\n" + " if var id = user.id { }\n" + "}\n", // if with else "for user in users {\n" + " if user.id == 1 { } else { }\n" + "}\n", // if with else if "for user in users {\n" + " if user.id == 1 {\n" + "} else if user.id == 2 { }\n" + "}\n", // if is not the only expression inside for "for user in users {\n" + " if user.id == 1 { }\n" + " print(user)\n" + "}\n", // if a variable is used "for user in users {\n" + " let id = user.id\n" + " if id == 1 { }\n" + "}\n", // if something is after if "for user in users {\n" + " if user.id == 1 { }\n" + " return true\n" + "}\n", // condition with multiple clauses "for user in users {\n" + " if user.id == 1 && user.age > 18 { }\n" + "}\n", // if case "for (index, value) in array.enumerated() {\n" + " if case .valueB(_) = value {\n" + " return index\n" + " }\n" + "}\n" ], triggeringExamples: [ "for user in users {\n" + " ↓if user.id == 1 { return true }\n" + "}\n" ] ) private static let commentKinds = SyntaxKind.commentAndStringKinds public func validate(file: File, kind: StatementKind, dictionary: [String: SourceKitRepresentable]) -> [StyleViolation] { guard kind == .forEach, let subDictionary = forBody(dictionary: dictionary), subDictionary.substructure.count == 1, let bodyDictionary = subDictionary.substructure.first, bodyDictionary.kind.flatMap(StatementKind.init) == .if, isOnlyOneIf(dictionary: bodyDictionary), isOnlyIfInsideFor(forDictionary: subDictionary, ifDictionary: bodyDictionary, file: file), !isComplexCondition(dictionary: bodyDictionary, file: file), let offset = bodyDictionary .offset else { return [] } return [ StyleViolation(ruleDescription: type(of: self).description, severity: configuration.severity, location: Location(file: file, byteOffset: offset)) ] } private func forBody(dictionary: [String: SourceKitRepresentable]) -> [String: SourceKitRepresentable]? { return dictionary.substructure.first(where: { subDict -> Bool in subDict.kind.flatMap(StatementKind.init) == .brace }) } private func isOnlyOneIf(dictionary: [String: SourceKitRepresentable]) -> Bool { let substructure = dictionary.substructure guard substructure.count == 1 else { return false } return dictionary.substructure.first?.kind.flatMap(StatementKind.init) == .brace } private func isOnlyIfInsideFor(forDictionary: [String: SourceKitRepresentable], ifDictionary: [String: SourceKitRepresentable], file: File) -> Bool { guard let offset = forDictionary.offset, let length = forDictionary.length, let ifOffset = ifDictionary.offset, let ifLength = ifDictionary.length else { return false } let beforeIfRange = NSRange(location: offset, length: ifOffset - offset) let ifFinalPosition = ifOffset + ifLength let afterIfRange = NSRange(location: ifFinalPosition, length: offset + length - ifFinalPosition) let allKinds = file.syntaxMap.kinds(inByteRange: beforeIfRange) + file.syntaxMap.kinds(inByteRange: afterIfRange) let doesntContainComments = !allKinds.contains { kind in !ForWhereRule.commentKinds.contains(kind) } return doesntContainComments } private func isComplexCondition(dictionary: [String: SourceKitRepresentable], file: File) -> Bool { let kind = "source.lang.swift.structure.elem.condition_expr" let contents = file.contents.bridge() return !dictionary.elements.filter { element in guard element.kind == kind, let offset = element.offset, let length = element.length, let range = contents.byteRangeToNSRange(start: offset, length: length) else { return false } let containsKeyword = !file.match(pattern: "\\blet|var|case\\b", with: [.keyword], range: range).isEmpty if containsKeyword { return true } return !file.match(pattern: "\\|\\||&&", with: [], range: range).isEmpty }.isEmpty } }
mit
e855657e3a8fe6ce68cdbf50aa04a3db
37.189189
116
0.535032
4.617647
false
false
false
false
Isuru-Nanayakkara/Swift-Extensions
Swift+Extensions/Swift+Extensions/Foundation/String+Extensions.swift
1
4777
import UIKit extension String { /// String encoded in base64. var base64Encoded: String? { let plainData = data(using: .utf8) return plainData?.base64EncodedString() } /// String decoded from base64. var base64Decoded: String? { guard let decodedData = Data(base64Encoded: self) else { return nil } return String(data: decodedData, encoding: .utf8) } /// First character of string. var firstCharacter: String? { return map({String($0)}).first } /// Check if string contains one or more letters. var hasLetters: Bool { return rangeOfCharacter(from: .letters, options: .numeric, range: nil) != nil } /// Check if string contains one or more numbers. var hasNumbers: Bool { return rangeOfCharacter(from: .decimalDigits, options: .literal, range: nil) != nil } /// Check if string contains only letters. var isAlphabetic: Bool { return hasLetters && !hasNumbers } /// Check if string contains only numbers. var isNumeric: Bool { return !hasLetters && hasNumbers } /// Check if string is valid email format. var isEmail: Bool { // http://stackoverflow.com/questions/25471114/how-to-validate-an-e-mail-address-in-swift let emailRegEx = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}" let emailTest = NSPredicate(format:"SELF MATCHES %@", emailRegEx) return emailTest.evaluate(with: self) } /// Reversed string. var reversed: String { return String(reversed()) } /// String with no spaces or new lines in beginning and end. var trimmed: String { return trimmingCharacters(in: .whitespacesAndNewlines) } /// Array with unicodes for all characters in a string. var unicodeArray: [Int] { return unicodeScalars.map({$0.hashValue}) } /// Readable string from a URL string. var urlDecoded: String { return removingPercentEncoding ?? self } /// URL escaped string. var urlEncoded: String { return addingPercentEncoding(withAllowedCharacters: .urlHostAllowed) ?? self } /// Bold string. var bold: NSAttributedString { return NSMutableAttributedString(string: self, attributes: convertToOptionalNSAttributedStringKeyDictionary([convertFromNSAttributedStringKey(NSAttributedString.Key.font): UIFont.boldSystemFont(ofSize: UIFont.systemFontSize)])) } /// Underlined string. var underline: NSAttributedString { return NSAttributedString(string: self, attributes: convertToOptionalNSAttributedStringKeyDictionary([convertFromNSAttributedStringKey(NSAttributedString.Key.underlineStyle): NSUnderlineStyle.single.rawValue])) } /// Italic string. var italic: NSAttributedString { return NSMutableAttributedString(string: self, attributes: convertToOptionalNSAttributedStringKeyDictionary([convertFromNSAttributedStringKey(NSAttributedString.Key.font): UIFont.italicSystemFont(ofSize: UIFont.systemFontSize)])) } /// Strikethrough string. var strikethrough: NSAttributedString { return NSAttributedString(string: self, attributes: convertToOptionalNSAttributedStringKeyDictionary([convertFromNSAttributedStringKey(NSAttributedString.Key.strikethroughStyle): NSNumber(value: NSUnderlineStyle.single.rawValue as Int)])) } var lastPathComponent: String { return (self as NSString).lastPathComponent } var pathExtension: String { return (self as NSString).pathExtension } var deletingLastPathComponent: String { return (self as NSString).deletingLastPathComponent } var deletingPathExtension: String { return (self as NSString).deletingPathExtension } var pathComponents: [String] { return (self as NSString).pathComponents } func appendingPathComponent(_ str: String) -> String { return (self as NSString).appendingPathComponent(str) } func appendingPathExtension(_ str: String) -> String? { return (self as NSString).appendingPathExtension(str) } } // Helper function inserted by Swift 4.2 migrator. fileprivate func convertToOptionalNSAttributedStringKeyDictionary(_ input: [String: Any]?) -> [NSAttributedString.Key: Any]? { guard let input = input else { return nil } return Dictionary(uniqueKeysWithValues: input.map { key, value in (NSAttributedString.Key(rawValue: key), value)}) } // Helper function inserted by Swift 4.2 migrator. fileprivate func convertFromNSAttributedStringKey(_ input: NSAttributedString.Key) -> String { return input.rawValue }
mit
de727fbb7d3817d7ad27c2e273756d1f
34.125
246
0.679925
5.319599
false
false
false
false
creatubbles/ctb-api-swift
CreatubblesAPIClientUnitTests/Spec/User/ReportUserRequestSpec.swift
1
2323
// // ReportUserRequestSpec.swift // CreatubblesAPIClient // // Copyright (c) 2017 Creatubbles Pte. Ltd. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Quick import Nimble @testable import CreatubblesAPIClient class ReportUserRequestSpec: QuickSpec { override func spec() { describe("Report user request") { it("Should have proper endpoint for user") { let userId = "userId" let message = "message" let request = ReportUserRequest(userId: userId, message: message) expect(request.endpoint) == "users/\(userId)/report" } it("Should have proper method") { let userId = "userId" let message = "message" let request = ReportUserRequest(userId: userId, message: message) expect(request.method) == RequestMethod.post } it("Should have proper parameters set") { let userId = "userId" let message = "message" let request = ReportUserRequest(userId: userId, message: message) let params = request.parameters expect(params["message"] as? String) == message } } } }
mit
6ff0c6039eebfe4532c13ca840bbe1ac
37.716667
81
0.651313
4.760246
false
false
false
false
steelwheels/Canary
Source/CNObjectCoder.swift
1
14626
/* * @file CNObjectCoder.swift * @brief Define CNObjectCoder class * @par Copyright * Copyright (C) 2017 Steel Wheels Project */ import Foundation private enum CNReservedWordId:Int { case OutputConnection case InputConnection public var description: String { get { var result: String switch self { case .OutputConnection: result = ">>" case .InputConnection: result = "<<" } return result } } public static func decode(firstChar fchar: Character, secondChar schar : Character) -> CNReservedWordId? { if fchar == ">" && schar == ">" { return .OutputConnection } else if fchar == "<" && schar == "<" { return .InputConnection } else { return nil } } public static func encode(reservedWordId rid: Int) -> String { var result: String if rid == CNReservedWordId.InputConnection.rawValue { let rword = CNReservedWordId.InputConnection result = rword.description } else if rid == CNReservedWordId.OutputConnection.rawValue { let rword = CNReservedWordId.OutputConnection result = rword.description } else { fatalError("Invalid raw value for enum") } return result } } public func CNEncodeObjectNotation(notation src: CNObjectNotation) -> String { let encoder = CNEncoder() return encoder.encode(indent: 0, notation: src) } public func CNDecodeObjectNotation(text src: String) -> (CNParseError, CNObjectNotation?) { do { let decoder = CNDecoder() let result = try decoder.decode(text: src) return (.NoError, result) } catch let error { if let psrerr = error as? CNParseError { return (psrerr, nil) } else { fatalError("Unknown error") } } } private class CNEncoder { public func encode(indent idt: Int, notation src: CNObjectNotation) -> String { let typename = src.typeName() let header = src.identifier + ": " + typename + " " let value = encodeValue(indent: idt, notation: src) return indent2string(indent: idt) + header + value ; } private func encodeValue(indent idt: Int, notation src: CNObjectNotation) -> String { var result: String switch src.value { case .PrimitiveValue(let v): result = v.description case .EventMethodValue(_, let script): result = "%{\n" result += script + "\n" result += indent2string(indent: idt) + "%}" case .ListenerMethodValue(_, let exps, let script): result = "" if exps.count > 0 { result += "[" var is1st = true for exp in exps { if is1st { is1st = false } else { result += ", " } result += exp.description } result += "] " } result += "%{\n" result += script + "\n" result += indent2string(indent: idt) + "%}" case .ClassValue(_, let children): result = "{\n" for child in children { result += encode(indent: idt+1, notation: child) + "\n" } result += indent2string(indent: idt) + "}" case .ConnectionValue(let type, let pathexp): switch type { case .InputConnection: result = "<<" case .OutputConnection: result = ">>" } result += pathexp.description } return result } private func indent2string(indent idt: Int) -> String { var result = "" for _ in 0..<idt { result += " " } return result ; } } private class CNDecoder { static let DO_DEBUG = false public func decode(text src: String) throws -> CNObjectNotation { /* Tokenier */ let (tkerr, tokens) = CNStringToToken(string: src) switch tkerr { case .NoError: /* Merge tokens */ let mtokens = mergeTokens(tokens: tokens) if CNDecoder.DO_DEBUG { dumpTokens(tokens: mtokens) } /* Decode tokens */ let (notation, _) = try decode(tokens: mtokens, index: 0) return notation case .TokenizeError(_, _), .ParseError(_, _): throw tkerr } } private func mergeTokens(tokens src: Array<CNToken>) -> Array<CNToken> { var result: Array<CNToken> = [] var idx = 0 let count = src.count while idx < count { switch src[idx].type { case .ReservedWordToken(_): result.append(src[idx]) idx += 1 case .SymbolToken(let c0): var didadded = false let idx1 = idx + 1 ; if idx1 < count { switch src[idx1].type { case .SymbolToken(let c1): if let rid = CNReservedWordId.decode(firstChar: c0, secondChar: c1) { let rtoken = CNToken(type: .ReservedWordToken(rid.rawValue), lineNo: src[idx].lineNo) result.append(rtoken) idx += 2 didadded = true } default: break } } if !didadded { result.append(src[idx]) idx += 1 } case .IdentifierToken(let ident): if ident == "true" { let newtoken = CNToken(type: .BoolToken(true), lineNo: src[idx].lineNo) result.append(newtoken) } else if ident == "false" { let newtoken = CNToken(type: .BoolToken(false), lineNo: src[idx].lineNo) result.append(newtoken) } else { result.append(src[idx]) } idx += 1 case .BoolToken(_), .IntToken(_), .UIntToken(_), .DoubleToken(_), .TextToken(_): result.append(src[idx]) idx += 1 case .StringToken(let str): var newstr = str var newidx = idx + 1 while newidx < count { if let nextstr = src[newidx].getString() { newstr += nextstr newidx += 1 } else { break } } result.append(CNToken(type: .StringToken(newstr), lineNo: src[idx].lineNo)) idx = newidx } } return result } public func decode(tokens src: Array<CNToken>, index idx: Int) throws -> (CNObjectNotation, Int) { /* Get identifier */ let (identp, idx0) = getIdentifier(tokens: src, index: idx) if identp == nil { let str = src[idx].toString() throw CNParseError.ParseError(src[idx].lineNo, "Identifier is required but \"\(str)\" is given") } /* Get ":" */ let (hascomma, idx1) = hasSymbol(tokens: src, index: idx0, symbol: ":") if !hascomma { throw CNParseError.ParseError(src[idx].lineNo, "\":\" is required after identifier \(identp!)") } /* Get type name */ let (typenamep, idx2) = getIdentifier(tokens: src, index: idx1) var typename: String if let t = typenamep { typename = t } else { throw CNParseError.ParseError(src[idx].lineNo, "Type name is expected") } if !(idx2 < src.count) { throw CNParseError.ParseError(src[idx].lineNo, "Object value is not declared") } /* Get value */ var objvalue3 : CNObjectNotation.ValueObject var idx3 : Int switch src[idx2].type { case .ReservedWordToken(let rid): idx3 = idx2 + 1 if idx3 < src.count { switch CNReservedWordId(rawValue: rid)! { case .InputConnection: let (pathexp, newidx) = try getPathExpression(tokens: src, index: idx3) objvalue3 = CNObjectNotation.ValueObject.ConnectionValue(type: .InputConnection, pathExpression: pathexp) idx3 = newidx case .OutputConnection: let (pathexp, newidx) = try getPathExpression(tokens: src, index: idx3) objvalue3 = CNObjectNotation.ValueObject.ConnectionValue(type: .OutputConnection, pathExpression: pathexp) idx3 = newidx } } else { throw CNParseError.ParseError(src[idx2].lineNo, "Pass expression is required") } case .SymbolToken(let sym): switch sym { case "{": let (objs, newidx) = try decodeClassValue(tokens: src, index: idx2) objvalue3 = CNObjectNotation.ValueObject.ClassValue(name: typename, value: objs) idx3 = newidx case "[": let type = try decodeType(tokens: src, index: idx, typeName: typename) let (exps, script, newidx) = try decodeMethodValue(tokens: src, index: idx2) if exps.count > 0 { objvalue3 = CNObjectNotation.ValueObject.ListenerMethodValue(type: type, pathExpressions: exps, script: script) } else { objvalue3 = CNObjectNotation.ValueObject.EventMethodValue(type: type, script: script) } idx3 = newidx default: throw CNParseError.ParseError(src[idx].lineNo, "Unexpected symbol \"\(sym)\"") } case .IdentifierToken(let ident): throw CNParseError.ParseError(src[idx].lineNo, "Unexpected identifier \"\(ident)\"") case .BoolToken(let value): objvalue3 = CNObjectNotation.ValueObject.PrimitiveValue(value: CNValue(booleanValue: value)) idx3 = idx2 + 1 case .IntToken(let value): objvalue3 = CNObjectNotation.ValueObject.PrimitiveValue(value: CNValue(intValue: value)) idx3 = idx2 + 1 case .UIntToken(let value): objvalue3 = CNObjectNotation.ValueObject.PrimitiveValue(value: CNValue(uIntValue: value)) idx3 = idx2 + 1 case .DoubleToken(let value): objvalue3 = CNObjectNotation.ValueObject.PrimitiveValue(value: CNValue(doubleValue: value)) idx3 = idx2 + 1 case .StringToken(let value): objvalue3 = CNObjectNotation.ValueObject.PrimitiveValue(value: CNValue(stringValue: value)) idx3 = idx2 + 1 case .TextToken(_): let type = try decodeType(tokens: src, index: idx, typeName: typename) let (exps, script, newidx) = try decodeMethodValue(tokens: src, index: idx2) if exps.count > 0 { objvalue3 = CNObjectNotation.ValueObject.ListenerMethodValue(type: type, pathExpressions: exps, script: script) } else { objvalue3 = CNObjectNotation.ValueObject.EventMethodValue(type: type, script: script) } idx3 = newidx } /* check type matching */ var objvalue4 : CNObjectNotation.ValueObject let idx4 : Int = idx3 objvalue4 = try cast(source: objvalue3, to: typename, lineNo: src[idx2].lineNo) /* allocate object notation */ return (CNObjectNotation(identifier: identp!, value: objvalue4, lineNo: src[idx].lineNo), idx4) } public func decodeClassValue(tokens src: Array<CNToken>, index idx: Int) throws -> (Array<CNObjectNotation>, Int) { var result: Array<CNObjectNotation> = [] var curidx = idx /* get "{" */ let (haslp, idx1) = hasSymbol(tokens: src, index: idx, symbol: "{") if !haslp { throw CNParseError.ParseError(src[idx].lineNo, "\"{\" is required") } curidx = idx1 /* get objects */ let count = src.count while curidx < count { let (hasrp, _) = hasSymbol(tokens: src, index: curidx, symbol: "}") if hasrp { break } /* get object */ let (newobj, idx2) = try decode(tokens: src, index: curidx) result.append(newobj) curidx = idx2 } /* get "}" */ let (hasrp, idx3) = hasSymbol(tokens: src, index: curidx, symbol: "}") if haslp && !hasrp { throw CNParseError.ParseError(src[idx].lineNo, "\"}\" is required") } curidx = idx3 return (result, curidx) } public func decodeMethodValue(tokens src: Array<CNToken>, index idx: Int) throws -> (Array<CNPathExpression>, String, Int) { /* get "[" */ var pathexps : Array<CNPathExpression> = [] var curidx = idx let (haslp0, idx0) = hasSymbol(tokens: src, index: curidx, symbol: "[") if haslp0 { curidx = idx0 var is1st = true while curidx < src.count { let (hasrp2, idx2) = hasSymbol(tokens: src, index: curidx, symbol: "]") if hasrp2 { curidx = idx2 break } else { /* get "," */ if is1st { is1st = false } else { let (hascm, idx3) = hasSymbol(tokens: src, index: curidx, symbol: ",") if hascm { curidx = idx3 } else { throw CNParseError.ParseError(src[curidx].lineNo, "\",\" is required") } } /* get path expression */ let (exp, idx4) = try getPathExpression(tokens: src, index: curidx) pathexps.append(exp) curidx = idx4 } } } /* Get text */ if curidx < src.count { switch src[curidx].type { case .TextToken(let script): let newidx = curidx + 1 return (pathexps, script, newidx) default: break } } throw CNParseError.ParseError(src[curidx].lineNo, "script of method is required") } private func decodeType(tokens src: Array<CNToken>, index idx: Int, typeName name: String) throws -> CNValueType { if let type = CNValueType.decode(typeName: name) { return type } else { throw CNParseError.ParseError(src[idx].lineNo, "Unknown data type: \"\(name)\"") } } private func cast(source src: CNObjectNotation.ValueObject, to dststr: String, lineNo line: Int) throws -> (CNObjectNotation.ValueObject) { var result: CNObjectNotation.ValueObject? = nil switch dststr { case "Bool": switch src { case .PrimitiveValue(let srcval): if let dstval = srcval.cast(to: .BooleanType) { result = .PrimitiveValue(value: dstval) } default: break } case "Int": switch src { case .PrimitiveValue(let srcval): if let dstval = srcval.cast(to: .IntType) { result = .PrimitiveValue(value: dstval) } default: break } case "UInt": switch src { case .PrimitiveValue(let srcval): if let dstval = srcval.cast(to: .UIntType) { result = .PrimitiveValue(value: dstval) } default: break } case "Double": switch src { case .PrimitiveValue(let srcval): if let dstval = srcval.cast(to: .DoubleType) { result = .PrimitiveValue(value: dstval) } default: break } case "Array": switch src { case .PrimitiveValue(let srcval): if let dstval = srcval.cast(to: .ArrayType) { result = .PrimitiveValue(value: dstval) } default: break } default: result = src } if let r = result { return r } else { throw CNParseError.TokenizeError(line, "Could not cast") } } private func getIdentifier(tokens src: Array<CNToken>, index idx: Int) -> (String?, Int) { let count = src.count if idx < count { if let ident = src[idx].getIdentifier() { return (ident, idx+1) } } return (nil, idx) } private func getPathExpression(tokens src:Array<CNToken>, index idx: Int) throws -> (CNPathExpression, Int) { var elms: Array<String> = [] var newidx = idx var is1st = true var docont = true while docont { if !is1st { let (hascm, idx1) = hasSymbol(tokens: src, index: newidx, symbol: ".") if hascm { newidx = idx1 } else { docont = false break } } else { is1st = false } let (identp, idx2) = getIdentifier(tokens: src, index: newidx) if let ident = identp { elms.append(ident) newidx = idx2 } else { throw CNParseError.ParseError(src[newidx].lineNo, "The identifier is required") } } return (CNPathExpression(pathElements: elms), newidx) } private func hasSymbol(tokens src:Array<CNToken>, index idx: Int, symbol sym: Character) -> (Bool, Int) { if idx < src.count { if src[idx].getSymbol() == sym { return (true, idx+1) } } return (false, idx) } private func dumpTokens(tokens tkns: Array<CNToken>){ print("[Tokens]") for token in tkns { print(" \(token.description)") } } }
gpl-2.0
69d518168f5041dcc96d1c2a27d5e617
27.235521
140
0.645084
3.117221
false
false
false
false
adamahrens/noisily
Noisily/Noisily/ViewControllers/NoiseSelectionViewController.swift
1
6060
// // NoiseSelectionViewController.swift // Noisily // // Created by Adam Ahrens on 3/4/15. // Copyright (c) 2015 Appsbyahrens. All rights reserved. // import UIKit class NoiseSelectionViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource { @IBOutlet weak var collectionView: UICollectionView! private let backgroundRandomizer = BackgroundColorRandomizer() private let dataSource = NoiseDataSource() private var timer : NSTimer? private var cellWidth = 0.0 private var cellHeight = 0.0 //MARK: View Lifecycle override func viewDidLoad() { super.viewDidLoad() collectionView.backgroundColor! = UIColor.clearColor() self.view.backgroundColor = backgroundRandomizer.randomBackgroundColor() configureCellSizeForCurrentTraitCollection(self.traitCollection) } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) timer = NSTimer.scheduledTimerWithTimeInterval(70.0, target: self, selector: #selector(NoiseSelectionViewController.changeBackgroundColor), userInfo: nil, repeats: true) } override func viewDidDisappear(animated: Bool) { super.viewDidDisappear(animated) timer!.invalidate() timer = nil } // override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) { // } //MARK: TraitCollection override func willTransitionToTraitCollection(newCollection: UITraitCollection, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) { super.willTransitionToTraitCollection(newCollection, withTransitionCoordinator: coordinator) // Animate the reloading of the collectionView configureCellSizeForCurrentTraitCollection(newCollection) coordinator.animateAlongsideTransition({context in self.collectionView.reloadData()}, completion: nil) } //MARK: NSTimer Selector func changeBackgroundColor() { let newBackgroundColor = backgroundRandomizer.randomBackgroundColor() let animation = CABasicAnimation(keyPath: "backgroundColor") animation.fromValue = self.view.backgroundColor?.CGColor animation.toValue = newBackgroundColor.CGColor animation.duration = 10 self.view.layer.addAnimation(animation, forKey: "fadeAnimation") self.view.backgroundColor = newBackgroundColor } //MARK: UICollectionView Datasource & Delegate func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int { return dataSource.numberOfSections() } func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { // Adding extra for plus return dataSource.numberOfNoises() + 1 } func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCellWithReuseIdentifier("NoiseCollectionViewCell", forIndexPath: indexPath) as! NoiseCollectionViewCell cell.backgroundColor! = UIColor.clearColor() if indexPath.row == dataSource.numberOfNoises() { cell.imageView.image = UIImage(named: "Plus") cell.volumeSlider.hidden = true } else { let noise = dataSource.noiseAtIndexPath(indexPath) cell.imageView.image = UIImage(named: noise.imageName) cell.volumeSlider.value = Float(dataSource.currentVolumeForNoise(noise)) cell.volumeSlider.addTarget(self, action: #selector(NoiseSelectionViewController.volumeSliderChanged(_:)), forControlEvents: .ValueChanged) cell.volumeSlider.tag = indexPath.row cell.volumeSlider.hidden = !dataSource.noiseIsPlaying(indexPath) } return cell } func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize { return CGSize(width: cellWidth, height: cellHeight) } func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) { if indexPath.row == dataSource.numberOfNoises() { self.performSegueWithIdentifier("ShowLayeringViewController", sender: nil) } else { dataSource.toggleNoiseAtIndexPath(indexPath) collectionView.reloadItemsAtIndexPaths([indexPath]) } } //MARK: Volume Changes func volumeSliderChanged(slider: UISlider) { let noise = dataSource.noiseAtIndexPath(NSIndexPath(forRow: slider.tag, inSection: 0)) dataSource.updateVolumeForNoise(noise, volume: Double(slider.value)) } //MARK: Private private func configureCellSizeForCurrentTraitCollection(traitCollection: UITraitCollection) { // iPhone 4, 5, 6 in Landscape if traitCollection.horizontalSizeClass == .Compact && traitCollection.verticalSizeClass == .Compact { cellWidth = 120.0 cellHeight = 130.0 } // iPhone 6+ in Landscape if traitCollection.horizontalSizeClass == .Regular && traitCollection.verticalSizeClass == .Compact { cellWidth = 160.0 cellHeight = 180.0 } // iPhone's in portrait if traitCollection.horizontalSizeClass == .Compact && traitCollection.verticalSizeClass == .Regular { cellWidth = 120.0 cellHeight = 150.0 } // iPad Portrait or Landscape // Check if pad. Could eventually have a phone that's Regular // in Vertical & Horizontal size class if traitCollection.userInterfaceIdiom == .Pad && traitCollection.horizontalSizeClass == .Regular && traitCollection.verticalSizeClass == .Regular { cellWidth = 300.0 cellHeight = 300.0 } } }
mit
ba5c081b13d3ea557f3257b5c417d026
42.285714
177
0.698845
5.849421
false
false
false
false
julienbodet/wikipedia-ios
WikipediaUnitTests/Code/MockNetworkReachabilityManager.swift
1
2859
import Foundation import SystemConfiguration @objc(WMFMockNetworkReachabilityManager) class MockNetworkReachabilityManager : AFNetworkReachabilityManager { fileprivate static let _sharedInstance = MockNetworkReachabilityManager() fileprivate var _networkReachabilityStatus: AFNetworkReachabilityStatus override var networkReachabilityStatus: AFNetworkReachabilityStatus { get { return _networkReachabilityStatus } set { let oldValue = _networkReachabilityStatus _networkReachabilityStatus = newValue if (oldValue != newValue) { if let block = _reachabilityStatusChangeBlock { block(newValue) } } } } override var isReachableViaWiFi: Bool { get { return (_networkReachabilityStatus == .reachableViaWiFi) } } override var isReachableViaWWAN: Bool { get { return (_networkReachabilityStatus == .reachableViaWWAN) } } override var isReachable: Bool { get { return isReachableViaWWAN || isReachableViaWiFi } } fileprivate var _reachabilityStatusChangeBlock: ((AFNetworkReachabilityStatus) -> Swift.Void)? override func startMonitoring() { // do nothing } override func stopMonitoring() { // do nothing } public init() { _networkReachabilityStatus = AFNetworkReachabilityStatus.unknown // you _must_ call the designated initializer (eyeroll) var zeroAddress = sockaddr_in() zeroAddress.sin_len = UInt8(MemoryLayout<sockaddr_in>.size) zeroAddress.sin_family = sa_family_t(AF_INET) let defaultRouteReachability = withUnsafePointer(to: &zeroAddress, { $0.withMemoryRebound(to: sockaddr.self, capacity: 1) { SCNetworkReachabilityCreateWithAddress(nil, $0) } }) super.init(reachability: defaultRouteReachability!) } override func setReachabilityStatusChange(_ block: ((AFNetworkReachabilityStatus) -> Swift.Void)?) { _reachabilityStatusChangeBlock = block } override class func shared() -> Self { return sharedHelper() // swift is annoying sometimes } private class func sharedHelper<T>() -> T { return _sharedInstance as! T } override private init(reachability: SCNetworkReachability) { assertionFailure("not implemented") _networkReachabilityStatus = AFNetworkReachabilityStatus.unknown super.init(reachability: reachability) } override open func localizedNetworkReachabilityStatusString() -> String { assertionFailure("not implemented") return "" } }
mit
79199ef0c94d4b4779ac2e28ef0ec309
29.094737
104
0.632389
6.108974
false
false
false
false
alperdemirci/To-Do
To Do/AppDelegate.swift
1
2869
// // AppDelegate.swift // To Do // // Created by alper on 5/11/17. // Copyright © 2017 alper. All rights reserved. // import UIKit import Firebase @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { let isUserLoggedIn:Bool = UserDefaults.standard.bool(forKey: "isUserLoggedIn") if(isUserLoggedIn) { print("user is logged in") // let vc = UIStoryboard(name:"ListItemsView", bundle:nil).instantiateViewController(withIdentifier: "listItem") as? ListItemTableViewController // let protectedPage = rootViewController?.pushViewController(vc!, animated:true) // window!.rootViewController = protectedPage // window!.makeKeyAndVisible() } else { print("user isn't logged in") } return true } override init() { super.init() FirebaseApp.configure() // not really needed unless you really need it FIRDatabase.database().persistenceEnabled = true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
mit
e39a2ee05cd41ebd04096fa0b00ba47e
45.258065
285
0.721757
5.504798
false
false
false
false
phillips07/StudyCast
StudyCast/AddGroupController.swift
1
6014
// // AddGroupController.swift // StudyCast // // Created by Dennis Huebert on 2016-11-18. // Copyright © 2016 Austin Phillips. All rights reserved. // // testing comment import UIKit class AddGroupController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource { var userCourses = [String]() var userName = String() var groupClass = "" var imgURL = "" override func viewDidLoad() { super.viewDidLoad() self.hideKeyboardWhenTappedAround() view.backgroundColor = UIColor(r: 61, g: 91, b: 151) self.navigationController?.navigationBar.barTintColor = UIColor(r: 61, g: 91, b: 151) self.navigationController?.navigationBar.tintColor = UIColor.white view.addSubview(cancelButton) view.addSubview(nameTextField) view.addSubview(groupImageView) view.addSubview(classLabel) view.addSubview(userClassPicker) view.addSubview(createGroupButton) setupCancelButton() setupNameTextField() setupGroupImageView() setupClassLabel() setupUserClassPicker() setupCreateGroupButton() fetchClasses() //setCurrentClass(row: 0) } let cancelButton: UIButton = { let button = UIButton(type: .system) button.setTitle("Cancel", for: UIControlState()) button.translatesAutoresizingMaskIntoConstraints = false button.setTitleColor(UIColor.white, for: UIControlState()) button.titleLabel?.font = UIFont.boldSystemFont(ofSize: 16) button.addTarget(nil, action: #selector(handleBack), for: .touchUpInside) return button }() lazy var groupImageView: UIImageView = { let imageView = UIImageView() imageView.image = UIImage(named: "AddProfileImage3") imageView.translatesAutoresizingMaskIntoConstraints = false imageView.layer.cornerRadius = imageView.frame.size.width/2 imageView.clipsToBounds = true imageView.contentMode = .scaleAspectFill imageView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(handleSelectProfileImageView))) imageView.isUserInteractionEnabled = true return imageView }() let nameTextField: UITextField = { let tf = UITextField() tf.placeholder = " Group Name" tf.translatesAutoresizingMaskIntoConstraints = false return tf }() lazy var userClassPicker: UIPickerView = { let picker = UIPickerView() picker.backgroundColor = UIColor.white picker.layer.cornerRadius = 6 picker.translatesAutoresizingMaskIntoConstraints = false picker.dataSource = self picker.delegate = self return picker }() let classLabel: UILabel = { let label = UILabel() label.text = "Select Group Class" label.textColor = UIColor.white label.font = UIFont.boldSystemFont(ofSize: 14) label.textAlignment = NSTextAlignment.center label.translatesAutoresizingMaskIntoConstraints = false return label }() lazy var createGroupButton: UIButton = { let button = UIButton(type: .system) button.backgroundColor = UIColor(r: 80, g: 101, b: 161) button.setTitle("Create Group", for: UIControlState()) button.translatesAutoresizingMaskIntoConstraints = false button.setTitleColor(UIColor.white, for: UIControlState()) button.titleLabel?.font = UIFont.boldSystemFont(ofSize: 16) button.addTarget(self, action: #selector(handleCreateGroup), for: .touchUpInside) return button }() func setupCancelButton() { cancelButton.leftAnchor.constraint(equalTo: view.leftAnchor, constant: 10).isActive = true cancelButton.topAnchor.constraint(equalTo: view.topAnchor, constant: 25).isActive = true } func setupGroupImageView(){ groupImageView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true groupImageView.bottomAnchor.constraint(equalTo: nameTextField.centerYAnchor, constant: -70).isActive = true groupImageView.widthAnchor.constraint(equalToConstant: 125).isActive = true groupImageView.heightAnchor.constraint(equalToConstant: 125).isActive = true } func setupNameTextField(){ nameTextField.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true nameTextField.centerYAnchor.constraint(equalTo: view.centerYAnchor, constant: -20).isActive = true nameTextField.widthAnchor.constraint(equalTo: view.widthAnchor, constant: -140).isActive = true nameTextField.heightAnchor.constraint(equalToConstant: 35).isActive = true nameTextField.backgroundColor = UIColor.white nameTextField.layer.cornerRadius = 6.0 } func setupClassLabel() { classLabel.leftAnchor.constraint(equalTo: nameTextField.leftAnchor).isActive = true classLabel.topAnchor.constraint(equalTo: nameTextField.bottomAnchor, constant: 15).isActive = true } func setupUserClassPicker(){ userClassPicker.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true userClassPicker.topAnchor.constraint(equalTo: classLabel.bottomAnchor, constant: 8).isActive = true userClassPicker.widthAnchor.constraint(equalTo: nameTextField.widthAnchor).isActive = true userClassPicker.heightAnchor.constraint(equalToConstant: 50).isActive = true } func setupCreateGroupButton() { createGroupButton.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true createGroupButton.topAnchor.constraint(equalTo: userClassPicker.bottomAnchor, constant: 20).isActive = true createGroupButton.widthAnchor.constraint(equalTo: nameTextField.widthAnchor).isActive = true createGroupButton.heightAnchor.constraint(equalToConstant: 45).isActive = true } }
mit
d98a5148f227349dc42199ebb466f0c7
40.468966
125
0.695327
5.316534
false
false
false
false
mapsme/omim
iphone/Maps/Core/Theme/MapStyleSheet.swift
4
3988
class MapStyleSheet: IStyleSheet { static func register(theme: Theme, colors: IColors, fonts: IFonts) { theme.add(styleName: "MenuButtonDisabled") { (s) -> (Void) in s.fontColor = colors.blackSecondaryText s.font = fonts.regular10 s.backgroundColor = colors.clear s.borderColor = colors.clear s.borderWidth = 0 s.cornerRadius = 6 } theme.add(styleName: "MenuButtonEnabled") { (s) -> (Void) in s.fontColor = colors.linkBlue s.font = fonts.regular10 s.backgroundColor = colors.linkBlue s.borderColor = colors.linkBlue s.borderWidth = 2 s.cornerRadius = 6 } theme.add(styleName: "StreetNameBackgroundView") { (s) -> (Void) in s.backgroundColor = colors.white s.shadowRadius = 2 s.shadowColor = UIColor(0, 0, 0, alpha26) s.shadowOpacity = 1 s.shadowOffset = CGSize(width: 0, height: 1) } theme.add(styleName: "PPRatingView") { (s) -> (Void) in s.backgroundColor = colors.blackOpaque s.round = true } theme.add(styleName: "PPRatingHorrible") { (s) -> (Void) in s.image = "ic_24px_rating_horrible" s.tintColor = colors.ratingRed } theme.add(styleName: "PPRatingBad") { (s) -> (Void) in s.image = "ic_24px_rating_bad" s.tintColor = colors.ratingOrange } theme.add(styleName: "PPRatingNormal") { (s) -> (Void) in s.image = "ic_24px_rating_normal" s.tintColor = colors.ratingYellow } theme.add(styleName: "PPRatingGood") { (s) -> (Void) in s.image = "ic_24px_rating_good" s.tintColor = colors.ratingLightGreen } theme.add(styleName: "PPRatingExellent") { (s) -> (Void) in s.image = "ic_24px_rating_excellent" s.tintColor = colors.ratingGreen } theme.add(styleName: "PPButton", from: "FlatNormalTransButtonBig") { (s) -> (Void) in s.borderColor = colors.linkBlue s.borderWidth = 1 } theme.add(styleName: "ButtonZoomIn") { (s) -> (Void) in s.mwmImage = "btn_zoom_in" } theme.add(styleName: "ButtonZoomOut") { (s) -> (Void) in s.mwmImage = "btn_zoom_out" } theme.add(styleName: "ButtonPending") { (s) -> (Void) in s.mwmImage = "btn_pending" } theme.add(styleName: "ButtonGetPosition") { (s) -> (Void) in s.mwmImage = "btn_get_position" } theme.add(styleName: "ButtonFollow") { (s) -> (Void) in s.mwmImage = "btn_follow" } theme.add(styleName: "ButtonFollowAndRotate") { (s) -> (Void) in s.mwmImage = "btn_follow_and_rotate" } theme.add(styleName: "ButtonMapBookmarks") { (s) -> (Void) in s.mwmImage = "ic_routing_bookmark" } theme.add(styleName: "PromoDiscroveryButton") { (s) -> (Void) in s.mwmImage = "promo_discovery_button" } theme.add(styleName: "ButtonBookmarksBack") { (s) -> (Void) in s.mwmImage = "btn_back" } theme.add(styleName: "ButtonBookmarksBackOpaque") { (s) -> (Void) in s.mwmImage = "btn_back_opaque" } theme.add(styleName: "FirstTurnView") { (s) -> (Void) in s.backgroundColor = colors.linkBlue s.cornerRadius = 4 s.shadowRadius = 2 s.shadowColor = colors.blackHintText s.shadowOpacity = 1 s.shadowOffset = CGSize(width: 0, height: 2) } theme.add(styleName: "SecondTurnView", from: "FirstTurnView") { (s) -> (Void) in s.backgroundColor = colors.white } theme.add(styleName: "MapAutoupdateView") { (s) -> (Void) in s.shadowOffset = CGSize(width: 0, height: 3) s.shadowRadius = 6 s.cornerRadius = 4 s.shadowOpacity = 1 s.backgroundColor = colors.white } theme.add(styleName: "GuidesNavigationBar") { (s) -> (Void) in s.barTintColor = colors.white s.tintColor = colors.linkBlue s.backgroundImage = UIImage() s.shadowImage = UIImage() s.font = fonts.regular18 s.fontColor = colors.blackPrimaryText } } }
apache-2.0
e743a4033e0cf34563596600cff0e425
28.761194
89
0.607322
3.373942
false
false
false
false
xmartlabs/XLSwiftKit
Sources/RoundedView.swift
1
2580
// // RoundedView.swift // XLSwiftKit ( https://github.com/xmartlabs/XLSwiftKit ) // // 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 open class RoundedView: UIView { public override init(frame: CGRect) { super.init(frame: frame) setup() } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setup() } fileprivate func setup() { clipsToBounds = true } open override func layoutSubviews() { super.layoutSubviews() layer.cornerRadius = bounds.width / 2 } } open class RoundedButton: UIButton { public override init(frame: CGRect) { super.init(frame: frame) setup() } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setup() } fileprivate func setup() { clipsToBounds = true } open override func layoutSubviews() { super.layoutSubviews() layer.cornerRadius = bounds.width / 2 } } open class RoundedImageView: UIImageView { public override init(frame: CGRect) { super.init(frame: frame) setup() } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setup() } fileprivate func setup() { clipsToBounds = true } open override func layoutSubviews() { super.layoutSubviews() layer.cornerRadius = bounds.width / 2 } }
mit
d0aa09ef87838696e0214aebf07dc8b3
26.157895
80
0.672093
4.542254
false
false
false
false
LoveZYForever/HXWeiboPhotoPicker
Pods/HXPHPicker/Sources/HXPHPicker/Camera/Controller/CameraViewController+Location.swift
1
947
// // CameraViewController+Location.swift // HXPHPicker // // Created by Slience on 2021/9/1. // import UIKit import CoreLocation extension CameraViewController: CLLocationManagerDelegate { var allowLocation: Bool { let whenIn = Bundle.main.object(forInfoDictionaryKey: "NSLocationWhenInUseUsageDescription") != nil let always = Bundle.main.object(forInfoDictionaryKey: "NSLocationAlwaysUsageDescription") != nil return config.allowLocation && (whenIn || always) } func startLocation() { if !allowLocation { return } if CLLocationManager.authorizationStatus() != .denied { locationManager.startUpdatingLocation() didLocation = true } } public func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { if !locations.isEmpty { currentLocation = locations.last } } }
mit
452b7a64495c32bfe879d26b67108276
28.59375
107
0.670539
5.350282
false
false
false
false
BrobotDubstep/BurningNut
BurningNut/BurningNut/Scenes/GameOverScene.swift
1
1508
// // GameOverScene.swift // BurningNut // // Created by Victor Gerling on 25.09.17. // Copyright © 2017 Tim Olbrich. All rights reserved. // import Foundation import SpriteKit class GameOverScene: SKScene { init(size: CGSize, won:Bool) { super.init(size: size) backgroundColor = SKColor.white var message = String() if(GameState.shared.playerNumber == 1 && !won || GameState.shared.playerNumber == 2 && won) { message = "Du hast gewonnen!" } else { message = "Du hast leider verloren!" } let label = SKLabelNode(fontNamed: "Chalkduster") label.text = message label.fontSize = 40 label.fontColor = SKColor.black label.position = CGPoint(x: size.width/2, y: size.height/2) addChild(label) GameState.shared.leftScore = 0 GameState.shared.rightScore = 0 run(SKAction.sequence([ SKAction.wait(forDuration: 3.0), SKAction.run() { if let scene = SKScene(fileNamed: "GameScene") { let reveal = SKTransition.flipHorizontal(withDuration: 0.5) scene.scaleMode = .aspectFill self.view?.presentScene(scene, transition:reveal) } } ])) } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
mit
4e836a76f8eb79c736214ab17c69e065
27.980769
101
0.550763
4.511976
false
false
false
false
ibm-bluemix-omnichannel-iclabs/ICLab-OmniChannelAppDev
iOS/BMDService/LoginViewController.swift
1
3593
// // ViewController.swift // BMDService // // Created by Anantha Krishnan K G on 16/02/17. // Copyright © 2017 Ananth. All rights reserved. // import UIKit import BluemixAppID import BMSCore import BMSAnalytics class LoginViewController: UIViewController, UITextFieldDelegate { let appDelegate = UIApplication.shared.delegate as! AppDelegate @IBOutlet var userNameText: UITextField! @IBOutlet var passwordText: UITextField! @IBOutlet var containerView: UIView! @IBOutlet var activityController: UIActivityIndicatorView! override func viewDidLoad() { super.viewDidLoad() activityController.isHidden = true; // Do any additional setup after loading the view, typically from a nib. self.userNameText.delegate = self self.passwordText.delegate = self let border = CALayer() border.frame = CGRect(x: 6, y: self.userNameText.frame.size.height - 2, width: self.userNameText.frame.size.width - 12, height: 0.2) border.borderColor = UIColor.black.cgColor border.borderWidth = 0.2 self.userNameText.layer.addSublayer(border) let border1 = CALayer() border1.frame = CGRect(x: 0, y: 0, width: self.containerView.frame.size.width, height: 0.2) border1.borderColor = UIColor.black.cgColor border1.borderWidth = 0.2 self.containerView.layer.addSublayer(border1) let border2 = CALayer() border2.frame = CGRect(x: 0, y: self.containerView.frame.size.height, width: self.containerView.frame.size.width, height: 0.2) border2.borderColor = UIColor.black.cgColor border2.borderWidth = 0.2 self.containerView.layer.addSublayer(border2) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func NeedToImplement(_ sender: Any) { print("Have to Implement") } @IBAction func log_inAppID(_ sender: AnyObject) { activityController.isHidden = false; //Invoking AppID login class delegate : AuthorizationDelegate { var view:UIViewController init(view:UIViewController) { self.view = view } public func onAuthorizationSuccess(accessToken: AccessToken, identityToken: IdentityToken, response:Response?) { let appDelegate = UIApplication.shared.delegate as! AppDelegate appDelegate.userID = identityToken.name ?? (identityToken.email?.components(separatedBy: "@"))?[0] ?? "Guest" let mainView = UIApplication.shared.keyWindow?.rootViewController let afterLoginView = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "ProfileViewController") as? ProfileViewController DispatchQueue.main.async { mainView?.present(afterLoginView!, animated: true, completion: nil) } } public func onAuthorizationCanceled() { print("cancel") } public func onAuthorizationFailure(error: AuthorizationError) { print(error) } } AppID.sharedInstance.loginWidget?.launch(delegate: delegate(view: self)) } }
apache-2.0
c27e128b5fdb7b58d05326ed37157182
32.570093
170
0.611637
5.168345
false
false
false
false
tkremenek/swift
test/IRGen/prespecialized-metadata/struct-outmodule-frozen-1argument-1distinct_use-struct-outmodule-frozen-samemodule.swift
16
3056
// RUN: %empty-directory(%t) // RUN: %target-build-swift -Xfrontend -prespecialize-generic-metadata -target %module-target-future %S/Inputs/struct-public-frozen-1argument.swift %S/Inputs/struct-public-frozen-0argument.swift -emit-library -o %t/%target-library-name(Generic) -emit-module -module-name Generic -emit-module-path %t/Generic.swiftmodule -enable-library-evolution // RUN: %swift -prespecialize-generic-metadata -target %module-target-future -emit-ir %s -L %t -I %t -lGeneric | %FileCheck %s -DINT=i%target-ptrsize -DALIGNMENT=%target-alignment // REQUIRES: VENDOR=apple || OS=linux-gnu // UNSUPPORTED: CPU=i386 && OS=ios // UNSUPPORTED: CPU=armv7 && OS=ios // UNSUPPORTED: CPU=armv7s && OS=ios // CHECK: @"$s7Generic11OneArgumentVyAA7IntegerVGMN" = linkonce_odr hidden constant <{ // CHECK-SAME: i8**, // CHECK-SAME: [[INT]], // CHECK-SAME: %swift.type_descriptor*, // CHECK-SAME: %swift.type*, // CHECK-SAME: i32, // CHECK-SAME: i32, // CHECK-SAME: i64 // CHECK-SAME: }> <{ // : i8** getelementptr inbounds ( // : %swift.vwtable, // : %swift.vwtable* @" // CHECK-SAME: $s7Generic11OneArgumentVyAA7IntegerVGWV // : ", // : i32 0, // : i32 0 // : ), // CHECK-SAME: [[INT]] 512, // : %swift.type_descriptor* @" // CHECK-SAME: $s7Generic11OneArgumentVMn // : ", // CHECK-SAME: %swift.type* @"$s7Generic7IntegerVN", // CHECK-SAME: i32 0, // CHECK-SAME: i32 {{4|8}}, // CHECK-SAME: i64 1 // CHECK-SAME: }>, // CHECK-SAME: align [[ALIGNMENT]] @inline(never) func consume<T>(_ t: T) { withExtendedLifetime(t) { t in } } import Generic // CHECK: define hidden swiftcc void @"$s4main4doityyF"() #{{[0-9]+}} { // CHECK: [[CANONICALIZED_METADATA_RESPONSE:%[0-9]+]] = call swiftcc %swift.metadata_response @swift_getCanonicalSpecializedMetadata( // CHECK-SAME: [[INT]] 0, // CHECK-SAME: %swift.type* getelementptr inbounds ( // CHECK-SAME: %swift.full_type, // CHECK-SAME: %swift.full_type* bitcast ( // CHECK-SAME: <{ // CHECK-SAME: i8**, // CHECK-SAME: [[INT]], // CHECK-SAME: %swift.type_descriptor*, // CHECK-SAME: %swift.type*, // CHECK-SAME: i32, // CHECK-SAME: i32, // CHECK-SAME: i64 // CHECK-SAME: }>* @"$s7Generic11OneArgumentVyAA7IntegerVGMN" to %swift.full_type* // CHECK-SAME: ), // CHECK-SAME: i32 0, // CHECK-SAME: i32 1 // CHECK-SAME: ), // CHECK-SAME: %swift.type** @"$s7Generic11OneArgumentVyAA7IntegerVGMJ" // CHECK-SAME: ) // CHECK-NEXT: [[CANONICALIZED_METADATA:%[0-9]+]] = extractvalue %swift.metadata_response [[CANONICALIZED_METADATA_RESPONSE]], 0 // CHECK-NEXT: call swiftcc void @"$s4main7consumeyyxlF"( // CHECK-SAME: %swift.opaque* noalias nocapture {{%[0-9]+}}, // CHECK-SAME: %swift.type* [[CANONICALIZED_METADATA]] // CHECK-SAME: ) // CHECK: } func doit() { consume( OneArgument(Integer(13)) ) } doit()
apache-2.0
0b15fe72fdc210bb8ec5795e31e77ade
37.683544
345
0.607003
3.150515
false
false
false
false
ndagrawal/TwitterRedux
TwitterRedux/Tweet.swift
1
876
// // Tweet.swift // TwitterOAuthDemo // // Created by Nilesh on 10/10/15. // Copyright © 2015 CA. All rights reserved. // import UIKit class Tweet: NSObject { var user: User? var text: String? var createdAtString : String? var createdAt: NSDate? init(dictionary:NSDictionary){ user = User(dictionary: dictionary["user"] as! NSDictionary) text = dictionary["text"] as? String createdAtString = dictionary["created_at"] as? String let formatter = NSDateFormatter() formatter.dateFormat = "EEE MMM d HH:MM:ss Z y" createdAt = formatter.dateFromString(createdAtString!) } class func tweetsWithArray(array:[NSDictionary])->[Tweet]{ var tweets = [Tweet]() for dictionary in array{ tweets.append(Tweet(dictionary: dictionary)) } return tweets } }
mit
a87bff34aec140aa70515b809af00148
24
68
0.632
4.247573
false
false
false
false
qualaroo/QualarooSDKiOS
Qualaroo/Survey/Body/LeadGenForm/LeadGenFormView.swift
1
2293
// // LeadGenFormView.swift // Qualaroo // // Copyright (c) 2018, Qualaroo, Inc. All Rights Reserved. // // Please refer to the LICENSE.md file for the terms and conditions // under which redistribution and use of this file is permitted. // import Foundation typealias LeadGenFormItem = (questionId: NodeId, canonicalName: String?, questionAlias: String?, title: String, kayboardType: UIKeyboardType, isRequired: Bool) class LeadGenFormView: UIView, FocusableAnswerView { var presenter: LeadGenFormPresenter? var cells = [LeadGenFormCell]() @IBOutlet weak var cellsScrollContainer: UIScrollView! @IBOutlet weak var scrollViewHeightConstraint: NSLayoutConstraint! @IBOutlet weak var topBorderLine: UIView! @IBOutlet weak var topBorderHeightConstraint: NSLayoutConstraint! @IBOutlet weak var bottomBorderLine: UIView! @IBOutlet weak var bottomBorderHeightConstraint: NSLayoutConstraint! func setupView(withBorderColor borderColor: UIColor, textColor: UIColor, keyboardStyle: UIKeyboardAppearance, cells: [LeadGenFormCell], presenter: LeadGenFormPresenter) { self.presenter = presenter commonSetup(withSeparatorColor: textColor) setup(withCells: cells) presenter.textDidChange() } override func layoutSubviews() { super.layoutSubviews() scrollViewHeightConstraint.constant = cellsScrollContainer.contentSize.height } private func commonSetup(withSeparatorColor color: UIColor) { translatesAutoresizingMaskIntoConstraints = false topBorderHeightConstraint.constant = 0.5 bottomBorderHeightConstraint.constant = 0.5 topBorderLine.backgroundColor = color.withAlphaComponent(0.5) bottomBorderLine.backgroundColor = color.withAlphaComponent(0.5) } func setup(withCells cells: [LeadGenFormCell]) { self.cells = cells NSLayoutConstraint.fillScrollView(cellsScrollContainer, with: cells, margin: 0, spacing: 1) scrollViewHeightConstraint.constant = 0 cells.first?.removeTopSeparator() } func getFocus() { cells.first?.answerTextField.becomeFirstResponder() } }
mit
f1f33d9d31cc6c465f581acd208b6866
33.223881
95
0.69952
5.095556
false
false
false
false
notreallyJake/SwiftLife
SwiftLife/GameScene.swift
1
4393
// // GameScene.swift // SwiftLife // // Created by Jan Willem de Birk on 6/4/14. // Copyright (c) 2014 notreallyJake. All rights reserved. // import SpriteKit extension CGPoint : Hashable { var hashValue: Int { get { return Int(x) * 10000 + Int(y) }} } class GameScene: SKScene { var cells: Array<CGPoint> = [] var lastGenerationTime: NSTimeInterval = NSTimeIntervalSince1970 let nodeSize: Float = 32.0 override func didMoveToView(view: SKView) { // an example (stable) pattern. self.addCell(CGPoint(x: 12, y: 15)) self.addCell(CGPoint(x: 13, y: 14)) self.addCell(CGPoint(x: 13, y: 13)) self.addCell(CGPoint(x: 12, y: 12)) self.addCell(CGPoint(x: 11, y: 14)) self.addCell(CGPoint(x: 11, y: 13)) // render and pause (until a touch occurs) self.renderGeneration() self.paused = true } override func touchesBegan(touches: NSSet, withEvent event: UIEvent) { for aTouch : AnyObject in touches { let touch = aTouch as UITouch // I'm sure I can do this differently, no idea how. // see what position has been touched. let location = touch.locationInNode(self) let point = locationToPoint(location) self.addCell(point) self.renderCell(point) } self.paused = false; } override func update(currentTime: CFTimeInterval) { if self.lastGenerationTime != NSTimeIntervalSince1970 && !self.paused { if (currentTime - self.lastGenerationTime >= 0.25) { self.simulateGeneration() self.renderGeneration() self.lastGenerationTime = currentTime } } else { self.lastGenerationTime = currentTime } } // ** game logic ** // func locationToPoint(location: CGPoint) -> CGPoint { let x = Int(floorf(location.x / nodeSize)) let y = Int(floorf(location.y / nodeSize)) return CGPoint(x: x, y: y) } func addCell(point: CGPoint) { cells.append(point) } func renderCell(cell: CGPoint) { var node: SKSpriteNode = SKSpriteNode(color: UIColor.greenColor(), size: CGSize(width: nodeSize, height: nodeSize)) node.anchorPoint = CGPoint(x: 0.0, y: 0.0) node.position = CGPoint(x: (nodeSize * Float(cell.x)), y: (nodeSize * Float(cell.y))) self.addChild(node) } func neighbors(cell: CGPoint) -> Array<CGPoint> { var neighbors: Array<CGPoint> = [] for x in (-1...1) { for y in (-1...1) { if x != 0 || y != 0 { neighbors.append(CGPoint(x: cell.x + Float(x), y: cell.y + Float(y))) } } } return neighbors } func simulateGeneration() { var simulatedCells: Array<CGPoint> = [] // create a dictionary with relationships between cells and neighbors. var relationships:Dictionary<CGPoint, Int> = [:] for cell in cells{ relationships[cell] = 0 } // go over the cells to count the neighbors. for cell in cells { for neighbour in self.neighbors(cell) { if let currentCount = relationships[neighbour]{ relationships[neighbour] = currentCount + 1 } else { relationships[neighbour] = 1 } } } // decide if cells need to remain alive for cell in cells { var count:Int? = relationships.removeValueForKey(cell) if count && (count == 2 || count == 3){ simulatedCells.append(cell) } } // decide if neighbors need to be revived for (cell, count) in relationships { if count == 3 { simulatedCells.append(cell) } } self.cells = simulatedCells } func renderGeneration() { self.removeAllChildren() // loop through cells to see what needs to be drawn. for cell : CGPoint in cells { self.renderCell(cell) } } }
mit
05d5ec514edbfa46a9db1a8476765f21
28.884354
123
0.532666
4.473523
false
false
false
false
debugsquad/Hyperborea
Hyperborea/Model/Search/MSearchContentMode.swift
1
973
import UIKit class MSearchContentMode { let items:[MSearchContentModeItem] var selectedIndex:Int init() { let itemDefinition:MSearchContentModeItemDefinition = MSearchContentModeItemDefinition() let itemSynonyms:MSearchContentModeItemSynonyms = MSearchContentModeItemSynonyms() let itemAntonyms:MSearchContentModeItemAntonyms = MSearchContentModeItemAntonyms() let itemTranslate:MSearchContentModeItemTranslate = MSearchContentModeItemTranslate() let itemOrigins:MSearchContentModeItemOrigins = MSearchContentModeItemOrigins() items = [ itemDefinition, itemSynonyms, itemAntonyms, itemTranslate, itemOrigins] selectedIndex = 0 } //MARK: public func currentItem() -> MSearchContentModeItem { let item:MSearchContentModeItem = items[selectedIndex] return item } }
mit
7707c38c3537b5a2eb3566307f806257
27.617647
96
0.67112
5.259459
false
false
false
false
Shopify/mobile-buy-sdk-ios
Buy/Generated/Storefront/TransactionKind.swift
1
1975
// // TransactionKind.swift // Buy // // Created by Shopify. // Copyright (c) 2017 Shopify Inc. 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 extension Storefront { /// The different kinds of order transactions. public enum TransactionKind: String { /// An amount reserved against the cardholder's funding source. Money does not /// change hands until the authorization is captured. case authorization = "AUTHORIZATION" /// A transfer of the money that was reserved during the authorization stage. case capture = "CAPTURE" /// Money returned to the customer when they have paid too much. case change = "CHANGE" /// An authorization for a payment taken with an EMV credit card reader. case emvAuthorization = "EMV_AUTHORIZATION" /// An authorization and capture performed together in a single step. case sale = "SALE" case unknownValue = "" } }
mit
a8522104e8ab341ea7a842414dd26653
38.5
81
0.739747
4.274892
false
false
false
false
ylovesy/CodeFun
mayu/3Sum.swift
1
1590
import Foundation /* Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero. Note: The solution set must not contain duplicate triplets. For example, given array S = [-1, 0, 1, 2, -1, -4], A solution set is: [ [-1, 0, 1], [-1, -1, 2] ] */ private class Solution { func threeSum(_ nums: [Int]) -> [[Int]] { if nums.count < 3 { return [] } let ary = nums.sorted() var res = [[Int]]() for i in 0 ..< nums.count - 2 { if i == 0 || (i > 0 && ary[i] != ary[i - 1]) { var leftIdx = i + 1 var rightIdx = nums.count - 1 let sum = 0 - ary[i] while leftIdx < rightIdx { if ary[leftIdx] + ary[rightIdx] == sum { res.append([ary[i], ary[leftIdx], ary[rightIdx]]) while leftIdx < rightIdx && ary[leftIdx] == ary[leftIdx + 1] { leftIdx += 1 } while leftIdx < rightIdx && ary[rightIdx] == ary[rightIdx - 1] { rightIdx -= 1 } rightIdx -= 1 leftIdx += 1 } else if ary[leftIdx] + ary[rightIdx] > sum { rightIdx -= 1 } else { leftIdx += 1 } } } } return res } }
apache-2.0
517a4289687f9d1c656c1a952f04487f
31.44898
156
0.403774
4.140625
false
false
false
false
lemberg/connfa-ios
Connfa/Common/DateManager.swift
1
761
// // DateManager.swift // Connfa // // Created by Marian Fedyk on 9/19/17. // import Foundation class DateManager { static func programDetailsDateString(date: Date) -> String { let dateFormatter = DateFormatter() dateFormatter.timeZone = TimeZone(identifier: Configurations().timeZoneIdentifier) dateFormatter.dateFormat = "EEEE - MMMM d" return dateFormatter.string(from: date) } static func programDetailsTimeIntervalString(first: Date, second: Date) -> String { let dateFormatter = DateFormatter() dateFormatter.timeZone = TimeZone(identifier: Configurations().timeZoneIdentifier) dateFormatter.dateFormat = "hh:mm a" return "\(dateFormatter.string(from: first)) - \(dateFormatter.string(from: second))" } }
apache-2.0
bcd0ed8fc449bcf613be06ddf76c03c3
29.44
89
0.725361
4.299435
false
true
false
false
oisinlavery/HackingWithSwift
project9-oisin/project7-oisin/MasterViewController.swift
1
3557
// // MasterViewController.swift // project7-oisin // // Created by Oisín Lavery on 10/4/15. // Copyright © 2015 Oisín Lavery. All rights reserved. // import UIKit class MasterViewController: UITableViewController { var detailViewController: DetailViewController? = nil var objects = [[String: String]]() override func viewDidLoad() { super.viewDidLoad() loadData() } func loadData(){ let urlString: String if navigationController?.tabBarItem.tag == 0 { urlString = "https://api.whitehouse.gov/v1/petitions.json?limit=100" } else { urlString = "https://api.whitehouse.gov/v1/petitions.json?signatureCountFloor=10000&limit=100" } dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0), { if let url = NSURL(string: urlString) { if let data = try? NSData(contentsOfURL: url, options: []) { let json = JSON(data: data) if json["metadata"]["responseInfo"]["status"].intValue == 200 { self.parseJSON(json) } else { self.showError() } } else { self.showError() } } else { self.showError() } }) } func parseJSON(json: JSON) { for result in json["results"].arrayValue { let title = result["title"].stringValue let body = result["body"].stringValue let signatures = result["signatureCount"].stringValue let object = ["title": title, "body": body, "signatures": signatures] objects.append(object) } dispatch_async(dispatch_get_main_queue(), { [unowned self] in self.tableView.reloadData() }) } func showError() { dispatch_async(dispatch_get_main_queue(), { [unowned self] in let ac = UIAlertController(title: "Loading error", message: "There was a problem loading the feed; please check your connection and try again.", preferredStyle: .Alert) ac.addAction(UIAlertAction(title: "OK", style: .Default, handler: nil)) self.presentViewController(ac, animated: true, completion: nil) }) } override func viewWillAppear(animated: Bool) { self.clearsSelectionOnViewWillAppear = self.splitViewController!.collapsed super.viewWillAppear(animated) } // MARK: - Segues override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "showDetail" { if let indexPath = self.tableView.indexPathForSelectedRow { let object = objects[indexPath.row] let controller = (segue.destinationViewController as! UINavigationController).topViewController as! DetailViewController controller.detailItem = object controller.navigationItem.leftBarButtonItem = self.splitViewController?.displayModeButtonItem() controller.navigationItem.leftItemsSupplementBackButton = true } } } // MARK: - Table View override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return objects.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) let object = objects[indexPath.row] cell.textLabel!.text = object["title"] cell.detailTextLabel!.text = object["body"] return cell } }
unlicense
705377d940e54d807a4e67780eb9114d
27.894309
176
0.660945
4.802703
false
false
false
false
apple/swift-nio
Tests/NIOCoreTests/CustomChannelTests.swift
1
2677
//===----------------------------------------------------------------------===// // // This source file is part of the SwiftNIO open source project // // Copyright (c) 2017-2021 Apple Inc. and the SwiftNIO project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of SwiftNIO project authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// import XCTest import NIOCore import NIOEmbedded struct NotImplementedError: Error { } struct InvalidTypeError: Error { } /// A basic ChannelCore that expects write0 to receive a NIOAny containing an Int. /// /// Everything else either throws or returns a failed future, except for things that cannot, /// which precondition instead. private class IntChannelCore: ChannelCore { func localAddress0() throws -> SocketAddress { throw NotImplementedError() } func remoteAddress0() throws -> SocketAddress { throw NotImplementedError() } func register0(promise: EventLoopPromise<Void>?) { promise?.fail(NotImplementedError()) } func registerAlreadyConfigured0(promise: EventLoopPromise<Void>?) { promise?.fail(NotImplementedError()) } func bind0(to: SocketAddress, promise: EventLoopPromise<Void>?) { promise?.fail(NotImplementedError()) } func connect0(to: SocketAddress, promise: EventLoopPromise<Void>?) { promise?.fail(NotImplementedError()) } func write0(_ data: NIOAny, promise: EventLoopPromise<Void>?) { _ = self.unwrapData(data, as: Int.self) promise?.succeed(()) } func flush0() { preconditionFailure("Must not flush") } func read0() { preconditionFailure("Must not ew") } func close0(error: Error, mode: CloseMode, promise: EventLoopPromise<Void>?) { promise?.fail(NotImplementedError()) } func triggerUserOutboundEvent0(_ event: Any, promise: EventLoopPromise<Void>?) { promise?.fail(NotImplementedError()) } func channelRead0(_ data: NIOAny) { preconditionFailure("Must not call channelRead0") } func errorCaught0(error: Error) { preconditionFailure("Must not call errorCaught0") } } class CustomChannelTests: XCTestCase { func testWritingIntToSpecialChannel() throws { let loop = EmbeddedEventLoop() let intCore = IntChannelCore() let writePromise = loop.makePromise(of: Void.self) intCore.write0(NIOAny(5), promise: writePromise) XCTAssertNoThrow(try writePromise.futureResult.wait()) } }
apache-2.0
ac1969174e56447827fd544ae07c1650
28.417582
92
0.643257
4.806104
false
false
false
false
apple/swift-nio
IntegrationTests/tests_04_performance/test_01_resources/test_1_reqs_1000_conn.swift
1
809
//===----------------------------------------------------------------------===// // // This source file is part of the SwiftNIO open source project // // Copyright (c) 2017-2019 Apple Inc. and the SwiftNIO project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of SwiftNIO project authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// func run(identifier: String) { measure(identifier: identifier) { var numberDone = 1 for _ in 0..<1000 { let newDones = try! doRequests(group: group, number: 1) precondition(newDones == 1) numberDone += newDones } return numberDone } }
apache-2.0
846f7574d7a0e60a1ad734ef20ef6562
31.36
80
0.516687
4.873494
false
false
false
false
inderdhir/DatWeatherDoe
DatWeatherDoe/ViewModel/WeatherViewModel.swift
1
5365
// // WeatherViewModel.swift // DatWeatherDoe // // Created by Inder Dhir on 1/9/22. // Copyright © 2022 Inder Dhir. All rights reserved. // import CoreLocation import Foundation final class WeatherViewModel: WeatherViewModelType { weak var delegate: WeatherViewModelDelegate? private let configManager: ConfigManagerType private let errorLabels = ErrorLabels() private let weatherTimerSerialQueue = DispatchQueue(label: "Weather Timer Serial Queue") private let forecaster = WeatherForecaster() private let logger: DatWeatherDoeLoggerType private var weatherRepository: WeatherRepository! private var weatherTimer: Timer? private var weatherResultParser: WeatherResultParser? private lazy var locationFetcher: SystemLocationFetcher = { let locationFetcher = SystemLocationFetcher(logger: logger) locationFetcher.delegate = self return locationFetcher }() init(appId: String, configManager: ConfigManagerType, logger: DatWeatherDoeLoggerType) { self.configManager = configManager self.logger = logger weatherRepository = WeatherRepository(appId: appId, logger: logger) } func getUpdatedWeather() { weatherTimerSerialQueue.sync { weatherTimer?.invalidate() weatherTimer = Timer.scheduledTimer( withTimeInterval: configManager.refreshInterval, repeats: true, block: { [weak self] _ in self?.getWeatherWithSelectedSource() }) weatherTimer?.fire() } } func updateCityWith(cityId: Int) { forecaster.updateCityWith(cityId: cityId) } func seeForecastForCurrentCity() { forecaster.seeForecastForCity() } private func getWeatherWithSelectedSource() { let weatherSource = WeatherSource(rawValue: configManager.weatherSource)! switch weatherSource { case .location: getWeatherAfterUpdatingLocation() case .zipCode: getWeatherViaZipCode() case .latLong: getWeatherViaLocationCoordinates() } } private func getWeatherAfterUpdatingLocation() { locationFetcher.startUpdatingLocation() } private func getWeatherViaZipCode() { guard let zipCode = configManager.weatherSourceText else { delegate?.didFailToUpdateWeatherData(errorLabels.zipCodeErrorString) return } weatherRepository.getWeatherViaZipCode( zipCode, options: buildWeatherDataOptions(), completion: { [weak self] result in guard let `self` = self else { return } ZipCodeWeatherResultParser( weatherDataResult: result, delegate: self.delegate, errorLabels: self.errorLabels ).parse() } ) } private func getWeatherViaLocationCoordinates() { guard let latLong = configManager.weatherSourceText else { delegate?.didFailToUpdateWeatherData(errorLabels.latLongErrorString) return } weatherRepository.getWeatherViaLatLong( latLong, options: buildWeatherDataOptions(), completion: { [weak self] result in guard let `self` = self else { return } self.weatherResultParser = LocationCoordinatesWeatherResultParser( weatherDataResult: result, delegate: self.delegate, errorLabels: self.errorLabels ) self.weatherResultParser?.parse() } ) } private func buildWeatherDataOptions() -> WeatherDataBuilder.Options { .init( showWeatherIcon: configManager.isShowingWeatherIcon, textOptions: buildWeatherTextOptions() ) } private func buildWeatherTextOptions() -> WeatherTextBuilder.Options { .init( isWeatherConditionAsTextEnabled: configManager.isWeatherConditionAsTextEnabled, temperatureOptions: .init( unit: TemperatureUnit(rawValue: configManager.temperatureUnit) ?? .fahrenheit, isRoundingOff: configManager.isRoundingOffData ), isShowingHumidity: configManager.isShowingHumidity ) } private func getWeatherViaLocation(_ location: CLLocationCoordinate2D) { weatherRepository.getWeatherViaLocation( location, options: buildWeatherDataOptions(), completion: { [weak self] result in guard let `self` = self else { return } self.weatherResultParser = SystemLocationWeatherResultParser( weatherDataResult: result, delegate: self.delegate, errorLabels: self.errorLabels ) self.weatherResultParser?.parse() }) } } // MARK: SystemLocationFetcherDelegate extension WeatherViewModel: SystemLocationFetcherDelegate { func didUpdateLocation(_ location: CLLocationCoordinate2D, isCachedLocation: Bool) { getWeatherViaLocation(location) } func didFailLocationUpdate() { delegate?.didFailToUpdateWeatherData(errorLabels.locationErrorString) } }
apache-2.0
d9d78bccbdb965eeb66f820b49a706f7
32.949367
94
0.640567
5.418182
false
true
false
false
radvansky-tomas/NutriFacts
nutri-facts/nutri-facts/Libraries/Ex/NSDate.swift
24
9452
// // File.swift // ExSwift // // Created by Piergiuseppe Longo on 23/11/14. // Copyright (c) 2014 pNre. All rights reserved. // import Foundation public extension NSDate { // MARK: NSDate Manipulation /** Returns a new NSDate object representing the date calculated by adding the amount specified to self date :param: seconds number of seconds to add :param: minutes number of minutes to add :param: hours number of hours to add :param: days number of days to add :param: weeks number of weeks to add :param: months number of months to add :param: years number of years to add :returns: the NSDate computed */ public func add(seconds: Int = 0, minutes: Int = 0, hours: Int = 0, days: Int = 0, weeks: Int = 0, months: Int = 0, years: Int = 0) -> NSDate { var calendar = NSCalendar.currentCalendar() let version = floor(NSFoundationVersionNumber) if version <= NSFoundationVersionNumber10_9_2 { var component = NSDateComponents() component.setValue(seconds, forComponent: .CalendarUnitSecond) var date : NSDate! = calendar.dateByAddingComponents(component, toDate: self, options: nil)! component = NSDateComponents() component.setValue(minutes, forComponent: .CalendarUnitMinute) date = calendar.dateByAddingComponents(component, toDate: date, options: nil)! component = NSDateComponents() component.setValue(hours, forComponent: .CalendarUnitHour) date = calendar.dateByAddingComponents(component, toDate: date, options: nil)! component = NSDateComponents() component.setValue(days, forComponent: .CalendarUnitDay) date = calendar.dateByAddingComponents(component, toDate: date, options: nil)! component = NSDateComponents() component.setValue(weeks, forComponent: .CalendarUnitWeekOfMonth) date = calendar.dateByAddingComponents(component, toDate: date, options: nil)! component = NSDateComponents() component.setValue(months, forComponent: .CalendarUnitMonth) date = calendar.dateByAddingComponents(component, toDate: date, options: nil)! component = NSDateComponents() component.setValue(years, forComponent: .CalendarUnitYear) date = calendar.dateByAddingComponents(component, toDate: date, options: nil)! return date } var date : NSDate! = calendar.dateByAddingUnit(.CalendarUnitSecond, value: seconds, toDate: self, options: nil) date = calendar.dateByAddingUnit(.CalendarUnitMinute, value: minutes, toDate: date, options: nil) date = calendar.dateByAddingUnit(.CalendarUnitDay, value: days, toDate: date, options: nil) date = calendar.dateByAddingUnit(.CalendarUnitHour, value: hours, toDate: date, options: nil) date = calendar.dateByAddingUnit(.CalendarUnitWeekOfMonth, value: weeks, toDate: date, options: nil) date = calendar.dateByAddingUnit(.CalendarUnitMonth, value: months, toDate: date, options: nil) date = calendar.dateByAddingUnit(.CalendarUnitYear, value: years, toDate: date, options: nil) return date } /** Returns a new NSDate object representing the date calculated by adding an amount of seconds to self date :param: seconds number of seconds to add :returns: the NSDate computed */ public func addSeconds (seconds: Int) -> NSDate { return add(seconds: seconds) } /** Returns a new NSDate object representing the date calculated by adding an amount of minutes to self date :param: minutes number of minutes to add :returns: the NSDate computed */ public func addMinutes (minutes: Int) -> NSDate { return add(minutes: minutes) } /** Returns a new NSDate object representing the date calculated by adding an amount of hours to self date :param: hours number of hours to add :returns: the NSDate computed */ public func addHours(hours: Int) -> NSDate { return add(hours: hours) } /** Returns a new NSDate object representing the date calculated by adding an amount of days to self date :param: days number of days to add :returns: the NSDate computed */ public func addDays(days: Int) -> NSDate { return add(days: days) } /** Returns a new NSDate object representing the date calculated by adding an amount of weeks to self date :param: weeks number of weeks to add :returns: the NSDate computed */ public func addWeeks(weeks: Int) -> NSDate { return add(weeks: weeks) } /** Returns a new NSDate object representing the date calculated by adding an amount of months to self date :param: months number of months to add :returns: the NSDate computed */ public func addMonths(months: Int) -> NSDate { return add(months: months) } /** Returns a new NSDate object representing the date calculated by adding an amount of years to self date :param: years number of year to add :returns: the NSDate computed */ public func addYears(years: Int) -> NSDate { return add(years: years) } // MARK: Date comparison /** Checks if self is after input NSDate :param: date NSDate to compare :returns: True if self is after the input NSDate, false otherwise */ public func isAfter(date: NSDate) -> Bool{ return (self.compare(date) == NSComparisonResult.OrderedDescending) } /** Checks if self is before input NSDate :param: date NSDate to compare :returns: True if self is before the input NSDate, false otherwise */ public func isBefore(date: NSDate) -> Bool{ return (self.compare(date) == NSComparisonResult.OrderedAscending) } // MARK: Getter /** Date year */ public var year : Int { get { return getComponent(.CalendarUnitYear) } } /** Date month */ public var month : Int { get { return getComponent(.CalendarUnitMonth) } } /** Date weekday */ public var weekday : Int { get { return getComponent(.CalendarUnitWeekday) } } /** Date weekMonth */ public var weekMonth : Int { get { return getComponent(.CalendarUnitWeekOfMonth) } } /** Date days */ public var days : Int { get { return getComponent(.CalendarUnitDay) } } /** Date hours */ public var hours : Int { get { return getComponent(.CalendarUnitHour) } } /** Date minuts */ public var minutes : Int { get { return getComponent(.CalendarUnitMinute) } } /** Date seconds */ public var seconds : Int { get { return getComponent(.CalendarUnitSecond) } } /** Returns the value of the NSDate component :param: component NSCalendarUnit :returns: the value of the component */ public func getComponent (component : NSCalendarUnit) -> Int { let calendar = NSCalendar.currentCalendar() let components = calendar.components(component, fromDate: self) return components.valueForComponent(component) } } extension NSDate: Strideable { public func distanceTo(other: NSDate) -> NSTimeInterval { return other - self } public func advancedBy(n: NSTimeInterval) -> Self { return self.dynamicType(timeIntervalSinceReferenceDate: self.timeIntervalSinceReferenceDate + n) } } // MARK: Arithmetic func +(date: NSDate, timeInterval: Int) -> NSDate { return date + NSTimeInterval(timeInterval) } func -(date: NSDate, timeInterval: Int) -> NSDate { return date - NSTimeInterval(timeInterval) } func +=(inout date: NSDate, timeInterval: Int) { date = date + timeInterval } func -=(inout date: NSDate, timeInterval: Int) { date = date - timeInterval } func +(date: NSDate, timeInterval: Double) -> NSDate { return date.dateByAddingTimeInterval(NSTimeInterval(timeInterval)) } func -(date: NSDate, timeInterval: Double) -> NSDate { return date.dateByAddingTimeInterval(NSTimeInterval(-timeInterval)) } func +=(inout date: NSDate, timeInterval: Double) { date = date + timeInterval } func -=(inout date: NSDate, timeInterval: Double) { date = date - timeInterval } func -(date: NSDate, otherDate: NSDate) -> NSTimeInterval { return date.timeIntervalSinceDate(otherDate) } extension NSDate: Equatable { } public func ==(lhs: NSDate, rhs: NSDate) -> Bool { return lhs.compare(rhs) == NSComparisonResult.OrderedSame } extension NSDate: Comparable { } public func <(lhs: NSDate, rhs: NSDate) -> Bool { return lhs.compare(rhs) == NSComparisonResult.OrderedAscending }
gpl-2.0
9057e15f4cd201b2e90d9017322d8180
28.72327
146
0.619763
4.964286
false
false
false
false
glorybird/KeepReading2
kr/Pods/YapDatabaseExtensions/YapDatabaseExtensions/Shared/Persistable/Persistable_AnyWithObjectMetadata.swift
3
1942
// // Persistable_AnyWithObjectMetadata.swift // YapDatabaseExtensions // // Created by Daniel Thorpe on 13/10/2015. // // import Foundation import ValueCoding // MARK: - Readable extension Readable where ItemType: Persistable, ItemType.MetadataType: NSCoding { func metadataInTransaction(transaction: Database.Connection.ReadTransaction, atIndex index: YapDB.Index) -> ItemType.MetadataType? { return transaction.readMetadataAtIndex(index) } func metadataAtIndexInTransaction(index: YapDB.Index) -> Database.Connection.ReadTransaction -> ItemType.MetadataType? { return { self.metadataInTransaction($0, atIndex: index) } } func metadataInTransactionAtIndex(transaction: Database.Connection.ReadTransaction) -> YapDB.Index -> ItemType.MetadataType? { return { self.metadataInTransaction(transaction, atIndex: $0) } } func metadataAtIndexesInTransaction< Indexes where Indexes: SequenceType, Indexes.Generator.Element == YapDB.Index>(indexes: Indexes) -> Database.Connection.ReadTransaction -> [ItemType.MetadataType] { let atIndex = metadataInTransactionAtIndex return { indexes.flatMap(atIndex($0)) } } /** Reads the metadata at a given index. - parameter index: a YapDB.Index - returns: an optional `ItemType.MetadataType` */ public func metadataAtIndex(index: YapDB.Index) -> ItemType.MetadataType? { return sync(metadataAtIndexInTransaction(index)) } /** Reads the metadata at the indexes. - parameter indexes: a SequenceType of YapDB.Index values - returns: an array of `ItemType.MetadataType` */ public func metadataAtIndexes< Indexes where Indexes: SequenceType, Indexes.Generator.Element == YapDB.Index>(indexes: Indexes) -> [ItemType.MetadataType] { return sync(metadataAtIndexesInTransaction(indexes)) } }
apache-2.0
b88c93d34bdc709a7e08c2492049a02a
31.366667
136
0.701854
4.736585
false
false
false
false
nicolasgomollon/PTATableViewCell
PTATableViewHeaderFooterView.swift
1
20100
// // PTATableViewHeaderFooterView.swift // PTATableViewCell // // Objective-C code Copyright (c) 2014 Ali Karagoz. All rights reserved. // Swift adaptation Copyright (c) 2015 Nicolas Gomollon. All rights reserved. // import Foundation import UIKit @objc public protocol ObjC_PTATableViewHeaderFooterViewDelegate: NSObjectProtocol { /** Asks the delegate whether a given header/footer view should be swiped. Defaults to `true` if not implemented. */ @objc optional func tableViewShouldSwipe(headerFooterView: PTATableViewHeaderFooterView) -> Bool /** Tells the delegate that the specified header/footer view is being swiped with the offset and percentage. */ @objc optional func tableViewIsSwiping(headerFooterView: PTATableViewHeaderFooterView, with offset: CGFloat, percentage: Double) /** Tells the delegate that the specified header/footer view started swiping. */ @objc optional func tableViewDidStartSwiping(headerFooterView: PTATableViewHeaderFooterView) /** Tells the delegate that the specified header/footer view ended swiping. */ @objc optional func tableViewDidEndSwiping(headerFooterView: PTATableViewHeaderFooterView) } /** The delegate of a PTATableViewHeaderFooterView object must adopt the PTATableViewHeaderFooterViewDelegate protocol in order to perform an action when triggered. Optional methods of the protocol allow the delegate to be notified of a header/footer view’s swipe state, and determine whether a header/footer view should be swiped. */ public protocol PTATableViewHeaderFooterViewDelegate: ObjC_PTATableViewHeaderFooterViewDelegate { /** Tells the delegate that the specified cell’s state was triggered. */ func tableView(headerFooterView: PTATableViewHeaderFooterView, didTrigger state: PTATableViewItemState, with mode: PTATableViewItemMode) } open class PTATableViewHeaderFooterView: UITableViewHeaderFooterView { /** The object that acts as the delegate of the receiving table view header/footer view. */ open weak var delegate: PTATableViewHeaderFooterViewDelegate! fileprivate var initialized: Bool = false fileprivate var panGestureRecognizer: UIPanGestureRecognizer! fileprivate var direction: PTATableViewItemState = .none fileprivate var stateOptions: PTATableViewItemState = .none /** The color that’s revealed before an action is triggered. Defaults to a light gray color. */ open var defaultColor: UIColor = UIColor(red: 227.0/255.0, green: 227.0/255.0, blue: 227.0/255.0, alpha: 1.0) /** The attributes used when swiping the header/footer view from left to right. */ open var leftToRightAttr: PTATableViewItemStateAttributes = .init() /** The attributes used when swiping the header/footer view from right to left. */ open var rightToLeftAttr: PTATableViewItemStateAttributes = .init() fileprivate var _slidingView: UIView? fileprivate var slidingView: UIView! { get { if let slidingView: UIView = _slidingView { return slidingView } _slidingView = UIView() _slidingView!.contentMode = .center return _slidingView } set { _slidingView = newValue } } fileprivate var _colorIndicatorView: UIView? fileprivate var colorIndicatorView: UIView! { get { if let colorIndicatorView: UIView = _colorIndicatorView { return colorIndicatorView } _colorIndicatorView = UIView(frame: bounds) _colorIndicatorView!.autoresizingMask = [.flexibleHeight, .flexibleWidth] _colorIndicatorView!.backgroundColor = defaultColor return _colorIndicatorView } set { _colorIndicatorView = newValue } } fileprivate func addSubviewToSlidingView(_ view: UIView) { for subview in slidingView.subviews { subview.removeFromSuperview() } slidingView.addSubview(view) } public override init(reuseIdentifier: String?) { super.init(reuseIdentifier: reuseIdentifier) initialize() } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) initialize() } fileprivate func initialize() { guard !initialized else { return } initialized = true contentView.backgroundColor = .white panGestureRecognizer = UIPanGestureRecognizer(target: self, action: #selector(PTATableViewHeaderFooterView._pan(_:))) panGestureRecognizer.delegate = self addGestureRecognizer(panGestureRecognizer) } open override func prepareForReuse() { super.prepareForReuse() removeSwipingView() stateOptions = .none leftToRightAttr = PTATableViewItemStateAttributes() rightToLeftAttr = PTATableViewItemStateAttributes() } } private extension PTATableViewHeaderFooterView { func setupSwipingView() { guard _colorIndicatorView == nil else { return } colorIndicatorView.addSubview(slidingView) // TODO: Check this out on iOS 7. insertSubview(colorIndicatorView, belowSubview: contentView) } func removeSwipingView() { guard _colorIndicatorView != nil else { return } slidingView?.removeFromSuperview() slidingView = nil colorIndicatorView?.removeFromSuperview() colorIndicatorView = nil } } private extension PTATableViewHeaderFooterView { func animationDurationWith(velocity: CGPoint) -> TimeInterval { let DurationHighLimit: Double = 0.1 let DurationLowLimit: Double = 0.25 let width: CGFloat = bounds.width let animationDurationDiff: TimeInterval = DurationHighLimit - DurationLowLimit var horizontalVelocity: CGFloat = velocity.x if horizontalVelocity < -width { horizontalVelocity = -width } else if horizontalVelocity > width { horizontalVelocity = width } return (DurationHighLimit + DurationLowLimit) - abs(Double(horizontalVelocity / width) * animationDurationDiff) } func viewWith(percentage: Double) -> UIView? { if percentage < 0.0 { return rightToLeftAttr.view } else if percentage > 0.0 { return leftToRightAttr.view } return nil } func viewBehaviorWith(percentage: Double) -> PTATableViewItemSlidingViewBehavior { if (PTATableViewItemHelper.directionWith(percentage: percentage) == .leftToRight) && (leftToRightAttr.mode != .none) { return leftToRightAttr.viewBehavior } else if (PTATableViewItemHelper.directionWith(percentage: percentage) == .rightToLeft) && (rightToLeftAttr.mode != .none) { return rightToLeftAttr.viewBehavior } return .none } func alphaWith(percentage: Double) -> CGFloat { let ltrTrigger: PTATableViewItemTrigger = leftToRightAttr.trigger let rtlTrigger: PTATableViewItemTrigger = rightToLeftAttr.trigger let offset: CGFloat = PTATableViewItemHelper.offsetWith(percentage: abs(percentage), relativeToWidth: bounds.width) if percentage > 0.0 { switch ltrTrigger.kind { case .percentage: if percentage < ltrTrigger.value { return CGFloat(percentage / ltrTrigger.value) } case .offset: let triggerValue: CGFloat = CGFloat(ltrTrigger.value) if offset < triggerValue { return offset / triggerValue } } } else if percentage < 0.0 { switch rtlTrigger.kind { case .percentage: if percentage > -rtlTrigger.value { return CGFloat(abs(percentage / rtlTrigger.value)) } case .offset: let triggerValue: CGFloat = CGFloat(rtlTrigger.value) if offset < triggerValue { return offset / triggerValue } } } return 1.0 } func colorWith(percentage: Double) -> UIColor { let ltrTrigger: PTATableViewItemTrigger = leftToRightAttr.trigger let rtlTrigger: PTATableViewItemTrigger = rightToLeftAttr.trigger let offset: CGFloat = PTATableViewItemHelper.offsetWith(percentage: abs(percentage), relativeToWidth: bounds.width) if (percentage > 0.0) && (leftToRightAttr.mode != .none) && (leftToRightAttr.color != nil) { switch ltrTrigger.kind { case .percentage: if percentage >= ltrTrigger.value { return leftToRightAttr.color! } case .offset: let triggerValue: CGFloat = CGFloat(ltrTrigger.value) if offset >= triggerValue { return leftToRightAttr.color! } } } else if (percentage < 0.0) && (rightToLeftAttr.mode != .none) && (rightToLeftAttr.color != nil) { switch rtlTrigger.kind { case .percentage: if percentage <= -rtlTrigger.value { return rightToLeftAttr.color! } case .offset: let triggerValue: CGFloat = CGFloat(rtlTrigger.value) if offset >= triggerValue { return rightToLeftAttr.color! } } } return defaultColor } func stateWith(percentage: Double) -> PTATableViewItemState { let ltrTrigger: PTATableViewItemTrigger = leftToRightAttr.trigger let rtlTrigger: PTATableViewItemTrigger = rightToLeftAttr.trigger let offset: CGFloat = PTATableViewItemHelper.offsetWith(percentage: abs(percentage), relativeToWidth: bounds.width) if (percentage > 0.0) && (leftToRightAttr.mode != .none) { switch ltrTrigger.kind { case .percentage: if percentage >= ltrTrigger.value { return .leftToRight } case .offset: let triggerValue: CGFloat = CGFloat(ltrTrigger.value) if offset >= triggerValue { return .leftToRight } } } else if (percentage < 0.0) && (rightToLeftAttr.mode != .none) { switch rtlTrigger.kind { case .percentage: if percentage <= -rtlTrigger.value { return .rightToLeft } case .offset: let triggerValue: CGFloat = CGFloat(rtlTrigger.value) if offset >= triggerValue { return .rightToLeft } } } return .none } } private extension PTATableViewHeaderFooterView { func animateWith(offset: Double) { let percentage: Double = PTATableViewItemHelper.percentageWith(offset: offset, relativeToWidth: Double(bounds.width)) if let view: UIView = viewWith(percentage: percentage) { addSubviewToSlidingView(view) slidingView.alpha = alphaWith(percentage: percentage) slideViewWith(percentage: percentage) } colorIndicatorView.backgroundColor = colorWith(percentage: percentage) } func slideViewWith(percentage: Double) { slideViewWith(percentage: percentage, view: viewWith(percentage: percentage), andDragBehavior: viewBehaviorWith(percentage: percentage)) } func slideViewWith(percentage: Double, view: UIView?, andDragBehavior dragBehavior: PTATableViewItemSlidingViewBehavior) { var position: CGPoint = .zero position.y = bounds.height / 2.0 let width: CGFloat = bounds.width let offset: CGFloat = PTATableViewItemHelper.offsetWith(percentage: percentage, relativeToWidth: width) let ltrTriggerPercentage: Double = leftToRightAttr.trigger.percentage(relativeToWidth: width) let rtlTriggerPercentage: Double = rightToLeftAttr.trigger.percentage(relativeToWidth: width) switch dragBehavior { case .stickThenDragWithPan: if direction == .leftToRight { if (percentage >= 0.0) && (percentage < ltrTriggerPercentage) { position.x = leftToRightAttr.trigger.offset(relativeToWidth: width) / 2.0 } else if percentage >= ltrTriggerPercentage { position.x = offset - (leftToRightAttr.trigger.offset(relativeToWidth: width) / 2.0) } } else if direction == .rightToLeft { if (percentage <= 0.0) && (percentage >= -rtlTriggerPercentage) { position.x = width - (rightToLeftAttr.trigger.offset(relativeToWidth: width) / 2.0) } else if percentage <= -rtlTriggerPercentage { position.x = width + offset + (rightToLeftAttr.trigger.offset(relativeToWidth: width) / 2.0) } } case .dragWithPanThenStick: if direction == .leftToRight { if (percentage >= 0.0) && (percentage < ltrTriggerPercentage) { position.x = offset - (leftToRightAttr.trigger.offset(relativeToWidth: width) / 2.0) } else if percentage >= ltrTriggerPercentage { position.x = leftToRightAttr.trigger.offset(relativeToWidth: width) / 2.0 } } else if direction == .rightToLeft { if (percentage <= 0.0) && (percentage >= -rtlTriggerPercentage) { position.x = width + offset + (rightToLeftAttr.trigger.offset(relativeToWidth: width) / 2.0) } else if percentage <= -rtlTriggerPercentage { position.x = width - (rightToLeftAttr.trigger.offset(relativeToWidth: width) / 2.0) } } case .dragWithPan: if direction == .leftToRight { position.x = offset - (leftToRightAttr.trigger.offset(relativeToWidth: width) / 2.0) } else if direction == .rightToLeft { position.x = width + offset + (rightToLeftAttr.trigger.offset(relativeToWidth: width) / 2.0) } case .none: if direction == .leftToRight { position.x = leftToRightAttr.trigger.offset(relativeToWidth: width) / 2.0 } else if direction == .rightToLeft { position.x = width - (rightToLeftAttr.trigger.offset(relativeToWidth: width) / 2.0) } } guard let activeView: UIView = view else { return } var activeViewFrame: CGRect = activeView.bounds activeViewFrame.origin.x = position.x - (activeViewFrame.size.width / 2.0) activeViewFrame.origin.y = position.y - (activeViewFrame.size.height / 2.0) slidingView.frame = activeViewFrame } func moveWith(percentage: Double, duration: TimeInterval, direction: PTATableViewItemState) { var origin: CGFloat = 0.0 if direction == .rightToLeft { origin -= bounds.width } else if direction == .leftToRight { origin += bounds.width } var frame: CGRect = contentView.frame frame.origin.x = origin colorIndicatorView.backgroundColor = colorWith(percentage: percentage) UIView.animate(withDuration: duration, delay: 0.0, options: [.curveEaseOut, .allowUserInteraction], animations: { self.contentView.frame = frame self.slidingView.alpha = 0.0 self.slideViewWith(percentage: PTATableViewItemHelper.percentageWith(offset: Double(origin), relativeToWidth: Double(self.bounds.width)), view: self.viewWith(percentage: percentage), andDragBehavior: self.viewBehaviorWith(percentage: percentage)) }, completion: { (finished: Bool) in self.executeCompletionBlockWith(percentage: percentage) }) } func swipeToOriginWith(percentage: Double) { executeCompletionBlockWith(percentage: percentage) let offset: CGFloat = PTATableViewItemHelper.offsetWith(percentage: percentage, relativeToWidth: bounds.width) UIView.animate(withDuration: 0.3, delay: 0.0, usingSpringWithDamping: 0.6, initialSpringVelocity: offset / 100.0, options: [.curveEaseOut, .allowUserInteraction], animations: { self.contentView.frame = self.contentView.bounds self.colorIndicatorView.backgroundColor = self.defaultColor self.slidingView.alpha = 0.0 if ((self.stateWith(percentage: percentage) == .none) || ((self.direction == .leftToRight) && (self.leftToRightAttr.viewBehavior == .stickThenDragWithPan)) || ((self.direction == .rightToLeft) && (self.rightToLeftAttr.viewBehavior == .stickThenDragWithPan))) { self.slideViewWith(percentage: 0.0, view: self.viewWith(percentage: percentage), andDragBehavior: self.viewBehaviorWith(percentage: percentage)) } else { self.slideViewWith(percentage: 0.0, view: self.viewWith(percentage: percentage), andDragBehavior: .none) } }, completion: { (finished: Bool) in self.removeSwipingView() }) } func executeCompletionBlockWith(percentage: Double) { let state: PTATableViewItemState = stateWith(percentage: percentage) let mode: PTATableViewItemMode switch state { case PTATableViewItemState.leftToRight: mode = leftToRightAttr.mode case PTATableViewItemState.rightToLeft: mode = rightToLeftAttr.mode default: mode = .none } delegate?.tableView(headerFooterView: self, didTrigger: state, with: mode) } } extension PTATableViewHeaderFooterView: UIGestureRecognizerDelegate { open override func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool { guard let panGestureRecognizer = gestureRecognizer as? UIPanGestureRecognizer else { return true } let point: CGPoint = panGestureRecognizer.velocity(in: self) if abs(point.x) > abs(point.y) { if (point.x < 0.0) && !stateOptions.contains(.rightToLeft) { return false } if (point.x > 0.0) && !stateOptions.contains(.leftToRight) { return false } delegate?.tableViewDidStartSwiping?(headerFooterView: self) return true } else { return false } } @objc internal func _pan(_ gesture: UIPanGestureRecognizer) { if let shouldSwipe: Bool = delegate?.tableViewShouldSwipe?(headerFooterView: self) { guard shouldSwipe else { return } } pan(gestureState: gesture.state, translation: gesture.translation(in: self), velocity: gesture.velocity(in: self)) } public func pan(gestureState: UIGestureRecognizer.State, translation: CGPoint) { pan(gestureState: gestureState, translation: translation, velocity: CGPoint.zero) } public func pan(gestureState: UIGestureRecognizer.State, translation: CGPoint, velocity: CGPoint) { let actualTranslation: CGPoint = actualizeTranslation(translation) let percentage: Double = PTATableViewItemHelper.percentageWith(offset: Double(actualTranslation.x), relativeToWidth: Double(bounds.width)) direction = PTATableViewItemHelper.directionWith(percentage: percentage) switch gestureState { case .began, .changed: setupSwipingView() contentView.frame = contentView.bounds.offsetBy(dx: actualTranslation.x, dy: 0.0) colorIndicatorView.backgroundColor = colorWith(percentage: percentage) slidingView.alpha = alphaWith(percentage: percentage) if let view: UIView = viewWith(percentage: percentage) { addSubviewToSlidingView(view) } slideViewWith(percentage: percentage) delegate?.tableViewIsSwiping?(headerFooterView: self, with: actualTranslation.x, percentage: percentage) case .ended, .cancelled: // // For use only with Xcode UI Testing: // Set launch argument `"-PTATableViewCellUITestingScreenshots", "1"` to disable returning a cell // to its origin, to facilitate taking a screenshot with a triggered cell. // guard !UserDefaults.standard.bool(forKey: "PTATableViewCellUITestingScreenshots") else { break } let cellState: PTATableViewItemState = stateWith(percentage: percentage) var cellMode: PTATableViewItemMode = .none if (cellState == .leftToRight) && (leftToRightAttr.mode != .none) { cellMode = leftToRightAttr.mode } else if (cellState == .rightToLeft) && (rightToLeftAttr.mode != .none) { cellMode = rightToLeftAttr.mode } if (cellMode == .exit) && (direction != .none) { moveWith(percentage: percentage, duration: animationDurationWith(velocity: velocity), direction: cellState) } else { swipeToOriginWith(percentage: percentage) } delegate?.tableViewDidEndSwiping?(headerFooterView: self) default: break } } public func actualizeTranslation(_ translation: CGPoint) -> CGPoint { let width: CGFloat = bounds.width var panOffset: CGFloat = translation.x if ((panOffset > 0.0) && leftToRightAttr.rubberbandBounce || (panOffset < 0.0) && rightToLeftAttr.rubberbandBounce) { let offset = abs(panOffset) panOffset = (offset * 0.55 * width) / (offset * 0.55 + width) panOffset *= (translation.x < 0) ? -1.0 : 1.0 } return CGPoint(x: panOffset, y: translation.y) } public func reset() { contentView.frame = contentView.bounds colorIndicatorView.backgroundColor = defaultColor removeSwipingView() } } extension PTATableViewHeaderFooterView { /** Sets a pan gesture for the specified state and mode. Don’t forget to implement the delegate method `tableViewHeaderFooterView(view:didTriggerState:withMode:)` to perform an action when the header/footer view’s state is triggered. */ public func setPanGesture(_ state: PTATableViewItemState, mode: PTATableViewItemMode, trigger: PTATableViewItemTrigger? = nil, color: UIColor?, view: UIView?) { stateOptions.insert(state) if state.contains(.leftToRight) { leftToRightAttr = PTATableViewItemStateAttributes(mode: mode, trigger: trigger, color: color, view: view) if mode == .none { stateOptions.remove(.leftToRight) } } if state.contains(.rightToLeft) { rightToLeftAttr = PTATableViewItemStateAttributes(mode: mode, trigger: trigger, color: color, view: view) if mode == .none { stateOptions.remove(.rightToLeft) } } } }
mit
68699c35a8a172bad39227098718edc3
35.660584
334
0.738377
3.87763
false
false
false
false
talk2junior/iOSND-Beginning-iOS-Swift-3.0
Playground Collection/Part 2 - Robot Maze 2/Boolean Expressions/Boolean Expressions.playground/Pages/Exercises with Logical Operators.xcplaygroundpage/Contents.swift
1
575
//: [Previous](@previous) import Foundation // Exercises with Logical Operators // Exercise 1 let finishedHomework = false let schoolTomorrow = true let notAllowedToPlayVideoGames = !finishedHomework && schoolTomorrow // Exercise 2 var hungry = false var isPie = true var shouldEat = hungry || isPie // Exercise 3 let audienceRating = 75 let criticsRating = 85 let goWatchMovie = audienceRating > 90 && criticsRating > 80 audienceRating > 90 || criticsRating > 80 audienceRating <= 90 || criticsRating <= 80 audienceRating <= 90 && criticsRating <= 80//: [Next](@next)
mit
8498c56f6cae2eacfafdb0164d205398
22.958333
68
0.73913
3.709677
false
false
false
false
Mioke/PlanB
PlanB/PlanB/Base/Persistance/DatabaseManager.swift
1
1605
// // DatabaseManager.swift // swiftArchitecture // // Created by Klein Mioke on 15/12/1. // Copyright © 2015年 KleinMioke. All rights reserved. // import Foundation import FMDB class DatabaseManager: NSObject { class func database(databaseQueue: FMDatabaseQueue, query: String, withArgumentsInArray args: [AnyObject]?) -> NSMutableArray { let rstArray = NSMutableArray() databaseQueue.inTransaction { (db: FMDatabase!, rollback: UnsafeMutablePointer<ObjCBool>) -> Void in if let rst = db.executeQuery(query, withArgumentsInArray: args) { while rst.next() { rstArray.addObject(rst.resultDictionary()) } rst.close() } } return rstArray } class func database(databaseQueue: FMDatabaseQueue, execute: String, withArgumentsInDictionary args: [String: AnyObject]!) -> Bool { var isSuccess = false databaseQueue.inTransaction { (db: FMDatabase!, rollback: UnsafeMutablePointer<ObjCBool>) -> Void in isSuccess = db.executeUpdate(execute, withParameterDictionary: args) } return isSuccess } class func database(databaseQueue: FMDatabaseQueue, execute: String, withArgumentsInArray args: [AnyObject]!) -> Bool { var isSuccess = false databaseQueue.inTransaction { (db: FMDatabase!, rollback: UnsafeMutablePointer<ObjCBool>) -> Void in isSuccess = db.executeUpdate(execute, withArgumentsInArray: args) } return isSuccess } }
gpl-3.0
5425c0063d4972ea0b61636c4b46a23d
34.6
136
0.639825
5.375839
false
false
false
false
superk589/CGSSGuide
DereGuide/Toolbox/Colleague/Composing/View/ColleagueMessageCell.swift
2
2128
// // ColleagueMessageCell.swift // DereGuide // // Created by zzk on 2017/8/2. // Copyright © 2017 zzk. All rights reserved. // import UIKit import SnapKit class ColleagueMessageCell: ColleagueBaseCell { var messageView = UITextView() var countLabel = UILabel() override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) contentView.addSubview(messageView) contentView.addSubview(countLabel) messageView.snp.makeConstraints { (make) in make.top.equalTo(leftLabel.snp.bottom).offset(5) make.left.equalTo(10) make.right.equalTo(-10) make.bottom.equalTo(-10) make.height.equalTo(85) } messageView.delegate = self messageView.font = UIFont.systemFont(ofSize: 14) messageView.layer.borderColor = UIColor.lightGray.cgColor messageView.layer.borderWidth = 1 / Screen.scale messageView.layer.cornerRadius = 6 messageView.layer.masksToBounds = true countLabel.snp.makeConstraints { (make) in make.bottom.right.equalTo(-15) } countLabel.isUserInteractionEnabled = false countLabel.textColor = UIColor.lightGray countLabel.font = UIFont.systemFont(ofSize: 14) } func setup(with message: String) { messageView.text = message countLabel.text = String(Config.maxCharactersOfMessage - messageView.text.count) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } extension ColleagueMessageCell: UITextViewDelegate { func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool { return textView.text.count + (text.count - range.length) <= Config.maxCharactersOfMessage } func textViewDidChange(_ textView: UITextView) { countLabel.text = String(Config.maxCharactersOfMessage - textView.text.count) } }
mit
ed198267222f9d7e5e21b004000bf4b5
30.746269
116
0.658204
4.867277
false
false
false
false
hyp/SwiftDocDigger
SwiftDocDigger/HTMLPrinter.swift
1
3234
// // HTMLPrinter.swift // SwiftDocDigger // import Foundation public protocol HTMLPrinter: class { func writeText(_ string: String) func writeHTML(_ html: String) func printNodes(_ nodes: [DocumentationNode]) } public protocol HTMLPrinterDelegate: class { /// Returns true if this node should be printed using the default behaviour. func HTMLPrinterShouldPrintNode(_ printer: HTMLPrinter, node: DocumentationNode) -> Bool } public func printSwiftDocToHTML(_ documentation: [DocumentationNode], delegate: HTMLPrinterDelegate? = nil) -> String { let printer = HTMLPrinterImpl(delegate: delegate) printer.printNodes(documentation) return printer.output } private final class HTMLPrinterImpl: HTMLPrinter { weak var delegate: HTMLPrinterDelegate? var output: String = "" init(delegate: HTMLPrinterDelegate?) { self.delegate = delegate } func writeText(_ string: String) { let escaped = CFXMLCreateStringByEscapingEntities(nil, string as CFString!, nil) as String escaped.write(to: &output) } func writeHTML(_ html: String) { html.write(to: &output) } func writeElement(_ tag: String, node: DocumentationNode) { writeHTML("<\(tag)>") printNodes(node.children) writeHTML("</\(tag)>") } func writeElement(_ tag: String, attributes: [String: String], node: DocumentationNode) { writeHTML("<\(tag)") for (name, value) in attributes { writeHTML(" \(name)=\"\(value)\"") } writeHTML(">") printNodes(node.children) writeHTML("</\(tag)>") } func printNode(_ node: DocumentationNode) { guard delegate?.HTMLPrinterShouldPrintNode(self, node: node) ?? true else { return } func writeElement(_ tag: String) { self.writeElement(tag, node: node) } switch node.element { case .text(let string): assert(node.children.isEmpty) writeText(string) case .paragraph: writeElement("p") case .codeVoice: writeElement("code") case .emphasis: writeElement("em") case .bold: writeElement("b") case .strong: writeElement("strong") case .rawHTML(let html): assert(node.children.isEmpty) writeHTML(html) case .link(let href): self.writeElement("a", attributes: ["href": href], node: node) case .bulletedList: writeElement("ul") case .numberedList: writeElement("ol") case .listItem: writeElement("li") case .codeBlock: writeElement("pre") case .numberedCodeLine: // Ignore it (for now?). printNodes(node.children) writeHTML("\n") case .label(let label): writeHTML("<dt>\(label): </dt><dd>") printNodes(node.children) writeHTML("</dd>") case .other: printNodes(node.children) } } func printNodes(_ nodes: [DocumentationNode]) { for node in nodes { printNode(node) } } }
mit
5f7ac98319a44025595275fc8317f060
28.135135
119
0.584106
4.418033
false
false
false
false
dnevera/ImageMetalling
ImageMetalling-00/ImageMetalling-00/IMPSaturationView.swift
1
15178
// // IMPView.swift // ImageMetalling-00 // // Created by denis svinarchuk on 27.10.15. // Copyright © 2015 ImageMetalling. All rights reserved. // import UIKit import Metal import MetalKit import GLKit /** * Представление результатов обработки картинки в GCD. */ class IMPSaturationView: UIView { /** * Степень насыщенности картинки. Этим папаремтром будем управлять в контроллере. * Этот параметр делаем публичным. */ var saturation:Float!{ didSet(oldValue){ // // Добавляем обзервер изменения, что-бы ловить изменения // saturationUniform = saturationUniform ?? // // если буфер еще не создан создаем (i love swift!:) // self.device.newBufferWithLength(sizeof(Float), options: MTLResourceOptions.CPUCacheModeDefaultCache) // // записвывем в буфер для передачи в GPU в момент исполнения металической команды // memcpy(saturationUniform.contents(), &saturation, sizeof(Float)) // // Обновляем вью // refresh() } } // // Универсальный буфер данных. Металический слой использует этот тип для обмена данными между памятью CPU // и кодом программы GPU. Создать буфер можно один раз и затем просо изменять его содержимое. // Содержимое может иметь произвольную структуру и имеет ограничение только по размеру. // // Все дальнейшие объявления перемнных класса делаем приватными - внешним объектам они ни к чему. // private var saturationUniform:MTLBuffer!=nil // // Текущее устройство GPU. Для работы с металическим устройством создаем новое представление. // private let device:MTLDevice! = MTLCreateSystemDefaultDevice() // // Очередь команд в которую мы будем записывать команды которые должен будет исполнить металический слой. // private var commandQueue:MTLCommandQueue!=nil // // Можно создать слой Core Animation, в котором можно отрендерить содержимое текстуры представленой в Metal, // а можно через MetalKit сразу рисовать в специальном view. MTKView появилась только в iOS 9.0, поэтому если // по каким-то причинам хочется сохранить совместимость с 8.x, то лучше использовать CAMetalLayer. // MetalKit немного экономит для нас время - дает сосредоточится на функционале, вместо того что бы писать // много лишнего кода. // private var metalView:MTKView!=nil // // Переменная котейнер доя храения текстуры с которой будем работать. В текстуру мы загрузим картинку // непосредственно из файла. Очевидно, что картинка в реальном проекте может быть загружена из // произвольного источника. К примеру, таким источником может быть потокй фреймов из камеры устройства. // private var imageTexture:MTLTexture!=nil // // Специальный объект который будет представлять ссылку на нашу функцию, // но уже в виде машинного кода для исполнения его в очереди команд GPU. // Алгоритм фильтра оформим в виде кода шейдера на Metal Shading Language. // Функция которую будем применять к изображению назовем kernel_adjustSaturation // и разместим в файле проекта: IMPSaturationFilter.metal. // private var pipeline:MTLComputePipelineState!=nil // // Настраиваем распараллеливание. Например, мы решили, что нам достаточно запустить по 8 тредов в каждом направлении // для запуска одной инструкции в стиле SIMD - т.е. распараллеливание одной инструкции по множеству потоков данных. // В случае с картинками - это количество пикселей, к которым мы применим фильтр одновременно. // Пусть будет 8x8 потоков в группе, т.е. 64., хотя по правильному количество потоков должно быть кратно размерности картинки. // Но на самом деле можно немного схитрить и считать, что количество групп тредов будет немного больше чем нужно. // private let threadGroupCount = MTLSizeMake(8, 8, 1) // // В этой переменной будем вычислять сколько групп потоков нам нужно создать для обсчета всей сетки данных картинки. // Группы дретов - центральная часть вычислений металического API. Суть заключается в том, что поток вычислений разбивается // на фиксированное количество одновременных вычислений в каждом блоке. Т.е. если это картинка, то картинка бъется сетку // из на множества групп, в каждой группе всегда будет запущено одновременно заданное количество потоков для применения фильра // (в нашем случае 8x8), // а вот как и когда будет запущен этот блок одновременных вычислений принимает решение диспетчер вычислений - и все будет // зависить от конкретной железки GPU и размерности данных. Если количество узлов GPU для одновременного вычичления всех групп будет // достаточно - будет запущены одновременные вычисления по всем группам, если нет - то группы будут выбираться из пула по очереди. // private var threadGroups:MTLSize? // // Загрузка картинки. // func loadImage(file: String){ autoreleasepool { // // Создаем лоадер текстуры из MetalKit // let textureLoader = MTKTextureLoader(device: self.device!) // // Подцепим картинку прямо из проекта. // if let image = UIImage(named: file){ // // Положим картинку в текстуру. Теперь мы можем применять различные преобразования к нашей картинке // используя всю мощь GPU. // imageTexture = try! textureLoader.newTextureWithCGImage(image.CGImage!, options: nil) // // Количество групп параллельных потоков зависит от размера картинки. // По сути мы должны сказать сколько раз мы должны запустить вычисления разных кусков картинки. // threadGroups = MTLSizeMake( (imageTexture.width+threadGroupCount.width)/threadGroupCount.width, (imageTexture.height+threadGroupCount.height)/threadGroupCount.height, 1) } } } // // Ну, тут понятно... // required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) // // Сначала подготовим анимационный слой в который будем рисовать результаты работы // нашего фильтра. // metalView = MTKView(frame: self.bounds, device: self.device) metalView.autoResizeDrawable = true metalView.autoresizingMask = [.FlexibleHeight, .FlexibleWidth] metalView.framebufferOnly = false // // Координатная система Metal: ...The origin of the window coordinates is in the upper-left corner... // https://developer.apple.com/library/ios/documentation/Miscellaneous/Conceptual/MetalProgrammingGuide/Render-Ctx/Render-Ctx.html // // Поэтому, что бы отобразить загруженную текстуру и не возится с вращением картинки пока сделаем так: // просто приведем координаты к bottom-left варианту, т.е. попросту зеркально отобразим // metalView.layer.transform = CATransform3DMakeRotation(CGFloat(M_PI),1.0,0.0,0.0) self.addSubview(metalView) // // Нам нужно сказать рисовалке о реальной размерности экрана в котором будет картинка рисоваться. // let scaleFactor:CGFloat! = metalView.contentScaleFactor metalView.drawableSize = CGSizeMake(self.bounds.width*scaleFactor, self.bounds.height*scaleFactor) // // Пусть по умолчанию картинка будет не десатурированной. // saturation = 1.0 // // Инициализируем очередь комманд один раз и в последующем будем ее использовать для исполнения контекста // программы нашего фильтра десатурации. // commandQueue = device.newCommandQueue() // // Библиотека шейдеров. В библиотеку компилируются все файлы с раcширением .metal добавленyые в проект. // let library:MTLLibrary! = self.device.newDefaultLibrary() // // Функция которую мы будем использовать в качестве функции фильтра из библиотеки шейдеров. // let function:MTLFunction! = library.newFunctionWithName("kernel_adjustSaturation") // // Теперь создаем основной объект который будет ссылаться на исполняемый код нашего фильтра. // pipeline = try! self.device.newComputePipelineStateWithFunction(function) } // // Теперь самое главное: собственно применение фильтра к картинке и отрисовка результатов на экране. // func refresh(){ if let actualImageTexture = imageTexture{ // // Вытягиваем из очереди одноразовый буфер команд. // let commandBuffer = commandQueue.commandBuffer() // // Подготавливаем кодер для интерпретации команд очереди. // let encoder = commandBuffer.computeCommandEncoder() // // Устанавливаем ссылку на код фильтра // encoder.setComputePipelineState(pipeline) // // Устанавливаем ссылку на память с данными текстуры (картинки) // encoder.setTexture(actualImageTexture, atIndex: 0) // // Устанавливаем ссылку на память результрующей текстуры - т.е. куда рисуем // В нашем случае это слой Core Animation подготовленный для рисования текстур из Metal // (ну или MTKview, что тоже самое) // encoder.setTexture(metalView.currentDrawable!.texture, atIndex: 1) // // Передаем ссылку на буфер с данными для параметризации функции фильтра. // encoder.setBuffer(self.saturationUniform, offset: 0, atIndex: 0) // // Говорим металическому диспетчеру как переллелить вычисления. // encoder.dispatchThreadgroups(threadGroups!, threadsPerThreadgroup: threadGroupCount) // // Упаковываем команды в код. // encoder.endEncoding() // // Говорим куда рисовать данные. // commandBuffer.presentDrawable(metalView.currentDrawable!) // // Говорим металическому слой запускать исполняемый код. Все. // commandBuffer.commit() } } }
mit
5d6c9bb5e9aee5b7478b181e2b71529b
40.262357
138
0.635827
3.145507
false
false
false
false
xsunsmile/zentivity
zentivity/EventDetailViewController.swift
1
24394
// // EventDetailViewController.swift // zentivity // // Created by Andrew Wen on 3/10/15. // Copyright (c) 2015 Zendesk. All rights reserved. // import UIKit import MapKit class EventDetailViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate, UIScrollViewDelegate, UIGestureRecognizerDelegate, MKMapViewDelegate { var event: ZenEvent! @IBOutlet weak var imageShadowView: UIView! @IBOutlet weak var contentView: UIView! @IBOutlet weak var eventHeaderView: UIView! @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var addressLabel: UILabel! @IBOutlet weak var phoneLabel: UILabel! @IBOutlet weak var mapView: MKMapView! @IBOutlet weak var joinButton: UIButton! @IBOutlet weak var usersGridView: UICollectionView! @IBOutlet weak var eventDateLabel: UILabel! @IBOutlet weak var imageScrollView: UIScrollView! @IBOutlet weak var imagePageControl: UIPageControl! @IBOutlet weak var eventDescription: UILabel! @IBOutlet weak var closeButton: UIButton! @IBOutlet weak var joinButtonView: UIView! @IBOutlet weak var contentTopConstraint: NSLayoutConstraint! @IBOutlet weak var headerTitleTopConstraint: NSLayoutConstraint! var contentViewOriginFrame: CGRect! var detailHeaderViewOriginFrame: CGRect! var dragStartingPoint: CGPoint! var detailsIsOpen = false var currentImageView: UIImageView? var eventImages: [UIImage]? var addressPlaceHolder = "1019 Market Street, San Francisco, CA" var didInitialAnimation = false var initialDragOffset = CGFloat(0) var initialImageDragOffset = CGFloat(0) var gestureWasHandled = false var pointCount = 0 var startPoint: CGPoint! var modalPanGuesture: UIPanGestureRecognizer? var modalPanGuesture2: UIPanGestureRecognizer? var headerUpToPosition = CGFloat(200) var eventPlaceMark: CLPlacemark? override func viewDidLoad() { super.viewDidLoad() initSubviews() refresh() } override func viewWillAppear(animated: Bool) { animateHeaderViewDown(0.5) if contentView.frame.height < view.frame.height { contentView.frame.size.height = view.frame.height } view.setNeedsDisplay() } func initSubviews() { eventImages = [] imageScrollView.contentSize = CGSizeMake(view.frame.size.width*3, view.frame.size.height) imageScrollView.scrollsToTop = false usersGridView.delegate = self usersGridView.dataSource = self let gradient = CAGradientLayer() let arrayColors = [ UIColor(rgba: "#211F20").CGColor, UIColor.clearColor().CGColor ] imageShadowView.backgroundColor = UIColor.clearColor() gradient.frame = imageShadowView.bounds gradient.frame.size.width = view.frame.width gradient.colors = arrayColors imageShadowView.layer.insertSublayer(gradient, atIndex: 0) imageScrollView.delegate = self if modalPanGuesture != nil { imageScrollView.addGestureRecognizer(modalPanGuesture!) imageShadowView.addGestureRecognizer(modalPanGuesture2!) } imagePageControl.hidden = true imagePageControl.currentPage = 0 mapView.delegate = self initMapView() } func refresh() { if event == nil { return } setupBackgroundImageView() titleLabel.text = event.getTitle() as String if !event.locationString.isEmpty { addressLabel.text = event.locationString } else { addressLabel.text = addressPlaceHolder } var name = "Hao Sun" var number = "(408) 673-4419" phoneLabel.text = "\(name): \(number)" var dateString = NSMutableAttributedString( string: event.startTimeWithFormat("EEEE") as String, attributes: NSDictionary( object: UIFont.boldSystemFontOfSize(17.0), forKey: NSFontAttributeName) as [NSObject : AnyObject]) dateString.appendAttributedString(NSAttributedString( string: "\n" + (event.startTimeWithFormat("MMM d, yyyy") as String), attributes: NSDictionary( object: UIFont(name: "Arial", size: 17.0)!, forKey: NSFontAttributeName) as [NSObject : AnyObject])) eventDateLabel.attributedText = dateString if GoogleClient.sharedInstance.alreadyLogin() { let currentUser = User.currentUser() if currentUser != nil { joinButton.backgroundColor = joinButtonColor() joinButton.setTitle(joinButtonText() as String, forState: .Normal) } } else { joinButton.setTitle("SignIn", forState: .Normal) } if !event.descript.isEmpty { eventDescription.text = event.descript eventDescription.preferredMaxLayoutWidth = view.frame.width - 40 // eventDescription.frame = println("label frame \(eventDescription.frame)") } } func setupBackgroundImageView() { if eventImages?.count == event.photos.count { return } eventImages?.removeAll(keepCapacity: true) if event.photos.count > 0 { for subview in imageScrollView.subviews { subview.removeFromSuperview() } for photo in event.photos { let photo = photo as! Photo photo.fetchIfNeededInBackgroundWithBlock { (photo, error) -> Void in let p = photo as! Photo p.file.getDataInBackgroundWithBlock({ (imageData, error) -> Void in if imageData != nil { println("Got a new photo") let image = UIImage(data:imageData!) self.eventImages?.append(image!) self.addBackgroundImage(image!) } else { println("Failed to download image data") } }) } } } } func initMapView() { // let location = CLLocation(latitude: 37.782193, longitude: -122.410254) // LocationUtils.sharedInstance.getPlacemarkFromLocationWithCompletion(location, completion: { (places, error) -> () in // if error == nil { // let pm = places as [CLPlacemark] // if pm.count > 0 { // println("got list of places: \(pm)") // } // } else { // println("Failed to get places: \(error)") // } // }) var address = addressPlaceHolder if !event.locationString.isEmpty { address = event.locationString } println("event location is \(address)") LocationUtils.sharedInstance.getGeocodeFromAddress(address, completion: { (places, error) -> () in if error == nil { let places = places as! [CLPlacemark] self.eventPlaceMark = places.last let miles = 0.09; let center = CLLocationCoordinate2D(latitude: self.eventPlaceMark!.location.coordinate.latitude, longitude: self.eventPlaceMark!.location.coordinate.longitude) var region = MKCoordinateRegionMakeWithDistance(center, 1609.344 * miles, 1609.344 * miles) self.mapView.setRegion(region, animated: true) let annotation = MKPointAnnotation() // annotation.setCoordinate(center) let title = self.event.getTitle() as String annotation.title = title.truncate(25, trailing: "...") self.mapView.addAnnotation(annotation) self.mapView.selectAnnotation(annotation, animated: true) } else { println("Failed to get places for address \(error)") } }) } func mapView(mapView: MKMapView!, viewForAnnotation annotation: MKAnnotation!) -> MKAnnotationView! { println("get annotaion: \(annotation)") let pinAnnotationView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: "myPin") pinAnnotationView.pinColor = .Purple pinAnnotationView.draggable = true pinAnnotationView.canShowCallout = true pinAnnotationView.animatesDrop = true let driveButton = UIButton.buttonWithType(UIButtonType.Custom) as! UIButton driveButton.frame.size.width = 45 driveButton.frame.size.height = 45 driveButton.backgroundColor = UIColor.whiteColor() let buttonImage = UIImage(named: "zentivity-logo-icon") driveButton.setImage(buttonImage, forState: .Normal) driveButton.imageView?.contentMode = UIViewContentMode.ScaleAspectFill pinAnnotationView.leftCalloutAccessoryView = driveButton return pinAnnotationView } func mapView(mapView: MKMapView!, annotationView view: MKAnnotationView!, calloutAccessoryControlTapped control: UIControl!) { if let annotation = view.annotation as? MKPointAnnotation { let currentLocation = MKMapItem.mapItemForCurrentLocation() let place = MKPlacemark(placemark: self.eventPlaceMark) let destination = MKMapItem(placemark: place) destination.name = self.event.getTitle() as String let items = NSArray(objects: currentLocation, destination) let options = NSDictionary(object: MKLaunchOptionsDirectionsModeDriving, forKey: MKLaunchOptionsDirectionsModeKey) MKMapItem.openMapsWithItems(items as [AnyObject], launchOptions: options as [NSObject : AnyObject]) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } func presentAuthModal() { let appVC = storyboard?.instantiateViewControllerWithIdentifier("AppViewController") as! AppViewController self.presentViewController(appVC, animated: true, completion: nil) } @IBAction func onJoin(sender: AnyObject) { if !GoogleClient.sharedInstance.alreadyLogin() || User.currentUser() == nil { presentAuthModal() return } if joinButton.titleLabel!.text == "Cancel" { joinButton.setTitle("Join", forState: .Normal) } else { joinButton.setTitle("Cancel", forState: .Normal) } // User.currentUser()!.toggleJoinEventWithCompletion(event, completion: { (success, error, state) -> () in // self.joinButton.backgroundColor = self.joinButtonColor() // self.joinButton.setTitle(self.joinButtonText() as String, forState: .Normal) // self.joinButton.setTitleColor(self.joinButtonTextColor(), forState: .Normal) // if self.detailsIsOpen { // self.setHeaderNewColor(self.joinButtonTextColor()) // } // // if state == kUserJoinEvent { // if success != nil { //// UIAlertView( //// title: "Great!", //// message: "See you at the event :)", //// delegate: self, //// cancelButtonTitle: "OK" //// ).show() // } else { //// UIAlertView( //// title: "Error", //// message: "Unable to join event.", //// delegate: self, //// cancelButtonTitle: "Well damn..." //// ).show() // } // } else { // } // self.reloadData() // }) } func joinButtonText() -> NSString { if event.userJoined(User.currentUser()) { return "Cancel" } else { return "Join" } } func joinButtonColor() -> UIColor { if detailsIsOpen { return UIColor.whiteColor() } else { if event.userJoined(User.currentUser()) { return UIColor(rgba: "#3366cc") } else { return UIColor(rgba: "#dd4b39") } } } func joinButtonTextColor() -> UIColor { if !detailsIsOpen { return UIColor.whiteColor() } else { if event.userJoined(User.currentUser()) { return UIColor(rgba: "#3366cc") } else { return UIColor(rgba: "#dd4b39") } } } func reloadData() { usersGridView.reloadData() } func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { if event == nil { return 0 } return event.confirmedUsers.count } func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { var cell = collectionView.dequeueReusableCellWithReuseIdentifier("UserGridViewCell", forIndexPath: indexPath) as! UserIconCollectionViewCell cell.user = event.confirmedUsers[indexPath.row] as? User return cell } func collectionView(collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView { if(kind == UICollectionElementKindSectionHeader) { let cell = collectionView.dequeueReusableSupplementaryViewOfKind(kind, withReuseIdentifier: "eventUserTypes", forIndexPath: indexPath) as! LabelCollectionReusableView return cell } else { return UICollectionReusableView() } } @IBAction func onQuit(sender: UIButton) { dismissViewControllerAnimated(true, completion: nil) } @IBAction func onDetailViewDrag(sender: UIPanGestureRecognizer) { let velocity = sender.velocityInView(view) let point = sender.translationInView(view) let loc = sender.locationInView(view) var direction = "up" detailsIsOpen = true if velocity.y > 0 { direction = "down" detailsIsOpen = false } if sender.state == .Began { println("staring dragging detail view") animateHeaderColorChanges(direction) dragStartingPoint = CGPoint(x: loc.x, y: loc.y) initialDragOffset = contentView.frame.origin.y if currentImageView != nil { initialImageDragOffset = currentImageView!.frame.origin.y println("set image y: \(initialImageDragOffset)") } } else if sender.state == .Changed { let dy = loc.y - dragStartingPoint.y let newYPos = initialDragOffset + dy if newYPos >= 200 { headerUpToPosition = CGFloat(200) contentView.frame.origin.y = newYPos let newImageYPos = initialImageDragOffset + dy/2 if currentImageView != nil { if newImageYPos > 0 { println("Can not drag image down when y is 0") } else { currentImageView?.frame.origin.y = newImageYPos } } else { // println("current image view is empty during dragging") } } else { headerUpToPosition = CGFloat(0) if contentView.frame.height <= view.frame.height { contentView.frame.size.height = view.frame.height if newYPos > 0 { contentView.frame.origin.y = newYPos joinButtonView.transform = CGAffineTransformMakeScale(newYPos/200, newYPos/200) } } else { contentView.frame.origin.y = newYPos if newYPos > 0 { joinButtonView.transform = CGAffineTransformMakeScale(newYPos/200, newYPos/200) } } } } else if sender.state == .Ended { if direction == "up" { animateHeaderViewUp() } else { animateHeaderViewDown(0) } } } func animateHeaderViewDown(delay: Double!) { view.layoutIfNeeded() let dy = self.view.frame.height - self.eventHeaderView.frame.height contentTopConstraint.constant = dy headerTitleTopConstraint.constant = 8 eventHeaderView.setNeedsUpdateConstraints() UIView.animateWithDuration(0.5, delay: delay, usingSpringWithDamping: 0.7, initialSpringVelocity: 1, options: nil, animations: { () -> Void in self.view.layoutIfNeeded() if self.currentImageView != nil { self.currentImageView?.frame.origin.y = 0 } self.joinButtonView.transform = CGAffineTransformIdentity }) { (completed) -> Void in if completed { self.detailsIsOpen = false } } } func animateHeaderViewUp() { view.layoutIfNeeded() let dy = self.view.frame.height - self.contentView.frame.height contentTopConstraint.constant = headerUpToPosition if headerUpToPosition == 0 { headerTitleTopConstraint.constant = 16 } eventHeaderView.setNeedsUpdateConstraints() UIView.animateWithDuration(0.5, delay: 0, usingSpringWithDamping: 0.7, initialSpringVelocity: 1, options: nil, animations: { () -> Void in self.view.layoutIfNeeded() if self.headerUpToPosition == 0 { self.contentView.frame.size.height = self.view.frame.height self.joinButtonView.transform = CGAffineTransformMakeScale(0.0001, 0.0001) } if self.currentImageView != nil { self.currentImageView?.transform = CGAffineTransformMakeTranslation(0, -self.view.frame.height/3) } else { println("current image view is empty") } }) { (completed) -> Void in if completed { self.detailsIsOpen = true } self.headerUpToPosition = CGFloat(200) } } func animateHeaderColorChanges(direction: NSString) { UIView.animateWithDuration(0.4, animations: { () -> Void in if direction == "up" { self.joinButton.backgroundColor = UIColor.whiteColor() self.joinButton.setTitleColor(self.joinButtonTextColor(), forState: .Normal) self.setHeaderNewColor(self.joinButtonTextColor()) } else { self.joinButton.backgroundColor = self.joinButtonColor() self.joinButton.setTitleColor(UIColor.whiteColor(), forState: .Normal) self.setHeaderOriginColor() } }) } func setHeaderOriginColor() { self.eventHeaderView.backgroundColor = UIColor.whiteColor() self.titleLabel.textColor = UIColor.blackColor() self.addressLabel.textColor = UIColor(rgba: "#7f7f7f") self.phoneLabel.textColor = UIColor(rgba: "#7f7f7f") } func setHeaderNewColor(color: UIColor!) { self.eventHeaderView.backgroundColor = color self.titleLabel.textColor = UIColor.whiteColor() self.addressLabel.textColor = UIColor.whiteColor() self.phoneLabel.textColor = UIColor.whiteColor() } func addBackgroundImage(image: UIImage!) { let numImages = eventImages!.count imagePageControl.hidden = false imagePageControl.numberOfPages = numImages let imageWidth = view.frame.size.width let imageHeight = view.frame.size.height let xPosition = imageWidth * CGFloat(numImages - 1) let mainFrame = CGRectMake(xPosition, 0, imageWidth, imageHeight) let imageView = UIImageView(frame: mainFrame) imageView.image = image imageView.clipsToBounds = true imageView.contentMode = UIViewContentMode.ScaleAspectFill // imageView.userInteractionEnabled = true imageScrollView.addSubview(imageView) imageScrollView.contentSize = CGSizeMake(imageWidth * CGFloat(numImages), imageHeight) if currentImageView == nil { currentImageView = imageView } } func scrollViewDidEndDragging(scrollView: UIScrollView, willDecelerate decelerate: Bool) { println("image view did end dragging") } func scrollViewWillBeginDragging(scrollView: UIScrollView) { println("image roll will begin dragging") } func scrollViewDidEndDecelerating(scrollView: UIScrollView) { let pageSize: Float = Float(view.bounds.size.width) var page: Float = floorf((Float(scrollView.contentOffset.x) - pageSize / 2.0) / pageSize) + 1 let numPages = eventImages?.count if (page >= Float(numPages!)) { page = Float(numPages!) - 1 } else if (page < 0) { page = 0 } imagePageControl.currentPage = Int(page) println("current page is: \(Int(page))") if Int(page) >= 0 && imageScrollView.subviews.count > Int(page) { currentImageView = imageScrollView.subviews[Int(page)] as? UIImageView println("current image view: \(currentImageView)") } } @IBAction func onHeaderTap(sender: UITapGestureRecognizer) { println("did tap detail view") let direction = detailsIsOpen ? "down" : "up" if detailsIsOpen { println("Hide detail view") detailsIsOpen = false animateHeaderColorChanges(direction) animateHeaderViewDown(0) } else { println("Show detail view") detailsIsOpen = true animateHeaderColorChanges(direction) animateHeaderViewUp() } } override func preferredStatusBarStyle() -> UIStatusBarStyle { return UIStatusBarStyle.LightContent } @IBAction func onCall(sender: UIButton) { println("There is no number to call") return // let contactNumber = event.contactNumber // if contactNumber == nil { // println("There is no number to call") // return // } // // let regex = NSRegularExpression(pattern: "\\(|\\)|-", options: nil, error: nil) // let number = regex?.stringByReplacingMatchesInString(contactNumber!, options: nil, range: NSMakeRange(0, count(contactNumber!)), withTemplate: "$1") // println("calling number \(number)") // let phoneNumber = "tel://".stringByAppendingString(number!) // UIApplication.sharedApplication().openURL(NSURL(string: phoneNumber)!) } func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWithGestureRecognizer otherGestureRecognizer: UIGestureRecognizer) -> Bool { 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
82acb06c8a2e1d5373a5ff36d19e62ce
37.843949
178
0.58539
5.459714
false
false
false
false
DarrenKong/firefox-ios
ClientTests/SearchTests.swift
4
6950
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import GCDWebServers @testable import Client import UIKit import XCTest class SearchTests: XCTestCase { func testParsing() { let parser = OpenSearchParser(pluginMode: true) let file = Bundle.main.path(forResource: "google", ofType: "xml", inDirectory: "SearchPlugins/") let engine: OpenSearchEngine! = parser.parse(file!, engineID: "google") XCTAssertEqual(engine.shortName, "Google") // Test regular search queries. XCTAssertEqual(engine.searchURLForQuery("foobar")!.absoluteString, "https://www.google.com/search?q=foobar&ie=utf-8&oe=utf-8&client=firefox-b") // Test search suggestion queries. XCTAssertEqual(engine.suggestURLForQuery("foobar")!.absoluteString, "https://www.google.com/complete/search?client=firefox&q=foobar") } func testURIFixup() { // Check valid URLs. We can load these after some fixup. checkValidURL("http://www.mozilla.org", afterFixup: "http://www.mozilla.org") checkValidURL("about:", afterFixup: "about:") checkValidURL("about:config", afterFixup: "about:config") checkValidURL("about: config", afterFixup: "about:%20config") checkValidURL("file:///f/o/o", afterFixup: "file:///f/o/o") checkValidURL("ftp://ftp.mozilla.org", afterFixup: "ftp://ftp.mozilla.org") checkValidURL("foo.bar", afterFixup: "http://foo.bar") checkValidURL(" foo.bar ", afterFixup: "http://foo.bar") checkValidURL("1.2.3", afterFixup: "http://1.2.3") // Check invalid URLs. These are passed along to the default search engine. checkInvalidURL("foobar") checkInvalidURL("foo bar") checkInvalidURL("mozilla. org") checkInvalidURL("123") checkInvalidURL("a/b") checkInvalidURL("创业咖啡") checkInvalidURL("创业咖啡 中国") checkInvalidURL("创业咖啡. 中国") } func testURIFixupPunyCode() { checkValidURL("http://创业咖啡.中国/", afterFixup: "http://xn--vhq70hq9bhxa.xn--fiqs8s/") checkValidURL("创业咖啡.中国", afterFixup: "http://xn--vhq70hq9bhxa.xn--fiqs8s") checkValidURL(" 创业咖啡.中国 ", afterFixup: "http://xn--vhq70hq9bhxa.xn--fiqs8s") } fileprivate func checkValidURL(_ beforeFixup: String, afterFixup: String) { XCTAssertEqual(URIFixup.getURL(beforeFixup)!.absoluteString, afterFixup) } fileprivate func checkInvalidURL(_ beforeFixup: String) { XCTAssertNil(URIFixup.getURL(beforeFixup)) } func testSuggestClient() { let webServerBase = startMockSuggestServer() let engine = OpenSearchEngine(engineID: "mock", shortName: "Mock engine", image: UIImage(), searchTemplate: "", suggestTemplate: "\(webServerBase)?q={searchTerms}", isCustomEngine: false) let client = SearchSuggestClient(searchEngine: engine, userAgent: "Fx-testSuggestClient") let query1 = self.expectation(description: "foo query") client.query("foo", callback: { response, error in withExtendedLifetime(client) { if error != nil { XCTFail("Error: \(error?.description ?? "nil")") } XCTAssertEqual(response![0], "foo") XCTAssertEqual(response![1], "foo2") XCTAssertEqual(response![2], "foo you") query1.fulfill() } }) waitForExpectations(timeout: 10, handler: nil) let query2 = self.expectation(description: "foo bar query") client.query("foo bar", callback: { response, error in withExtendedLifetime(client) { if error != nil { XCTFail("Error: \(error?.description ?? "nil")") } XCTAssertEqual(response![0], "foo bar soap") XCTAssertEqual(response![1], "foo barstool") XCTAssertEqual(response![2], "foo bartender") query2.fulfill() } }) waitForExpectations(timeout: 10, handler: nil) } func testExtractingOfSearchTermsFromURL() { let parser = OpenSearchParser(pluginMode: true) var file = Bundle.main.path(forResource: "google", ofType: "xml", inDirectory: "SearchPlugins/") let googleEngine: OpenSearchEngine! = parser.parse(file!, engineID: "google") // create URL let searchTerm = "Foo Bar" let encodedSeachTerm = searchTerm.replacingOccurrences(of: " ", with: "+") let googleSearchURL = URL(string: "https://www.google.com/search?q=\(encodedSeachTerm)&ie=utf-8&oe=utf-8&gws_rd=cr&ei=I0UyVp_qK4HtUoytjagM") let duckDuckGoSearchURL = URL(string: "https://duckduckgo.com/?q=\(encodedSeachTerm)&ia=about") let invalidSearchURL = URL(string: "https://www.google.co.uk") // check it correctly matches google search term given google config XCTAssertEqual(searchTerm, googleEngine.queryForSearchURL(googleSearchURL)) // check it doesn't match when the URL is not a search URL XCTAssertNil(googleEngine.queryForSearchURL(invalidSearchURL)) // check that it matches given a different configuration file = Bundle.main.path(forResource: "duckduckgo", ofType: "xml", inDirectory: "SearchPlugins/") let duckDuckGoEngine: OpenSearchEngine! = parser.parse(file!, engineID: "duckduckgo") XCTAssertEqual(searchTerm, duckDuckGoEngine.queryForSearchURL(duckDuckGoSearchURL)) // check it doesn't match search URLs for different configurations XCTAssertNil(duckDuckGoEngine.queryForSearchURL(googleSearchURL)) // check that if you pass in a nil URL that everything works XCTAssertNil(duckDuckGoEngine.queryForSearchURL(nil)) } fileprivate func startMockSuggestServer() -> String { let webServer: GCDWebServer = GCDWebServer() webServer.addHandler(forMethod: "GET", path: "/", request: GCDWebServerRequest.self) { (request) -> GCDWebServerResponse! in var suggestions: [String]! let query = request?.query["q"] as! String switch query { case "foo": suggestions = ["foo", "foo2", "foo you"] case "foo bar": suggestions = ["foo bar soap", "foo barstool", "foo bartender"] default: XCTFail("Unexpected query: \(query)") } return GCDWebServerDataResponse(jsonObject: [query, suggestions]) } if !webServer.start(withPort: 0, bonjourName: nil) { XCTFail("Can't start the GCDWebServer") } return "http://localhost:\(webServer.port)" } }
mpl-2.0
9f4189c54deda0f094b2c90a322cf260
43.688312
172
0.634554
4.2613
false
true
false
false
roecrew/AudioKit
Examples/iOS/AnalogSynthX/AnalogSynthX/CustomControls/Knob.swift
1
1929
// // Knob.swift // Swift Synth // // Created by Matthew Fecher on 1/9/16. // Copyright © 2016 AudioKit. All rights reserved. // import UIKit @IBDesignable class Knob: UIView { var minimum = 0.0 { didSet { self.knobValue = CGFloat((value - minimum) / (maximum - minimum)) } } var maximum = 1.0 { didSet { self.knobValue = CGFloat((value - minimum) / (maximum - minimum)) } } var value: Double = 0 { didSet { if value > maximum { value = maximum } if value < minimum { value = minimum } self.knobValue = CGFloat((value - minimum) / (maximum - minimum)) } } // Knob properties var knobValue: CGFloat = 0.5 var knobSensitivity = 0.005 var lastX: CGFloat = 0 var lastY: CGFloat = 0 // Init / Lifecycle override init(frame: CGRect) { super.init(frame: frame) contentMode = .Redraw } required init?(coder: NSCoder) { super.init(coder: coder) self.userInteractionEnabled = true contentMode = .Redraw } override func prepareForInterfaceBuilder() { super.prepareForInterfaceBuilder() contentMode = .ScaleAspectFill clipsToBounds = true } class override func requiresConstraintBasedLayout() -> Bool { return true } // Helper func setPercentagesWithTouchPoint(touchPoint: CGPoint) { // Knobs assume up or right is increasing, and down or left is decreasing let horizontalChange = Double(touchPoint.x - lastX) * knobSensitivity value += horizontalChange * (maximum - minimum) let verticalChange = Double(touchPoint.y - lastY) * knobSensitivity value -= verticalChange * (maximum - minimum) lastX = touchPoint.x lastY = touchPoint.y } }
mit
863eae940f6454b15c50bc009edd5d9d
22.802469
81
0.57832
4.668281
false
false
false
false
roambotics/swift
validation-test/compiler_crashers_2_fixed/0166-issue-50772-2.swift
2
631
// RUN: %target-typecheck-verify-swift // RUN: %target-swift-frontend -typecheck %s -debug-generic-signatures 2>&1 | %FileCheck %s // https://github.com/apple/swift/issues/50772 struct Box<Representation, T> { let value: Representation } enum Repr {} extension Repr { typealias RawEnum = () } // CHECK-LABEL: ExtensionDecl line={{.*}} base=Box // CHECK-NEXT: Generic signature: <Representation, T where Representation == Repr, T == ()> extension Box where Representation == Repr, T == Representation.RawEnum { init(rawEnumValue: Representation.RawEnum) { let _: ().Type = T.self fatalError() } }
apache-2.0
568837e05062ed3fa632c0780a4327cb
29.047619
91
0.676704
3.690058
false
false
false
false
Brightify/ReactantUI
Sources/Tokenizer/Contexts/ComponentContext.swift
1
1165
// // ComponentContext.swift // Tokenizer // // Created by Tadeas Kriz on 01/06/2018. // import Foundation /** * The "file"'s context. This context is available throughout a Component's file. * It's used to resolve local styles and delegate global style resolving to global context. */ public struct ComponentContext: DataContext { public let globalContext: GlobalContext public let component: ComponentDefinition public init(globalContext: GlobalContext, component: ComponentDefinition) { self.globalContext = globalContext self.component = component } public func resolvedStyleName(named styleName: StyleName) -> String { guard case .local(let name) = styleName else { return globalContext.resolvedStyleName(named: styleName) } return component.stylesName + "." + name } public func style(named styleName: StyleName) -> Style? { guard case .local(let name) = styleName else { return globalContext.style(named: styleName) } return component.styles.first { $0.name.name == name } } } extension ComponentContext: HasGlobalContext { }
mit
8494ddc905d73539ae42e30224f6b43e
29.657895
91
0.687554
4.498069
false
false
false
false
practicalswift/swift
test/IDE/complete_decl_attribute.swift
1
10197
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=AVAILABILITY1 | %FileCheck %s -check-prefix=AVAILABILITY1 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=AVAILABILITY2 | %FileCheck %s -check-prefix=AVAILABILITY2 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=KEYWORD2 | %FileCheck %s -check-prefix=KEYWORD2 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=KEYWORD3 | %FileCheck %s -check-prefix=KEYWORD3 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=KEYWORD3_2 | %FileCheck %s -check-prefix=KEYWORD3 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=KEYWORD4 | %FileCheck %s -check-prefix=KEYWORD4 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=KEYWORD5 | %FileCheck %s -check-prefix=KEYWORD5 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=KEYWORD_LAST | %FileCheck %s -check-prefix=KEYWORD_LAST @available(#^AVAILABILITY1^#) // NOTE: Please do not include the ", N items" after "Begin completions". The // item count creates needless merge conflicts given that we use the "-NEXT" // feature of FileCheck and because an "End completions" line exists for each // test. // AVAILABILITY1: Begin completions // AVAILABILITY1-NEXT: Keyword/None: *[#Platform#]; name=*{{$}} // AVAILABILITY1-NEXT: Keyword/None: iOS[#Platform#]; name=iOS{{$}} // AVAILABILITY1-NEXT: Keyword/None: tvOS[#Platform#]; name=tvOS{{$}} // AVAILABILITY1-NEXT: Keyword/None: watchOS[#Platform#]; name=watchOS{{$}} // AVAILABILITY1-NEXT: Keyword/None: OSX[#Platform#]; name=OSX{{$}} // AVAILABILITY1-NEXT: Keyword/None: iOSApplicationExtension[#Platform#]; name=iOSApplicationExtension{{$}} // AVAILABILITY1-NEXT: Keyword/None: tvOSApplicationExtension[#Platform#]; name=tvOSApplicationExtension{{$}} // AVAILABILITY1-NEXT: Keyword/None: watchOSApplicationExtension[#Platform#]; name=watchOSApplicationExtension{{$}} // AVAILABILITY1-NEXT: Keyword/None: OSXApplicationExtension[#Platform#]; name=OSXApplicationExtension{{$}} // AVAILABILITY1-NEXT: End completions @available(*, #^AVAILABILITY2^#) // AVAILABILITY2: Begin completions // AVAILABILITY2-NEXT: Keyword/None: unavailable; name=unavailable{{$}} // AVAILABILITY2-NEXT: Keyword/None: message: [#Specify message#]; name=message{{$}} // AVAILABILITY2-NEXT: Keyword/None: renamed: [#Specify replacing name#]; name=renamed{{$}} // AVAILABILITY2-NEXT: Keyword/None: introduced: [#Specify version number#]; name=introduced{{$}} // AVAILABILITY2-NEXT: Keyword/None: deprecated: [#Specify version number#]; name=deprecated{{$}} // AVAILABILITY2-NEXT: End completions @#^KEYWORD2^# func method(){} // KEYWORD2: Begin completions // KEYWORD2-NEXT: Keyword/None: available[#Func Attribute#]; name=available{{$}} // KEYWORD2-NEXT: Keyword/None: objc[#Func Attribute#]; name=objc{{$}} // KEYWORD2-NEXT: Keyword/None: IBAction[#Func Attribute#]; name=IBAction{{$}} // KEYWORD2-NEXT: Keyword/None: NSManaged[#Func Attribute#]; name=NSManaged{{$}} // KEYWORD2-NEXT: Keyword/None: inline[#Func Attribute#]; name=inline{{$}} // KEYWORD2-NEXT: Keyword/None: nonobjc[#Func Attribute#]; name=nonobjc{{$}} // KEYWORD2-NEXT: Keyword/None: inlinable[#Func Attribute#]; name=inlinable{{$}} // KEYWORD2-NEXT: Keyword/None: warn_unqualified_access[#Func Attribute#]; name=warn_unqualified_access{{$}} // KEYWORD2-NEXT: Keyword/None: usableFromInline[#Func Attribute#]; name=usableFromInline // KEYWORD2-NEXT: Keyword/None: discardableResult[#Func Attribute#]; name=discardableResult // KEYWORD2-NEXT: End completions @#^KEYWORD3^# class C {} // KEYWORD3: Begin completions // KEYWORD3-NEXT: Keyword/None: available[#Class Attribute#]; name=available{{$}} // KEYWORD3-NEXT: Keyword/None: objc[#Class Attribute#]; name=objc{{$}} // KEYWORD3-NEXT: Keyword/None: dynamicCallable[#Class Attribute#]; name=dynamicCallable{{$}} // KEYWORD3-NEXT: Keyword/None: dynamicMemberLookup[#Class Attribute#]; name=dynamicMemberLookup{{$}} // KEYWORD3-NEXT: Keyword/None: IBDesignable[#Class Attribute#]; name=IBDesignable{{$}} // KEYWORD3-NEXT: Keyword/None: UIApplicationMain[#Class Attribute#]; name=UIApplicationMain{{$}} // KEYWORD3-NEXT: Keyword/None: requires_stored_property_inits[#Class Attribute#]; name=requires_stored_property_inits{{$}} // KEYWORD3-NEXT: Keyword/None: objcMembers[#Class Attribute#]; name=objcMembers{{$}} // KEYWORD3-NEXT: Keyword/None: NSApplicationMain[#Class Attribute#]; name=NSApplicationMain{{$}} // KEYWORD3-NEXT: Keyword/None: usableFromInline[#Class Attribute#]; name=usableFromInline // KEYWORD3-NEXT: End completions @#^KEYWORD3_2^#IB class C2 {} // Same as KEYWORD3. @#^KEYWORD4^# enum E {} // KEYWORD4: Begin completions // KEYWORD4-NEXT: Keyword/None: available[#Enum Attribute#]; name=available{{$}} // KEYWORD4-NEXT: Keyword/None: objc[#Enum Attribute#]; name=objc{{$}} // KEYWORD4-NEXT: Keyword/None: dynamicCallable[#Enum Attribute#]; name=dynamicCallable // KEYWORD4-NEXT: Keyword/None: dynamicMemberLookup[#Enum Attribute#]; name=dynamicMemberLookup // KEYWORD4-NEXT: Keyword/None: usableFromInline[#Enum Attribute#]; name=usableFromInline // KEYWORD4-NEXT: End completions @#^KEYWORD5^# struct S{} // KEYWORD5: Begin completions // KEYWORD5-NEXT: Keyword/None: available[#Struct Attribute#]; name=available{{$}} // KEYWORD5-NEXT: Keyword/None: dynamicCallable[#Struct Attribute#]; name=dynamicCallable // KEYWORD5-NEXT: Keyword/None: dynamicMemberLookup[#Struct Attribute#]; name=dynamicMemberLookup // KEYWORD5-NEXT: Keyword/None: usableFromInline[#Struct Attribute#]; name=usableFromInline // KEYWORD5-NEXT: End completions @#^KEYWORD_LAST^# // KEYWORD_LAST: Begin completions // KEYWORD_LAST-NEXT: Keyword/None: available[#Declaration Attribute#]; name=available{{$}} // KEYWORD_LAST-NEXT: Keyword/None: objc[#Declaration Attribute#]; name=objc{{$}} // KEYWORD_LAST-NEXT: Keyword/None: dynamicCallable[#Declaration Attribute#]; name=dynamicCallable // KEYWORD_LAST-NEXT: Keyword/None: dynamicMemberLookup[#Declaration Attribute#]; name=dynamicMemberLookup // KEYWORD_LAST-NEXT: Keyword/None: NSCopying[#Declaration Attribute#]; name=NSCopying{{$}} // KEYWORD_LAST-NEXT: Keyword/None: IBAction[#Declaration Attribute#]; name=IBAction{{$}} // KEYWORD_LAST-NEXT: Keyword/None: IBDesignable[#Declaration Attribute#]; name=IBDesignable{{$}} // KEYWORD_LAST-NEXT: Keyword/None: IBInspectable[#Declaration Attribute#]; name=IBInspectable{{$}} // KEYWORD_LAST-NEXT: Keyword/None: IBOutlet[#Declaration Attribute#]; name=IBOutlet{{$}} // KEYWORD_LAST-NEXT: Keyword/None: NSManaged[#Declaration Attribute#]; name=NSManaged{{$}} // KEYWORD_LAST-NEXT: Keyword/None: UIApplicationMain[#Declaration Attribute#]; name=UIApplicationMain{{$}} // KEYWORD_LAST-NEXT: Keyword/None: inline[#Declaration Attribute#]; name=inline{{$}} // KEYWORD_LAST-NEXT: Keyword/None: requires_stored_property_inits[#Declaration Attribute#]; name=requires_stored_property_inits{{$}} // KEYWORD_LAST-NEXT: Keyword/None: nonobjc[#Declaration Attribute#]; name=nonobjc{{$}} // KEYWORD_LAST-NEXT: Keyword/None: inlinable[#Declaration Attribute#]; name=inlinable{{$}} // KEYWORD_LAST-NEXT: Keyword/None: objcMembers[#Declaration Attribute#]; name=objcMembers{{$}} // KEYWORD_LAST-NEXT: Keyword/None: NSApplicationMain[#Declaration Attribute#]; name=NSApplicationMain{{$}} // KEYWORD_LAST-NEXT: Keyword/None: warn_unqualified_access[#Declaration Attribute#]; name=warn_unqualified_access // KEYWORD_LAST-NEXT: Keyword/None: usableFromInline[#Declaration Attribute#]; name=usableFromInline{{$}} // KEYWORD_LAST-NEXT: Keyword/None: discardableResult[#Declaration Attribute#]; name=discardableResult // KEYWORD_LAST-NEXT: Keyword/None: GKInspectable[#Declaration Attribute#]; name=GKInspectable{{$}} // KEYWORD_LAST-NEXT: End completions
apache-2.0
d595ef1b535ea42eaa2159fa3752c261
83.975
167
0.588506
4.926087
false
true
false
false
blockchain/My-Wallet-V3-iOS
Blockchain/Accessibility/AccessibilityIdentifiers.swift
1
1812
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import Foundation class AccessibilityIdentifiers: NSObject { enum PinScreen { static let prefix = "PinScreen." static let pinSecureViewTitle = "\(prefix)titleLabel" static let pinIndicatorFormat = "\(prefix)pinIndicator-" static let errorLabel = "\(prefix)errorLabel" static let lockTimeLabel = "\(prefix)lockTimeLabel" static let versionLabel = "\(prefix)versionLabel" static let swipeLabel = "\(prefix)swipeLabel" } enum Address { static let prefix = "AddressScreen." static let pageControl = "\(prefix)pageControl" } enum TabViewContainerScreen { static let activity = "TabViewContainerScreen.activity" static let swap = "TabViewContainerScreen.swap" static let home = "TabViewContainerScreen.home" static let send = "TabViewContainerScreen.send" static let request = "TabViewContainerScreen.request" } // MARK: - Navigation enum Navigation { private static let prefix = "NavigationBar." enum Button { private static let prefix = "\(Navigation.prefix)Button." static let qrCode = "\(prefix)qrCode" static let dismiss = "\(prefix)dismiss" static let menu = "\(prefix)menu" static let help = "\(prefix)help" static let back = "\(prefix)back" static let error = "\(prefix)error" static let activityIndicator = "\(prefix)activityIndicator" } } // MARK: - Asset Selection enum AssetSelection { private static let prefix = "AssetSelection." static let toggleButton = "\(prefix)toggleButton" static let assetPrefix = "\(prefix)" } }
lgpl-3.0
ea995f78f67643ac33a4ccf0a277f7c3
29.694915
71
0.629486
5.030556
false
false
false
false
huonw/swift
validation-test/stdlib/Dictionary.swift
1
136493
// 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 #if os(OSX) || os(iOS) || os(tvOS) || os(watchOS) import Darwin #else import Glibc #endif 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) var 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() var identity1 = d._rawIdentifier() var startIndex = d.startIndex var 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() var identity1 = d._rawIdentifier() var startIndex = d.startIndex var 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") { var d = getCOWFastDictionary() var identity1 = d._rawIdentifier() var 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") { var d = getCOWSlowDictionary() var identity1 = d._rawIdentifier() var 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() var 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() var 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() var 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() var 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() var 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() var 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() var 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() var 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() var 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() var 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() var 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() var 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() var 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() var 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() var 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() var 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() var 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() var 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() var 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") { var d = getCOWFastDictionary() var identity1 = d._rawIdentifier() // Find an existing key. do { var foundIndex1 = d.index(forKey: 10)! assert(identity1 == d._rawIdentifier()) var 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 { var foundIndex1 = d.index(forKey: 1111) assert(foundIndex1 == nil) assert(identity1 == d._rawIdentifier()) } do { var 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") { var d = getCOWSlowDictionary() var identity1 = d._rawIdentifier() // Find an existing key. do { var foundIndex1 = d.index(forKey: TestKeyTy(10))! assert(identity1 == d._rawIdentifier()) var 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 { var foundIndex1 = d.index(forKey: TestKeyTy(1111)) assert(foundIndex1 == nil) assert(identity1 == d._rawIdentifier()) } do { var 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() var 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 { var d1 = getCOWFastDictionary() var identity1 = d1._rawIdentifier() var d2 = d1 assert(identity1 == d1._rawIdentifier()) assert(identity1 == d2._rawIdentifier()) var 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() var identity1 = d._rawIdentifier() var 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 { var d1 = getCOWSlowDictionary() var identity1 = d1._rawIdentifier() var d2 = d1 assert(identity1 == d1._rawIdentifier()) assert(identity1 == d2._rawIdentifier()) var 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() var 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 { var d1 = getCOWFastDictionary() var 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() var 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 { var d1 = getCOWSlowDictionary() var 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. var 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() var 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() var identity1 = d1._rawIdentifier() assert(d1.count == 3) assert(d1[10]! == 1010) var d2 = d1 d2.removeAll() var 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() var identity1 = d1._rawIdentifier() let originalCapacity = d1.capacity assert(d1.count == 3) assert(d1[10] == 1010) var d2 = d1 d2.removeAll(keepingCapacity: true) var 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. var 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() var 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() var identity1 = d1._rawIdentifier() assert(d1.count == 3) assert(d1[TestKeyTy(10)]!.value == 1010) var d2 = d1 d2.removeAll() var 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() var identity1 = d1._rawIdentifier() let originalCapacity = d1.capacity assert(d1.count == 3) assert(d1[TestKeyTy(10)]!.value == 1010) var d2 = d1 d2.removeAll(keepingCapacity: true) var 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") { var d = getCOWFastDictionary() var identity1 = d._rawIdentifier() assert(d.count == 3) assert(identity1 == d._rawIdentifier()) } DictionaryTestSuite.test("COW.Slow.CountDoesNotReallocate") { var d = getCOWSlowDictionary() var identity1 = d._rawIdentifier() assert(d.count == 3) assert(identity1 == d._rawIdentifier()) } DictionaryTestSuite.test("COW.Fast.GenerateDoesNotReallocate") { var d = getCOWFastDictionary() var 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") { var d = getCOWSlowDictionary() var 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") { var d1 = getCOWFastDictionary() var identity1 = d1._rawIdentifier() var d2 = getCOWFastDictionary() var 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") { var d1 = getCOWSlowEquatableDictionary() var identity1 = d1._rawIdentifier() var d2 = getCOWSlowEquatableDictionary() var 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() var 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)) #if swift(>=4.0) d2.values[i] += 1 assert(d2.values[i] == 1011) assert(d2[10]! == 1011) assert(identity1 != d2._rawIdentifier()) #endif assert(d1[10]! == 1010) assert(identity1 == d1._rawIdentifier()) checkCollection( Array(d1.values), d1.values, stackTrace: SourceLocStack()) { $0 == $1 } } DictionaryTestSuite.test("COW.Fast.KeysAccessDoesNotReallocate") { var d1 = getCOWFastDictionary() var 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 { var 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)! #if swift(>=4.0) expectLE(MinimalHashableValue.timesEqualEqualWasCalled, 4) #endif 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") { var k1 = TestKeyTy(value: 10, hashValue: 0) var k2 = TestKeyTy(value: 20, hashValue: 0) var k3 = TestKeyTy(value: 30, hashValue: 0) helperDeleteThree(k1, k2, k3) } DictionaryTestSuite.test("deleteChainNoCollision") { var k1 = TestKeyTy(value: 10, hashValue: 0) var k2 = TestKeyTy(value: 20, hashValue: 1) var k3 = TestKeyTy(value: 30, hashValue: 2) helperDeleteThree(k1, k2, k3) } DictionaryTestSuite.test("deleteChainCollision2") { var k1_0 = TestKeyTy(value: 10, hashValue: 0) var k2_0 = TestKeyTy(value: 20, hashValue: 0) var k3_2 = TestKeyTy(value: 30, hashValue: 2) var k4_0 = TestKeyTy(value: 40, hashValue: 0) var k5_2 = TestKeyTy(value: 50, hashValue: 2) var 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) } func uniformRandom(_ max: Int) -> Int { #if os(Linux) // SR-685: Can't use arc4random on Linux return Int(random() % (max + 1)) #else return Int(arc4random_uniform(UInt32(max))) #endif } func pickRandom<T>(_ a: [T]) -> T { return a[uniformRandom(a.count)] } func product<C1 : Collection, C2 : Collection>( _ c1: C1, _ c2: C2 ) -> [(C1.Iterator.Element, C2.Iterator.Element)] { var result: [(C1.Iterator.Element, C2.Iterator.Element)] = [] for e1 in c1 { for e2 in c2 { result.append((e1, e2)) } } return result } DictionaryTestSuite.test("deleteChainCollisionRandomized") .forEach(in: product(1...8, 0...5)) { (collisionChains, chainOverlap) in func check(_ d: Dictionary<TestKeyTy, TestValueTy>) { var keys = Array(d.keys) for i in 0..<keys.count { for j in 0..<i { assert(keys[i] != keys[j]) } } for k in keys { assert(d[k] != nil) } } let chainLength = 7 var knownKeys: [TestKeyTy] = [] func getKey(_ value: Int) -> TestKeyTy { for k in knownKeys { if k.value == value { return k } } let hashValue = uniformRandom(chainLength - chainOverlap) * collisionChains let k = TestKeyTy(value: value, hashValue: hashValue) knownKeys += [k] return k } var d = Dictionary<TestKeyTy, TestValueTy>(minimumCapacity: 30) for i in 1..<300 { let key = getKey(uniformRandom(collisionChains * chainLength)) if uniformRandom(chainLength * 2) == 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() var d = Dictionary(uniqueKeysWithValues: [(10, 1010), (20, 1020), (10, 2010)]) } } DictionaryTestSuite.test("init(_:uniquingKeysWith:)") { do { var 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 { var 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 { var 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 { var d = Dictionary([(10, 1010), (10, 2010), (10, 3010), (10, 4010)]) { $1 } expectEqual(d.count, 1) expectEqual(d[10]!, 4010) expectNil(d[1111]) } do { var 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. var d1 = try Dictionary([(10, 1), (20, 2), (30, 3)]) { _ in throw TE() } expectEqual(d1.count, 3) // Duplicate keys, should throw error. var d2 = 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, value) in d1 { expectEqual(String(d1[key]!), d2[key]!) } do { var 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") { var (d, nsd) = getBridgedVerbatimDictionaryAndNSMutableDictionary() var 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) } // 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 { var kv = d[d.index(forKey: TestObjCKeyTy(10))!] assert(kv.0 == TestObjCKeyTy(10)) assert((kv.1 as! TestObjCValueTy).value == 1010) } } DictionaryTestSuite.test("BridgedFromObjC.Nonverbatim.DictionaryIsCopied") { var (d, nsd) = getBridgedNonverbatimDictionaryAndNSMutableDictionary() var 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) } // 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 { var kv = d[d.index(forKey: TestBridgedKeyTy(10))!] assert(kv.0 == TestBridgedKeyTy(10)) assert(kv.1.value == 1010) } } DictionaryTestSuite.test("BridgedFromObjC.Verbatim.NSDictionaryIsRetained") { var nsd: NSDictionary = NSDictionary(dictionary: getAsNSDictionary([10: 1010, 20: 1020, 30: 1030])) var d: [NSObject : AnyObject] = convertNSDictionaryToDictionary(nsd) var 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") { var nsd: NSDictionary = NSDictionary(dictionary: getAsNSDictionary([10: 1010, 20: 1020, 30: 1030])) var d: [TestBridgedKeyTy : TestBridgedValueTy] = convertNSDictionaryToDictionary(nsd) var 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") { var nsd: NSDictionary = CustomImmutableNSDictionary(_privateInit: ()) CustomImmutableNSDictionary.timesCopyWithZoneWasCalled = 0 CustomImmutableNSDictionary.timesObjectForKeyWasCalled = 0 CustomImmutableNSDictionary.timesKeyEnumeratorWasCalled = 0 CustomImmutableNSDictionary.timesCountWasCalled = 0 var d: [NSObject : AnyObject] = convertNSDictionaryToDictionary(nsd) expectEqual(1, CustomImmutableNSDictionary.timesCopyWithZoneWasCalled) expectEqual(0, CustomImmutableNSDictionary.timesObjectForKeyWasCalled) expectEqual(0, CustomImmutableNSDictionary.timesKeyEnumeratorWasCalled) expectEqual(0, CustomImmutableNSDictionary.timesCountWasCalled) var 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") { var nsd: NSDictionary = CustomImmutableNSDictionary(_privateInit: ()) CustomImmutableNSDictionary.timesCopyWithZoneWasCalled = 0 CustomImmutableNSDictionary.timesObjectForKeyWasCalled = 0 CustomImmutableNSDictionary.timesKeyEnumeratorWasCalled = 0 CustomImmutableNSDictionary.timesCountWasCalled = 0 TestBridgedValueTy.bridgeOperations = 0 var 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) var 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") { var d = getBridgedVerbatimDictionary() var 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") { var d = getBridgedNonverbatimDictionary() var 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") { var d = getBridgedVerbatimDictionary() var identity1 = d._rawIdentifier() assert(isCocoaDictionary(d)) var startIndex = d.startIndex var 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 { var (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") { var d = getBridgedNonverbatimDictionary() var identity1 = d._rawIdentifier() assert(isNativeDictionary(d)) var startIndex = d.startIndex var 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 { var (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") { var d = getBridgedVerbatimDictionary([:]) var identity1 = d._rawIdentifier() assert(isCocoaDictionary(d)) var startIndex = d.startIndex var 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") { var d = getBridgedNonverbatimDictionary([:]) var identity1 = d._rawIdentifier() assert(isNativeDictionary(d)) var startIndex = d.startIndex var 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() var 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) var 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() var 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) var 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() var identity1 = d._rawIdentifier() assert(isCocoaDictionary(d)) var oldValue: AnyObject? = d.updateValue(TestObjCValueTy(2040), forKey: TestObjCKeyTy(40)) assert(oldValue == nil) var 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() var identity1 = d._rawIdentifier() assert(isCocoaDictionary(d)) var oldValue: AnyObject? = d.updateValue(TestObjCValueTy(2010), forKey: TestObjCKeyTy(10)) assert((oldValue as! TestObjCValueTy).value == 1010) var 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() var identity1 = d._rawIdentifier() assert(isNativeDictionary(d)) var oldValue = d.updateValue(TestBridgedValueTy(2040), forKey: TestBridgedKeyTy(40)) assert(oldValue == nil) var 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() var identity1 = d._rawIdentifier() assert(isNativeDictionary(d)) var oldValue = d.updateValue(TestBridgedValueTy(2010), forKey: TestBridgedKeyTy(10))! assert(oldValue.value == 1010) var 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() var 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() var 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() var 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) var 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() var 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) var 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() var 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) var 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() var 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) var 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([:]) var identity1 = d._rawIdentifier() assert(isCocoaDictionary(d)) assert(d.count == 0) d.removeAll() assert(identity1 == d._rawIdentifier()) assert(d.count == 0) } do { var d = getBridgedVerbatimDictionary() var 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() var 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() var 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() var 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() var 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) var 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([:]) var identity1 = d._rawIdentifier() assert(isNativeDictionary(d)) assert(d.count == 0) d.removeAll() assert(identity1 == d._rawIdentifier()) assert(d.count == 0) } do { var d = getBridgedNonverbatimDictionary() var 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() var 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 { var d1 = getBridgedNonverbatimDictionary() var 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() var 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 { var d1 = getBridgedNonverbatimDictionary() var 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) var 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") { var d = getBridgedVerbatimDictionary() var identity1 = d._rawIdentifier() assert(isCocoaDictionary(d)) assert(d.count == 3) assert(identity1 == d._rawIdentifier()) } DictionaryTestSuite.test("BridgedFromObjC.Nonverbatim.Count") { var d = getBridgedNonverbatimDictionary() var identity1 = d._rawIdentifier() assert(isNativeDictionary(d)) assert(d.count == 3) assert(identity1 == d._rawIdentifier()) } DictionaryTestSuite.test("BridgedFromObjC.Verbatim.Generate") { var d = getBridgedVerbatimDictionary() var 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") { var d = getBridgedNonverbatimDictionary() var 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") { var d = getBridgedVerbatimDictionary([:]) var 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") { var d = getBridgedNonverbatimDictionary([:]) var 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") { var d = getHugeBridgedVerbatimDictionary() var 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") { var d = getHugeBridgedNonverbatimDictionary() var 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. var d = getParallelArrayBridgedVerbatimDictionary() var 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 = [ (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. var d = getParallelArrayBridgedNonverbatimDictionary() var 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 = [ (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") { var d1 = getBridgedVerbatimEquatableDictionary([:]) var 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") { var d1 = getBridgedNonverbatimEquatableDictionary([:]) var identity1 = d1._rawIdentifier() assert(isNativeDictionary(d1)) var d2 = getBridgedNonverbatimEquatableDictionary([:]) var 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") { var 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 { var 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) } var expectedPairs = [ (10, 1010 + i), (20, 1020 + i), (30, 1030 + i) ] assert(equalsUnordered(pairs, expectedPairs)) } } DictionaryTestSuite.test("BridgedFromObjC.Nonverbatim.ArrayOfDictionaries") { var 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 { var 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) } var 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 i 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 i 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 }) } //===--- // 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 }) } 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) let nsd: NSDictionary = d as NSDictionary 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 dCC = _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 let dCC = d as? 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 dCV = _dictionaryBridgeFromObjectiveCConditional(d) as Dictionary<TestObjCKeyTy, TestBridgedValueTy>?{ assert(false) } if let dVC = _dictionaryBridgeFromObjectiveCConditional(d) as Dictionary<TestBridgedKeyTy, TestObjCValueTy>?{ assert(false) } if let dVV = _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 let dCV = d as? Dictionary<TestObjCKeyTy, TestBridgedValueTy> { assert(false) } if let dVC = d as? Dictionary<TestBridgedKeyTy, TestObjCValueTy> { assert(false) } if let dVV = d as? 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 { var empty = Dictionary<Int, Int>() expectTrue(empty.isEmpty) } do { var 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 { var d = getMockDictionaryWithCustomCount(count: 0) MockDictionaryWithCustomCount.timesCountWasCalled = 0 expectTrue(d.isEmpty) expectEqual(1, MockDictionaryWithCustomCount.timesCountWasCalled) } do { var d = getMockDictionaryWithCustomCount(count: 0) MockDictionaryWithCustomCount.timesCountWasCalled = 0 expectTrue(callGenericIsEmpty(d)) expectEqual(1, MockDictionaryWithCustomCount.timesCountWasCalled) } do { var d = getMockDictionaryWithCustomCount(count: 4) MockDictionaryWithCustomCount.timesCountWasCalled = 0 expectFalse(d.isEmpty) expectEqual(1, MockDictionaryWithCustomCount.timesCountWasCalled) } do { var d = getMockDictionaryWithCustomCount(count: 4) MockDictionaryWithCustomCount.timesCountWasCalled = 0 expectFalse(callGenericIsEmpty(d)) expectEqual(1, MockDictionaryWithCustomCount.timesCountWasCalled) } } #endif // _runtime(_ObjC) DictionaryDerivedAPIs.test("keys") { do { var empty = Dictionary<Int, Int>() var keys = Array(empty.keys) expectTrue(equalsUnordered(keys, [])) } do { var d = getDerivedAPIsDictionary() var keys = Array(d.keys) expectTrue(equalsUnordered(keys, [ 10, 20, 30 ])) } } DictionaryDerivedAPIs.test("values") { do { var empty = Dictionary<Int, Int>() var 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 { dynamic func acceptArrayBridgedVerbatim(_ array: [TestObjCValueTy]) { expectEqual(10, array[0].value) expectEqual(20, array[1].value) expectEqual(30, array[2].value) } dynamic func acceptArrayBridgedNonverbatim(_ array: [TestBridgedValueTy]) { // Cannot check elements because doing so would bridge them. expectEqual(3, array.count) } dynamic func returnArrayBridgedVerbatim() -> [TestObjCValueTy] { return [ TestObjCValueTy(10), TestObjCValueTy(20), TestObjCValueTy(30) ] } dynamic func returnArrayBridgedNonverbatim() -> [TestBridgedValueTy] { return [ TestBridgedValueTy(10), TestBridgedValueTy(20), TestBridgedValueTy(30) ] } 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) } dynamic func acceptDictionaryBridgedNonverbatim( _ d: [TestBridgedKeyTy : TestBridgedValueTy]) { expectEqual(3, d.count) // Cannot check elements because doing so would bridge them. } dynamic func returnDictionaryBridgedVerbatim() -> [TestObjCKeyTy : TestObjCValueTy] { return [ TestObjCKeyTy(10): TestObjCValueTy(1010), TestObjCKeyTy(20): TestObjCValueTy(1020), TestObjCKeyTy(30): TestObjCValueTy(1030), ] } dynamic func returnDictionaryBridgedNonverbatim() -> [TestBridgedKeyTy : TestBridgedValueTy] { return [ TestBridgedKeyTy(10): TestBridgedValueTy(1010), TestBridgedKeyTy(20): TestBridgedValueTy(1020), TestBridgedKeyTy(30): TestBridgedValueTy(1030), ] } } ObjCThunks.test("Array/Accept") { var 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") { var 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") { var 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") { var 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() var iter = dict.makeIterator() dict[10] = 1011 expectEqualsUnordered( [ (10, 1010), (20, 1020), (30, 1030) ], Array(IteratorSequence(iter))) } DictionaryTestSuite.test("mutationDoesNotAffectIterator/removeValueForKey,1") { var dict = getDerivedAPIsDictionary() var 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() var 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() var 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() var 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 { var bridged: NSDictionary = dict as NSDictionary expectEqual(10, bridged[0 as NSNumber] as! Int) } dict[0] = 11 do { var bridged: NSDictionary = dict as NSDictionary expectEqual(11, bridged[0 as NSNumber] as! Int) } } DictionaryTestSuite.test("getObjects:andKeys:") { let native = [1: "one", 2: "two"] as Dictionary<Int, String> let d = native as NSDictionary var keys = UnsafeMutableBufferPointer( start: UnsafeMutablePointer<NSNumber>.allocate(capacity: 2), count: 2) var values = UnsafeMutableBufferPointer( start: UnsafeMutablePointer<NSString>.allocate(capacity: 2), count: 2) var kp = AutoreleasingUnsafeMutablePointer<AnyObject?>(keys.baseAddress!) var vp = AutoreleasingUnsafeMutablePointer<AnyObject?>(values.baseAddress!) var null: AutoreleasingUnsafeMutablePointer<AnyObject?>? 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) // don't segfault d.available_getObjects(null, andKeys: kp) expectEqual(expectedKeys, Array(keys)) d.available_getObjects(vp, andKeys: null) expectEqual(expectedValues, Array(values)) d.available_getObjects(vp, andKeys: kp) 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 { resetLeaksOfDictionaryKeysValues() #if _runtime(_ObjC) resetLeaksOfObjCDictionaryKeysValues() #endif } DictionaryTestSuite.tearDown { expectNoLeaksOfDictionaryKeysValues() #if _runtime(_ObjC) expectNoLeaksOfObjCDictionaryKeysValues() #endif } runAllTests()
apache-2.0
1d9f0ee73b30d889bab713df3345d4c3
28.176999
285
0.67602
3.947308
false
true
false
false
markedwardmurray/Precipitate
Precipitate/WeatherIconName.swift
1
1866
// // WeatherIconName.swift // Precipitate // // Created by Mark Murray on 12/14/15. // Copyright © 2015 markedwardmurray. All rights reserved. // import UIKit enum WeatherIconName: String { case ClearDay = "clear-day" case ClearNight = "clear-night" case Rain = "rain" case Snow = "snow" case Sleet = "sleet" case Wind = "wind" case Fog = "fog" case Cloudy = "cloudy" case PartlyCloudyDay = "partly-cloudy-day" case PartlyCloudyNight = "partly-cloudy-night" case Hail = "hail" case Thunderstorm = "thunderstorm" case Tornado = "tornado" } // Weather icons by https://erikflowers.github.io/weather-icons/ func weatherIconForName(name: WeatherIconName?) -> (String, CGFloat) { if let name = name { switch name { case .ClearDay: return ("\u{f00d}", 25.0) // wi-day-sunny case .ClearNight: return ("\u{f0d1}", 25.0) // wi-moon-alt-waxing-crescent-2 case .Rain: return ("\u{f01c}", 25.0) // wi-sprinkle case .Snow: return ("\u{f01b}", 25.0) // wi-snow case .Sleet: return ("\u{f017}", 25.0) // wi-rain-mix case .Wind: return ("\u{f011}", 25.0) // wi-cloudy-gusts case .Fog: return ("\u{f014}", 25.0) // wi-fog case .Cloudy: return ("\u{f013}", 25.0) // wi-cloudy case .PartlyCloudyDay: return ("\u{f002}", 25.0) // wi-day-cloudy case .PartlyCloudyNight: return ("\u{f086}", 25.0) // wi-night-alt-cloudy case .Hail: return ("\u{f071}", 25.0) // wi-meteor case .Thunderstorm: return ("\u{f01e}", 25.0) // wi-thunderstorm case .Tornado: return ("\u{f056}", 25.0) // wi-tornado } } else { return ("❄️", 25.0) } }
mit
a3b253951b984b1a624fb97cae938ceb
29.016129
70
0.54057
3.293805
false
false
false
false
huonw/swift
validation-test/compiler_crashers_fixed/00214-swift-typebase-gettypeofmember.swift
65
2736
// This source file is part of the Swift.org open source project // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -typecheck func f<m>() -> (m, m -> m) -> m { e c e.i = { } { m) { n } } protocol f { class func i() } class e: f{ class func i {} func n<j>() -> (j, j -> j) -> j { var m: ((j> j)! f m } protocol k { typealias m } struct e<j : k> {n: j let i: j.m } l func f() { ({}) } protocol f : f { } func h<d { enum h { func e var _ = e } } protocol e { e func e() } struct h { var d: e.h func e() { d.e() ol A { typealias B } class C<D> { init <A: A where A.B == D>(e: A.B) { } } } class d { func l<j where j: h, j: d>(l: j) { l.k() } func i(k: b) -> <j>(() -> j) -> b { f { m m "\(k): \(m())" } } protocol h func r<t>() { f f { i i } } struct i<o : u> { o f: o } func r<o>() -> [i<o>] { p [] } class g<t : g> { } class g: g { } class n : h { } typealias h = n protocol g { func i() -> l func o() -> m { q"" } } func j<t k t: g, t: n>(s: t) { s.i() } protocol r { } protocol f : r { } protocol i : r { } j var x1 =I Bool !(a) } func prefix(with: Strin) -> <T>(() -> T) in d) func e(h: b) -> <f>(() -> f) -> b { return { c):h())" } } protocol a { typealias d typealias e = d typealias f = d } class b<h : c, i : c where h.g == i> : a { } clas-> i) -> i) { b { (h -> i) d $k } let e: Int = 1, 1) class g<j :g protocol p { class func g() } class h: p { class func g() { } } (h() as p).dynamicType.g() protocol p { } protocol h : p { } protocol g : p { } protocol n { o t = p } struct h : n { t : n q m.t == m> (h: m) { } func q<t : n q t.t == g> (h: t) { ) e protocol g : e { func e import Foundation class m<j>k i<g : g, e : f k(f: l) { } i(()) class h { typealias g = g n) func f<o>() -> (o, o -> o) -> o { o m o.j = { } { o) { r } } p q) { } o m = j m() class m { func r((Any, m))(j: (Any, AnyObject)) { r(j) } } func m< f { class func n() } class l: f{ class func n {} func a<i>() { b b { l j } } class a<f : b, l : b m f.l == l> { } protocol b { typ typealias k } struct j<n : b> : b { typealias l = n typealias k = a<j<n>, l> } a } struct e : f { i f = g } func i<g : g, e : g> : g { typealias f = h typealias e = a<c<h>, f> func b<d { enum b { func c var _ = c } }
apache-2.0
237c548471cfd8737a12ef91cf2abe85
13.030769
79
0.459795
2.423384
false
false
false
false
pcperini/Thrust
Thrust/Source/Dictionary+ThrustExtensions.swift
1
869
// // Dictionary+ThrustExtensions.swift // Thrust // // Created by Patrick Perini on 7/22/14. // Copyright (c) 2014 pcperini. All rights reserved. // import Foundation // MARK: - Operators /// Adds the key-value relationships from the right-hand dictionary to the left-hand dictionary. func +=<Key, Value>(inout lhs: [Key: Value], rhs: [Key: Value]) { for key: Key in rhs.keys { lhs[key] = rhs[key] } } /// Removes the keys found in the right-hand array from the left-hand dictionary. func -=<Key, Value>(inout lhs: [Key: Value], rhs: [Key]) { for key: Key in rhs { lhs.removeValueForKey(key) } } extension Dictionary { /// Initializes the dictionary from a set of 2-tuple key/values. init(_ values: [(Key, Value)]) { self = [:] for (key, value) in values { self[key] = value } } }
mit
79313c9adb3c5bb0ed5e48041fa28617
24.588235
96
0.61565
3.48996
false
false
false
false
Eonil/EditorLegacy
Modules/EditorToolComponents/EditorToolComponents/CargoExecutionController.swift
1
3814
// // CargoExecutionController.swift // Editor // // Created by Hoon H. on 2015/01/12. // Copyright (c) 2015 Eonil. All rights reserved. // import Foundation public struct CargoExecutionResult { public var output:String public var error:String public func issues() -> [RustCompilerIssue] { return RustCompilerOutputParsing.parseErrorOutput(error) } } /// CAUTION /// ------- /// All methods can be called from non-main thread. public protocol CargoExecutionControllerDelegate: class { func cargoExecutionControllerDidPrintMessage(s:String) func cargoExecutionControllerDidDiscoverRustCompilationIssue(issue:RustCompilerIssue) func cargoExecutionControllerRemoteProcessDidTerminate() } /// Asynchronous `cargo` execution controller. /// /// This is one-time use only object. You cannot run multiple /// commands on single object. You have to create a new object /// to run another command. /// /// CAUTION /// ------- /// Delegate methods can be called from non-main thread. public class CargoExecutionController { public weak var delegate:CargoExecutionControllerDelegate? { willSet { assert(delegate == nil) // Once bound delegate cannot be changed. } } public init() { _taskexec = ShellTaskExecutionController() _stdout_linedisp = LineDispatcher() _stderr_linedisp = LineDispatcher() _stdout_linedisp.onLine = { [weak self] (line:String)->() in assert(self != nil) assert(self?.delegate != nil) self?.delegate!.cargoExecutionControllerDidPrintMessage(line) () } _stderr_linedisp.onLine = { [weak self] (line:String)->() in let ss = RustCompilerOutputParsing.parseErrorOutput(line) if ss.count > 0 { for s in ss { assert(self != nil) assert(self?.delegate != nil) self?.delegate!.cargoExecutionControllerDidDiscoverRustCompilationIssue(s) } } } _taskexec.delegate = self } public func launch(#workingDirectoryURL:NSURL, arguments expression:String) { _taskexec.launch(workingDirectoryURL: workingDirectoryURL) _taskexec.writeToStandardInput("cargo \(expression)\n") _taskexec.writeToStandardInput("exit $?;\n") } public func kill() { _taskexec.kill() } public func waitUntilExit() { _taskexec.waitUntilExit() } //// private let _taskexec : ShellTaskExecutionController private var _stdout_linedisp : LineDispatcher private var _stderr_linedisp : LineDispatcher } extension CargoExecutionController: ShellTaskExecutionControllerDelegate { public func shellTaskExecutableControllerDidReadFromStandardOutput(s: String) { _stdout_linedisp.push(s) } public func shellTaskExecutableControllerDidReadFromStandardError(s: String) { _stderr_linedisp.push(s) } public func shellTaskExecutableControllerRemoteProcessDidTerminate(#exitCode: Int32, reason: NSTaskTerminationReason) { _stdout_linedisp.dispatchIncompleteLine() _stderr_linedisp.dispatchIncompleteLine() self.delegate!.cargoExecutionControllerRemoteProcessDidTerminate() } } extension CargoExecutionController { /// `workingDirectoryURL` must be parent directory of new project directory. public func launchNew(#workingDirectoryURL:NSURL, desiredWorkspaceName:String) { self.launch(workingDirectoryURL: workingDirectoryURL, arguments: "new --verbose \(desiredWorkspaceName)") } public func launchBuild(#workingDirectoryURL:NSURL) { self.launch(workingDirectoryURL: workingDirectoryURL, arguments: "build --verbose") } public func launchClean(#workingDirectoryURL:NSURL) { self.launch(workingDirectoryURL: workingDirectoryURL, arguments: "clean --verbose") } /// Performs `cargo run`. Take care that this runs the target without debugger. public func launchRun(#workingDirectoryURL:NSURL) { self.launch(workingDirectoryURL: workingDirectoryURL, arguments: "run --verbose") } }
mit
37358c94f91f8bdac9c7109e36402a78
27.251852
120
0.753277
3.817818
false
false
false
false
Asura19/SwiftAlgorithm
SwiftAlgorithm/SwiftAlgorithm/Sort.swift
1
1438
// // Sort.swift // SwiftAlgorithm // // Created by Phoenix on 2017/8/14. // Copyright © 2017年 Phoenix. All rights reserved. // import Cocoa public class Sort { } public extension Array where Element: Comparable { func bubbleSorted() -> [Element] { var a = self for i in 0..<(a.count - 1) { for j in 0..<(a.count - 1 - i) { if a[j] > a[j + 1] { a.swapAt(j, j + 1) } } } return a } func quickSorted() -> [Element] { func quick(_ array: [Element], left: Int, right: Int) -> [Element] { var a = array if a.isEmpty || a.count == 1 || left >= right { return a } var i = left var j = right let pivot = a[i] while i < j { while a[j] >= pivot && i < j { j -= 1 } a[i] = a[j] while a[i] <= pivot && i < j { i += 1 } a[j] = a[i] } a[i] = pivot a = quick(a, left: left, right: i - 1) a = quick(a, left: i + 1, right: right) return a } return quick(self, left: 0, right: self.count - 1) } }
mit
ff39453804b9b88370e49c4d7f76cf71
22.145161
76
0.357491
4.042254
false
false
false
false