repo_name
stringlengths
6
91
path
stringlengths
6
999
copies
stringclasses
283 values
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
moonrailgun/OpenCode
OpenCode/Classes/RepositoryDetail/View/RepoEventCell.swift
1
483
// // RepoEventCell.swift // OpenCode // // Created by 陈亮 on 16/5/26. // Copyright © 2016年 moonrailgun. All rights reserved. // import UIKit class RepoEventCell: UITableViewCell { override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } }
gpl-2.0
LibraryLoupe/PhotosPlus
PhotosPlus/Cameras/Pentax/PentaxKS2.swift
3
483
// // Photos Plus, https://github.com/LibraryLoupe/PhotosPlus // // Copyright (c) 2016-2017 Matt Klosterman and contributors. All rights reserved. // import Foundation extension Cameras.Manufacturers.Pentax { public struct KS2: CameraModel { public init() {} public let name = "Pentax K-S2" public let manufacturerType: CameraManufacturer.Type = Cameras.Manufacturers.Pentax.self } } public typealias PentaxKS2 = Cameras.Manufacturers.Pentax.KS2
mit
mhatzitaskos/TurnBasedSkeleton
TurnBasedTest/ListOfGamesViewController.swift
1
8107
// // ListOfGamesViewController.swift // TurnBasedTest // // Created by Markos Hatzitaskos on 350/12/15. // Copyright © 2015 Markos Hatzitaskos. All rights reserved. // import UIKit import GameKit class ListOfGamesViewController: UITableViewController { var refreshTable = UIRefreshControl() override func viewDidLoad() { super.viewDidLoad() NSNotificationCenter.defaultCenter().addObserver(self , selector: "reloadTable", name: "kReloadMatchTable", object: nil) NSNotificationCenter.defaultCenter().addObserver(self , selector: "reloadMatches", name: "kReloadMatches", object: nil) refreshTable.addTarget(self, action: "reloadMatches", forControlEvents: UIControlEvents.ValueChanged) refreshTable.tintColor = UIColor.grayColor() refreshTable.attributedTitle = NSAttributedString(string: "LOADING", attributes: [NSForegroundColorAttributeName : UIColor.grayColor()]) refreshTable.backgroundColor = UIColor.clearColor() tableView.addSubview(refreshTable) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func reloadMatches() { GameCenterSingleton.sharedInstance.reloadMatches({ (matches: [String:[GKTurnBasedMatch]]?) in if matches != nil { print("") print("Matches loaded") } else { print("") print("There were no matches to load or some error occured") } NSNotificationCenter.defaultCenter().postNotificationName("kReloadMatchTable", object: nil) self.refreshTable.endRefreshing() }) } func reloadTable() { print("") print("Reloading list of games table") self.tableView.reloadData() } // MARK: - Table view data source override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { //let cell = tableView.cellForRowAtIndexPath(indexPath) as! GameCell } override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 6 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { switch section { case 0: if let inSearchingModeMatches = GameCenterSingleton.sharedInstance.matchDictionary["inSearchingModeMatches"] { return inSearchingModeMatches.count } else { return 0 } case 1: if let inInvitationModeMatches = GameCenterSingleton.sharedInstance.matchDictionary["inInvitationModeMatches"] { return inInvitationModeMatches.count } else { return 0 } case 2: if let inWaitingForIntivationReplyModeMatches = GameCenterSingleton.sharedInstance.matchDictionary["inWaitingForIntivationReplyModeMatches"] { return inWaitingForIntivationReplyModeMatches.count } else { return 0 } case 3: if let localPlayerTurnMatches = GameCenterSingleton.sharedInstance.matchDictionary["localPlayerTurnMatches"] { return localPlayerTurnMatches.count } else { return 0 } case 4: if let opponentTurnMatches = GameCenterSingleton.sharedInstance.matchDictionary["opponentTurnMatches"] { return opponentTurnMatches.count } else { return 0 } case 5: if let endedMatches = GameCenterSingleton.sharedInstance.matchDictionary["endedMatches"] { return endedMatches.count } else { return 0 } default: return 0 } } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("GameCell", forIndexPath: indexPath) as! GameCell switch indexPath.section { case 0: if let inSearchingModeMatches = GameCenterSingleton.sharedInstance.matchDictionary["inSearchingModeMatches"] { cell.match = inSearchingModeMatches[indexPath.row] cell.opponentLabel.text = "Random Opponent" cell.mode = MatchMode.inSearchingModeMatches } case 1: if let inInvitationModeMatches = GameCenterSingleton.sharedInstance.matchDictionary["inInvitationModeMatches"] { cell.match = inInvitationModeMatches[indexPath.row] let opponent = GameCenterSingleton.sharedInstance.findParticipantsForMatch(cell.match!)?.opponent cell.opponentLabel.text = opponent?.player?.alias cell.mode = MatchMode.inInvitationModeMatches } case 2: if let inWaitingForIntivationReplyModeMatches = GameCenterSingleton.sharedInstance.matchDictionary["inWaitingForIntivationReplyModeMatches"] { cell.match = inWaitingForIntivationReplyModeMatches[indexPath.row] let opponent = GameCenterSingleton.sharedInstance.findParticipantsForMatch(cell.match!)?.opponent cell.opponentLabel.text = opponent?.player?.alias cell.mode = MatchMode.inWaitingForIntivationReplyModeMatches } case 3: if let localPlayerTurnMatches = GameCenterSingleton.sharedInstance.matchDictionary["localPlayerTurnMatches"] { cell.match = localPlayerTurnMatches[indexPath.row] let opponent = GameCenterSingleton.sharedInstance.findParticipantsForMatch(cell.match!)?.opponent cell.opponentLabel.text = opponent?.player?.alias cell.mode = MatchMode.localPlayerTurnMatches print("match in cell \(indexPath.section) \(indexPath.row) \(cell.match)") } case 4: if let opponentTurnMatches = GameCenterSingleton.sharedInstance.matchDictionary["opponentTurnMatches"] { cell.match = opponentTurnMatches[indexPath.row] let opponent = GameCenterSingleton.sharedInstance.findParticipantsForMatch(cell.match!)?.opponent cell.opponentLabel.text = opponent?.player?.alias cell.mode = MatchMode.opponentTurnMatches } case 5: if let endedMatches = GameCenterSingleton.sharedInstance.matchDictionary["endedMatches"] { cell.match = endedMatches[indexPath.row] let opponent = GameCenterSingleton.sharedInstance.findParticipantsForMatch(cell.match!)?.opponent cell.opponentLabel.text = opponent?.player?.alias cell.mode = MatchMode.endedMatches } default: break } cell.updateButtons() return cell } override func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let headerCell = tableView.dequeueReusableCellWithIdentifier("GameHeaderCell") as! GameHeaderCell headerCell.backgroundColor = UIColor.lightGrayColor() switch (section) { case 0: headerCell.label.text = "Searching for opponent..." case 1: headerCell.label.text = "Invited by opponent" case 2: headerCell.label.text = "Invited opponent & waiting" case 3: headerCell.label.text = "My turn" case 4: headerCell.label.text = "Opponent's turn & waiting" case 5: headerCell.label.text = "Ended matches" default: headerCell.label.text = "Other" } return headerCell } }
mit
Adiel-Sharabi/Mobile-App-Performance
SwiftApp/SwiftApp/Point.swift
2
4762
// // Copyright (c) 2015 Harry Cheung // import UIKit func toRadians(value: Double) -> Double { return value * M_PI / 180.0 } func toDegrees(value: Double) -> Double { return value * 180.0 / M_PI } func == (left: Point, right: Point) -> Bool { return (left.latitudeDegrees() == right.latitudeDegrees()) && (left.longitudeDegrees() == right.longitudeDegrees()) } struct Point: Equatable { let RADIUS: Double = 6371000 var latitude: Double var longitude: Double var speed: Double var bearing: Double var hAccuracy: Double var vAccuracy: Double var timestamp: Double var lapDistance: Double var lapTime: Double var splitTime: Double var acceleration: Double var generated: Bool = false init() { self.init(latitude: 0, longitude: 0, inRadians: false) } init (latitude: Double, longitude: Double, inRadians: Bool) { if inRadians { self.latitude = latitude self.longitude = longitude } else { self.latitude = toRadians(latitude) self.longitude = toRadians(longitude) } self.speed = 0 self.bearing = 0 self.hAccuracy = 0 self.vAccuracy = 0 self.timestamp = 0 self.lapDistance = 0 self.lapTime = 0 self.splitTime = 0 self.acceleration = 0 } init (latitude: Double, longitude: Double) { self.init(latitude: latitude, longitude: longitude, inRadians: false) } init (latitude: Double, longitude: Double, bearing: Double) { self.init(latitude: latitude, longitude: longitude, inRadians: false) self.bearing = bearing } init (latitude: Double, longitude: Double, speed: Double, bearing: Double, horizontalAccuracy: Double, verticalAccuracy: Double, timestamp: Double) { self.init(latitude: latitude, longitude: longitude, inRadians: false) self.speed = speed self.bearing = bearing self.hAccuracy = horizontalAccuracy self.vAccuracy = verticalAccuracy self.timestamp = timestamp } mutating func setLapTime(startTime: Double, splitStartTime: Double) { lapTime = timestamp - startTime splitTime = timestamp - splitStartTime } func roundValue(value: Double) -> Double { return round(value * 1000000.0) / 1000000.0 } func latitudeDegrees() -> Double { return roundValue(toDegrees(latitude)) } func longitudeDegrees() -> Double { return roundValue(toDegrees(longitude)) } func subtract(point: Point) -> Point { return Point(latitude: latitude - point.latitude, longitude: longitude - point.longitude, inRadians: true) } func bearingTo(point: Point, inRadians: Bool) -> Double { let φ1 = latitude let φ2 = point.latitude let Δλ = point.longitude - longitude let y = sin(Δλ) * cos(φ2) let x = cos(φ1) * sin(φ2) - sin(φ1) * cos(φ2) * cos(Δλ) let θ = atan2(y, x) if (inRadians) { return roundValue((θ + 2 * M_PI) % M_PI) } else { return roundValue((toDegrees(θ) + 2 * 360) % 360) } } func bearingTo(point: Point) -> Double { return bearingTo(point, inRadians: false) } func destination(bearing: Double, distance: Double) -> Point { let θ = toRadians(bearing) let δ = distance / RADIUS let φ1 = latitude let λ1 = longitude let φ2 = asin(sin(φ1) * cos(δ) + cos(φ1) * sin(δ) * cos(θ)) var λ2 = λ1 + atan2(sin(θ) * sin(δ) * cos(φ1), cos(δ) - sin(φ1) * sin(φ2)) λ2 = (λ2 + 3.0 * M_PI) % (2.0 * M_PI) - M_PI // normalise to -180..+180 return Point(latitude: φ2, longitude: λ2, inRadians: true) } func distanceTo(point: Point) -> Double { let φ1 = latitude let λ1 = longitude let φ2 = point.latitude let λ2 = point.longitude let Δφ = φ2 - φ1 let Δλ = λ2 - λ1 let a = sin(Δφ / 2) * sin(Δφ / 2) + cos(φ1) * cos(φ2) * sin(Δλ / 2) * sin(Δλ / 2) return RADIUS * 2 * atan2(sqrt(a), sqrt(1 - a)) } static func intersectSimple(#p: Point, p2: Point, q: Point, q2: Point, inout intersection: Point) -> Bool { let s1_x = p2.longitude - p.longitude let s1_y = p2.latitude - p.latitude let s2_x = q2.longitude - q.longitude let s2_y = q2.latitude - q.latitude let den = (-s2_x * s1_y + s1_x * s2_y) if den == 0 { return false } let s = (-s1_y * (p.longitude - q.longitude) + s1_x * (p.latitude - q.latitude)) / den let t = ( s2_x * (p.latitude - q.latitude) - s2_y * (p.longitude - q.longitude)) / den if s >= 0 && s <= 1 && t >= 0 && t <= 1 { intersection.latitude = p.latitude + (t * s1_y) intersection.longitude = p.longitude + (t * s1_x) return true } return false } }
gpl-3.0
SteveRohrlack/CitySimCore
src/Model/TileableAttributes/MapStatistical.swift
1
371
// // MapStatistical.swift // CitySimCore // // Created by Steve Rohrlack on 16.05.16. // Copyright © 2016 Steve Rohrlack. All rights reserved. // import Foundation /// a MapStatistical object contains a set of statistics public protocol MapStatistical { /// container for multiple MapStatistic elements var statistics: MapStatisticContainer { get } }
mit
paulo17/Find-A-Movie-iOS
FindAMovie/NetworkOperation.swift
1
1978
import Foundation import Alamofire import SwiftyJSON enum NetworkError: ErrorType { case NetworkFailure case EmptyResult } /** * Network Operation class to perform webservice request */ class NetworkOperation { let queryURL: String typealias JSONDictionaryCompletion = ([String: AnyObject]?, ErrorType?) -> (Void) /** Initialize NetworkOperation - parameter url: URL of the web service */ init(url: String) { self.queryURL = url } /** Execute a GET request to featch data from the web - parameter completion: Callback to retour JSON Dictionnary */ func executeRequest(completionHandler: JSONDictionaryCompletion) { Alamofire .request(.GET, self.queryURL) .responseJSON { (response) in switch response.result { case .Success: guard let value = response.result.value else { return completionHandler(nil, NetworkError.EmptyResult) } let jsonDictionary = value as? [String: AnyObject] completionHandler(jsonDictionary, nil) case .Failure(let error): print(error) completionHandler(nil, NetworkError.NetworkFailure) } } } /** Get data form URL - parameter url: NSURL - parameter completion: (NSData) -> Void */ func getDataFromUrl(url: NSURL, completion: ((data: NSData?) -> Void)) { NSURLSession.sharedSession().dataTaskWithURL(url) { (data, response, error) in if let error = error { print(error) } completion(data: data) }.resume() } }
gpl-2.0
zhuhaow/NEKit
src/Rule/DNSSessionMatchType.swift
3
413
import Foundation /** The information available in current round of matching. Since we want to speed things up, we first match the request without resolving it (`.Domain`). If any rule returns `.Unknown`, we lookup the request and rematches that rule (`.IP`). - Domain: Only domain information is available. - IP: The IP address is resolved. */ public enum DNSSessionMatchType { case domain, ip }
bsd-3-clause
mengxiangyue/Swift-Design-Pattern-In-Chinese
Design_Pattern.playground/Pages/Decorator.xcplaygroundpage/Contents.swift
1
3844
/*: ### **Decorator** --- [回到列表](Index) 1. 定义:装饰模式,动态地给一个对象添加一些额外的职责,就增加功能来说,装饰模式比生成子类更为灵活。 2. 问题:咖啡店里有最基本的咖啡,还有用基本咖啡添加不同物品新调制的咖啡。 3. 解决方案:定义基本咖啡,然后创建不同物品的装饰类,用装饰类装饰基本咖啡就获得了最终的咖啡了。 4. 使用方法: 1. 定义 Coffee 协议,明确咖啡的定义。 2. 定义具体的 Coffee (SimpleCoffee)。 3. 定义咖啡的装饰类(CoffeeDecorator),在构造的时候传入要被装饰的咖啡。 4. 定义具体的咖啡装饰类,添加新的功能。 5. 优点: 1. 对于扩展一个对象的功能,装饰模式比继承更加灵活性,不会导致类的个数急剧增加。 2. 可以通过一种动态的方式来扩展一个对象的功能,通过配置文件可以在运行时选择不同的具体装饰类,从而实现不同的行为。 3. 可以对一个对象进行多次装饰,通过使用不同的具体装饰类以及这些装饰类的排列组合,可以创造出很多不同行为的组合,得到功能更为强大的对象。 4. 具体构件类与具体装饰类可以独立变化,用户可以根据需要增加新的具体构件类和具体装饰类,原有类库代码无须改变,符合“开闭原则”。 6. 缺点: 1. 使用装饰模式进行系统设计时将产生很多小对象,这些对象的区别在于它们之间相互连接的方式有所不同,而不是它们的类或者属性值有所不同,大量小对象的产生势必会占用更多的系统资源,在一定程序上影响程序的性能。 2. 装饰模式提供了一种比继承更加灵活机动的解决方案,但同时也意味着比继承更加易于出错,排错也很困难,对于多次装饰的对象,调试时寻找错误可能需要逐级排查,较为繁琐。 */ import Foundation protocol Coffee { func getCost() -> Double func getIngredients() -> String } class SimpleCoffee: Coffee { func getCost() -> Double { return 1.0 } func getIngredients() -> String { return "Coffee" } } class CoffeeDecorator: Coffee { private let decoratedCoffee: Coffee fileprivate let ingredientSeparator: String = ", " required init(decoratedCoffee: Coffee) { self.decoratedCoffee = decoratedCoffee } func getCost() -> Double { return decoratedCoffee.getCost() } func getIngredients() -> String { return decoratedCoffee.getIngredients() } } final class Milk: CoffeeDecorator { required init(decoratedCoffee: Coffee) { super.init(decoratedCoffee: decoratedCoffee) } override func getCost() -> Double { return super.getCost() + 0.5 } override func getIngredients() -> String { return super.getIngredients() + ingredientSeparator + "Milk" } } final class WhipCoffee: CoffeeDecorator { required init(decoratedCoffee: Coffee) { super.init(decoratedCoffee: decoratedCoffee) } override func getCost() -> Double { return super.getCost() + 0.7 } override func getIngredients() -> String { return super.getIngredients() + ingredientSeparator + "Whip" } } /*: ### Usage: */ var someCoffee: Coffee = SimpleCoffee() print("Cost : \(someCoffee.getCost()); Ingredients: \(someCoffee.getIngredients())") someCoffee = Milk(decoratedCoffee: someCoffee) print("Cost : \(someCoffee.getCost()); Ingredients: \(someCoffee.getIngredients())") someCoffee = WhipCoffee(decoratedCoffee: someCoffee) print("Cost : \(someCoffee.getCost()); Ingredients: \(someCoffee.getIngredients())")
mit
TonnyTao/HowSwift
how_to_update_view_in_mvvm.playground/Sources/RxSwift/Platform/Platform.Linux.swift
13
804
// // Platform.Linux.swift // Platform // // Created by Krunoslav Zaher on 12/29/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // #if os(Linux) import Foundation extension Thread { static func setThreadLocalStorageValue<T: AnyObject>(_ value: T?, forKey key: String) { if let newValue = value { Thread.current.threadDictionary[key] = newValue } else { Thread.current.threadDictionary[key] = nil } } static func getThreadLocalStorageValueForKey<T: AnyObject>(_ key: String) -> T? { let currentThread = Thread.current let threadDictionary = currentThread.threadDictionary return threadDictionary[key] as? T } } #endif
mit
haijianhuo/TopStore
TopStore/Vendors/MIBadgeButton/HHImageCropper/HHImageScrollView.swift
1
10007
// // HHImageScrollView.swift // // Created by Haijian Huo on 8/13/17. // Copyright © 2017 Haijian Huo. All rights reserved. // import UIKit class HHImageScrollView: UIScrollView { var zoomView: UIImageView? var aspectFill: Bool = false private var imageSize: CGSize? private var pointToCenterAfterResize: CGPoint = .zero private var scaleToRestoreAfterResize: CGFloat = 0 private var sizeChanging: Bool = false required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override init(frame: CGRect) { super.init(frame: frame) self.aspectFill = false self.showsVerticalScrollIndicator = false self.showsHorizontalScrollIndicator = false self.bouncesZoom = true self.scrollsToTop = false self.decelerationRate = UIScrollViewDecelerationRateFast self.delegate = self } override func didAddSubview(_ subview: UIView) { super.didAddSubview(subview) self.centerZoomView() } func setAspectFill(aspectFill: Bool) { if self.aspectFill != aspectFill { self.aspectFill = aspectFill if self.zoomView != nil { self.setMaxMinZoomScalesForCurrentBounds() if (self.zoomScale < self.minimumZoomScale) { self.zoomScale = self.minimumZoomScale } } } } override var frame: CGRect { willSet { self.sizeChanging = !newValue.size.equalTo(self.frame.size) if (self.sizeChanging) { self.prepareToResize() } } didSet { if (self.sizeChanging) { self.recoverFromResizing() } self.centerZoomView() } } // MARK: - Center zoomView within scrollView fileprivate func centerZoomView() { guard let zoomView = self.zoomView else { return } // center zoomView as it becomes smaller than the size of the screen // we need to use contentInset instead of contentOffset for better positioning when zoomView fills the screen if (self.aspectFill) { var top: CGFloat = 0 var left: CGFloat = 0 // center vertically if (self.contentSize.height < self.bounds.height) { top = (self.bounds.height - self.contentSize.height) * 0.5 } // center horizontally if (self.contentSize.width < self.bounds.width) { left = (self.bounds.width - self.contentSize.width) * 0.5 } self.contentInset = UIEdgeInsetsMake(top, left, top, left); } else { var frameToCenter = zoomView.frame // center horizontally if (frameToCenter.width < self.bounds.width) { frameToCenter.origin.x = (self.bounds.width - frameToCenter.width) * 0.5 } else { frameToCenter.origin.x = 0 } // center vertically if (frameToCenter.height < self.bounds.height) { frameToCenter.origin.y = (self.bounds.height - frameToCenter.height) * 0.5 } else { frameToCenter.origin.y = 0 } zoomView.frame = frameToCenter } } // MARK: - Configure scrollView to display new image func displayImage(image: UIImage) { // clear view for the previous image self.zoomView?.removeFromSuperview() self.zoomView = nil // reset our zoomScale to 1.0 before doing any further calculations self.zoomScale = 1.0 // make views to display the new image let zoomView = UIImageView(image: image) self.addSubview(zoomView) self.zoomView = zoomView self.configureForImageSize(imageSize: image.size) } private func configureForImageSize(imageSize: CGSize) { self.imageSize = imageSize self.contentSize = imageSize self.setMaxMinZoomScalesForCurrentBounds() self.setInitialZoomScale() self.setInitialContentOffset() self.contentInset = .zero } private func setMaxMinZoomScalesForCurrentBounds() { guard let imageSize = self.imageSize else { return } let boundsSize = self.bounds.size // calculate min/max zoomscale let xScale = boundsSize.width / imageSize.width // the scale needed to perfectly fit the image width-wise let yScale = boundsSize.height / imageSize.height // the scale needed to perfectly fit the image height-wise var minScale: CGFloat = 0 if (!self.aspectFill) { minScale = min(xScale, yScale) // use minimum of these to allow the image to become fully visible } else { minScale = max(xScale, yScale) // use maximum of these to allow the image to fill the screen } var maxScale = max(xScale, yScale) // Image must fit/fill the screen, even if its size is smaller. let xImageScale = maxScale * imageSize.width / boundsSize.width let yImageScale = maxScale * imageSize.height / boundsSize.height var maxImageScale = max(xImageScale, yImageScale) maxImageScale = max(minScale, maxImageScale) maxScale = max(maxScale, maxImageScale) // don't let minScale exceed maxScale. (If the image is smaller than the screen, we don't want to force it to be zoomed.) if (minScale > maxScale) { minScale = maxScale; } self.maximumZoomScale = maxScale self.minimumZoomScale = minScale } private func setInitialZoomScale() { guard let imageSize = self.imageSize else { return } let boundsSize = self.bounds.size let xScale = boundsSize.width / imageSize.width // the scale needed to perfectly fit the image width-wise let yScale = boundsSize.height / imageSize.height // the scale needed to perfectly fit the image height-wise let scale = max(xScale, yScale) self.zoomScale = scale } private func setInitialContentOffset() { guard let zoomView = self.zoomView else { return } let boundsSize = self.bounds.size let frameToCenter = zoomView.frame var contentOffset: CGPoint = .zero if (frameToCenter.width > boundsSize.width) { contentOffset.x = (frameToCenter.width - boundsSize.width) * 0.5 } else { contentOffset.x = 0 } if (frameToCenter.height > boundsSize.height) { contentOffset.y = (frameToCenter.height - boundsSize.height) * 0.5 } else { contentOffset.y = 0 } self.setContentOffset(contentOffset, animated: false) } // MARK: // MARK: Methods called during rotation to preserve the zoomScale and the visible portion of the image // MARK: Rotation support private func prepareToResize() { guard let zoomView = self.zoomView else { return } let boundsCenter = CGPoint(x: self.bounds.midX, y: self.bounds.midY) pointToCenterAfterResize = self.convert(boundsCenter, to: zoomView) self.scaleToRestoreAfterResize = self.zoomScale // If we're at the minimum zoom scale, preserve that by returning 0, which will be converted to the minimum // allowable scale when the scale is restored. if Float(self.scaleToRestoreAfterResize) <= Float(self.minimumZoomScale) + Float.ulpOfOne { self.scaleToRestoreAfterResize = 0 } } private func recoverFromResizing() { guard let zoomView = self.zoomView else { return } self.setMaxMinZoomScalesForCurrentBounds() // Step 1: restore zoom scale, first making sure it is within the allowable range. let maxZoomScale = max(self.minimumZoomScale, scaleToRestoreAfterResize) self.zoomScale = min(self.maximumZoomScale, maxZoomScale) // Step 2: restore center point, first making sure it is within the allowable range. // 2a: convert our desired center point back to our own coordinate space let boundsCenter = self.convert(self.pointToCenterAfterResize, from: zoomView) // 2b: calculate the content offset that would yield that center point var offset = CGPoint(x: boundsCenter.x - self.bounds.size.width / 2.0, y: boundsCenter.y - self.bounds.size.height / 2.0) // 2c: restore offset, adjusted to be within the allowable range let maxOffset = self.maximumContentOffset() let minOffset = self.minimumContentOffset() var realMaxOffset = min(maxOffset.x, offset.x) offset.x = max(minOffset.x, realMaxOffset) realMaxOffset = min(maxOffset.y, offset.y) offset.y = max(minOffset.y, realMaxOffset) self.contentOffset = offset } private func maximumContentOffset() -> CGPoint { let contentSize = self.contentSize let boundsSize = self.bounds.size return CGPoint(x: contentSize.width - boundsSize.width, y: contentSize.height - boundsSize.height) } private func minimumContentOffset() -> CGPoint { return .zero } } // MARK: UIScrollViewDelegate extension HHImageScrollView: UIScrollViewDelegate { func viewForZooming(in scrollView: UIScrollView) -> UIView? { return self.zoomView } func scrollViewDidZoom(_ scrollView: UIScrollView) { self.centerZoomView() } }
mit
mohamede1945/quran-ios
Quran/QuranTranslationBaseCollectionViewCell.swift
2
1439
// // QuranTranslationBaseCollectionViewCell.swift // Quran // // Created by Mohamed Afifi on 3/31/17. // // Quran for iOS is a Quran reading application for iOS. // Copyright (C) 2017 Quran.com // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // import UIKit class QuranTranslationBaseCollectionViewCell: UICollectionViewCell { var ayah: AyahNumber? required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setUp() } override init(frame: CGRect) { super.init(frame: frame) setUp() } private func setUp() { backgroundColor = .readingBackground() contentView.backgroundColor = .readingBackground() } override var backgroundColor: UIColor? { set { super.backgroundColor = newValue ?? .readingBackground() contentView.backgroundColor = super.backgroundColor } get { return super.backgroundColor } } }
gpl-3.0
CaiMiao/CGSSGuide
DereGuide/Card/Detail/View/CardDetailEvolutionCell.swift
1
2400
// // CardDetailEvolutionCell.swift // DereGuide // // Created by zzk on 2017/6/26. // Copyright © 2017年 zzk. All rights reserved. // import UIKit class CardDetailEvolutionCell: UITableViewCell { var leftLabel: UILabel! var toIcon: CGSSCardIconView! var fromIcon: CGSSCardIconView! var arrowImageView = UIImageView(image: #imageLiteral(resourceName: "arrow-rightward").withRenderingMode(.alwaysTemplate)) weak var delegate: CGSSIconViewDelegate? override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) leftLabel = UILabel() leftLabel.textColor = UIColor.black leftLabel.font = UIFont.systemFont(ofSize: 16) leftLabel.text = NSLocalizedString("进化信息", comment: "卡片详情页") contentView.addSubview(leftLabel) leftLabel.snp.makeConstraints { (make) in make.left.equalTo(10) make.top.equalTo(10) } fromIcon = CGSSCardIconView() contentView.addSubview(fromIcon) fromIcon.snp.makeConstraints { (make) in make.top.equalTo(leftLabel.snp.bottom).offset(5) make.left.equalTo(10) } contentView.addSubview(arrowImageView) arrowImageView.tintColor = .darkGray arrowImageView.snp.makeConstraints { (make) in make.left.equalTo(fromIcon.snp.right).offset(17) make.centerY.equalTo(fromIcon) } toIcon = CGSSCardIconView() contentView.addSubview(toIcon) toIcon.snp.makeConstraints { (make) in make.left.equalTo(arrowImageView.snp.right).offset(17) make.top.equalTo(fromIcon) make.bottom.equalTo(-10) } selectionStyle = .none } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } extension CardDetailEvolutionCell: CardDetailSetable { func setup(with card: CGSSCard) { if card.evolutionId == 0 { toIcon.cardID = card.id fromIcon.cardID = card.id - 1 fromIcon.delegate = self.delegate } else { fromIcon.cardID = card.id toIcon.cardID = card.evolutionId toIcon.delegate = self.delegate } } }
mit
Chris-Perkins/Lifting-Buddy
Lifting Buddy/MessageView.swift
1
4163
// // MessageView.swift // Lifting Buddy // // Created by Christopher Perkins on 2/5/18. // Copyright © 2018 Christopher Perkins. All rights reserved. // import UIKit class MessageView: UIView { // MARK: View properties // Height that this view should be drawn as private let height: CGFloat // The message we should be displaying public let message: Message public let imageView: UIImageView public let titleLabel: UILabel // MARK: View inits init(withMessage message: Message, andHeight height: CGFloat) { imageView = UIImageView() titleLabel = UILabel() self.message = message self.height = height super.init(frame: .zero) addSubview(titleLabel) addSubview(imageView) createAndActivateTitleLabelConstraints() //createAndActivateImageViewConstraints() } required init?(coder aDecoder: NSCoder) { fatalError("aDecoder Init Set for UIView") } // MARK: View overrides override func layoutSubviews() { super.layoutSubviews() // Title label titleLabel.setDefaultProperties() titleLabel.textColor = .white titleLabel.font = UIFont.boldSystemFont(ofSize: 18.0) titleLabel.text = message.messageTitle } // MARK: Constraints // Cling to left, top of self ; right to image view ; height of titlelabelheight private func createAndActivateTitleLabelConstraints() { titleLabel.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.createViewAttributeCopyConstraint(view: titleLabel, withCopyView: self, attribute: .left, plusConstant: 10).isActive = true NSLayoutConstraint.createViewAttributeCopyConstraint(view: titleLabel, withCopyView: self, attribute: .top, plusConstant: statusBarHeight).isActive = true /*NSLayoutConstraint(item: imageView, attribute: .left, relatedBy: .equal, toItem: titleLabel, attribute: .right, multiplier: 1, constant: 0).isActive = true*/ NSLayoutConstraint.createViewAttributeCopyConstraint(view: titleLabel, withCopyView: self, attribute: .right).isActive = true NSLayoutConstraint.createHeightConstraintForView(view: titleLabel, height: height - statusBarHeight).isActive = true } // Cling to right, bottom of self ; height of self ; width = height private func createAndActivateImageViewConstraints() { imageView.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.createViewAttributeCopyConstraint(view: imageView, withCopyView: self, attribute: .right).isActive = true NSLayoutConstraint.createViewAttributeCopyConstraint(view: imageView, withCopyView: self, attribute: .bottom).isActive = true NSLayoutConstraint.createHeightConstraintForView(view: imageView, height: height).isActive = true NSLayoutConstraint.createWidthConstraintForView(view: imageView, width: height).isActive = true } }
mit
AutomationStation/BouncerBuddy
BouncerBuddyV6/BouncerBuddy/BannedModel.swift
3
936
// // BannedModel.swift // BouncerBuddy // // Created by Sha Wu on 16/3/7. // Copyright © 2016年 Sheryl Hong. All rights reserved. // import Foundation class BannedModel:NSObject { //properties var name: String? var gender: String? var notes: String? //empty constructor override init() { } //construct with @name, @address, @latitude, and @longitude parameters init(name: String, gender: String, notes: String) { self.name = name self.gender = gender self.notes = notes } //prints object's current state override var description: String { return "Name: \(name), Gender: \(gender), Notes: \(notes)" } }
apache-2.0
onekiloparsec/SwiftAA
Tests/SwiftAATests/NumericTypeTests.swift
2
3495
// // NumericTypeTests.swift // SwiftAA // // Created by Alexander Vasenin on 03/01/2017. // Copyright © 2017 onekiloparsec. All rights reserved. // import XCTest @testable import SwiftAA class NumericTypeTests: XCTestCase { func testCircularInterval() { XCTAssertTrue(Degree(15).isWithinCircularInterval(from: 10, to: 20)) XCTAssertFalse(Degree(55).isWithinCircularInterval(from: 10, to: 20)) XCTAssertFalse(Degree(10).isWithinCircularInterval(from: 10, to: 20, isIntervalOpen: true)) XCTAssertTrue(Degree(15).isWithinCircularInterval(from: 10, to: 20, isIntervalOpen: false)) XCTAssertTrue(Degree(10).isWithinCircularInterval(from: 340, to: 20)) XCTAssertTrue(Degree(350).isWithinCircularInterval(from: 340, to: 20)) XCTAssertFalse(Degree(340).isWithinCircularInterval(from: 340, to: 20, isIntervalOpen: true)) XCTAssertTrue(Degree(340).isWithinCircularInterval(from: 340, to: 20, isIntervalOpen: false)) } func testRoundingToIncrement() { let accuracy = Second(1e-3).inJulianDays let jd = JulianDay(year: 2017, month: 1, day: 9, hour: 13, minute: 53, second: 39.87) AssertEqual(jd.rounded(toIncrement: Minute(1).inJulianDays), JulianDay(year: 2017, month: 1, day: 9, hour: 13, minute: 54), accuracy: accuracy) AssertEqual(jd.rounded(toIncrement: Minute(15).inJulianDays), JulianDay(year: 2017, month: 1, day: 9, hour: 14), accuracy: accuracy) AssertEqual(jd.rounded(toIncrement: Hour(3).inJulianDays), JulianDay(year: 2017, month: 1, day: 9, hour: 15), accuracy: accuracy) } func testConstructors() { // Damn one needs to do to increase UT coverage... AssertEqual(1.234.degrees, Degree(1.234)) AssertEqual(-1.234.degrees, Degree(-1.234)) AssertEqual(1.234.arcminutes, ArcMinute(1.234)) AssertEqual(-1.234.arcminutes, ArcMinute(-1.234)) AssertEqual(1.234.arcseconds, ArcSecond(1.234)) AssertEqual(-1.234.arcseconds, ArcSecond(-1.234)) AssertEqual(1.234.hours, Hour(1.234)) AssertEqual(-1.234.hours, Hour(-1.234)) AssertEqual(1.234.minutes, Minute(1.234)) AssertEqual(-1.234.minutes, Minute(-1.234)) AssertEqual(1.234.seconds, Second(1.234)) AssertEqual(-1.234.seconds, Second(-1.234)) AssertEqual(1.234.radians, Radian(1.234)) AssertEqual(-1.234.radians, Radian(-1.234)) AssertEqual(1.234.days, Day(1.234)) AssertEqual(-1.234.days, Day(-1.234)) AssertEqual(1.234.julianDays, JulianDay(1.234)) AssertEqual(-1.234.julianDays, JulianDay(-1.234)) let s1 = 1.234.sexagesimal XCTAssertEqual(s1.sign, .plus) XCTAssertEqual(s1.radical, 1) XCTAssertEqual(s1.minute, 14) XCTAssertEqual(s1.second, 2.4, accuracy: 0.000000001) // rounding error... XCTAssertEqual(1.234.sexagesimalShortString, "+01:14:02.4") // One needs a true sexagesimal library... // let s2 = -1.234.sexagesimal // let s3 = -0.123.sexagesimal // XCTAssertEqual(s2.sign, .minus) // XCTAssertEqual(s2.radical, -1) // XCTAssertEqual(s2.minute, 2) // XCTAssertEqual(s2.second, 3.4) // // XCTAssertEqual(s3.sign, .minus) // XCTAssertEqual(s3.radical, 0) // XCTAssertEqual(s3.minute, 1) // XCTAssertEqual(s3.second, 2.3) // XCTAssertEqual(-1.234.sexagesimalShortString, "") } }
mit
liuchuo/Swift-practice
20150626-1.playground/Contents.swift
1
883
//: Playground - noun: a place where people can play import UIKit //元组类型的访问级别,遵循元组中字段最低级的访问级别 private class Employee { var no : Int = 0 var name : String = "" var job : String? var salary : Double = 0 var dept : Department? } struct Department { var no : Int = 0 var name : String = "" } private let emp = Employee() var dept = Department() private var student1 = (dept,emp) //因为字段dept和emp的最低访问级别是private 所以student1访问级别也是private 符合统一性原则 //枚举类型的访问级别继承自该枚举,因此我们不能为枚举中的成员指定访问级别 public enum WeekDays { case Monday case Tuesday case Wednsday case Thursday case Friday } //由于WeekDays枚举类型是public访问级别,因而它的成员也是public级别
gpl-2.0
chenkaige/EasyIOS-Swift
Pod/Classes/Easy/Lib/EZExtend+UIAlertController.swift
7
823
// // EZExtend+UIAlertController.swift // medical // // Created by zhuchao on 15/4/28. // Copyright (c) 2015年 zhuchao. All rights reserved. // import UIKit // MARK: - UIAlertController public func alert (title: String, message: String, cancelAction: ((UIAlertAction!)->Void)? = nil, okAction: ((UIAlertAction!)->Void)? = nil) -> UIAlertController { let a = UIAlertController (title: title, message: message, preferredStyle: .Alert) if let ok = okAction { a.addAction(UIAlertAction(title: "OK", style: .Default, handler: ok)) a.addAction(UIAlertAction(title: "Cancel", style: .Cancel, handler: cancelAction)) } else { a.addAction(UIAlertAction(title: "OK", style: .Cancel, handler: cancelAction)) } return a }
mit
AcelLuxembourg/LidderbuchApp
Lidderbuch/LBIntroViewController.swift
1
978
// // LBIntroViewController.swift // Lidderbuch // // Created by Fränz Friederes on 12/11/16. // Copyright © 2016 ACEL. All rights reserved. // import UIKit class LBIntroViewController: UIViewController { lazy var backer: LBBacker = { return LBBacker() }() @IBOutlet weak var logoView: UIImageView! override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) if let backerImage = backer.randomBackerImage() { logoView.image = backerImage // perform segue to main view in 2s DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) { self.performSegueToMain() } } else { // perform immediate segue to main view self.performSegueToMain() } } fileprivate func performSegueToMain() { self.performSegue(withIdentifier: "ShowMain", sender: self) } }
mit
blinksh/blink
Blink/SmarterKeys/SmarterTermInput.swift
1
15610
////////////////////////////////////////////////////////////////////////////////// // // B L I N K // // Copyright (C) 2016-2019 Blink Mobile Shell Project // // This file is part of Blink. // // Blink is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // Blink is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Blink. If not, see <http://www.gnu.org/licenses/>. // // In addition, Blink is also subject to certain additional terms under // GNU GPL version 3 section 7. // // You should have received a copy of these additional terms immediately // following the terms and conditions of the GNU General Public License // which accompanied the Blink Source Code. If not, see // <http://www.github.com/blinksh/blink>. // //////////////////////////////////////////////////////////////////////////////// import UIKit import Combine class CaretHider { var _cancelable: AnyCancellable? = nil init(view: UIView) { _cancelable = view.layer.publisher(for: \.sublayers).sink { (layers) in if let caretView = view.value(forKeyPath: "caretView") as? UIView { caretView.isHidden = true } if let floatingView = view.value(forKeyPath: "floatingCaretView") as? UIView { floatingView.isHidden = true } } } } @objc class SmarterTermInput: KBWebView { var kbView = KBView() lazy var _kbProxy: KBProxy = { KBProxy(kbView: self.kbView) }() private var _inputAccessoryView: UIView? = nil var isHardwareKB: Bool { kbView.traits.isHKBAttached } weak var device: TermDevice? = nil { didSet { reportStateReset() } } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } override init(frame: CGRect, configuration: WKWebViewConfiguration) { super.init(frame: frame, configuration: configuration) kbView.keyInput = self kbView.lang = textInputMode?.primaryLanguage ?? "" // Assume hardware kb by default, since sometimes we don't have kbframe change events // if shortcuts toggle in Settings.app is off. kbView.traits.isHKBAttached = true if traitCollection.userInterfaceIdiom == .pad { _setupAssistantItem() } else { _setupAccessoryView() } KBSound.isMutted = BKUserConfigurationManager.userSettingsValue(forKey: BKUserConfigMuteSmartKeysPlaySound) } override func layoutSubviews() { super.layoutSubviews() kbView.setNeedsLayout() } func shouldUseWKCopyAndPaste() -> Bool { false } private var _caretHider: CaretHider? = nil override func ready() { super.ready() reportLang() // device?.focus() kbView.isHidden = false kbView.invalidateIntrinsicContentSize() // _refreshInputViews() if let v = selectionView() { _caretHider = CaretHider(view: v) } } func reset() { } func reportLang() { let lang = self.textInputMode?.primaryLanguage ?? "" kbView.lang = lang reportLang(lang, isHardwareKB: kbView.traits.isHKBAttached) } override var inputAssistantItem: UITextInputAssistantItem { let item = super.inputAssistantItem if item.trailingBarButtonGroups.count > 1 { item.trailingBarButtonGroups = [item.trailingBarButtonGroups[0]] } if item.trailingBarButtonGroups.count > 0 { item.leadingBarButtonGroups = [] } kbView.setNeedsLayout() return item } override func becomeFirstResponder() -> Bool { sync(traits: KBTracker.shared.kbTraits, device: KBTracker.shared.kbDevice, hideSmartKeysWithHKB: KBTracker.shared.hideSmartKeysWithHKB) let res = super.becomeFirstResponder() if !webViewReady { return res } device?.focus() kbView.isHidden = false setNeedsLayout() _refreshInputViews() _inputAccessoryView?.isHidden = false return res } var isRealFirstResponder: Bool { contentView()?.isFirstResponder == true } func reportStateReset() { reportStateReset(false) device?.view?.cleanSelection() } func reportStateWithSelection() { reportStateReset(device?.view?.hasSelection ?? false) } func _refreshInputViews() { guard traitCollection.userInterfaceIdiom == .pad, let assistantItem = contentView()?.inputAssistantItem else { if (KBTracker.shared.hideSmartKeysWithHKB && kbView.traits.isHKBAttached) { _removeSmartKeys() } contentView()?.reloadInputViews() kbView.reset() // _inputAccessoryView?.invalidateIntrinsicContentSize() reportStateReset() return; } assistantItem.leadingBarButtonGroups = [.init(barButtonItems: [UIBarButtonItem()], representativeItem: nil)] contentView()?.reloadInputViews() if (KBTracker.shared.hideSmartKeysWithHKB && kbView.traits.isHKBAttached) { _removeSmartKeys() } contentView()?.reloadInputViews() kbView.reset() reportStateReset() // Double reload inputs fixes: https://github.com/blinksh/blink/issues/803 contentView()?.reloadInputViews() kbView.isHidden = false } override func resignFirstResponder() -> Bool { let res = super.resignFirstResponder() if res { device?.blur() kbView.isHidden = true _inputAccessoryView?.isHidden = true reloadInputViews() } return res } func _setupAccessoryView() { inputAssistantItem.leadingBarButtonGroups = [] inputAssistantItem.trailingBarButtonGroups = [] if let _ = _inputAccessoryView as? KBAccessoryView { } else { _inputAccessoryView = KBAccessoryView(kbView: kbView) } } override var inputAccessoryView: UIView? { _inputAccessoryView } func sync(traits: KBTraits, device: KBDevice, hideSmartKeysWithHKB: Bool) { kbView.kbDevice = device var needToReload = false defer { kbView.traits = traits if let scene = window?.windowScene { if traitCollection.userInterfaceIdiom == .phone { kbView.traits.isPortrait = scene.interfaceOrientation.isPortrait } else if kbView.traits.isFloatingKB { kbView.traits.isPortrait = true } else { kbView.traits.isPortrait = scene.interfaceOrientation.isPortrait } } if needToReload { DispatchQueue.main.async { self._refreshInputViews() } } } if hideSmartKeysWithHKB && traits.isHKBAttached { _removeSmartKeys() return } if traits.isFloatingKB { _setupAccessoryView() return } if traitCollection.userInterfaceIdiom == .pad { needToReload = inputAssistantItem.trailingBarButtonGroups.count != 1 _setupAssistantItem() } else { needToReload = (_inputAccessoryView as? KBAccessoryView) == nil _setupAccessoryView() } } func _setupAssistantItem() { let item = inputAssistantItem let proxyItem = UIBarButtonItem(customView: _kbProxy) let group = UIBarButtonItemGroup(barButtonItems: [proxyItem], representativeItem: nil) item.leadingBarButtonGroups = [] item.trailingBarButtonGroups = [group] } func _removeSmartKeys() { _inputAccessoryView = UIView(frame: .zero) guard let item = contentView()?.inputAssistantItem else { return } item.leadingBarButtonGroups = [] item.trailingBarButtonGroups = [] setNeedsLayout() } override func _keyboardDidChangeFrame(_ notification: Notification) { } override func _keyboardWillChangeFrame(_ notification: Notification) { } override func _keyboardWillShow(_ notification: Notification) { } override func _keyboardWillHide(_ notification: Notification) { } override func _keyboardDidHide(_ notification: Notification) { } override func _keyboardDidShow(_ notification: Notification) { } } // - MARK: Web communication extension SmarterTermInput { override func onOut(_ data: String) { defer { kbView.turnOffUntracked() } guard let device = device, let deviceView = device.view, let scene = deviceView.window?.windowScene, scene.activationState == .foregroundActive else { return } deviceView.displayInput(data) let ctrlC = "\u{0003}" let ctrlD = "\u{0004}" if data == ctrlC || data == ctrlD, device.delegate?.handleControl(data) == true { return } device.write(data) } override func onCommand(_ command: String) { kbView.turnOffUntracked() guard let device = device, let scene = device.view.window?.windowScene, scene.activationState == .foregroundActive, let cmd = Command(rawValue: command), let spCtrl = spaceController else { return } spCtrl._onCommand(cmd) } var spaceController: SpaceController? { var n = next while let responder = n { if let spCtrl = responder as? SpaceController { return spCtrl } n = responder.next } return nil } override func onSelection(_ args: [AnyHashable : Any]) { if let dir = args["dir"] as? String, let gran = args["gran"] as? String { device?.view?.modifySelection(inDirection: dir, granularity: gran) } else if let op = args["command"] as? String { switch op { case "change": device?.view?.modifySideOfSelection() case "copy": copy(self) case "paste": device?.view?.pasteSelection(self) case "cancel": fallthrough default: device?.view?.cleanSelection() } } } override func onMods() { kbView.stopRepeats() } override func onIME(_ event: String, data: String) { if event == "compositionstart" && data.isEmpty { } else if event == "compositionend" { kbView.traits.isIME = false } else { // "compositionupdate" kbView.traits.isIME = true } } func stuckKey() -> KeyCode? { let mods: UIKeyModifierFlags = [.shift, .control, .alternate, .command] let stuck = mods.intersection(trackingModifierFlags) // Return command key first if stuck.contains(.command) { return KeyCode.commandLeft } if stuck.contains(.shift) { return KeyCode.shiftLeft } if stuck.contains(.control) { return KeyCode.controlLeft } if stuck.contains(.alternate) { return KeyCode.optionLeft } return nil } } // - MARK: Config extension SmarterTermInput { @objc private func _updateSettings() { // KBSound.isMutted = BKUserConfigurationManager.userSettingsValue(forKey: BKUserConfigMuteSmartKeysPlaySound) // let hideSmartKeysWithHKB = !BKUserConfigurationManager.userSettingsValue(forKey: BKUserConfigShowSmartKeysWithXKeyBoard) // // if hideSmartKeysWithHKB != hideSmartKeysWithHKB { // _hideSmartKeysWithHKB = hideSmartKeysWithHKB // if traitCollection.userInterfaceIdiom == .pad { // _setupAssistantItem() // } else { // _setupAccessoryView() // } // _refreshInputViews() // } } } // - MARK: Commands extension SmarterTermInput { override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool { switch action { case #selector(UIResponder.paste(_:)): // do not touch UIPasteboard before actual paste to skip exta notification. return true// UIPasteboard.general.string != nil case #selector(UIResponder.copy(_:)), #selector(UIResponder.cut(_:)): // When the action is requested from the keyboard, the sender will be nil. // In that case we let it go through to the WKWebView. // Otherwise, we check if there is a selection. return (sender == nil) || (sender != nil && device?.view?.hasSelection == true) case #selector(TermView.pasteSelection(_:)), #selector(Self.soSelection(_:)), #selector(Self.googleSelection(_:)), #selector(Self.shareSelection(_:)): return sender != nil && device?.view?.hasSelection == true case #selector(Self.copyLink(_:)), #selector(Self.openLink(_:)): return sender != nil && device?.view?.detectedLink != nil default: // if #available(iOS 15.0, *) { // switch action { // case #selector(UIResponder.pasteAndMatchStyle(_:)), // #selector(UIResponder.pasteAndSearch(_:)), // #selector(UIResponder.pasteAndGo(_:)): return false // case _: break // } // } return super.canPerformAction(action, withSender: sender) } } override func copy(_ sender: Any?) { if shouldUseWKCopyAndPaste() { super.copy(sender) } else { device?.view?.copy(sender) } } override func paste(_ sender: Any?) { if shouldUseWKCopyAndPaste() { super.paste(sender) } else { device?.view?.paste(sender) } } @objc func copyLink(_ sender: Any) { guard let deviceView = device?.view, let url = deviceView.detectedLink else { return } UIPasteboard.general.url = url deviceView.cleanSelection() } @objc func openLink(_ sender: Any) { guard let deviceView = device?.view, let url = deviceView.detectedLink else { return } deviceView.cleanSelection() blink_openurl(url) } @objc func pasteSelection(_ sender: Any) { device?.view?.pasteSelection(sender) } @objc func googleSelection(_ sender: Any) { guard let deviceView = device?.view, let query = deviceView.selectedText?.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed), let url = URL(string: "https://google.com/search?q=\(query)") else { return } blink_openurl(url) } @objc func soSelection(_ sender: Any) { guard let deviceView = device?.view, let query = deviceView.selectedText?.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed), let url = URL(string: "https://stackoverflow.com/search?q=\(query)") else { return } blink_openurl(url) } @objc func shareSelection(_ sender: Any) { guard let vc = device?.delegate?.viewController(), let deviceView = device?.view, let text = deviceView.selectedText else { return } let ctrl = UIActivityViewController(activityItems: [text], applicationActivities: nil) ctrl.popoverPresentationController?.sourceView = deviceView ctrl.popoverPresentationController?.sourceRect = deviceView.selectionRect vc.present(ctrl, animated: true, completion: nil) } } extension SmarterTermInput: TermInput { var secureTextEntry: Bool { get { false } set(secureTextEntry) { } } } class VSCodeInput: SmarterTermInput { override func shouldUseWKCopyAndPaste() -> Bool { true } override func canBeFocused() -> Bool { let res = super.canBeFocused() if res == false { return KBTracker.shared.input == self } return res } }
gpl-3.0
practicalswift/swift
validation-test/stdlib/SwiftNativeNSBase.swift
10
3380
//===--- SwiftNativeNSBase.swift - Test __SwiftNativeNS*Base classes -------===// // // 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: %empty-directory(%t) // // RUN: %target-clang %S/Inputs/SwiftNativeNSBase/SwiftNativeNSBase.m -c -o %t/SwiftNativeNSBase.o -g // RUN: %target-clang -fobjc-arc %S/Inputs/SlurpFastEnumeration/SlurpFastEnumeration.m -c -o %t/SlurpFastEnumeration.o // RUN: echo '#sourceLocation(file: "%s", line: 1)' > "%t/main.swift" && cat "%s" >> "%t/main.swift" && chmod -w "%t/main.swift" // RUN: %target-build-swift -Xfrontend -disable-access-control %t/main.swift %S/Inputs/DictionaryKeyValueTypes.swift %S/Inputs/DictionaryKeyValueTypesObjC.swift -I %S/Inputs/SwiftNativeNSBase/ -I %S/Inputs/SlurpFastEnumeration/ -Xlinker %t/SlurpFastEnumeration.o -Xlinker %t/SwiftNativeNSBase.o -o %t/SwiftNativeNSBase -swift-version 4.2 // RUN: %target-codesign %t/SwiftNativeNSBase // RUN: %target-run %t/SwiftNativeNSBase // REQUIRES: executable_test // REQUIRES: objc_interop import Foundation import StdlibUnittest @_silgen_name("TestSwiftNativeNSBase_UnwantedCdtors") func TestSwiftNativeNSBase_UnwantedCdtors() -> Bool @_silgen_name("TestSwiftNativeNSBase_RetainCount") func TestSwiftNativeNSBase_RetainCount(_: UnsafeMutableRawPointer) -> Bool func classChain(of cls: AnyClass) -> [String] { var chain: [String] = [] var cls: AnyClass? = cls while cls != nil { chain.append(NSStringFromClass(cls!)) cls = class_getSuperclass(cls) } return chain } var SwiftNativeNSBaseTestSuite = TestSuite("SwiftNativeNSBase") SwiftNativeNSBaseTestSuite.test("UnwantedCdtors") { expectTrue(TestSwiftNativeNSBase_UnwantedCdtors()) } SwiftNativeNSBaseTestSuite.test("__SwiftNativeNSArrayBase.retainCount") { let bridged = getBridgedNSArrayOfRefTypeVerbatimBridged() assert(classChain(of: type(of: bridged)).contains("__SwiftNativeNSArrayBase")) expectTrue(TestSwiftNativeNSBase_RetainCount( Unmanaged.passUnretained(bridged).toOpaque())) _fixLifetime(bridged) } SwiftNativeNSBaseTestSuite.test("__SwiftNativeNSDictionaryBase.retainCount") { let bridged = getBridgedNSDictionaryOfRefTypesBridgedVerbatim() assert(classChain(of: type(of: bridged)) .contains("__SwiftNativeNSDictionaryBase")) expectTrue(TestSwiftNativeNSBase_RetainCount( Unmanaged.passUnretained(bridged).toOpaque())) _fixLifetime(bridged) } SwiftNativeNSBaseTestSuite.test("__SwiftNativeNSSetBase.retainCount") { let bridged = Set([10, 20, 30].map{ TestObjCKeyTy($0) })._bridgeToObjectiveC() assert(classChain(of: type(of: bridged)).contains("__SwiftNativeNSSetBase")) expectTrue(TestSwiftNativeNSBase_RetainCount( Unmanaged.passUnretained(bridged).toOpaque())) _fixLifetime(bridged) } SwiftNativeNSBaseTestSuite.setUp { resetLeaksOfDictionaryKeysValues() resetLeaksOfObjCDictionaryKeysValues() } SwiftNativeNSBaseTestSuite.tearDown { expectNoLeaksOfDictionaryKeysValues() expectNoLeaksOfObjCDictionaryKeysValues() } runAllTests()
apache-2.0
practicalswift/swift
validation-test/compiler_crashers_fixed/00118-swift-dependentgenerictyperesolver-resolvegenerictypeparamtype.swift
65
1225
// 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 v<ih>() -> (ih, ih -> ih) -> ih { h ih h.b = { } { ih) { ed } } protocol v { } class h: v{ class func b {} class m<n : m> { } func u(l: Any, kj: Any) -> (((Any, Any) -> Any) -> Any) { l { } } func l(lk: (((Any, Any) -> Any) -> Any)) -> Any { l lk({ }) } func dc(a: v) -> <n>(() -> n) -> v { } class m: m { } class f : x { } protocol m { } k f : m { } k x<g, q: m where g.x == q> { } class ji<n>: u { q(fe: n) { } } protocol m { } k w<gf> : m { func l(l: w.r) { } } func ^(u: kj, l) -> l { } protocol u { } protocol l : u { } protocol w : u { } protocol h { } k h : h { } func b<ih : l, l : h where l.v == ih> (l: l) { } func b<f : h where f.v == w> (l: f) { } k m<n> { } class u<v : l, ih : l where v.h == ih> { } protocol l { } k w<ed : l> : l { } protocol w : l { func l
apache-2.0
Harvey-CH/TEST
v2exProject/v2exProject/View/HotCell.swift
2
1125
// // HotCell.swift // v2exProject // // Created by 郑建文 on 16/8/4. // Copyright © 2016年 Zheng. All rights reserved. // import UIKit import Alamofire import Kingfisher class HotCell: UITableViewCell { //MARK: 控件属性 @IBOutlet weak var AuthorImage: UIImageView! @IBOutlet weak var authorName: UILabel! @IBOutlet weak var topicTitle: UILabel! @IBOutlet weak var topicContent: UILabel! var topic:Topic? { didSet{ topicTitle.text = topic?.title topicContent.text = topic?.content authorName.text = topic?.member?.username AuthorImage.kf_setImageWithURL(NSURL(string: "https:" + (topic?.member?.avatar_normal)!)!) } } //content hugging 压缩优先级 // 谁的优先级大,当高度不够时先压缩谁 override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } }
mit
blockchain/My-Wallet-V3-iOS
Modules/FeatureOpenBanking/Sources/FeatureOpenBankingDomain/FailureAction.swift
1
1113
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import Blockchain public protocol FailureAction { static func failure(_ error: OpenBanking.Error) -> Self } extension FailureAction { public static func failure(_ error: Error) -> Self { failure(.init(error)) } } extension Publisher where Output: ResultProtocol { @_disfavoredOverload public func map<T>( _ action: @escaping (Output.Success) -> T ) -> Publishers.Map<Self, T> where T: FailureAction { map { it -> T in switch it.result { case .success(let value): return action(value) case .failure(let error): return T.failure(error) } } } public func map<T>( _ action: CasePath<T, Output.Success> ) -> Publishers.Map<Self, T> where T: FailureAction { map { it -> T in switch it.result { case .success(let value): return action.embed(value) case .failure(let error): return T.failure(error) } } } }
lgpl-3.0
RogueAndy/RogueKit2
RogueKitDemo/RogueKitDemo/Carthage/Checkouts/SnapKit/Example-iOS/demos/SimpleLayoutViewController.swift
3
2634
// // SimpleLayoutViewController.swift // SnapKit // // Created by Spiros Gerokostas on 01/03/16. // Copyright © 2016 SnapKit Team. All rights reserved. // import UIKit class SimpleLayoutViewController: UIViewController { var didSetupConstraints = false let blackView: UIView = { let view = UIView() view.backgroundColor = .blackColor() return view }() let redView: UIView = { let view = UIView() view.backgroundColor = .redColor() return view }() let yellowView: UIView = { let view = UIView() view.backgroundColor = .yellowColor() return view }() let blueView: UIView = { let view = UIView() view.backgroundColor = .blueColor() return view }() let greenView: UIView = { let view = UIView() view.backgroundColor = .greenColor() return view }() override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = UIColor.whiteColor() view.addSubview(blackView) view.addSubview(redView) view.addSubview(yellowView) view.addSubview(blueView) view.addSubview(greenView) view.setNeedsUpdateConstraints() } override func updateViewConstraints() { if (!didSetupConstraints) { blackView.snp_makeConstraints { make in make.center.equalTo(view) make.size.equalTo(CGSizeMake(100.0, 100.0)) } redView.snp_makeConstraints { make in make.top.equalTo(blackView.snp_bottom).offset(20.0) make.left.equalTo(20.0) make.size.equalTo(CGSizeMake(100.0, 100.0)) } yellowView.snp_makeConstraints { make in make.top.equalTo(blackView.snp_bottom).offset(20.0) make.left.equalTo(blackView.snp_right).offset(20.0) make.size.equalTo(CGSizeMake(100.0, 100.0)) } blueView.snp_makeConstraints { make in make.bottom.equalTo(blackView.snp_top).offset(-20.0) make.left.equalTo(blackView.snp_right).offset(20.0) make.size.equalTo(CGSizeMake(100.0, 100.0)) } greenView.snp_makeConstraints { make in make.bottom.equalTo(blackView.snp_top).offset(-20.0) make.right.equalTo(blackView.snp_left).offset(-20.0) make.size.equalTo(CGSizeMake(100.0, 100.0)) } didSetupConstraints = true } super.updateViewConstraints() } }
mit
xasos/BitWatch
BitWatchKit/Tracker.swift
1
2923
// // Tracker.swift // BitWatch // // Created by Niraj Pant on 12/7/2014. // Copyright (c) 2014 Niraj Pant All rights reserved. // import Foundation public typealias PriceRequestCompletionBlock = (price: NSNumber?, error: NSError?) -> () public class Tracker { let defaults = NSUserDefaults.standardUserDefaults() let session: NSURLSession let URL = "https://api.bitcoinaverage.com/ticker/USD" public class var dateFormatter: NSDateFormatter { struct DateFormatter { static var token: dispatch_once_t = 0 static var instance: NSDateFormatter? = nil } dispatch_once(&DateFormatter.token) { let formatter = NSDateFormatter() formatter.dateFormat = "HH:mm" DateFormatter.instance = formatter; } return DateFormatter.instance! } public class var priceFormatter: NSNumberFormatter { struct PriceFormatter { static var token: dispatch_once_t = 0 static var instance: NSNumberFormatter? = nil } dispatch_once(&PriceFormatter.token) { let formatter = NSNumberFormatter() formatter.currencyCode = "USD" formatter.numberStyle = NSNumberFormatterStyle.CurrencyStyle PriceFormatter.instance = formatter } return PriceFormatter.instance! } public init() { let configuration = NSURLSessionConfiguration.defaultSessionConfiguration() session = NSURLSession(configuration: configuration); } public func cachedDate() -> NSDate { if let date = defaults.objectForKey("date") as? NSDate { return date } return NSDate() } public func cachedPrice() -> NSNumber { if let price = defaults.objectForKey("price") as? NSNumber { return price } return NSNumber(double: 0.00) } public func requestPrice(completion: PriceRequestCompletionBlock) { let request = NSURLRequest(URL: NSURL(string: URL)!) let task = session.dataTaskWithRequest(request, completionHandler: { (data, response, error) -> Void in if error == nil { var JSONError: NSError? let responseDict = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments, error: &JSONError) as NSDictionary if JSONError == nil { let price: NSNumber = responseDict["24h_avg"] as NSNumber self.defaults.setObject(price, forKey: "price") self.defaults.setObject(NSDate(), forKey: "date") self.defaults.synchronize() dispatch_async(dispatch_get_main_queue(), { () -> Void in completion(price: price, error: nil) }) } else { dispatch_async(dispatch_get_main_queue(), { () -> Void in completion(price: nil, error: JSONError) }) } } else { dispatch_async(dispatch_get_main_queue(), { () -> Void in completion(price: nil, error: error) }) } }) task.resume() } }
mit
nikriek/gesundheit.space
Carthage/Checkouts/RxDataSources/ExampleUITests/ExampleUITests.swift
1
1262
// // ExampleUITests.swift // ExampleUITests // // Created by Krunoslav Zaher on 1/1/16. // Copyright © 2016 kzaher. All rights reserved. // import XCTest import CoreLocation class ExampleUITests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. // In UI tests it is usually best to stop immediately when a failure occurs. continueAfterFailure = false // UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method. XCUIApplication().launch() // In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // Use recording to get started writing UI tests. // Use XCTAssert and related functions to verify your tests produce the correct results. } }
mit
eofster/Telephone
UseCases/Products.swift
1
765
// // Products.swift // Telephone // // Copyright © 2008-2016 Alexey Kuznetsov // Copyright © 2016-2021 64 Characters // // Telephone is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // Telephone is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // public protocol Products { var all: [Product] { get } subscript(identifier: String) -> Product? { get } func fetch() }
gpl-3.0
Conche/Conche
Conche/Source.swift
2
1713
import Darwin import PathKit public protocol SourceType { func search(dependency:Dependency) -> [Specification] func update() throws } public class LocalFilesystemSource : SourceType { let path: Path public init(path: Path) { self.path = path } public func search(dependency:Dependency) -> [Specification] { let filename = "\(dependency.name).podspec.json" let paths = try? path.children().filter { $0.description.hasSuffix(filename) } ?? [] let specs = paths!.flatMap { (file:Path) in try? Specification(path:file) } return specs.filter { dependency.satisfies($0.version) } } public func update() throws {} } public class GitFilesystemSource : SourceType { let name:String let uri:String public init(name:String, uri:String) { self.name = name self.uri = uri } // TODO, silent error handling public func search(dependency:Dependency) -> [Specification] { let children = try? (path + "Specs" + dependency.name).children() let podspecs = (children ?? []).map { path in return path + "\(dependency.name).podspec.json" } return podspecs.flatMap(loadFile).filter { dependency.satisfies($0.version) } } func loadFile(path:Path) -> Specification? { do { return try Specification(path: path) } catch { print("\(path): \(error)") return nil } } var path:Path { return Path("~/.conche/sources/\(name)").normalize() } public func update() throws { let destination = path if destination.exists { try path.chdir { try invoke("git", ["pull", uri, "master"]) } } else { try invoke("git", ["clone", "--depth", "1", uri, path.description]) } } }
bsd-2-clause
JaSpa/swift
test/stmt/statements.swift
4
13788
// RUN: %target-typecheck-verify-swift /* block comments */ /* /* nested too */ */ func markUsed<T>(_ t: T) {} func f1(_ a: Int, _ y: Int) {} func f2() {} func f3() -> Int {} func invalid_semi() { ; // expected-error {{';' statements are not allowed}} {{3-5=}} } func nested1(_ x: Int) { var y : Int func nested2(_ z: Int) -> Int { return x+y+z } _ = nested2(1) } func funcdecl5(_ a: Int, y: Int) { var x : Int // a few statements if (x != 0) { if (x != 0 || f3() != 0) { // while with and without a space after it. while(true) { 4; 2; 1 } // expected-warning 3 {{integer literal is unused}} while (true) { 4; 2; 1 } // expected-warning 3 {{integer literal is unused}} } } // Assignment statement. x = y (x) = y 1 = x // expected-error {{cannot assign to a literal value}} (1) = x // expected-error {{cannot assign to a literal value}} (x:1).x = 1 // expected-error {{cannot assign to immutable expression of type 'Int'}} var tup : (x:Int, y:Int) tup.x = 1 _ = tup let B : Bool // if/then/else. if (B) { } else if (y == 2) { } // This diagnostic is terrible - rdar://12939553 if x {} // expected-error {{'Int' is not convertible to 'Bool'}} if true { if (B) { } else { } } if (B) { f1(1,2) } else { f2() } if (B) { if (B) { f1(1,2) } else { f2() } } else { f2() } // while statement. while (B) { } // It's okay to leave out the spaces in these. while(B) {} if(B) {} } struct infloopbool { var boolValue: infloopbool { return self } } func infloopbooltest() { if (infloopbool()) {} // expected-error {{'infloopbool' is not convertible to 'Bool'}} } // test "builder" API style extension Int { static func builder() -> Int { } var builderProp: Int { return 0 } func builder2() {} } Int .builder() .builderProp .builder2() struct SomeGeneric<T> { static func builder() -> SomeGeneric<T> { } var builderProp: SomeGeneric<T> { return .builder() } func builder2() {} } SomeGeneric<Int> .builder() .builderProp .builder2() break // expected-error {{'break' is only allowed inside a loop, if, do, or switch}} continue // expected-error {{'continue' is only allowed inside a loop}} while true { func f() { break // expected-error {{'break' is only allowed inside a loop}} continue // expected-error {{'continue' is only allowed inside a loop}} } // Labeled if MyIf: if 1 != 2 { break MyIf continue MyIf // expected-error {{'continue' cannot be used with if statements}} break // break the while continue // continue the while. } } // Labeled if MyOtherIf: if 1 != 2 { break MyOtherIf continue MyOtherIf // expected-error {{'continue' cannot be used with if statements}} break // expected-error {{unlabeled 'break' is only allowed inside a loop or switch, a labeled break is required to exit an if}} continue // expected-error {{'continue' is only allowed inside a loop}} } do { break // expected-error {{unlabeled 'break' is only allowed inside a loop or switch, a labeled break is required to exit an if or do}} } func tuple_assign() { var a,b,c,d : Int (a,b) = (1,2) func f() -> (Int,Int) { return (1,2) } ((a,b), (c,d)) = (f(), f()) } func missing_semicolons() { var w = 321 func g() {} g() w += 1 // expected-error{{consecutive statements}} {{6-6=;}} var z = w"hello" // expected-error{{consecutive statements}} {{12-12=;}} expected-warning {{string literal is unused}} class C {}class C2 {} // expected-error{{consecutive statements}} {{14-14=;}} struct S {}struct S2 {} // expected-error{{consecutive statements}} {{14-14=;}} func j() {}func k() {} // expected-error{{consecutive statements}} {{14-14=;}} } //===--- Return statement. return 42 // expected-error {{return invalid outside of a func}} return // expected-error {{return invalid outside of a func}} func NonVoidReturn1() -> Int { return // expected-error {{non-void function should return a value}} } func NonVoidReturn2() -> Int { return + // expected-error {{unary operator cannot be separated from its operand}} {{11-1=}} expected-error {{expected expression in 'return' statement}} } func VoidReturn1() { if true { return } // Semicolon should be accepted -- rdar://11344875 return; // no-error } func VoidReturn2() { return () // no-error } func VoidReturn3() { return VoidReturn2() // no-error } //===--- If statement. func IfStmt1() { if 1 > 0 // expected-error {{expected '{' after 'if' condition}} _ = 42 } func IfStmt2() { if 1 > 0 { } else // expected-error {{expected '{' after 'else'}} _ = 42 } //===--- While statement. func WhileStmt1() { while 1 > 0 // expected-error {{expected '{' after 'while' condition}} _ = 42 } //===-- Do statement. func DoStmt() { // This is just a 'do' statement now. do { } } func DoWhileStmt() { do { // expected-error {{'do-while' statement is not allowed; use 'repeat-while' instead}} {{3-5=repeat}} } while true } //===--- Repeat-while statement. func RepeatWhileStmt1() { repeat {} while true repeat {} while false repeat { break } while true repeat { continue } while true } func RepeatWhileStmt2() { repeat // expected-error {{expected '{' after 'repeat'}} expected-error {{expected 'while' after body of 'repeat' statement}} } func RepeatWhileStmt4() { repeat { } while + // expected-error {{unary operator cannot be separated from its operand}} {{12-1=}} expected-error {{expected expression in 'repeat-while' condition}} } func brokenSwitch(_ x: Int) -> Int { switch x { case .Blah(var rep): // expected-error{{enum case 'Blah' not found in type 'Int'}} return rep } } func switchWithVarsNotMatchingTypes(_ x: Int, y: Int, z: String) -> Int { switch (x,y,z) { case (let a, 0, _), (0, let a, _): // OK return a case (let a, _, _), (_, _, let a): // expected-error {{pattern variable bound to type 'String', expected type 'Int'}} return a } } func breakContinue(_ x : Int) -> Int { Outer: for _ in 0...1000 { Switch: switch x { case 42: break Outer case 97: continue Outer case 102: break Switch case 13: continue case 139: break // <rdar://problem/16563853> 'break' should be able to break out of switch statements } } // <rdar://problem/16692437> shadowing loop labels should be an error Loop: // expected-note {{previously declared here}} for _ in 0...2 { Loop: // expected-error {{label 'Loop' cannot be reused on an inner statement}} for _ in 0...2 { } } // <rdar://problem/16798323> Following a 'break' statement by another statement on a new line result in an error/fit-it switch 5 { case 5: markUsed("before the break") break markUsed("after the break") // 'markUsed' is not a label for the break. default: markUsed("") } let x : Int? = 42 // <rdar://problem/16879701> Should be able to pattern match 'nil' against optionals switch x { case .some(42): break case nil: break } } enum MyEnumWithCaseLabels { case Case(one: String, two: Int) } func testMyEnumWithCaseLabels(_ a : MyEnumWithCaseLabels) { // <rdar://problem/20135489> Enum case labels are ignored in "case let" statements switch a { case let .Case(one: _, two: x): break // ok case let .Case(xxx: _, two: x): break // expected-error {{tuple pattern element label 'xxx' must be 'one'}} // TODO: In principle, reordering like this could be supported. case let .Case(two: _, one: x): break // expected-error {{tuple pattern element label}} } } // "defer" func test_defer(_ a : Int) { defer { VoidReturn1() } defer { breakContinue(1)+42 } // expected-warning {{result of operator '+' is unused}} // Ok: defer { while false { break } } // Not ok. while false { defer { break } } // expected-error {{'break' cannot transfer control out of a defer statement}} defer { return } // expected-error {{'return' cannot transfer control out of a defer statement}} } class SomeTestClass { var x = 42 func method() { defer { x = 97 } // self. not required here! } } class SomeDerivedClass: SomeTestClass { override init() { defer { super.init() // expected-error {{initializer chaining ('super.init') cannot be nested in another expression}} } } } func test_guard(_ x : Int, y : Int??, cond : Bool) { // These are all ok. guard let a = y else {} markUsed(a) guard let b = y, cond else {} guard case let c = x, cond else {} guard case let Optional.some(d) = y else {} guard x != 4, case _ = x else { } guard let e, cond else {} // expected-error {{variable binding in a condition requires an initializer}} guard case let f? : Int?, cond else {} // expected-error {{variable binding in a condition requires an initializer}} guard let g = y else { markUsed(g) // expected-error {{variable declared in 'guard' condition is not usable in its body}} } guard let h = y, cond {} // expected-error {{expected 'else' after 'guard' condition}} guard case _ = x else {} // expected-warning {{'guard' condition is always true, body is unreachable}} } func test_is_as_patterns() { switch 4 { case is Int: break // expected-warning {{'is' test is always true}} case _ as Int: break // expected-warning {{'as' test is always true}} case _: break } } // <rdar://problem/21387308> Fuzzing SourceKit: crash in Parser::parseStmtForEach(...) func matching_pattern_recursion() { switch 42 { case { // expected-error {{expression pattern of type '() -> ()' cannot match values of type 'Int'}} for i in zs { } }: break } } // <rdar://problem/18776073> Swift's break operator in switch should be indicated in errors func r18776073(_ a : Int?) { switch a { case nil: // expected-error {{'case' label in a 'switch' should have at least one executable statement}} {{14-14= break}} case _?: break } } // <rdar://problem/22491782> unhelpful error message from "throw nil" func testThrowNil() throws { throw nil // expected-error {{cannot infer concrete Error for thrown 'nil' value}} } // rdar://problem/23684220 // Even if the condition fails to typecheck, save it in the AST anyway; the old // condition may have contained a SequenceExpr. func r23684220(_ b: Any) { if let _ = b ?? b {} // expected-error {{initializer for conditional binding must have Optional type, not 'Any'}} } // <rdar://problem/21080671> QoI: try/catch (instead of do/catch) creates silly diagnostics func f21080671() { try { // expected-error {{the 'do' keyword is used to specify a 'catch' region}} {{3-6=do}} } catch { } try { // expected-error {{the 'do' keyword is used to specify a 'catch' region}} {{3-6=do}} f21080671() } catch let x as Int { } catch { } } // <rdar://problem/24467411> QoI: Using "&& #available" should fixit to comma // https://twitter.com/radexp/status/694561060230184960 func f(_ x : Int, y : Int) { if x == y && #available(iOS 52, *) {} // expected-error {{expected ',' joining parts of a multi-clause condition}} {{12-15=,}} if #available(iOS 52, *) && x == y {} // expected-error {{expected ',' joining parts of a multi-clause condition}} {{27-30=,}} // https://twitter.com/radexp/status/694790631881883648 if x == y && let _ = Optional(y) {} // expected-error {{expected ',' joining parts of a multi-clause condition}} {{12-15=,}} if x == y&&let _ = Optional(y) {} // expected-error {{expected ',' joining parts of a multi-clause condition}} {{12-14=,}} } // <rdar://problem/25178926> QoI: Warn about cases where switch statement "ignores" where clause enum Type { case Foo case Bar } func r25178926(_ a : Type) { switch a { case .Foo, .Bar where 1 != 100: // expected-warning @-1 {{'where' only applies to the second pattern match in this case}} // expected-note @-2 {{disambiguate by adding a line break between them if this is desired}} {{14-14=\n }} // expected-note @-3 {{duplicate the 'where' on both patterns to check both patterns}} {{12-12= where 1 != 100}} break } switch a { case .Foo: break case .Bar where 1 != 100: break } switch a { case .Foo, // no warn .Bar where 1 != 100: break } switch a { case .Foo where 1 != 100, .Bar where 1 != 100: break } } do { guard 1 == 2 else { break // expected-error {{unlabeled 'break' is only allowed inside a loop or switch, a labeled break is required to exit an if or do}} } } func fn(a: Int) { guard a < 1 else { break // expected-error {{'break' is only allowed inside a loop, if, do, or switch}} } } func fn(x: Int) { if x >= 0 { guard x < 1 else { guard x < 2 else { break // expected-error {{unlabeled 'break' is only allowed inside a loop or switch, a labeled break is required to exit an if or do}} } return } } } func bad_if() { if 1 {} // expected-error {{'Int' is not convertible to 'Bool'}} if (x: false) {} // expected-error {{'(x: Bool)' is not convertible to 'Bool'}} if (x: 1) {} // expected-error {{'(x: Int)' is not convertible to 'Bool'}} } // Errors in case syntax class case, // expected-error {{expected identifier in enum 'case' declaration}} expected-error {{expected pattern}} case // expected-error {{expected identifier after comma in enum 'case' declaration}} expected-error {{expected identifier in enum 'case' declaration}} expected-error {{enum 'case' is not allowed outside of an enum}} expected-error {{expected pattern}} // NOTE: EOF is important here to properly test a code path that used to crash the parser
apache-2.0
googlearchive/science-journal-ios
ScienceJournalTests/UI/NoteDetailControllerTest.swift
1
4041
/* * Copyright 2019 Google LLC. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import XCTest @testable import third_party_sciencejournal_ios_ScienceJournalOpen import third_party_objective_c_material_components_ios_components_TextFields_TextFields class NoteDetailControllerTest: XCTestCase { var noteDetailVC: TestCaptionableNoteDetailController! override func setUp() { super.setUp() let displayPictureNote = DisplayPictureNoteViewData(ID: "TESTID", trialID: "TRIALID", imagePath: "image/path", timestamp: Timestamp(1000), caption: "Foo") noteDetailVC = TestCaptionableNoteDetailController(displayNote: displayPictureNote) } func testUpdatingCaptionWithSameValue() { noteDetailVC.updateCaptionFromDisplayNote() XCTAssertEqual(noteDetailVC.currentCaption, "Foo") let newPictureNote = DisplayPictureNoteViewData(ID: "TESTID", trialID: "TRIALID", imagePath: "image/path/2", timestamp: Timestamp(2000), caption: "Foo") noteDetailVC.displayNote = newPictureNote noteDetailVC.updateCaptionFromDisplayNote() XCTAssertEqual(noteDetailVC.currentCaption, "Foo") } func testUpdatingCaptionWithNewValue() { noteDetailVC.updateCaptionFromDisplayNote() XCTAssertEqual(noteDetailVC.currentCaption, "Foo") let newPictureNote = DisplayPictureNoteViewData(ID: "TESTID", trialID: "TRIALID", imagePath: "image/path/2", timestamp: Timestamp(2000), caption: "Bar") noteDetailVC.displayNote = newPictureNote noteDetailVC.updateCaptionFromDisplayNote() XCTAssertEqual(noteDetailVC.currentCaption, "Foo / Bar") } func testUpdatingCaptionWithEmptyString() { let pictureNote = DisplayPictureNoteViewData(ID: "TESTID", trialID: "TRIALID", imagePath: "image/path/2", timestamp: Timestamp(2000), caption: "") noteDetailVC.displayNote = pictureNote noteDetailVC.updateCaptionFromDisplayNote() let newPictureNote = DisplayPictureNoteViewData(ID: "TESTID", trialID: "TRIALID", imagePath: "image/path/2", timestamp: Timestamp(2000), caption: "Foo") noteDetailVC.displayNote = newPictureNote noteDetailVC.updateCaptionFromDisplayNote() XCTAssertEqual(noteDetailVC.currentCaption, "Foo") } // MARK: - TestNoteDetailController class TestCaptionableNoteDetailController: CaptionableNoteDetailController { var displayNote: DisplayNote var currentCaption: String? init(displayNote: DisplayNote) { self.displayNote = displayNote } } }
apache-2.0
taka0125/AddressBookSync
Pod/Classes/Scan/AddressBook.swift
1
907
// // AddressBook.swift // AddressBookSync // // Created by Takahiro Ooishi // Copyright (c) 2015 Takahiro Ooishi. All rights reserved. // Released under the MIT license. // import Foundation public struct AddressBook: AdapterProtocol { public static let sharedInstance = AddressBook() public enum Error: ErrorType { case RequestAccessFailed } private let adapter: AdapterProtocol private init() { if #available(iOS 9, *) { adapter = ContactsFrameworkBookAdapter() } else { adapter = AddressBookFrameworkAdapter() } } public func authorizationStatus() -> AuthorizationStatus { return adapter.authorizationStatus() } public func requestAccess(completionHandler: (Bool, ErrorType?) -> Void) { return adapter.requestAccess(completionHandler) } public func fetchAll() -> [AddressBookRecord] { return adapter.fetchAll() } }
mit
tungvoduc/DTPhotoViewerController
Example/DTPhotoViewerController/AppDelegate.swift
1
2489
// // AppDelegate.swift // DTPhotoViewerController // // Created by Tung Vo on 05/07/2016. // Copyright (c) 2016 Tung Vo. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. window = UIWindow(frame: UIScreen.main.bounds) let navigationController = UINavigationController(rootViewController: ViewController()) navigationController.navigationBar.isTranslucent = false window?.rootViewController = navigationController window?.makeKeyAndVisible() return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
mit
yotao/YunkuSwiftSDKTEST
YunkuSwiftSDK/YunkuSwiftSDK/Class/Data/OauthData.swift
1
883
// // Created by Brandon on 15/6/1. // Copyright (c) 2015 goukuai. All rights reserved. // import Foundation class OauthData: BaseData { static let keyAccessToken = "access_token" static let keyExpiresIn = "expires_in" static let keyError = "error" var accessToken: String = "" var expiresIn: Int = 0 class func create(_ dic: NSDictionary) -> OauthData { let data = OauthData() data.code = (dic[ReturnResult.keyCode] as? Int)! var returnResult = dic[ReturnResult.keyResult] as? Dictionary<String, AnyObject>; if data.code == HTTPStatusCode.ok.rawValue { data.accessToken = (returnResult?[keyAccessToken] as? String)! data.expiresIn = (returnResult?[keyExpiresIn] as? Int)! } else { data.errorMsg = (returnResult?[keyError] as? String)! } return data } }
mit
coach-plus/ios
Pods/RxSwift/RxSwift/Observables/Map.swift
6
2544
// // Map.swift // RxSwift // // Created by Krunoslav Zaher on 3/15/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // extension ObservableType { /** Projects each element of an observable sequence into a new form. - seealso: [map operator on reactivex.io](http://reactivex.io/documentation/operators/map.html) - parameter transform: A transform function to apply to each source element. - returns: An observable sequence whose elements are the result of invoking the transform function on each element of source. */ public func map<Result>(_ transform: @escaping (Element) throws -> Result) -> Observable<Result> { return Map(source: self.asObservable(), transform: transform) } } final private class MapSink<SourceType, Observer: ObserverType>: Sink<Observer>, ObserverType { typealias Transform = (SourceType) throws -> ResultType typealias ResultType = Observer.Element typealias Element = SourceType private let _transform: Transform init(transform: @escaping Transform, observer: Observer, cancel: Cancelable) { self._transform = transform super.init(observer: observer, cancel: cancel) } func on(_ event: Event<SourceType>) { switch event { case .next(let element): do { let mappedElement = try self._transform(element) self.forwardOn(.next(mappedElement)) } catch let e { self.forwardOn(.error(e)) self.dispose() } case .error(let error): self.forwardOn(.error(error)) self.dispose() case .completed: self.forwardOn(.completed) self.dispose() } } } final private class Map<SourceType, ResultType>: Producer<ResultType> { typealias Transform = (SourceType) throws -> ResultType private let _source: Observable<SourceType> private let _transform: Transform init(source: Observable<SourceType>, transform: @escaping Transform) { self._source = source self._transform = transform } override func run<Observer: ObserverType>(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == ResultType { let sink = MapSink(transform: self._transform, observer: observer, cancel: cancel) let subscription = self._source.subscribe(sink) return (sink: sink, subscription: subscription) } }
mit
keatongreve/fastlane
fastlane/swift/SnapshotfileProtocol.swift
8
2846
protocol SnapshotfileProtocol: class { var workspace: String? { get } var project: String? { get } var xcargs: String? { get } var xcconfig: String? { get } var devices: [String]? { get } var languages: [String] { get } var launchArguments: [String] { get } var outputDirectory: String { get } var outputSimulatorLogs: Bool { get } var iosVersion: String? { get } var skipOpenSummary: Bool { get } var skipHelperVersionCheck: Bool { get } var clearPreviousScreenshots: Bool { get } var reinstallApp: Bool { get } var eraseSimulator: Bool { get } var localizeSimulator: Bool { get } var appIdentifier: String? { get } var addPhotos: [String]? { get } var addVideos: [String]? { get } var buildlogPath: String { get } var clean: Bool { get } var testWithoutBuilding: Bool? { get } var configuration: String? { get } var xcprettyArgs: String? { get } var sdk: String? { get } var scheme: String? { get } var numberOfRetries: Int { get } var stopAfterFirstError: Bool { get } var derivedDataPath: String? { get } var resultBundle: Bool { get } var testTargetName: String? { get } var namespaceLogFiles: String? { get } var concurrentSimulators: Bool { get } } extension SnapshotfileProtocol { var workspace: String? { return nil } var project: String? { return nil } var xcargs: String? { return nil } var xcconfig: String? { return nil } var devices: [String]? { return nil } var languages: [String] { return ["en-US"] } var launchArguments: [String] { return [""] } var outputDirectory: String { return "screenshots" } var outputSimulatorLogs: Bool { return false } var iosVersion: String? { return nil } var skipOpenSummary: Bool { return false } var skipHelperVersionCheck: Bool { return false } var clearPreviousScreenshots: Bool { return false } var reinstallApp: Bool { return false } var eraseSimulator: Bool { return false } var localizeSimulator: Bool { return false } var appIdentifier: String? { return nil } var addPhotos: [String]? { return nil } var addVideos: [String]? { return nil } var buildlogPath: String { return "~/Library/Logs/snapshot" } var clean: Bool { return false } var testWithoutBuilding: Bool? { return nil } var configuration: String? { return nil } var xcprettyArgs: String? { return nil } var sdk: String? { return nil } var scheme: String? { return nil } var numberOfRetries: Int { return 1 } var stopAfterFirstError: Bool { return false } var derivedDataPath: String? { return nil } var resultBundle: Bool { return false } var testTargetName: String? { return nil } var namespaceLogFiles: String? { return nil } var concurrentSimulators: Bool { return true } } // Please don't remove the lines below // They are used to detect outdated files // FastlaneRunnerAPIVersion [0.9.4]
mit
cornerstonecollege/402
Younseo/NavigationController/NavigationController/ViewControllerGreen.swift
1
484
// // ViewControllerGreen.swift // NavigationController // // Created by hoconey on 2016/10/18. // Copyright © 2016年 younseo. All rights reserved. // import UIKit class ViewControllerGreen: UIViewController { override func viewDidLoad() { super.viewDidLoad() print("GREEN") } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
gpl-3.0
neilpa/Rex
Source/UIKit/UILabel.swift
2
1057
// // UILabel.swift // Rex // // Created by Neil Pankey on 6/19/15. // Copyright (c) 2015 Neil Pankey. All rights reserved. // import ReactiveCocoa import UIKit extension UILabel { /// Wraps a label's `text` value in a bindable property. public var rex_text: MutableProperty<String?> { return associatedProperty(self, key: &textKey, initial: { $0.text }, setter: { $0.text = $1 }) } /// Wraps a label's `attributedText` value in a bindable property. public var rex_attributedText: MutableProperty<NSAttributedString?> { return associatedProperty(self, key: &attributedTextKey, initial: { $0.attributedText }, setter: { $0.attributedText = $1 }) } /// Wraps a label's `textColor` value in a bindable property. public var rex_textColor: MutableProperty<UIColor> { return associatedProperty(self, key: &textColorKey, initial: { $0.textColor }, setter: { $0.textColor = $1 }) } } private var textKey: UInt8 = 0 private var attributedTextKey: UInt8 = 0 private var textColorKey: UInt8 = 0
mit
jonandersen/calendar
Example/Example/AppDelegate.swift
1
2139
// // AppDelegate.swift // Example // // Created by Jon Andersen on 4/10/16. // Copyright © 2016 Andersen. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
mit
ctarda/Turnstile
Sources/TurnstileTests/EventTests.swift
1
2425
// // EventTests.swift // Turnstile // // Created by Cesar Tardaguila on 09/05/15. // import XCTest import Turnstile class EventTests: XCTestCase { private struct Constants { static let eventName = "Event under test" static let sourceStates = [State(value: "State 1"), State(value: "State 2")] static let destinationState = State(value: "State3") static let stringDiff = "💩" } var event: Event<String>? override func setUp() { super.setUp() event = Event(name: Constants.eventName, sourceStates: Constants.sourceStates, destinationState: Constants.destinationState) } override func tearDown() { event = nil super.tearDown() } func testEventCanBeConstructed() { XCTAssertNotNil(event, "Event must not be nil") } func testEventNameIsSetProperly() { XCTAssertNotNil(event?.name, "Event name must not be nil") } func testEqualEventsAreEqual() { let secondEvent = Event(name: Constants.eventName, sourceStates: Constants.sourceStates, destinationState: Constants.destinationState) XCTAssertTrue( event == secondEvent, "A event must be equal to itself") } func testEventsWithDifferentNamesAreDifferent() { let secondEvent = Event(name: Constants.eventName + Constants.stringDiff, sourceStates: Constants.sourceStates, destinationState: Constants.destinationState) XCTAssertFalse( event == secondEvent, "Events with different name are different") } func testEventsWithDiffrentSourceStatesAndSameNameAreDifferent() { let secondEvent = Event(name: Constants.eventName, sourceStates: [State(value: "State 3")], destinationState: Constants.destinationState) XCTAssertFalse( event == secondEvent, "Events with different source states are different") } func testEventsWithSameNameAndSourceEventsAndDifferentDestinationEventsAreDifferent() { let secondEvent = Event(name: Constants.eventName, sourceStates: Constants.sourceStates , destinationState: State(value: "State 3")) XCTAssertFalse( event == secondEvent, "Events with different destination states are different") } func testSourceStatesCanBeSet() { XCTAssertTrue((event!.sourceStates == Constants.sourceStates), "Source states must be set properly") } }
mit
austinzheng/swift-compiler-crashes
crashes-duplicates/19481-swift-type-walk.swift
11
238
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing class A { func a { } var d = a<T class A { enum S<T where A: A > : e
mit
austinzheng/swift-compiler-crashes
crashes-duplicates/24308-swift-modulefile-lookupvalue.swift
9
247
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing class B{ struct Q<T{ func f:A{ } } } class d<T where B:d{ class d<j:A class A
mit
austinzheng/swift-compiler-crashes
crashes-duplicates/19155-no-stacktrace.swift
11
367
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing func f { func f { deinit { if true { { { protocol A { { { { [ { { { { { { { { { { { { { { { ( ( ) { { [ { { { { { { [ { [ [ { { { { [ [ ] { { { { { [ { { [ { { { { { { { { { B a" class case c, case
mit
elkanaoptimove/OptimoveSDK
OptimoveSDK/Optimove Components/OptiPush/Registrar/Builder/MbaasRequestBody.swift
1
3551
// // UserPushToken.swift // OptimoveSDK // // Created by Elkana Orbach on 25/04/2018. // Copyright © 2018 Optimove. All rights reserved. // import Foundation struct MbaasRequestBody:Codable,CustomStringConvertible { let tenantId: Int let deviceId:String let appNs:String let osVersion:String var visitorId : String? var publicCustomerId: String? var optIn:Bool? var token: String? let operation:MbaasOperations var isConversion: Bool? var description: String { return "tenantId=\(tenantId)&deviceId=\(deviceId)&appNs=\(appNs)&osVersion=\(osVersion)&visitorId=\(visitorId ?? "" )&publicCustomerId=\(publicCustomerId ?? "")&optIn=\(optIn?.description ?? "")&token=\(token ?? "")&operation=\(operation)&isConversion=\(isConversion?.description ?? "")" } init(operation: MbaasOperations) { self.operation = operation tenantId = TenantID ?? -1 deviceId = DeviceID appNs = Bundle.main.bundleIdentifier?.replacingOccurrences(of: ".", with: "_") ?? "" osVersion = OSVersion } func toMbaasJsonBody() ->Data? { var requestJsonData = [String: Any]() switch operation { case .optIn: fallthrough case .optOut: fallthrough case .unregistration: let iOSToken = [Keys.Registration.bundleID.rawValue : appNs, Keys.Registration.deviceID.rawValue : DeviceID ] requestJsonData[Keys.Registration.iOSToken.rawValue] = iOSToken requestJsonData[Keys.Registration.tenantID.rawValue] = TenantID if let customerId = UserInSession.shared.customerID { requestJsonData[Keys.Registration.customerID.rawValue] = customerId } else { requestJsonData[Keys.Registration.visitorID.rawValue] = VisitorID } case .registration: var bundle = [String:Any]() bundle[Keys.Registration.optIn.rawValue] = UserInSession.shared.isMbaasOptIn bundle[Keys.Registration.token.rawValue] = UserInSession.shared.fcmToken let app = [appNs: bundle] var device: [String: Any] = [Keys.Registration.apps.rawValue: app] device[Keys.Registration.osVersion.rawValue] = OSVersion let ios = [deviceId: device] requestJsonData[Keys.Registration.iOSToken.rawValue] = ios requestJsonData[Keys.Registration.tenantID.rawValue] = UserInSession.shared.siteID if let customerId = UserInSession.shared.customerID { requestJsonData[Keys.Registration.origVisitorID.rawValue] = UserInSession.shared.visitorID if UserInSession.shared.isFirstConversion == nil { UserInSession.shared.isFirstConversion = true } else { UserInSession.shared.isFirstConversion = false } requestJsonData[Keys.Registration.isConversion.rawValue] = UserInSession.shared.isFirstConversion requestJsonData[Keys.Registration.customerID.rawValue] = customerId } else { requestJsonData[Keys.Registration.visitorID.rawValue] = UserInSession.shared.visitorID } } let dictionary = [operation.rawValue : requestJsonData] return try! JSONSerialization.data(withJSONObject: dictionary, options: []) } }
mit
prey/prey-ios-client
Prey/Classes/TriggersEvents+Class.swift
1
267
// // TriggersEvents+CoreDataClass.swift // Prey // // Created by Javier Cala Uribe on 17/7/19. // Copyright © 2019 Prey, Inc. All rights reserved. // // import Foundation import CoreData @objc(TriggersEvents) public class TriggersEvents: NSManagedObject { }
gpl-3.0
Laptopmini/SwiftyArtik
Source/MessagesAPI.swift
1
21222
// // MessagesAPI.swift // SwiftyArtik // // Created by Paul-Valentin Mini on 6/12/17. // Copyright © 2017 Paul-Valentin Mini. All rights reserved. // import Foundation import PromiseKit import Alamofire open class MessagesAPI { public enum MessageType: String { case message = "message" case action = "action" } public enum MessageStatisticsInterval: String { case minute = "minute" case hour = "hour" case day = "day" case month = "month" case year = "year" } // MARK: - Messages /// Send a Message to ARTIK Cloud. /// /// - Parameters: /// - data: The message payload. /// - did: The Device's id, used as the sender. /// - timestamp: (Optional) Message timestamp. Must be a valid time: past time, present or future up to the current server timestamp grace period. Current time if omitted. /// - Returns: A `Promise<String>`, returning the resulting message's id. open class func sendMessage(data: [String:Any], fromDid did: String, timestamp: Int64? = nil) -> Promise<String> { let parameters: [String:Any] = [ "data": data, "type": MessageType.message.rawValue, "sdid": did ] return postMessage(baseParameters: parameters, timestamp: timestamp) } /// Get the messages sent by a Device using pagination. /// /// - Parameters: /// - did: The Device's id. /// - startDate: Time of the earliest possible item, in milliseconds since epoch. /// - endDate: Time of the latest possible item, in milliseconds since epoch. /// - count: The count of results, max `100` (default). /// - offset: (Optional) The offset cursor for pagination. /// - order: (Optional) The order of the results, `.ascending` if ommited. /// - fieldPresence: (Optional) Return only messages which contain the provided field names /// - Returns: A `Promise<MessagePage>` open class func getMessages(did: String, startDate: ArtikTimestamp, endDate: ArtikTimestamp, count: Int = 100, offset: String? = nil, order: PaginationOrder? = nil, fieldPresence: [String]? = nil) -> Promise<MessagePage> { let promise = Promise<MessagePage>.pending() let path = SwiftyArtikSettings.basePath + "/messages" var presenceValue: String? if let fieldPresence = fieldPresence { presenceValue = "(" + fieldPresence.map { return "+_exists_:\($0)" }.joined(separator: " ") + ")" } let parameters = APIHelpers.removeNilParameters([ "sdid": did, "startDate": startDate, "endDate": endDate, "count": count, "offset": offset, "order": order?.rawValue, "filter": presenceValue ]) APIHelpers.makeRequest(url: path, method: .get, parameters: parameters, encoding: URLEncoding.queryString).then { response -> Void in if let page = MessagePage(JSON: response) { page.count = count page.fieldPresence = fieldPresence promise.fulfill(page) } else { promise.reject(ArtikError.json(reason: .unexpectedFormat)) } }.catch { error -> Void in promise.reject(error) } return promise.promise } /// Get a specific Message /// /// - Parameters: /// - mid: The Message's id. /// - uid: (Optional) The owner's user ID, required when using an `ApplicationToken`. /// - Returns: A `Promise<Message>` open class func getMessage(mid: String, uid: String? = nil) -> Promise<Message> { let promise = Promise<Message>.pending() let path = SwiftyArtikSettings.basePath + "/messages" var parameters = [ "mid": mid ] if let uid = uid { parameters["uid"] = uid } APIHelpers.makeRequest(url: path, method: .get, parameters: parameters, encoding: URLEncoding.queryString).then { response -> Void in if let data = (response["data"] as? [[String:Any]])?.first, let message = Message(JSON: data) { promise.fulfill(message) } else { promise.reject(ArtikError.json(reason: .unexpectedFormat)) } }.catch { error -> Void in promise.reject(error) } return promise.promise } /// Get the presence of Messages for a given time period. /// /// - Parameters: /// - sdid: The source Device's id. /// - fieldPresence: (Optional) Return only messages which contain the provided field name /// - startDate: Time of the earliest possible item, in milliseconds since epoch. /// - endDate: Time of the latest possible item, in milliseconds since epoch. /// - interval: The grouping interval /// - Returns: A `Promise<MessagesPresence>` open class func getPresence(sdid: String?, fieldPresence: String? = nil, startDate: ArtikTimestamp, endDate: ArtikTimestamp, interval: MessageStatisticsInterval) -> Promise<MessagesPresence> { let promise = Promise<MessagesPresence>.pending() let path = SwiftyArtikSettings.basePath + "/messages/presence" let parameters = APIHelpers.removeNilParameters([ "sdid": sdid, "fieldPresence": fieldPresence, "interval": interval.rawValue, "startDate": startDate, "endDate": endDate ]) APIHelpers.makeRequest(url: path, method: .get, parameters: parameters, encoding: URLEncoding.queryString).then { response -> Void in if let presence = MessagesPresence(JSON: response) { promise.fulfill(presence) } else { promise.reject(ArtikError.json(reason: .unexpectedFormat)) } }.catch { error -> Void in promise.reject(error) } return promise.promise } /// Get the latest messages sent by a Device. /// /// - Parameters: /// - did: The Device's id /// - count: The count of results, max 100 /// - fieldPresence: (Optional) Return only messages which contain the provided field names /// - Returns: A `Promise<MessagePage>` open class func getLastMessages(did: String, count: Int = 100, fieldPresence: [String]? = nil) -> Promise<MessagePage> { let promise = Promise<MessagePage>.pending() getMessages(did: did, startDate: 1, endDate: currentArtikEpochtime(), count: count, order: .descending, fieldPresence: fieldPresence).then { page -> Void in promise.fulfill(page) }.catch { error -> Void in promise.reject(error) } return promise.promise } /// Get the lastest message sent by a Device. /// /// - Parameter did: The Device's id. /// - Returns: A `Promise<Message>` open class func getLastMessage(did: String) -> Promise<Message?> { let promise = Promise<Message?>.pending() getLastMessages(did: did, count: 1).then { page -> Void in if let message = page.data.first { promise.fulfill(message) } else { promise.fulfill(nil) } }.catch { error -> Void in promise.reject(error) } return promise.promise } // MARK: - Actions /// Send an Action to a Device through ARTIK Cloud. /// /// - Parameters: /// - named: The name of the action /// - parameters: (Optional) The parameters of the action. /// - target: The Device's id receiving the action. /// - sender: (Optional) The id of the Device sending the action. /// - timestamp: (Optional) Action timestamp, a past/present/future time up to the current server timestamp grace period. Current time if omitted. /// - Returns: A `Promise<String>` returning the resulting action's id. open class func sendAction(named: String, parameters: [String:Any]? = nil, toDid target: String, fromDid sender: String? = nil, timestamp: Int64? = nil) -> Promise<String> { var parameters: [String:Any] = [ "ddid": target, "type": MessageType.action.rawValue, "data": [ "actions": [ [ "name": named, "parameters": parameters ?? [:] ] ] ] ] if let sender = sender { parameters["sdid"] = sender } return postMessage(baseParameters: parameters, timestamp: timestamp) } /// Send multiple Actions to a Device through ARTIK Cloud. /// /// - Parameters: /// - actions: A dict where the `key` is the name of the action and the `value` is its parameters. /// - target: The Device's id receiving the action. /// - sender: (Optional) The id of the Device sending the action. /// - timestamp: (Optional) Action timestamp, a past/present/future time up to the current server timestamp grace period. Current time if omitted. /// - Returns: A `Promise<String>` returning the resulting action's id. open class func sendActions(_ actions: [String:[String:Any]?], toDid target: String, fromDid sender: String? = nil, timestamp: Int64? = nil) -> Promise<String> { var data = [[String:Any]]() for (name, parameters) in actions { data.append([ "name": name, "parameters": parameters ?? [:] ]) } var parameters: [String:Any] = [ "ddid": target, "type": MessageType.action.rawValue, "data": [ "actions": data ] ] if let sender = sender { parameters["sdid"] = sender } return postMessage(baseParameters: parameters, timestamp: timestamp) } /// Get the actions sent to a Device. /// /// - Parameters: /// - did: The Device's id /// - startDate: Time of the earliest possible item, in milliseconds since epoch. /// - endDate: Time of the latest possible item, in milliseconds since epoch. /// - count: The count of results, max `100` (default). /// - offset: (Optional) The offset cursor for pagination. /// - order: (Optional) The order of the results, `.ascending` if ommited. /// - name: (Optional) Return only actions with the provided name. /// - Returns: A `Promise<MessagePage>` open class func getActions(did: String, startDate: ArtikTimestamp, endDate: ArtikTimestamp, count: Int = 100, offset: String? = nil, order: PaginationOrder? = nil, name: String? = nil) -> Promise<MessagePage> { let promise = Promise<MessagePage>.pending() let path = SwiftyArtikSettings.basePath + "/actions" let parameters = APIHelpers.removeNilParameters([ "sdid": did, "startDate": startDate, "endDate": endDate, "count": count, "offset": offset, "order": order?.rawValue, "name": name ]) APIHelpers.makeRequest(url: path, method: .get, parameters: parameters, encoding: URLEncoding.queryString).then { response -> Void in if let page = MessagePage(JSON: response) { page.count = count page.name = name promise.fulfill(page) } else { promise.reject(ArtikError.json(reason: .unexpectedFormat)) } }.catch { error -> Void in promise.reject(error) } return promise.promise } /// Get a particular action sent to a Device. /// /// - Parameters: /// - mid: The Action's (message) id. /// - uid: (Optional) The owner's user ID, required when using an `ApplicationToken`. /// - Returns: A `Promise<Message>` open class func getAction(mid: String, uid: String? = nil) -> Promise<Message> { let promise = Promise<Message>.pending() let path = SwiftyArtikSettings.basePath + "/actions" var parameters = [ "mid": mid ] if let uid = uid { parameters["uid"] = uid } APIHelpers.makeRequest(url: path, method: .get, parameters: parameters, encoding: URLEncoding.queryString).then { response -> Void in if let data = (response["data"] as? [[String:Any]])?.first, let message = Message(JSON: data) { promise.fulfill(message) } else { promise.reject(ArtikError.json(reason: .unexpectedFormat)) } }.catch { error -> Void in promise.reject(error) } return promise.promise } /// Get the latest actions sent to a Device. /// /// - Parameters: /// - did: The Device's id. /// - count: The count of results, max 100. /// - name: (Optional) Return only actions with the provided name. /// - Returns: A `Promise<MessagePage>` open class func getLastActions(did: String, count: Int = 100, name: String? = nil) -> Promise<MessagePage> { let promise = Promise<MessagePage>.pending() getActions(did: did, startDate: 1, endDate: currentArtikEpochtime(), count: count, order: .descending, name: name).then { page -> Void in promise.fulfill(page) }.catch { error -> Void in promise.reject(error) } return promise.promise } /// Get the latest action sent to a Device /// /// - Parameter did: The Device's id. /// - Returns: A `Promise<Message?>` open class func getLastAction(did: String) -> Promise<Message?> { let promise = Promise<Message?>.pending() getLastActions(did: did, count: 1).then { page -> Void in if let message = page.data.first { promise.fulfill(message) } else { promise.fulfill(nil) } }.catch { error -> Void in promise.reject(error) } return promise.promise } // MARK: - Analytics /// Get the sum, minimum, maximum, mean and count of message fields that are numerical. Values for `startDate` and `endDate` are rounded to start of minute, and the date range between `startDate` and `endDate` is restricted to 31 days max. /// /// - Parameters: /// - sdid: The source Device's id. /// - startDate: Time of the earliest possible item, in milliseconds since epoch. /// - endDate: Time of the latest possible item, in milliseconds since epoch. /// - field: Message field being queried for analytics. /// - Returns: A `Promise<MessageAggregates>` open class func getAggregates(sdid: String, startDate: ArtikTimestamp, endDate: ArtikTimestamp, field: String) -> Promise<MessageAggregates> { let promise = Promise<MessageAggregates>.pending() let path = SwiftyArtikSettings.basePath + "/messages/analytics/aggregates" let parameters: [String:Any] = [ "sdid": sdid, "startDate": startDate, "endDate": endDate, "field": field ] APIHelpers.makeRequest(url: path, method: .get, parameters: parameters, encoding: URLEncoding.queryString).then { response -> Void in if let aggregate = MessageAggregates(JSON: response) { promise.fulfill(aggregate) } else { promise.reject(ArtikError.json(reason: .unexpectedFormat)) } }.catch { error -> Void in promise.reject(error) } return promise.promise } /// Returns message aggregates over equal intervals, which can be used to draw a histogram. /// /// - Parameters: /// - sdid: The source Device's id. /// - startDate: Time of the earliest possible item, in milliseconds since epoch. /// - endDate: Time of the latest possible item, in milliseconds since epoch. /// - interval: Interval on histogram X-axis. /// - field: Message field being queried for histogram aggregation (histogram Y-axis). /// - Returns: A `Promise<MessageHistogram>` open class func getHistogram(sdid: String, startDate: ArtikTimestamp, endDate: ArtikTimestamp, interval: MessageStatisticsInterval, field: String) -> Promise<MessageHistogram> { let promise = Promise<MessageHistogram>.pending() let path = SwiftyArtikSettings.basePath + "/messages/analytics/histogram" let parameters: [String:Any] = [ "sdid": sdid, "startDate": startDate, "endDate": endDate, "interval": interval.rawValue, "field": field ] APIHelpers.makeRequest(url: path, method: .get, parameters: parameters, encoding: URLEncoding.queryString).then { response -> Void in if let histogram = MessageHistogram(JSON: response) { promise.fulfill(histogram) } else { promise.reject(ArtikError.json(reason: .unexpectedFormat)) } }.catch { error -> Void in promise.reject(error) } return promise.promise } // MARK: - Snapshots /// Get the last received value for all Manifest fields (aka device "state") of devices. /// /// - Parameters: /// - dids: An array containing the Devices' ids. /// - includeTimestamp: (Optional) Include the timestamp of the last modification for each field. /// - Returns: A `Promise<[String:[String:Any]]>` where the `key` is the Device id and the `value` is its snapshot. open class func getSnapshots(dids: [String], includeTimestamp: Bool? = nil) -> Promise<[String:[String:Any]]> { let promise = Promise<[String:[String:Any]]>.pending() let path = SwiftyArtikSettings.basePath + "/messages/snapshots" if dids.count > 0 { var didsString = "" for did in dids { didsString += "\(did)," } APIHelpers.makeRequest(url: path, method: .get, parameters: ["sdids": didsString], encoding: URLEncoding.queryString).then { response -> Void in if let data = response["data"] as? [[String:Any]] { var result = [String:[String:Any]]() for item in data { if let sdid = item["sdid"] as? String, let data = item["data"] as? [String:Any] { result[sdid] = data } else { promise.reject(ArtikError.json(reason: .invalidItem)) return } } promise.fulfill(result) } else { promise.reject(ArtikError.json(reason: .unexpectedFormat)) } }.catch { error -> Void in promise.reject(error) } } else { promise.fulfill([:]) } return promise.promise } /// Get the last received value for all Manifest fields (aka device "state") of a device. /// /// - Parameters: /// - did: The Device's id. /// - includeTimestamp: (Optional) Include the timestamp of the last modification for each field. /// - Returns: A `Promise<[String:Any]>` returning the snapshot open class func getSnapshot(did: String, includeTimestamp: Bool? = nil) -> Promise<[String:Any]> { let promise = Promise<[String:Any]>.pending() getSnapshots(dids: [did], includeTimestamp: includeTimestamp).then { result -> Void in if let snapshot = result[did] { promise.fulfill(snapshot) } else { promise.fulfill([:]) } }.catch { error -> Void in promise.reject(error) } return promise.promise } // MARK: - Private Methods fileprivate class func currentArtikEpochtime() -> Int64 { return Int64(Date().timeIntervalSince1970 * 1000.0) } fileprivate class func postMessage(baseParameters: [String:Any], timestamp: Int64?) -> Promise<String> { let promise = Promise<String>.pending() let path = SwiftyArtikSettings.basePath + "/messages" var parameters = baseParameters if let timestamp = timestamp { parameters["ts"] = timestamp } APIHelpers.makeRequest(url: path, method: .post, parameters: parameters, encoding: JSONEncoding.default).then { response -> Void in if let mid = (response["data"] as? [String:Any])?["mid"] as? String { promise.fulfill(mid) } else { promise.reject(ArtikError.json(reason: .unexpectedFormat)) } }.catch { error -> Void in promise.reject(error) } return promise.promise } }
mit
nastia05/TTU-iOS-Developing-Course
Lecture 3/RawRepresentable.playground/Contents.swift
1
2394
struct Location { let langitude: Double let longitude: Double } struct University: CustomStringConvertible { let name: String let acronim: String let location: Location var description: String { return acronim + " - " + name } } extension University { static var ttu: University { let ttuLocation = Location(langitude: 59.394860, longitude: 24.661367) return University(name: "Tallinn Technological University", acronim: "TTU", location: ttuLocation) } static var mipt: University { let location = Location(langitude: 55.930053, longitude: 37.518253) return University(name: "Moscow Institute of Physics and Technology", acronim: "MIPT", location: location) } } // Xcode uses CustomStringConvertible to show information on the right side let ttu = University.ttu print(ttu) // In order to compare University instances, we must support Equatable protocol func ==(lhs: University, rhs: University) -> Bool { return lhs.name == rhs.name && lhs.acronim == rhs.acronim && lhs.location.langitude == rhs.location.langitude && lhs.location.longitude == rhs.location.longitude } extension University: Equatable { } University.ttu == University.ttu University.mipt == University.ttu // we should know about Array, Dictionary, Set here // In order to use in a set extension University: Hashable { var hashValue: Int { return name.hashValue ^ acronim.hashValue ^ location.langitude.hashValue ^ location.longitude.hashValue } } let universities = Set(arrayLiteral: University.mipt, .ttu) universities.contains(.mipt) // In order to decode and encode University into some entity(of Any type), we must support RawRepresentable protocol extension University: RawRepresentable { // Idealy we should encode and decode to Dictionary type([AnyHashable : Any]) in order to grab any unknown university init?(rawValue: String) { switch rawValue { case "MIPT": self = .mipt case "TTU": self = .ttu default: return nil } } var rawValue: String { return acronim } } // Little test that encoding and deconding will return the same entity let originalCopy = University(rawValue: University.mipt.rawValue) originalCopy == University.mipt
mit
bmancini55/iOSExamples-StaticCells
Swift/StaticCellsSwift/AppDelegate.swift
1
790
// // AppDelegate.swift // StaticCellsSwift // // Created by Brian Mancini on 9/28/14. // Copyright (c) 2014 iOSExamples. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { let tableViewController = TableViewController(style: UITableViewStyle.Grouped) let navController = UINavigationController(rootViewController: tableViewController) self.window = UIWindow(frame: UIScreen.mainScreen().bounds) self.window?.rootViewController = navController self.window?.makeKeyAndVisible() return true } }
mit
jaanussiim/weather-scrape
Tests/WeatherScrape/HourlyTableParse.swift
1
1324
/* * Copyright 2016 JaanusSiim * * 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 XCTest @testable import WeatherScrape class HourlyTableParse: XCTestCase, DataLoader { func testHourlyTableParse() { let data = dataFromFile(named: "Tunniandmed") let table = Page.parseTable(from: data) XCTAssertNotNil(table) guard let t = table else { return } XCTAssertNotNil(t.measuredAt) if let m = t.measuredAt { XCTAssertTrue(m.isSame(Time(year: 2016, month: 06, day: 25, hour: 14, minute: 0)), "Got \(m)") } XCTAssertEqual(85, t.rows.count) guard let first = t.rows.first else { return } XCTAssertEqual(13, first.columns.count) } }
apache-2.0
xnitech/nopeekgifts
NoPeekGifts/GiftsViewController.swift
1
2230
// // FirstViewController.swift // NoPeekGifts // // Created by Mark Gruetzner on 10/31/15. // Copyright © 2015 XNI Technologies, LLC. All rights reserved. // import UIKit class GiftsViewController: UITableViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return giftMgr.gifts.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("GiftCell", forIndexPath: indexPath) let gift = giftMgr.gifts[indexPath.row] as Gift cell.textLabel?.text = gift.name cell.detailTextLabel?.text = gift.desc return cell } override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == UITableViewCellEditingStyle.Delete { giftMgr.gifts.removeAtIndex(indexPath.row) tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Automatic) } } @IBAction func cancelToGiftsViewController(segue:UIStoryboardSegue) { } @IBAction func saveGiftDetail(segue:UIStoryboardSegue) { if let giftDetailsViewController = segue.sourceViewController as? GiftDetailsViewController { if let gift = giftDetailsViewController.giftDetails { // Add gift giftMgr.addGift(gift) // Update the tableView let indexPath = NSIndexPath(forRow: giftMgr.gifts.count-1, inSection: 0) tableView.insertRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Automatic) } } } }
mit
smartystreets/smartystreets-ios-sdk
Tests/SmartyStreetsTests/USZipCodeTests/USZipCodeClientTests.swift
1
2455
import XCTest @testable import SmartyStreets class USZipCodeClientTests: XCTestCase { var sender:RequestCapturingSender! var serializer:USZipCodeSerializer! var batch:USZipCodeBatch! var error:NSError! override func setUp() { super.setUp() self.sender = RequestCapturingSender() self.serializer = USZipCodeSerializer() self.batch = USZipCodeBatch() self.error = nil } override func tearDown() { super.tearDown() self.sender = nil self.serializer = nil self.batch = nil self.error = nil } func testSendingSingleZipOnlyLookup() { let client = USZipCodeClient(sender:self.sender as Any, serializer:self.serializer) var lookup = USZipCodeLookup(city: String(), state: String(), zipcode: "1", inputId: "1") _ = client.sendLookup(lookup:&lookup, error:&self.error) let url = sender.request.getUrl() XCTAssertTrue(url.contains("input_id=1")) XCTAssertTrue(url.contains("zipcode=1")) } func testSendingSingleFullyPopulatedLookup() { let client = USZipCodeClient(sender: self.sender as Any, serializer: self.serializer) var lookup = USZipCodeLookup(city: "1", state: "2", zipcode: "3", inputId: "4") _ = client.sendLookup(lookup: &lookup, error: &self.error) let url = sender.request.getUrl() XCTAssertTrue(url.contains("zipcode=3")) XCTAssertTrue(url.contains("state=2")) XCTAssertTrue(url.contains("city=1")) } func testEmptyBatchNotSent() { let client = USZipCodeClient(sender: self.sender as Any, serializer: self.serializer) _ = client.sendBatch(batch: USZipCodeBatch(), error: &self.error) XCTAssertNil(self.sender.request) } func testSuccessfullySendsBatchOfLookups() { let client = USZipCodeClient(sender: self.sender as Any, serializer: self.serializer) _ = self.batch.add(newAddress: USZipCodeLookup(city: "123 North", state: "Pole", zipcode: String(), inputId: "1"), error: &self.error) _ = self.batch.add(newAddress: USZipCodeLookup(city: String(), state: String(), zipcode: "12345", inputId: "2"), error: &self.error) _ = client.sendBatch(batch: self.batch, error: &self.error) XCTAssertNotNil(sender.request.payload) } }
apache-2.0
Esri/arcgis-runtime-samples-ios
arcgis-ios-sdk-samples/Layers/RGB renderer/RGBRendererViewController.swift
1
2909
// // Copyright 2016 Esri. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import UIKit import ArcGIS class RGBRendererViewController: UIViewController, RGBRendererSettingsViewControllerDelegate { @IBOutlet var mapView: AGSMapView! private var rasterLayer: AGSRasterLayer? override func viewDidLoad() { super.viewDidLoad() // add the source code button item to the right of navigation bar (navigationItem.rightBarButtonItem as! SourceCodeBarButtonItem).filenames = ["RGBRendererViewController", "RGBRendererSettingsViewController", "OptionsTableViewController"] // create raster let raster = AGSRaster(name: "Shasta", extension: "tif") // create raster layer using the raster let rasterLayer = AGSRasterLayer(raster: raster) self.rasterLayer = rasterLayer // initialize a map with raster layer as the basemap let map = AGSMap(basemap: AGSBasemap(baseLayer: rasterLayer)) // assign map to the map view mapView.map = map } // MARK: - RGBRendererSettingsViewControllerDelegate func rgbRendererSettingsViewController(_ rgbRendererSettingsViewController: RGBRendererSettingsViewController, didSelectStretchParameters parameters: AGSStretchParameters) { let renderer = AGSRGBRenderer(stretchParameters: parameters, bandIndexes: [], gammas: [], estimateStatistics: true) rasterLayer?.renderer = renderer } // MARK: - Navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if let navController = segue.destination as? UINavigationController, let controller = navController.viewControllers.first as? RGBRendererSettingsViewController { controller.preferredContentSize = CGSize(width: 375, height: 135) controller.delegate = self if let parameters = (rasterLayer?.renderer as? AGSRGBRenderer)?.stretchParameters { controller.setupForParameters(parameters) } navController.presentationController?.delegate = self } } } extension RGBRendererViewController: UIAdaptivePresentationControllerDelegate { func adaptivePresentationStyle(for controller: UIPresentationController, traitCollection: UITraitCollection) -> UIModalPresentationStyle { return .none } }
apache-2.0
PigDogBay/swift-utils
SwiftUtils/MockIAP.swift
1
2137
// // MockIAP.swift // SwiftUtils // // Created by Mark Bailey on 06/07/2016. // Copyright © 2016 MPD Bailey Technology. All rights reserved. // import Foundation open class MockIAP : IAPInterface { open var observable: IAPObservable open var serverProducts : [IAPProduct] = [] open var retrievedProducts : [IAPProduct] = [] open var canMakePaymentsFlag = true open var failPurchaseFlag = false open var delay : Int64 = 1 public init(){ observable = IAPObservable() } open func canMakePayments() -> Bool { return canMakePaymentsFlag } open func requestPurchase(_ productID: String) { let time = DispatchTime.now() + Double(delay * Int64(NSEC_PER_SEC)) / Double(NSEC_PER_SEC) DispatchQueue.global(qos: .default).asyncAfter(deadline: time) { if self.failPurchaseFlag { self.observable.onPurchaseRequestFailed(productID) } else { self.observable.onPurchaseRequestCompleted(productID) } } } open func restorePurchases() { let time = DispatchTime.now() + Double(delay * Int64(NSEC_PER_SEC)) / Double(NSEC_PER_SEC) DispatchQueue.global(qos: .default).asyncAfter(deadline: time) { for p in self.serverProducts { self.observable.onRestorePurchaseCompleted(p.id) } } } open func requestProducts() { print("request Products") let time = DispatchTime.now() + Double(delay * Int64(NSEC_PER_SEC)) / Double(NSEC_PER_SEC) DispatchQueue.global(qos: .default).asyncAfter(deadline: time) { print("request Products - Dispatched") self.retrievedProducts = self.serverProducts self.observable.onProductsRequestCompleted() } } open func getProduct(_ productID : String) -> IAPProduct? { for p in retrievedProducts { if p.id == productID { return p } } return nil } }
apache-2.0
acsalu/Keymochi
Keymochi/DataChunk.swift
2
6836
// // DataChunk.swift // Keymochi // // Created by Huai-Che Lu on 3/17/16. // Copyright © 2016 Cornell Tech. All rights reserved. // import Foundation import RealmSwift import PAM class DataChunk: Object { fileprivate dynamic var emotionDescription: String? dynamic var symbolKeyEventSequence: SymbolKeyEventSequence? dynamic var backspaceKeyEventSequence: BackspaceKeyEventSequence? dynamic var accelerationDataSequence: MotionDataSequence? dynamic var gyroDataSequence: MotionDataSequence? dynamic var realmId: String = UUID().uuidString dynamic var createdAt: Date = Date() dynamic var parseId: String? dynamic var firebaseKey: String? dynamic var appVersion: String? = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String dynamic var emotionPosition: Int = 0 dynamic var sentiment: Float = 0.0 var emotion: Emotion { return Emotion(position: Position(emotionPosition))! } override class func primaryKey() -> String? { return "realmId" } override var description: String { let symbolKeyEventCount = (symbolKeyEventSequence != nil) ? symbolKeyEventSequence!.keyEvents.count : -1 let accelerationDataPointCount = (accelerationDataSequence != nil) ? accelerationDataSequence!.motionDataPoints.count : -1 let gyroDataPointCount = (gyroDataSequence != nil) ? gyroDataSequence!.motionDataPoints.count : -1 return String(format: "[DataChunk] %d symbols, %d acceleration dps, %d gyro dps", symbolKeyEventCount, accelerationDataPointCount, gyroDataPointCount) } var startTime: Double? { return keyEvents?.first?.downTime } var endTime: Double? { return keyEvents?.last?.upTime } var keyEvents: [KeyEvent]? { guard symbolKeyEventSequence != nil && backspaceKeyEventSequence != nil else { return nil } let symbolKeyEvents: [SymbolKeyEvent] = (symbolKeyEventSequence != nil) ? Array(symbolKeyEventSequence!.keyEvents) : [] let backspaceKeyEvents: [BackspaceKeyEvent] = (backspaceKeyEventSequence != nil) ? Array(backspaceKeyEventSequence!.keyEvents) : [] let keyEvents = ((symbolKeyEvents as [KeyEvent]) + (backspaceKeyEvents as [KeyEvent])).sorted { $0.downTime < $1.downTime } return keyEvents } var accelerationDataPoints: [MotionDataPoint]? { return accelerationDataSequence?.motionDataPoints.map { $0 } } var gyroDataPoints: [MotionDataPoint]? { return gyroDataSequence?.motionDataPoints.map { $0 } } convenience init(emotion: Emotion) { // convenience init(emotion: Emotion, sentiment: Float) { self.init() self.emotionPosition = Int(emotion.position) } // convenience init(emotion: Emotion, sentiment: Sentiment) { // self.init() // self.emotionPosition = Int(emotion.position) // } } extension Array { var pair: [(Element, Element)]? { guard count > 1 else { return nil } return Array<(Element, Element)>(zip(self[0..<count-1], self[1..<count])) } } // MARK: - Stats extension DataChunk { var symbolCounts: [String: Int]? { guard let symbols = symbolKeyEventSequence?.keyEvents.map({ $0.key }) else { return nil } var symbolCounts = [String: Int]() for symbol in symbols { if let symbol = symbol { if symbolCounts[symbol] == nil { symbolCounts[symbol] = 1 } else { symbolCounts[symbol]! += 1 } } } return symbolCounts } var totalNumberOfDeletions: Int? { return backspaceKeyEventSequence?.keyEvents .map { $0.numberOfDeletions } .reduce(0, +) } var interTapDistances: [Double]? { guard let keyEvents = keyEvents else { return nil } return keyEvents.pair? .map { return $0.1.downTime - $0.0.upTime } } var tapDurations: [Double]? { return keyEvents?.map { $0.duration } } var accelerationMagnitudes: [Double]? { return accelerationDataPoints?.map { $0.magnitude } } var gyroMagnitudes: [Double]? { return gyroDataPoints?.map { $0.magnitude } } var dictionaryForm: [String: Any]? { guard let totalNumberOfDeletions = totalNumberOfDeletions, let interTapDistances = interTapDistances, let tapDurations = tapDurations, let accelerationMagnitudes = accelerationMagnitudes, let gyroMagnitudes = gyroMagnitudes, let appVersion = appVersion, let symbolCounts = symbolCounts else { return nil } var dictionary = [String: Any]() dictionary["emotion"] = emotion.tag dictionary["totalNumDel"] = NSNumber(value: totalNumberOfDeletions) dictionary["interTapDist"] = NSArray(array: interTapDistances.map { NSNumber(value: $0) }) dictionary["tapDur"] = NSArray(array: tapDurations.map { NSNumber(value: $0) }) dictionary["accelMag"] = NSArray(array: accelerationMagnitudes.map { NSNumber(value: $0) }) dictionary["gyroMag"] = NSArray(array: gyroMagnitudes.map { NSNumber(value: $0) }) dictionary["appVer"] = NSString(string: appVersion) dictionary["createdAtSince1970"] = createdAt.timeIntervalSince1970 dictionary["sentiment"] = sentiment var puncuationCount = 0 for (symbol, count) in symbolCounts { for scalar in symbol.unicodeScalars { let value = scalar.value if (value >= 65 && value <= 90) || (value >= 97 && value <= 122) || (value >= 48 && value <= 57) { dictionary["symbol_\(symbol)"] = NSNumber(value: count) } else { puncuationCount += count var key: String! switch symbol { case " ": key = "symbol_space" case "!": key = "symbol_exclamation_mark" case ".": key = "symbol_period" case "?": key = "symbol_question_mark" default: continue } dictionary[key] = NSNumber(value: count) } } dictionary["symbol_punctuation"] = NSNumber(value: puncuationCount) } return dictionary } }
bsd-3-clause
121372288/Refresh
Refresh/Base/RefreshHeader.swift
1
6146
// // RefreshHeaderView.swift // RefreshDemo // // Created by 马磊 on 2016/10/18. // Copyright © 2016年 MLCode.com. All rights reserved. // import UIKit import AudioToolbox open class RefreshHeader: RefreshComponent { public required init(_ refreshingCallback: (()->())?) { super.init() refreshingBlock = refreshingCallback } public required init(_ target: Any?, action: Selector) { super.init() addRefreshingTarget(target, action: action) } public required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } /** 这个key用来存储上一次下拉刷新成功的时间 */ var lastUpdatedTimeKey: String = RefreshHeaderTimeKey /** 上一次下拉刷新成功的时间 */ open var lastUpdatedTime: Date? { return UserDefaults.standard.object(forKey: lastUpdatedTimeKey) as? Date } var insetTDelta: CGFloat = 0 /** 忽略多少scrollView的contentInset的top */ open var ignoredScrollViewContentInsetTop: CGFloat = 0 open override func prepare() { super.prepare() frame.size.height = RefreshHeaderHeight } open override func placeSubViews() { super.placeSubViews() // 设置y值(当自己的高度发生改变了,肯定要重新调整Y值,所以放到placeSubviews方法中设置y值) self.frame.origin.y = -self.frame.size.height - self.ignoredScrollViewContentInsetTop } open override func scrollView(contentOffset changed: [NSKeyValueChangeKey : Any]?) { super.scrollView(contentOffset: changed) guard let scrollView = scrollView else { return } // 在刷新的refreshing状态 switch state { case .refreshing: if self.window == nil { return } // sectionheader停留解决 let scrollViewOriginalInset = self.scrollViewOriginalInset ?? .zero var insetT = max(-scrollView.contentOffset.y, scrollViewOriginalInset.top) insetT = min(insetT, frame.size.height + scrollViewOriginalInset.top) scrollView.mlInset.top = insetT insetTDelta = scrollViewOriginalInset.top - insetT default: // 跳转到下一个控制器时,contentInset可能会变 scrollViewOriginalInset = scrollView.mlInset // 当前的contentOffset let offsetY = scrollView.contentOffset.y // 头部控件刚好出现的offsetY let happenOffsetY = -(scrollViewOriginalInset?.top ?? 0) // 如果是向上滚动到看不见头部控件,直接返回 // >= -> > if offsetY > happenOffsetY { return } // 普通 和 即将刷新 的临界点 let normal2pullingOffsetY = happenOffsetY - self.frame.size.height let pullingPercent = (happenOffsetY - offsetY) / self.frame.size.height if scrollView.isDragging { // 如果正在拖拽 self.pullingPercent = pullingPercent if state == .idle || state == .willRefresh, offsetY < normal2pullingOffsetY { // 转为即将刷新状态 state = .pulling } else if state == .pulling, offsetY >= normal2pullingOffsetY { // 转为普通状态 state = .idle } } else if state == .pulling {// 即将刷新 && 手松开 // 开始刷新 beginRefreshing() } else if pullingPercent < 1 { self.pullingPercent = pullingPercent } } } public override var state: RefreshState { didSet { if oldValue == state { return } if state == .pulling { //建立的SystemSoundID对象 if #available(iOS 10.0, *) { let impactLight = UIImpactFeedbackGenerator(style: .light) impactLight.impactOccurred() } else { AudioServicesPlaySystemSound(1519) } } switch state { case .idle: if oldValue != .refreshing { return } // 保存刷新时间 UserDefaults.standard.set(Date(), forKey: lastUpdatedTimeKey) UserDefaults.standard.synchronize() // 恢复inset和offset UIView.animate(withDuration: RefreshSlowAnimationDuration, animations: { self.scrollView?.mlInset.top += self.insetTDelta // 自动调整透明度 if self.isAutomaticallyChangeAlpha == true { self.alpha = 0.0 } }) { (isFinished) in self.pullingPercent = 0.0 self.endRefreshingCompletionBlock?() } case .refreshing: DispatchQueue.main.async { UIView.animate(withDuration: RefreshFastAnimationDuration, animations: { if self.scrollView?.panGestureRecognizer.state != .cancelled { let top = (self.scrollViewOriginalInset?.top ?? 0) + self.frame.size.height // 增加滚动区域top self.scrollView?.mlInset.top = top // 设置滚动位置 var offset = (self.scrollView?.contentOffset) ?? .zero offset.y = -top self.scrollView?.setContentOffset(offset, animated: false) } }, completion: { (isFinished) in self.executeRefreshingCallback() }) } default: break } } } }
mit
kousun12/RxSwift
RxExample/RxExample/Services/ReachabilityService.swift
6
1538
// // ReachabilityService.swift // RxExample // // Created by Vodovozov Gleb on 22.10.2015. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // #if !RX_NO_MODULE import RxSwift #endif public enum ReachabilityStatus { case Reachable, Unreachable } class ReachabilityService { private let reachabilityRef = try! Reachability.reachabilityForInternetConnection() private let _reachabilityChangedSubject = PublishSubject<ReachabilityStatus>() private var reachabilityChanged: Observable<ReachabilityStatus> { get { return _reachabilityChangedSubject.asObservable() } } // singleton static let sharedReachabilityService = ReachabilityService() init(){ reachabilityRef.whenReachable = { reachability in self._reachabilityChangedSubject.on(.Next(.Reachable)) } reachabilityRef.whenUnreachable = { reachability in self._reachabilityChangedSubject.on(.Next(.Unreachable)) } try! reachabilityRef.startNotifier() } } extension ObservableConvertibleType { func retryOnBecomesReachable(valueOnFailure:E, reachabilityService: ReachabilityService) -> Observable<E> { return self.asObservable() .catchError { (e) -> Observable<E> in reachabilityService.reachabilityChanged .filter { $0 == .Reachable } .flatMap { _ in failWith(e) } .startWith(valueOnFailure) } .retry() } }
mit
leizh007/HiPDA
HiPDA/HiPDA/Sections/Home/SDWebImageManager+HiPDA.swift
1
1546
// // SDWebImageManag+HiPDA.swift // HiPDA // // Created by leizh007 on 2017/5/23. // Copyright © 2017年 HiPDA. All rights reserved. // import Foundation import SDWebImage typealias ImageDataLoadResult = HiPDA.Result<Data, NSError> typealias ImageDataLoadCompletion = (ImageDataLoadResult) -> Void extension SDWebImageManager { func loadImageData(with url: URL?, completed completedBlock: ImageDataLoadCompletion? = nil) { guard let url = url, let completedBlock = completedBlock else { return } SDWebImageManager.shared().loadImage(with: url, options: [.highPriority], progress: nil) { (image, data, error, _, _, _) in if let error = error { completedBlock(.failure(error as NSError)) } else if let data = data { completedBlock(.success(data)) } else if let image = image { DispatchQueue.global().async { if let data = UIImageJPEGRepresentation(image, 1.0) { DispatchQueue.main.async { completedBlock(.success(data)) } } else { DispatchQueue.main.async { completedBlock(.failure(NSError(domain: C.URL.HiPDA.image, code: -1, userInfo: nil))) } } } } else { completedBlock(.failure(NSError(domain: C.URL.HiPDA.image, code: -1, userInfo: nil))) } } } }
mit
alickbass/SweetRouter
SweetRouterTests/TestRoute.swift
1
699
// // TestRoute.swift // SweetRouter // // Created by Oleksii on 17/03/2017. // Copyright © 2017 ViolentOctopus. All rights reserved. // import XCTest import SweetRouter class TestRoute: XCTestCase { func testUrlRouteEquatable() { XCTAssertEqual(URL.Route(at: "myPath").query(("user", nil), ("date", "12.04.02")), URL.Route(path: ["myPath"], query: URL.Query(("user", nil), ("date", "12.04.02")))) XCTAssertEqual(URL.Route(at: "myPath").fragment("fragment"), URL.Route(path: ["myPath"], fragment: "fragment")) XCTAssertNotEqual(URL.Route(at: "myPath").query(("user", nil)).fragment("fragment"), URL.Route(path: ["myPath"], fragment: "fragment")) } }
mit
jakub-tucek/fit-checker-2.0
fit-checker/networking/EduxRetrier.swift
1
2436
// // EduxRetrier.swift // fit-checker // // Created by Josef Dolezal on 20/01/2017. // Copyright © 2017 Josef Dolezal. All rights reserved. // import Foundation import Alamofire /// Allows to retry failed operations. If operation failed because of /// missing cookies (uh, authorization) retrier tries to login /// user with stored credential and if it's successfull, calls original /// request again. class EduxRetrier: RequestRetrier { /// Network request manager - private weak var networkController: NetworkController? /// Thread safe token refreshning indicator private var isRefreshing = false /// Synchronizing queue private let accessQueue = DispatchQueue(label: "EduxRetrier") init(networkController: NetworkController) { self.networkController = networkController } /// Determines wheter /// /// - Parameters: /// - manager: Requests session manager /// - request: Failed request /// - error: Request error /// - completion: Retry decision public func should(_ manager: SessionManager, retry request: Request, with error: Error, completion: @escaping RequestRetryCompletion) { Logger.shared.info("Ooops, request failed") // Run validation on serial queue accessQueue.async { [weak self] in let keychain = Keechain(service: .edux) // Retry only on recognized errors guard case EduxValidators.ValidationError.badCredentials = error else { Logger.shared.info("Unrecognized error, not retrying.") completion(false, 0.0) return } guard self?.isRefreshing == false, let networkController = self?.networkController, let (username, password) = keychain.getAccount() else { return } Logger.shared.info("Retrying request") self?.isRefreshing = true let promise = networkController.authorizeUser(with: username, password: password) // Try to authorize user promise.success = { completion(true, 0.0) } promise.failure = { completion(false, 0.0) } self?.isRefreshing = false } } }
mit
JaySonGD/SwiftDayToDay
SQL/SQLTests/SQLTests.swift
1
947
// // SQLTests.swift // SQLTests // // Created by czljcb on 16/3/21. // Copyright © 2016年 lQ. All rights reserved. // import XCTest @testable import SQL class SQLTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct results. } func testPerformanceExample() { // This is an example of a performance test case. self.measureBlock { // Put the code you want to measure the time of here. } } }
mit
sschiau/swift
stdlib/public/core/SequenceAlgorithms.swift
6
31690
//===--- SequenceAlgorithms.swift -----------------------------*- swift -*-===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// //===----------------------------------------------------------------------===// // enumerated() //===----------------------------------------------------------------------===// extension Sequence { /// Returns a sequence of pairs (*n*, *x*), where *n* represents a /// consecutive integer starting at zero and *x* represents an element of /// the sequence. /// /// This example enumerates the characters of the string "Swift" and prints /// each character along with its place in the string. /// /// for (n, c) in "Swift".enumerated() { /// print("\(n): '\(c)'") /// } /// // Prints "0: 'S'" /// // Prints "1: 'w'" /// // Prints "2: 'i'" /// // Prints "3: 'f'" /// // Prints "4: 't'" /// /// When you enumerate a collection, the integer part of each pair is a counter /// for the enumeration, but is not necessarily the index of the paired value. /// These counters can be used as indices only in instances of zero-based, /// integer-indexed collections, such as `Array` and `ContiguousArray`. For /// other collections the counters may be out of range or of the wrong type /// to use as an index. To iterate over the elements of a collection with its /// indices, use the `zip(_:_:)` function. /// /// This example iterates over the indices and elements of a set, building a /// list consisting of indices of names with five or fewer letters. /// /// let names: Set = ["Sofia", "Camilla", "Martina", "Mateo", "Nicolás"] /// var shorterIndices: [Set<String>.Index] = [] /// for (i, name) in zip(names.indices, names) { /// if name.count <= 5 { /// shorterIndices.append(i) /// } /// } /// /// Now that the `shorterIndices` array holds the indices of the shorter /// names in the `names` set, you can use those indices to access elements in /// the set. /// /// for i in shorterIndices { /// print(names[i]) /// } /// // Prints "Sofia" /// // Prints "Mateo" /// /// - Returns: A sequence of pairs enumerating the sequence. /// /// - Complexity: O(1) @inlinable // protocol-only public func enumerated() -> EnumeratedSequence<Self> { return EnumeratedSequence(_base: self) } } //===----------------------------------------------------------------------===// // min(), max() //===----------------------------------------------------------------------===// extension Sequence { /// Returns the minimum element in the sequence, using the given predicate as /// the comparison between elements. /// /// The predicate must be a *strict weak ordering* over the elements. That /// is, for any elements `a`, `b`, and `c`, the following conditions must /// hold: /// /// - `areInIncreasingOrder(a, a)` is always `false`. (Irreflexivity) /// - If `areInIncreasingOrder(a, b)` and `areInIncreasingOrder(b, c)` are /// both `true`, then `areInIncreasingOrder(a, c)` is also /// `true`. (Transitive comparability) /// - Two elements are *incomparable* if neither is ordered before the other /// according to the predicate. If `a` and `b` are incomparable, and `b` /// and `c` are incomparable, then `a` and `c` are also incomparable. /// (Transitive incomparability) /// /// This example shows how to use the `min(by:)` method on a /// dictionary to find the key-value pair with the lowest value. /// /// let hues = ["Heliotrope": 296, "Coral": 16, "Aquamarine": 156] /// let leastHue = hues.min { a, b in a.value < b.value } /// print(leastHue) /// // Prints "Optional(("Coral", 16))" /// /// - Parameter areInIncreasingOrder: A predicate that returns `true` /// if its first argument should be ordered before its second /// argument; otherwise, `false`. /// - Returns: The sequence's minimum element, according to /// `areInIncreasingOrder`. If the sequence has no elements, returns /// `nil`. /// /// - Complexity: O(*n*), where *n* is the length of the sequence. @inlinable // protocol-only @warn_unqualified_access public func min( by areInIncreasingOrder: (Element, Element) throws -> Bool ) rethrows -> Element? { var it = makeIterator() guard var result = it.next() else { return nil } while let e = it.next() { if try areInIncreasingOrder(e, result) { result = e } } return result } /// Returns the maximum element in the sequence, using the given predicate /// as the comparison between elements. /// /// The predicate must be a *strict weak ordering* over the elements. That /// is, for any elements `a`, `b`, and `c`, the following conditions must /// hold: /// /// - `areInIncreasingOrder(a, a)` is always `false`. (Irreflexivity) /// - If `areInIncreasingOrder(a, b)` and `areInIncreasingOrder(b, c)` are /// both `true`, then `areInIncreasingOrder(a, c)` is also /// `true`. (Transitive comparability) /// - Two elements are *incomparable* if neither is ordered before the other /// according to the predicate. If `a` and `b` are incomparable, and `b` /// and `c` are incomparable, then `a` and `c` are also incomparable. /// (Transitive incomparability) /// /// This example shows how to use the `max(by:)` method on a /// dictionary to find the key-value pair with the highest value. /// /// let hues = ["Heliotrope": 296, "Coral": 16, "Aquamarine": 156] /// let greatestHue = hues.max { a, b in a.value < b.value } /// print(greatestHue) /// // Prints "Optional(("Heliotrope", 296))" /// /// - Parameter areInIncreasingOrder: A predicate that returns `true` if its /// first argument should be ordered before its second argument; /// otherwise, `false`. /// - Returns: The sequence's maximum element if the sequence is not empty; /// otherwise, `nil`. /// /// - Complexity: O(*n*), where *n* is the length of the sequence. @inlinable // protocol-only @warn_unqualified_access public func max( by areInIncreasingOrder: (Element, Element) throws -> Bool ) rethrows -> Element? { var it = makeIterator() guard var result = it.next() else { return nil } while let e = it.next() { if try areInIncreasingOrder(result, e) { result = e } } return result } } extension Sequence where Element: Comparable { /// Returns the minimum element in the sequence. /// /// This example finds the smallest value in an array of height measurements. /// /// let heights = [67.5, 65.7, 64.3, 61.1, 58.5, 60.3, 64.9] /// let lowestHeight = heights.min() /// print(lowestHeight) /// // Prints "Optional(58.5)" /// /// - Returns: The sequence's minimum element. If the sequence has no /// elements, returns `nil`. /// /// - Complexity: O(*n*), where *n* is the length of the sequence. @inlinable @warn_unqualified_access public func min() -> Element? { return self.min(by: <) } /// Returns the maximum element in the sequence. /// /// This example finds the largest value in an array of height measurements. /// /// let heights = [67.5, 65.7, 64.3, 61.1, 58.5, 60.3, 64.9] /// let greatestHeight = heights.max() /// print(greatestHeight) /// // Prints "Optional(67.5)" /// /// - Returns: The sequence's maximum element. If the sequence has no /// elements, returns `nil`. /// /// - Complexity: O(*n*), where *n* is the length of the sequence. @inlinable @warn_unqualified_access public func max() -> Element? { return self.max(by: <) } } //===----------------------------------------------------------------------===// // starts(with:) //===----------------------------------------------------------------------===// extension Sequence { /// Returns a Boolean value indicating whether the initial elements of the /// sequence are equivalent to the elements in another sequence, using /// the given predicate as the equivalence test. /// /// The predicate must be a *equivalence relation* over the elements. That /// is, for any elements `a`, `b`, and `c`, the following conditions must /// hold: /// /// - `areEquivalent(a, a)` is always `true`. (Reflexivity) /// - `areEquivalent(a, b)` implies `areEquivalent(b, a)`. (Symmetry) /// - If `areEquivalent(a, b)` and `areEquivalent(b, c)` are both `true`, then /// `areEquivalent(a, c)` is also `true`. (Transitivity) /// /// - Parameters: /// - possiblePrefix: A sequence to compare to this sequence. /// - areEquivalent: A predicate that returns `true` if its two arguments /// are equivalent; otherwise, `false`. /// - Returns: `true` if the initial elements of the sequence are equivalent /// to the elements of `possiblePrefix`; otherwise, `false`. If /// `possiblePrefix` has no elements, the return value is `true`. /// /// - Complexity: O(*m*), where *m* is the lesser of the length of the /// sequence and the length of `possiblePrefix`. @inlinable public func starts<PossiblePrefix: Sequence>( with possiblePrefix: PossiblePrefix, by areEquivalent: (Element, PossiblePrefix.Element) throws -> Bool ) rethrows -> Bool { var possiblePrefixIterator = possiblePrefix.makeIterator() for e0 in self { if let e1 = possiblePrefixIterator.next() { if try !areEquivalent(e0, e1) { return false } } else { return true } } return possiblePrefixIterator.next() == nil } } extension Sequence where Element: Equatable { /// Returns a Boolean value indicating whether the initial elements of the /// sequence are the same as the elements in another sequence. /// /// This example tests whether one countable range begins with the elements /// of another countable range. /// /// let a = 1...3 /// let b = 1...10 /// /// print(b.starts(with: a)) /// // Prints "true" /// /// Passing a sequence with no elements or an empty collection as /// `possiblePrefix` always results in `true`. /// /// print(b.starts(with: [])) /// // Prints "true" /// /// - Parameter possiblePrefix: A sequence to compare to this sequence. /// - Returns: `true` if the initial elements of the sequence are the same as /// the elements of `possiblePrefix`; otherwise, `false`. If /// `possiblePrefix` has no elements, the return value is `true`. /// /// - Complexity: O(*m*), where *m* is the lesser of the length of the /// sequence and the length of `possiblePrefix`. @inlinable public func starts<PossiblePrefix: Sequence>( with possiblePrefix: PossiblePrefix ) -> Bool where PossiblePrefix.Element == Element { return self.starts(with: possiblePrefix, by: ==) } } //===----------------------------------------------------------------------===// // elementsEqual() //===----------------------------------------------------------------------===// extension Sequence { /// Returns a Boolean value indicating whether this sequence and another /// sequence contain equivalent elements in the same order, using the given /// predicate as the equivalence test. /// /// At least one of the sequences must be finite. /// /// The predicate must be a *equivalence relation* over the elements. That /// is, for any elements `a`, `b`, and `c`, the following conditions must /// hold: /// /// - `areEquivalent(a, a)` is always `true`. (Reflexivity) /// - `areEquivalent(a, b)` implies `areEquivalent(b, a)`. (Symmetry) /// - If `areEquivalent(a, b)` and `areEquivalent(b, c)` are both `true`, then /// `areEquivalent(a, c)` is also `true`. (Transitivity) /// /// - Parameters: /// - other: A sequence to compare to this sequence. /// - areEquivalent: A predicate that returns `true` if its two arguments /// are equivalent; otherwise, `false`. /// - Returns: `true` if this sequence and `other` contain equivalent items, /// using `areEquivalent` as the equivalence test; otherwise, `false.` /// /// - Complexity: O(*m*), where *m* is the lesser of the length of the /// sequence and the length of `other`. @inlinable public func elementsEqual<OtherSequence: Sequence>( _ other: OtherSequence, by areEquivalent: (Element, OtherSequence.Element) throws -> Bool ) rethrows -> Bool { var iter1 = self.makeIterator() var iter2 = other.makeIterator() while true { switch (iter1.next(), iter2.next()) { case let (e1?, e2?): if try !areEquivalent(e1, e2) { return false } case (_?, nil), (nil, _?): return false case (nil, nil): return true } } } } extension Sequence where Element: Equatable { /// Returns a Boolean value indicating whether this sequence and another /// sequence contain the same elements in the same order. /// /// At least one of the sequences must be finite. /// /// This example tests whether one countable range shares the same elements /// as another countable range and an array. /// /// let a = 1...3 /// let b = 1...10 /// /// print(a.elementsEqual(b)) /// // Prints "false" /// print(a.elementsEqual([1, 2, 3])) /// // Prints "true" /// /// - Parameter other: A sequence to compare to this sequence. /// - Returns: `true` if this sequence and `other` contain the same elements /// in the same order. /// /// - Complexity: O(*m*), where *m* is the lesser of the length of the /// sequence and the length of `other`. @inlinable public func elementsEqual<OtherSequence: Sequence>( _ other: OtherSequence ) -> Bool where OtherSequence.Element == Element { return self.elementsEqual(other, by: ==) } } //===----------------------------------------------------------------------===// // lexicographicallyPrecedes() //===----------------------------------------------------------------------===// extension Sequence { /// Returns a Boolean value indicating whether the sequence precedes another /// sequence in a lexicographical (dictionary) ordering, using the given /// predicate to compare elements. /// /// The predicate must be a *strict weak ordering* over the elements. That /// is, for any elements `a`, `b`, and `c`, the following conditions must /// hold: /// /// - `areInIncreasingOrder(a, a)` is always `false`. (Irreflexivity) /// - If `areInIncreasingOrder(a, b)` and `areInIncreasingOrder(b, c)` are /// both `true`, then `areInIncreasingOrder(a, c)` is also /// `true`. (Transitive comparability) /// - Two elements are *incomparable* if neither is ordered before the other /// according to the predicate. If `a` and `b` are incomparable, and `b` /// and `c` are incomparable, then `a` and `c` are also incomparable. /// (Transitive incomparability) /// /// - Parameters: /// - other: A sequence to compare to this sequence. /// - areInIncreasingOrder: A predicate that returns `true` if its first /// argument should be ordered before its second argument; otherwise, /// `false`. /// - Returns: `true` if this sequence precedes `other` in a dictionary /// ordering as ordered by `areInIncreasingOrder`; otherwise, `false`. /// /// - Note: This method implements the mathematical notion of lexicographical /// ordering, which has no connection to Unicode. If you are sorting /// strings to present to the end user, use `String` APIs that perform /// localized comparison instead. /// /// - Complexity: O(*m*), where *m* is the lesser of the length of the /// sequence and the length of `other`. @inlinable public func lexicographicallyPrecedes<OtherSequence: Sequence>( _ other: OtherSequence, by areInIncreasingOrder: (Element, Element) throws -> Bool ) rethrows -> Bool where OtherSequence.Element == Element { var iter1 = self.makeIterator() var iter2 = other.makeIterator() while true { if let e1 = iter1.next() { if let e2 = iter2.next() { if try areInIncreasingOrder(e1, e2) { return true } if try areInIncreasingOrder(e2, e1) { return false } continue // Equivalent } return false } return iter2.next() != nil } } } extension Sequence where Element: Comparable { /// Returns a Boolean value indicating whether the sequence precedes another /// sequence in a lexicographical (dictionary) ordering, using the /// less-than operator (`<`) to compare elements. /// /// This example uses the `lexicographicallyPrecedes` method to test which /// array of integers comes first in a lexicographical ordering. /// /// let a = [1, 2, 2, 2] /// let b = [1, 2, 3, 4] /// /// print(a.lexicographicallyPrecedes(b)) /// // Prints "true" /// print(b.lexicographicallyPrecedes(b)) /// // Prints "false" /// /// - Parameter other: A sequence to compare to this sequence. /// - Returns: `true` if this sequence precedes `other` in a dictionary /// ordering; otherwise, `false`. /// /// - Note: This method implements the mathematical notion of lexicographical /// ordering, which has no connection to Unicode. If you are sorting /// strings to present to the end user, use `String` APIs that /// perform localized comparison. /// /// - Complexity: O(*m*), where *m* is the lesser of the length of the /// sequence and the length of `other`. @inlinable public func lexicographicallyPrecedes<OtherSequence: Sequence>( _ other: OtherSequence ) -> Bool where OtherSequence.Element == Element { return self.lexicographicallyPrecedes(other, by: <) } } //===----------------------------------------------------------------------===// // contains() //===----------------------------------------------------------------------===// extension Sequence { /// Returns a Boolean value indicating whether the sequence contains an /// element that satisfies the given predicate. /// /// You can use the predicate to check for an element of a type that /// doesn't conform to the `Equatable` protocol, such as the /// `HTTPResponse` enumeration in this example. /// /// enum HTTPResponse { /// case ok /// case error(Int) /// } /// /// let lastThreeResponses: [HTTPResponse] = [.ok, .ok, .error(404)] /// let hadError = lastThreeResponses.contains { element in /// if case .error = element { /// return true /// } else { /// return false /// } /// } /// // 'hadError' == true /// /// Alternatively, a predicate can be satisfied by a range of `Equatable` /// elements or a general condition. This example shows how you can check an /// array for an expense greater than $100. /// /// let expenses = [21.37, 55.21, 9.32, 10.18, 388.77, 11.41] /// let hasBigPurchase = expenses.contains { $0 > 100 } /// // 'hasBigPurchase' == true /// /// - Parameter predicate: A closure that takes an element of the sequence /// as its argument and returns a Boolean value that indicates whether /// the passed element represents a match. /// - Returns: `true` if the sequence contains an element that satisfies /// `predicate`; otherwise, `false`. /// /// - Complexity: O(*n*), where *n* is the length of the sequence. @inlinable public func contains( where predicate: (Element) throws -> Bool ) rethrows -> Bool { for e in self { if try predicate(e) { return true } } return false } /// Returns a Boolean value indicating whether every element of a sequence /// satisfies a given predicate. /// /// The following code uses this method to test whether all the names in an /// array have at least five characters: /// /// let names = ["Sofia", "Camilla", "Martina", "Mateo", "Nicolás"] /// let allHaveAtLeastFive = names.allSatisfy({ $0.count >= 5 }) /// // allHaveAtLeastFive == true /// /// - Parameter predicate: A closure that takes an element of the sequence /// as its argument and returns a Boolean value that indicates whether /// the passed element satisfies a condition. /// - Returns: `true` if the sequence contains only elements that satisfy /// `predicate`; otherwise, `false`. /// /// - Complexity: O(*n*), where *n* is the length of the sequence. @inlinable public func allSatisfy( _ predicate: (Element) throws -> Bool ) rethrows -> Bool { return try !contains { try !predicate($0) } } } extension Sequence where Element: Equatable { /// Returns a Boolean value indicating whether the sequence contains the /// given element. /// /// This example checks to see whether a favorite actor is in an array /// storing a movie's cast. /// /// let cast = ["Vivien", "Marlon", "Kim", "Karl"] /// print(cast.contains("Marlon")) /// // Prints "true" /// print(cast.contains("James")) /// // Prints "false" /// /// - Parameter element: The element to find in the sequence. /// - Returns: `true` if the element was found in the sequence; otherwise, /// `false`. /// /// - Complexity: O(*n*), where *n* is the length of the sequence. @inlinable public func contains(_ element: Element) -> Bool { if let result = _customContainsEquatableElement(element) { return result } else { return self.contains { $0 == element } } } } //===----------------------------------------------------------------------===// // reduce() //===----------------------------------------------------------------------===// extension Sequence { /// Returns the result of combining the elements of the sequence using the /// given closure. /// /// Use the `reduce(_:_:)` method to produce a single value from the elements /// of an entire sequence. For example, you can use this method on an array /// of numbers to find their sum or product. /// /// The `nextPartialResult` closure is called sequentially with an /// accumulating value initialized to `initialResult` and each element of /// the sequence. This example shows how to find the sum of an array of /// numbers. /// /// let numbers = [1, 2, 3, 4] /// let numberSum = numbers.reduce(0, { x, y in /// x + y /// }) /// // numberSum == 10 /// /// When `numbers.reduce(_:_:)` is called, the following steps occur: /// /// 1. The `nextPartialResult` closure is called with `initialResult`---`0` /// in this case---and the first element of `numbers`, returning the sum: /// `1`. /// 2. The closure is called again repeatedly with the previous call's return /// value and each element of the sequence. /// 3. When the sequence is exhausted, the last value returned from the /// closure is returned to the caller. /// /// If the sequence has no elements, `nextPartialResult` is never executed /// and `initialResult` is the result of the call to `reduce(_:_:)`. /// /// - Parameters: /// - initialResult: The value to use as the initial accumulating value. /// `initialResult` is passed to `nextPartialResult` the first time the /// closure is executed. /// - nextPartialResult: A closure that combines an accumulating value and /// an element of the sequence into a new accumulating value, to be used /// in the next call of the `nextPartialResult` closure or returned to /// the caller. /// - Returns: The final accumulated value. If the sequence has no elements, /// the result is `initialResult`. /// /// - Complexity: O(*n*), where *n* is the length of the sequence. @inlinable public func reduce<Result>( _ initialResult: Result, _ nextPartialResult: (_ partialResult: Result, Element) throws -> Result ) rethrows -> Result { var accumulator = initialResult for element in self { accumulator = try nextPartialResult(accumulator, element) } return accumulator } /// Returns the result of combining the elements of the sequence using the /// given closure. /// /// Use the `reduce(into:_:)` method to produce a single value from the /// elements of an entire sequence. For example, you can use this method on an /// array of integers to filter adjacent equal entries or count frequencies. /// /// This method is preferred over `reduce(_:_:)` for efficiency when the /// result is a copy-on-write type, for example an Array or a Dictionary. /// /// The `updateAccumulatingResult` closure is called sequentially with a /// mutable accumulating value initialized to `initialResult` and each element /// of the sequence. This example shows how to build a dictionary of letter /// frequencies of a string. /// /// let letters = "abracadabra" /// let letterCount = letters.reduce(into: [:]) { counts, letter in /// counts[letter, default: 0] += 1 /// } /// // letterCount == ["a": 5, "b": 2, "r": 2, "c": 1, "d": 1] /// /// When `letters.reduce(into:_:)` is called, the following steps occur: /// /// 1. The `updateAccumulatingResult` closure is called with the initial /// accumulating value---`[:]` in this case---and the first character of /// `letters`, modifying the accumulating value by setting `1` for the key /// `"a"`. /// 2. The closure is called again repeatedly with the updated accumulating /// value and each element of the sequence. /// 3. When the sequence is exhausted, the accumulating value is returned to /// the caller. /// /// If the sequence has no elements, `updateAccumulatingResult` is never /// executed and `initialResult` is the result of the call to /// `reduce(into:_:)`. /// /// - Parameters: /// - initialResult: The value to use as the initial accumulating value. /// - updateAccumulatingResult: A closure that updates the accumulating /// value with an element of the sequence. /// - Returns: The final accumulated value. If the sequence has no elements, /// the result is `initialResult`. /// /// - Complexity: O(*n*), where *n* is the length of the sequence. @inlinable public func reduce<Result>( into initialResult: __owned Result, _ updateAccumulatingResult: (_ partialResult: inout Result, Element) throws -> () ) rethrows -> Result { var accumulator = initialResult for element in self { try updateAccumulatingResult(&accumulator, element) } return accumulator } } //===----------------------------------------------------------------------===// // reversed() //===----------------------------------------------------------------------===// extension Sequence { /// Returns an array containing the elements of this sequence in reverse /// order. /// /// The sequence must be finite. /// /// - Returns: An array containing the elements of this sequence in /// reverse order. /// /// - Complexity: O(*n*), where *n* is the length of the sequence. @inlinable public __consuming func reversed() -> [Element] { // FIXME(performance): optimize to 1 pass? But Array(self) can be // optimized to a memcpy() sometimes. Those cases are usually collections, // though. var result = Array(self) let count = result.count for i in 0..<count/2 { result.swapAt(i, count - ((i + 1) as Int)) } return result } } //===----------------------------------------------------------------------===// // flatMap() //===----------------------------------------------------------------------===// extension Sequence { /// Returns an array containing the concatenated results of calling the /// given transformation with each element of this sequence. /// /// Use this method to receive a single-level collection when your /// transformation produces a sequence or collection for each element. /// /// In this example, note the difference in the result of using `map` and /// `flatMap` with a transformation that returns an array. /// /// let numbers = [1, 2, 3, 4] /// /// let mapped = numbers.map { Array(repeating: $0, count: $0) } /// // [[1], [2, 2], [3, 3, 3], [4, 4, 4, 4]] /// /// let flatMapped = numbers.flatMap { Array(repeating: $0, count: $0) } /// // [1, 2, 2, 3, 3, 3, 4, 4, 4, 4] /// /// In fact, `s.flatMap(transform)` is equivalent to /// `Array(s.map(transform).joined())`. /// /// - Parameter transform: A closure that accepts an element of this /// sequence as its argument and returns a sequence or collection. /// - Returns: The resulting flattened array. /// /// - Complexity: O(*m* + *n*), where *n* is the length of this sequence /// and *m* is the length of the result. @inlinable public func flatMap<SegmentOfResult: Sequence>( _ transform: (Element) throws -> SegmentOfResult ) rethrows -> [SegmentOfResult.Element] { var result: [SegmentOfResult.Element] = [] for element in self { result.append(contentsOf: try transform(element)) } return result } } extension Sequence { /// Returns an array containing the non-`nil` results of calling the given /// transformation with each element of this sequence. /// /// Use this method to receive an array of non-optional values when your /// transformation produces an optional value. /// /// In this example, note the difference in the result of using `map` and /// `compactMap` with a transformation that returns an optional `Int` value. /// /// let possibleNumbers = ["1", "2", "three", "///4///", "5"] /// /// let mapped: [Int?] = possibleNumbers.map { str in Int(str) } /// // [1, 2, nil, nil, 5] /// /// let compactMapped: [Int] = possibleNumbers.compactMap { str in Int(str) } /// // [1, 2, 5] /// /// - Parameter transform: A closure that accepts an element of this /// sequence as its argument and returns an optional value. /// - Returns: An array of the non-`nil` results of calling `transform` /// with each element of the sequence. /// /// - Complexity: O(*m* + *n*), where *n* is the length of this sequence /// and *m* is the length of the result. @inlinable // protocol-only public func compactMap<ElementOfResult>( _ transform: (Element) throws -> ElementOfResult? ) rethrows -> [ElementOfResult] { return try _compactMap(transform) } // The implementation of flatMap accepting a closure with an optional result. // Factored out into a separate functions in order to be used in multiple // overloads. @inlinable // protocol-only @inline(__always) public func _compactMap<ElementOfResult>( _ transform: (Element) throws -> ElementOfResult? ) rethrows -> [ElementOfResult] { var result: [ElementOfResult] = [] for element in self { if let newElement = try transform(element) { result.append(newElement) } } return result } }
apache-2.0
chrisbudro/GrowlerHour
growlers/DisplayImageService.swift
1
888
// // DisplayImageService.swift // growlers // // Created by Chris Budro on 10/13/15. // Copyright © 2015 chrisbudro. All rights reserved. // import UIKit import AlamofireImage let kDisplayImageFadeDuration = 0.4 class DisplayImageService { class func setImageView(imageView: UIImageView?, withUrlString urlString: String?, placeholderImage: UIImage?) { if let imageView = imageView { if let urlString = urlString, url = NSURL(string: urlString) { let size = imageView.frame.size let filter = AspectScaledToFillSizeFilter(size: size) imageView.af_setImageWithURL(url, placeholderImage: nil, filter: filter, imageTransition: .CrossDissolve(kDisplayImageFadeDuration)) } else { imageView.contentMode = .ScaleAspectFit imageView.image = placeholderImage } } } }
mit
gregomni/swift
test/Interop/Cxx/templates/template-type-parameter-not-in-signature.swift
1
1935
// RUN: %target-run-simple-swift(-I %S/Inputs -Xfrontend -enable-experimental-cxx-interop -Xfrontend -validate-tbd-against-ir=none) // // REQUIRES: executable_test import TemplateTypeParameterNotInSignature import StdlibUnittest var TemplateNotInSignatureTestSuite = TestSuite("Template Type Parameters Not in Function Signature") TemplateNotInSignatureTestSuite.test("Function with defaulted template type parameters") { templateTypeParamNotUsedInSignature(T: Int.self) multiTemplateTypeParamNotUsedInSignature(T: Float.self, U: Int.self) let x: Int = multiTemplateTypeParamOneUsedInSignature(1, T: Int.self) expectEqual(x, 1) multiTemplateTypeParamNotUsedInSignatureWithUnrelatedParams(1, 1, T: Int32.self, U: Int.self) let y: Int = templateTypeParamUsedInReturnType(10) expectEqual(y, 10) } TemplateNotInSignatureTestSuite.test("Instanciate the same function template twice.") { // Intentionally test the same thing twice. templateTypeParamNotUsedInSignature(T: Int.self) templateTypeParamNotUsedInSignature(T: Int.self) } TemplateNotInSignatureTestSuite.test("Pointer types") { var x = 1 x = templateTypeParamUsedInReferenceParam(&x) expectEqual(x, 1) } TemplateNotInSignatureTestSuite.test("Member function templates") { let s = Struct() s.templateTypeParamNotUsedInSignature(T: Int.self) let x: Int = templateTypeParamUsedInReturnType(42) expectEqual(x, 42) } TemplateNotInSignatureTestSuite.test("Member function templates (mutable)") { var s = Struct() s.templateTypeParamNotUsedInSignatureMutable(T: Int.self) } TemplateNotInSignatureTestSuite.test("Member function templates (static)") { Struct.templateTypeParamNotUsedInSignatureStatic(T: Int.self) } TemplateNotInSignatureTestSuite.test("Type not used in signature and takes an inout parameter.") { var x = 42 let out = templateTypeParamNotUsedInSignatureWithRef(&x, U: Int.self) expectEqual(out, 42) } runAllTests()
apache-2.0
XeresRazor/FFXIVServer
Sources/FFXIVServer/ZoneDatabase.swift
1
4860
// // ZoneDatabase.swift // FFXIVServer // // Created by David Green on 2/24/16. // Copyright © 2016 David Green. All rights reserved. // import Foundation import SMGOLFramework // Convenience functions func parseFloat(valueString: String) -> Float32 { guard let result = Float32(valueString) else { return 0.0 } return result } func parseVector3(vectorString: String) -> ActorVector3 { var components = vectorString.componentsSeparatedByString(", ") if components.count != 3 { return ActorVector3(0.0, 0.0, 0.0) } return (parseFloat(components[0]), parseFloat(components[1]), parseFloat(components[2])) } // MARK: Types typealias ActorVector3 = (Float32, Float32, Float32) struct ActorDefinition { var id: UInt32 = 0 var nameStringID: UInt32 = 0 var baseModelID: UInt32 = 0 var topModelID: UInt32 = 0 var pos = ActorVector3(0.0, 0.0, 0.0) } struct ZoneDefinition { typealias ActorArray = [ActorDefinition] var backgroundMusicID: UInt32 = 0 var battleMusicID: UInt32 = 0 var actors = ActorArray() } class ZoneDatabase { private let LogName = "ZoneDatabase" private let zoneLocations = [ ZoneDefLocation(zoneID: 101, name: "lanoscea"), ZoneDefLocation(zoneID: 102, name: "coerthas"), ZoneDefLocation(zoneID: 103, name: "blackshroud"), ZoneDefLocation(zoneID: 104, name: "thanalan"), ZoneDefLocation(zoneID: 105, name: "mordhona"), ZoneDefLocation(zoneID: 109, name: "rivenroad") ] private struct ZoneDefLocation { var zoneID: UInt32 var name: String } private typealias ZoneDefinitionMap = [UInt32: ZoneDefinition] private var defaultZone = ZoneDefinition() private var zones = ZoneDefinitionMap() private static var zoneLocations = [ZoneDefLocation]() init() { defaultZone.backgroundMusicID = 0x39 defaultZone.battleMusicID = 0x0D } func load() { let configPath = AppConfig.getBasePath() for zoneLocation in zoneLocations { let zoneDefFilename = "ffxivd_zone_\(zoneLocation.name).xml" let zoneDefPath = configPath + "/" + zoneDefFilename if NSFileManager.defaultManager().fileExistsAtPath(zoneDefPath) { guard let inputStream = CreateInputStandardStream(zoneDefPath) else { return } guard let zone = loadZoneDefinition(inputStream) else { return } zones[zoneLocation.zoneID] = zone } else { Log.instance().logMessage(LogName, message: "File \(zoneDefPath) doesn't exist. Not loading any data for that zone.") } } } func getZone(zoneID: UInt32) -> ZoneDefinition? { guard let zone = zones[zoneID] else { return nil } return zone } func getDefaultZone() -> ZoneDefinition? { return defaultZone } func getZoneOrDefault(zoneID: UInt32) -> ZoneDefinition? { guard let zone = getZone(zoneID) else { return getDefaultZone() } return zone } private func loadZoneDefinition(stream: Stream) -> ZoneDefinition? { var result = ZoneDefinition() guard let documentNode = ParseDocument(stream) else { print("Cannot parse zone definition file."); return result } guard let zoneNode = documentNode.select("Zone") else { print("Zone definition file doesn't contain a 'Zone' node."); return result } if let backgroundMusicID = GetAttributeIntValue(zoneNode, name: "BackgroundMusicId") { result.backgroundMusicID = UInt32(backgroundMusicID) } if let battleMusicID = GetAttributeIntValue(zoneNode, name: "BattleMusicId") { result.battleMusicID = UInt32(battleMusicID) } let actorNodes = zoneNode.selectNodes("Actors/Actor") result.actors.reserveCapacity(actorNodes.count) for actorNode in actorNodes { var actor = ActorDefinition() if let id = GetAttributeIntValue(actorNode, name: "Id") { actor.id = UInt32(id) } if let nameStringID = GetAttributeIntValue(actorNode, name: "NameString") { actor.nameStringID = UInt32(nameStringID) } if let baseModelID = GetAttributeIntValue(actorNode, name: "BaseModel") { actor.baseModelID = UInt32(baseModelID) } if let topModelID = GetAttributeIntValue(actorNode, name: "TopModel") { actor.topModelID = UInt32(topModelID) } if let position = GetAttributeStringValue(actorNode, name: "Position") { actor.pos = parseVector3(position) } result.actors.append(actor) } return result } }
mit
antoninbiret/DataSourceKit
DataSourceKit/Classes/Collection/CollectionDataSource+Sections.swift
1
2148
// // CollectionDataSource+Sections.swift // DataSourceKit // // Created by Antonin Biret on 26/09/2017. // import Foundation extension CollectionDataSource { // internal func index(of section: Section) -> Int? { // return self._mutatingSections.index(of: section) // } // public func add(item: Section.Item, in section: Section) { // if let index = self.index(of: section) { // self._mutatingSections[index].items.append(item) // } else { // fatalError() // } // } // // public func add(items: [Section.Item], in section: Section) { // if let index = self.index(of: section) { // self._mutatingSections[index].items.append(contentsOf: items) // } else { // fatalError() // } // } // // public func insert(item: Section.Item, in section: Section, at index: Int) { // if let index = self.index(of: section) { // self._mutatingSections[index].items.insert(item, at: index) // } else { // fatalError() // } // } // // public func insert(items: [Section.Item], in section: Section, from index: Int) { // if let index = self.index(of: section) { // self._mutatingSections[index].items.insert(contentsOf: items, at: index) // } else { // fatalError() // } // } // // // MARK: - Deletion // // public func removeItem(in section: Section, at index: Int) { // if let index = self.index(of: section) { // self._mutatingSections[index].items.remove(at: index) // } else { // fatalError() // } // } // // public func removeItems(in section: Section, in range: Range<Int>) { // if let index = self.index(of: section) { // self._mutatingSections[index].items.removeSubrange(range) // } else { // fatalError() // } // } // // // MARK: - Modification // // public func replace(item: Section.Item, in section: Section, at index: Int) { // if let index = self.index(of: section) { // self._mutatingSections[index].items[index] = item // } else { // fatalError() // } // } }
mit
klundberg/swift-corelibs-foundation
Foundation/NSObjCRuntime.swift
1
11159
// This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // import CoreFoundation #if os(OSX) || os(iOS) internal let kCFCompareLessThan = CFComparisonResult.compareLessThan internal let kCFCompareEqualTo = CFComparisonResult.compareEqualTo internal let kCFCompareGreaterThan = CFComparisonResult.compareGreaterThan #endif internal enum _NSSimpleObjCType : UnicodeScalar { case ID = "@" case Class = "#" case Sel = ":" case Char = "c" case UChar = "C" case Short = "s" case UShort = "S" case Int = "i" case UInt = "I" case Long = "l" case ULong = "L" case LongLong = "q" case ULongLong = "Q" case Float = "f" case Double = "d" case Bitfield = "b" case Bool = "B" case Void = "v" case Undef = "?" case Ptr = "^" case CharPtr = "*" case Atom = "%" case ArrayBegin = "[" case ArrayEnd = "]" case UnionBegin = "(" case UnionEnd = ")" case StructBegin = "{" case StructEnd = "}" case Vector = "!" case Const = "r" } extension Int { init(_ v: _NSSimpleObjCType) { self.init(UInt8(ascii: v.rawValue)) } } extension Int8 { init(_ v: _NSSimpleObjCType) { self.init(Int(v)) } } extension String { init(_ v: _NSSimpleObjCType) { self.init(v.rawValue) } } extension _NSSimpleObjCType { init?(_ v: UInt8) { self.init(rawValue: UnicodeScalar(v)) } init?(_ v: String?) { if let rawValue = v?.unicodeScalars.first { self.init(rawValue: rawValue) } else { return nil } } } // mapping of ObjC types to sizes and alignments (note that .Int is 32-bit) // FIXME use a generic function, unfortuantely this seems to promote the size to 8 private let _NSObjCSizesAndAlignments : Dictionary<_NSSimpleObjCType, (Int, Int)> = [ .ID : ( sizeof(AnyObject.self), alignof(AnyObject.self) ), .Class : ( sizeof(AnyClass.self), alignof(AnyClass.self) ), .Char : ( sizeof(CChar.self), alignof(CChar.self) ), .UChar : ( sizeof(UInt8.self), alignof(UInt8.self) ), .Short : ( sizeof(Int16.self), alignof(Int16.self) ), .UShort : ( sizeof(UInt16.self), alignof(UInt16.self) ), .Int : ( sizeof(Int32.self), alignof(Int32.self) ), .UInt : ( sizeof(UInt32.self), alignof(UInt32.self) ), .Long : ( sizeof(Int32.self), alignof(Int32.self) ), .ULong : ( sizeof(UInt32.self), alignof(UInt32.self) ), .LongLong : ( sizeof(Int64.self), alignof(Int64.self) ), .ULongLong : ( sizeof(UInt64.self), alignof(UInt64.self) ), .Float : ( sizeof(Float.self), alignof(Float.self) ), .Double : ( sizeof(Double.self), alignof(Double.self) ), .Bool : ( sizeof(Bool.self), alignof(Bool.self) ), .CharPtr : ( sizeof(UnsafePointer<CChar>.self), alignof(UnsafePointer<CChar>.self)) ] internal func _NSGetSizeAndAlignment(_ type: _NSSimpleObjCType, _ size : inout Int, _ align : inout Int) -> Bool { guard let sizeAndAlignment = _NSObjCSizesAndAlignments[type] else { return false } size = sizeAndAlignment.0 align = sizeAndAlignment.1 return true } public func NSGetSizeAndAlignment(_ typePtr: UnsafePointer<Int8>, _ sizep: UnsafeMutablePointer<Int>?, _ alignp: UnsafeMutablePointer<Int>?) -> UnsafePointer<Int8> { let type = _NSSimpleObjCType(UInt8(typePtr.pointee))! var size : Int = 0 var align : Int = 0 if !_NSGetSizeAndAlignment(type, &size, &align) { // FIXME: This used to return nil, but the corresponding Darwin // implementation is defined as returning a non-optional value. fatalError("invalid type encoding") } sizep?.pointee = size alignp?.pointee = align return typePtr.advanced(by: 1) } public enum ComparisonResult : Int { case orderedAscending = -1 case orderedSame case orderedDescending internal static func _fromCF(_ val: CFComparisonResult) -> ComparisonResult { if val == kCFCompareLessThan { return .orderedAscending } else if val == kCFCompareGreaterThan { return .orderedDescending } else { return .orderedSame } } } /* Note: QualityOfService enum is available on all platforms, but it may not be implemented on all platforms. */ public enum NSQualityOfService : Int { /* UserInteractive QoS is used for work directly involved in providing an interactive UI such as processing events or drawing to the screen. */ case userInteractive /* UserInitiated QoS is used for performing work that has been explicitly requested by the user and for which results must be immediately presented in order to allow for further user interaction. For example, loading an email after a user has selected it in a message list. */ case userInitiated /* Utility QoS is used for performing work which the user is unlikely to be immediately waiting for the results. This work may have been requested by the user or initiated automatically, does not prevent the user from further interaction, often operates at user-visible timescales and may have its progress indicated to the user by a non-modal progress indicator. This work will run in an energy-efficient manner, in deference to higher QoS work when resources are constrained. For example, periodic content updates or bulk file operations such as media import. */ case utility /* Background QoS is used for work that is not user initiated or visible. In general, a user is unaware that this work is even happening and it will run in the most efficient manner while giving the most deference to higher QoS work. For example, pre-fetching content, search indexing, backups, and syncing of data with external systems. */ case background /* Default QoS indicates the absence of QoS information. Whenever possible QoS information will be inferred from other sources. If such inference is not possible, a QoS between UserInitiated and Utility will be used. */ case `default` } public struct SortOptions: OptionSet { public let rawValue : UInt public init(rawValue: UInt) { self.rawValue = rawValue } public static let concurrent = SortOptions(rawValue: UInt(1 << 0)) public static let stable = SortOptions(rawValue: UInt(1 << 4)) } public struct EnumerationOptions: OptionSet { public let rawValue : UInt public init(rawValue: UInt) { self.rawValue = rawValue } public static let concurrent = EnumerationOptions(rawValue: UInt(1 << 0)) public static let reverse = EnumerationOptions(rawValue: UInt(1 << 1)) } public typealias Comparator = (AnyObject, AnyObject) -> ComparisonResult public let NSNotFound: Int = Int.max @noreturn internal func NSRequiresConcreteImplementation(_ fn: String = #function, file: StaticString = #file, line: UInt = #line) { fatalError("\(fn) must be overriden in subclass implementations", file: file, line: line) } @noreturn internal func NSUnimplemented(_ fn: String = #function, file: StaticString = #file, line: UInt = #line) { fatalError("\(fn) is not yet implemented", file: file, line: line) } @noreturn internal func NSInvalidArgument(_ message: String, method: String = #function, file: StaticString = #file, line: UInt = #line) { fatalError("\(method): \(message)", file: file, line: line) } internal struct _CFInfo { // This must match _CFRuntimeBase var info: UInt32 var pad : UInt32 init(typeID: CFTypeID) { // This matches what _CFRuntimeCreateInstance does to initialize the info value info = UInt32((UInt32(typeID) << 8) | (UInt32(0x80))) pad = 0 } init(typeID: CFTypeID, extra: UInt32) { info = UInt32((UInt32(typeID) << 8) | (UInt32(0x80))) pad = extra } } internal protocol _CFBridgable { associatedtype CFType var _cfObject: CFType { get } } internal protocol _SwiftBridgable { associatedtype SwiftType var _swiftObject: SwiftType { get } } internal protocol _NSBridgable { associatedtype NSType var _nsObject: NSType { get } } #if os(OSX) || os(iOS) private let _SwiftFoundationModuleName = "SwiftFoundation" #else private let _SwiftFoundationModuleName = "Foundation" #endif /** Returns the class name for a class. For compatibility with Foundation on Darwin, Foundation classes are returned as unqualified names. Only top-level Swift classes (Foo.bar) are supported at present. There is no canonical encoding for other types yet, except for the mangled name, which is neither stable nor human-readable. */ public func NSStringFromClass(_ aClass: AnyClass) -> String { let aClassName = String(reflecting: aClass).bridge() let components = aClassName.components(separatedBy: ".") guard components.count == 2 else { fatalError("NSStringFromClass: \(String(reflecting: aClass)) is not a top-level class") } if components[0] == _SwiftFoundationModuleName { return components[1] } else { return String(aClassName) } } /** Returns the class metadata given a string. For compatibility with Foundation on Darwin, unqualified names are looked up in the Foundation module. Only top-level Swift classes (Foo.bar) are supported at present. There is no canonical encoding for other types yet, except for the mangled name, which is neither stable nor human-readable. */ public func NSClassFromString(_ aClassName: String) -> AnyClass? { let aClassNameWithPrefix : String let components = aClassName.bridge().components(separatedBy: ".") switch components.count { case 1: guard !aClassName.hasPrefix("_Tt") else { NSLog("*** NSClassFromString(\(aClassName)): cannot yet decode mangled class names") return nil } aClassNameWithPrefix = _SwiftFoundationModuleName + "." + aClassName break case 2: aClassNameWithPrefix = aClassName break default: NSLog("*** NSClassFromString(\(aClassName)): nested class names not yet supported") return nil } return _typeByName(aClassNameWithPrefix) as? AnyClass }
apache-2.0
benlangmuir/swift
test/attr/attr_ibaction_ios.swift
29
1611
// RUN: not %target-build-swift -typecheck %s 2>&1 | %FileCheck -check-prefix=CHECK-%target-os %s // REQUIRES: objc_interop // REQUIRES: executable_test class IBActionWrapperTy { @IBAction func nullary() {} // CHECK-ios-NOT: attr_ibaction_ios.swift:[[@LINE-1]] // CHECK-macosx: attr_ibaction_ios.swift:[[@LINE-2]]:18: error: @IBAction methods must have 1 argument // CHECK-tvos-NOT: attr_ibaction_ios.swift:[[@LINE-3]] // CHECK-watchos-NOT: attr_ibaction_ios.swift:[[@LINE-4]] @IBAction func unary(_: AnyObject) {} // CHECK-ios-NOT: attr_ibaction_ios.swift:[[@LINE-1]] // CHECK-macosx-NOT: attr_ibaction_ios.swift:[[@LINE-2]] // CHECK-tvos-NOT: attr_ibaction_ios.swift:[[@LINE-3]] // CHECK-watchos-NOT: attr_ibaction_ios.swift:[[@LINE-4]] @IBAction func binary(_: AnyObject, _: AnyObject) {} // CHECK-ios-NOT: attr_ibaction_ios.swift:[[@LINE-1]] // CHECK-macosx: attr_ibaction_ios.swift:[[@LINE-2]]:18: error: @IBAction methods must have 1 argument // CHECK-tvos-NOT: attr_ibaction_ios.swift:[[@LINE-3]] // CHECK-watchos-NOT: attr_ibaction_ios.swift:[[@LINE-4]] @IBAction func ternary(_: AnyObject, _: AnyObject, _: AnyObject) {} // CHECK-ios: attr_ibaction_ios.swift:[[@LINE-1]]:18: error: @IBAction methods must have at most 2 arguments // CHECK-macosx: attr_ibaction_ios.swift:[[@LINE-2]]:18: error: @IBAction methods must have 1 argument // CHECK-tvos: attr_ibaction_ios.swift:[[@LINE-3]]:18: error: @IBAction methods must have at most 2 arguments // CHECK-watchos: attr_ibaction_ios.swift:[[@LINE-4]]:18: error: @IBAction methods must have at most 2 arguments }
apache-2.0
emericspiroux/Open42
correct42/Services/Delegations/SearchManagerDelegation.swift
1
399
// // SearchManagerDelegation.swift // correct42 // // Created by larry on 24/05/2016. // Copyright © 2016 42. All rights reserved. // import Foundation /// Delegate fonctionnality of the SearchManager to a Controller @objc protocol SearchManagerDelegation { /// To know where is the searchManager when he do `fetchUsersOnAPI` optional func searchManager(percentOfCompletion percent:Int) }
apache-2.0
PureSwift/Cacao
Sources/CacaoDemo/SwitchViewController.swift
1
820
// // SwitchViewController.swift // CacaoDemo // // Created by Alsey Coleman Miller on 6/15/17. // #if os(Linux) import Glibc #elseif os(macOS) import Darwin.C #endif import Foundation #if os(iOS) || os(tvOS) import UIKit import CoreGraphics #else import Cacao import Silica #endif final class SwitchViewController: UIViewController { // MARK: - Views private(set) weak var switchView: UISwitch! // MARK: - Loading override func loadView() { view = UIView() let switchView = UISwitch() self.switchView = switchView view.backgroundColor = UIColor.white view.addSubview(switchView) } override func viewWillLayoutSubviews() { switchView.center = view.center } }
mit
marselan/patient-records
Patient-Records/Patient-Records/RecordViewController.swift
1
5194
// // RecordViewController.swift // patient_records // // Created by Mariano Arselan on 24/12/16. // Copyright © 2016 Mariano Arselan. All rights reserved. // import Foundation import UIKit class RecordViewController : UITableViewController { var record : Record? var patientRecord : PatientRecord init(withRecord patientRecord: PatientRecord) { self.record = nil self.patientRecord = patientRecord super.init(style: .grouped); } override func viewDidLoad() { self.tableView.frame = self.view.bounds self.title = patientRecord.timestamp loadData() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func numberOfSections(in tableView: UITableView) -> Int { return 3 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { switch section{ case 0: return 1 case 1: return 1 default: return self.studies.count } } override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { switch section{ case 0: return "Reason" case 1: return "Treatment" case 2: return "Studies" default: return nil } } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { var cell = tableView.dequeueReusableCell(withIdentifier: "LabelCell") if cell == nil { cell = UITableViewCell(style: .subtitle, reuseIdentifier: "LabelCell") cell?.detailTextLabel?.textColor = UIColor.lightGray if indexPath.section == 2 { cell?.accessoryType = UITableViewCellAccessoryType.disclosureIndicator } } switch indexPath.section { case 0: cell!.textLabel!.text = self.record.reason case 1: cell!.textLabel!.text = self.record.treatment default: let study : Study = studies[indexPath.row]; cell!.textLabel!.text = String(describing: study.label) let studyType : StudyType = self.studyTypes[study.studyTypeId]! //cell!.detailTextLabel!.text = studyType.aDescription } return cell! } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if indexPath.section == 2 { let backItem = UIBarButtonItem() backItem.title = "Back" navigationItem.backBarButtonItem = backItem let studyId = studies[indexPath.row].id let studyTypeId = studies[indexPath.row].studyTypeId switch studyTypeId { case 1: // X-ray scan let xRayScanViewController = XrayScanViewController(studyId) self.navigationController?.pushViewController(xRayScanViewController, animated: true) case 2: // CT scan let ctImageViewController = CtImageViewController(studyId) self.navigationController?.pushViewController(ctImageViewController, animated: true) case 3: // MRI scan let mriImageViewController = MriImageViewController(studyId) self.navigationController?.pushViewController(mriImageViewController, animated: true) default: return } } } func loadData() { let urlString = URL(string: Config.instance.backendUrl + "/PatientManager/PatientService/patient/\(self.patientRecord.patientId)/record/\(self.patientRecord.id)"); var request : URLRequest = URLRequest(url: urlString!) request.addValue(Config.instance.user, forHTTPHeaderField: "user") request.addValue(Config.instance.password, forHTTPHeaderField: "password") let config = URLSessionConfiguration.default let session = URLSession(configuration: config) let task = session.dataTask(with: request, completionHandler: {(data, response, error) in if let error = error { return } guard let response = response else { return } switch(response.httpStatusCode()) { case 200: do { guard let json = data else { return } self.record = try JSONDecoder().decode(Record.self, from: json) } catch let e { print(e) } case 404: return default: return } DispatchQueue.main.async(execute:self.tableView.reloadData()) }) task.resume() } }
gpl-3.0
xhacker/radar
UITestingDatePicker/PickerWheel/AppDelegate.swift
1
796
// // AppDelegate.swift // PickerWheel // // Created by Dongyuan Liu on 2015-11-04. // Copyright © 2015 Ela Workshop. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { return true } func applicationWillResignActive(application: UIApplication) { } func applicationDidEnterBackground(application: UIApplication) { } func applicationWillEnterForeground(application: UIApplication) { } func applicationDidBecomeActive(application: UIApplication) { } func applicationWillTerminate(application: UIApplication) { } }
mit
suzuki-0000/SKPhotoBrowser
SKPhotoBrowser/SKZoomingScrollView.swift
1
11063
// // SKZoomingScrollView.swift // SKViewExample // // Created by suzuki_keihsi on 2015/10/01. // Copyright © 2015 suzuki_keishi. All rights reserved. // import UIKit open class SKZoomingScrollView: UIScrollView { var captionView: SKCaptionView! var photo: SKPhotoProtocol! { didSet { imageView.image = nil if photo != nil && photo.underlyingImage != nil { displayImage(complete: true) return } if photo != nil { displayImage(complete: false) } } } fileprivate weak var browser: SKPhotoBrowser? fileprivate(set) var imageView: SKDetectingImageView! fileprivate var tapView: SKDetectingView! fileprivate var indicatorView: SKIndicatorView! required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setup() } override init(frame: CGRect) { super.init(frame: frame) setup() } convenience init(frame: CGRect, browser: SKPhotoBrowser) { self.init(frame: frame) self.browser = browser setup() } deinit { browser = nil } func setup() { // tap tapView = SKDetectingView(frame: bounds) tapView.delegate = self tapView.backgroundColor = .clear tapView.autoresizingMask = [.flexibleHeight, .flexibleWidth] addSubview(tapView) // image imageView = SKDetectingImageView(frame: frame) imageView.delegate = self imageView.contentMode = .bottom imageView.backgroundColor = .clear addSubview(imageView) // indicator indicatorView = SKIndicatorView(frame: frame) addSubview(indicatorView) // self backgroundColor = .clear delegate = self showsHorizontalScrollIndicator = SKPhotoBrowserOptions.displayHorizontalScrollIndicator showsVerticalScrollIndicator = SKPhotoBrowserOptions.displayVerticalScrollIndicator autoresizingMask = [.flexibleWidth, .flexibleTopMargin, .flexibleBottomMargin, .flexibleRightMargin, .flexibleLeftMargin] } // MARK: - override open override func layoutSubviews() { tapView.frame = bounds indicatorView.frame = bounds super.layoutSubviews() let boundsSize = bounds.size var frameToCenter = imageView.frame // horizon if frameToCenter.size.width < boundsSize.width { frameToCenter.origin.x = floor((boundsSize.width - frameToCenter.size.width) / 2) } else { frameToCenter.origin.x = 0 } // vertical if frameToCenter.size.height < boundsSize.height { frameToCenter.origin.y = floor((boundsSize.height - frameToCenter.size.height) / 2) } else { frameToCenter.origin.y = 0 } // Center if !imageView.frame.equalTo(frameToCenter) { imageView.frame = frameToCenter } } open func setMaxMinZoomScalesForCurrentBounds() { maximumZoomScale = 1 minimumZoomScale = 1 zoomScale = 1 guard let imageView = imageView else { return } let boundsSize = bounds.size let imageSize = imageView.frame.size let xScale = boundsSize.width / imageSize.width let yScale = boundsSize.height / imageSize.height var minScale: CGFloat = min(xScale.isNormal ? xScale : 1.0, yScale.isNormal ? yScale : 1.0) var maxScale: CGFloat = 1.0 let scale = max(SKMesurement.screenScale, 2.0) let deviceScreenWidth = SKMesurement.screenWidth * scale // width in pixels. scale needs to remove if to use the old algorithm let deviceScreenHeight = SKMesurement.screenHeight * scale // height in pixels. scale needs to remove if to use the old algorithm if SKPhotoBrowserOptions.longPhotoWidthMatchScreen && imageView.frame.height >= imageView.frame.width { minScale = 1.0 maxScale = 2.5 } else if imageView.frame.width < deviceScreenWidth { // I think that we should to get coefficient between device screen width and image width and assign it to maxScale. I made two mode that we will get the same result for different device orientations. if UIApplication.shared.statusBarOrientation.isPortrait { maxScale = deviceScreenHeight / imageView.frame.width } else { maxScale = deviceScreenWidth / imageView.frame.width } } else if imageView.frame.width > deviceScreenWidth { maxScale = 1.0 } else { // here if imageView.frame.width == deviceScreenWidth maxScale = 2.5 } maximumZoomScale = maxScale minimumZoomScale = minScale zoomScale = minScale // on high resolution screens we have double the pixel density, so we will be seeing every pixel if we limit the // maximum zoom scale to 0.5 // After changing this value, we still never use more maxScale /= scale if maxScale < minScale { maxScale = minScale * 2 } // reset position imageView.frame.origin = CGPoint.zero setNeedsLayout() } open func prepareForReuse() { photo = nil if captionView != nil { captionView.removeFromSuperview() captionView = nil } } open func displayImage(_ image: UIImage) { // image imageView.image = image imageView.contentMode = photo.contentMode var imageViewFrame: CGRect = .zero imageViewFrame.origin = .zero // long photo if SKPhotoBrowserOptions.longPhotoWidthMatchScreen && image.size.height >= image.size.width { let imageHeight = SKMesurement.screenWidth / image.size.width * image.size.height imageViewFrame.size = CGSize(width: SKMesurement.screenWidth, height: imageHeight) } else { imageViewFrame.size = image.size } imageView.frame = imageViewFrame contentSize = imageViewFrame.size setMaxMinZoomScalesForCurrentBounds() } // MARK: - image open func displayImage(complete flag: Bool) { // reset scale maximumZoomScale = 1 minimumZoomScale = 1 zoomScale = 1 if !flag { if photo.underlyingImage == nil { indicatorView.startAnimating() } photo.loadUnderlyingImageAndNotify() } else { indicatorView.stopAnimating() } if let image = photo.underlyingImage, photo != nil { displayImage(image) } else { // change contentSize will reset contentOffset, so only set the contentsize zero when the image is nil contentSize = CGSize.zero } setNeedsLayout() } open func displayImageFailure() { indicatorView.stopAnimating() } // MARK: - handle tap open func handleDoubleTap(_ touchPoint: CGPoint) { if let browser = browser { NSObject.cancelPreviousPerformRequests(withTarget: browser) } if zoomScale > minimumZoomScale { // zoom out setZoomScale(minimumZoomScale, animated: true) } else { // zoom in // I think that the result should be the same after double touch or pinch /* var newZoom: CGFloat = zoomScale * 3.13 if newZoom >= maximumZoomScale { newZoom = maximumZoomScale } */ let zoomRect = zoomRectForScrollViewWith(maximumZoomScale, touchPoint: touchPoint) zoom(to: zoomRect, animated: true) } // delay control browser?.hideControlsAfterDelay() } } // MARK: - UIScrollViewDelegate extension SKZoomingScrollView: UIScrollViewDelegate { public func viewForZooming(in scrollView: UIScrollView) -> UIView? { return imageView } public func scrollViewWillBeginZooming(_ scrollView: UIScrollView, with view: UIView?) { browser?.cancelControlHiding() } public func scrollViewDidZoom(_ scrollView: UIScrollView) { setNeedsLayout() layoutIfNeeded() } } // MARK: - SKDetectingImageViewDelegate extension SKZoomingScrollView: SKDetectingViewDelegate { func handleSingleTap(_ view: UIView, touch: UITouch) { guard let browser = browser else { return } guard SKPhotoBrowserOptions.enableZoomBlackArea == true else { return } if browser.areControlsHidden() == false && SKPhotoBrowserOptions.enableSingleTapDismiss == true { browser.determineAndClose() } else { browser.toggleControls() } } func handleDoubleTap(_ view: UIView, touch: UITouch) { if SKPhotoBrowserOptions.enableZoomBlackArea == true { let needPoint = getViewFramePercent(view, touch: touch) handleDoubleTap(needPoint) } } } // MARK: - SKDetectingImageViewDelegate extension SKZoomingScrollView: SKDetectingImageViewDelegate { func handleImageViewSingleTap(_ touchPoint: CGPoint) { guard let browser = browser else { return } if SKPhotoBrowserOptions.enableSingleTapDismiss { browser.determineAndClose() } else { browser.toggleControls() } } func handleImageViewDoubleTap(_ touchPoint: CGPoint) { handleDoubleTap(touchPoint) } } private extension SKZoomingScrollView { func getViewFramePercent(_ view: UIView, touch: UITouch) -> CGPoint { let oneWidthViewPercent = view.bounds.width / 100 let viewTouchPoint = touch.location(in: view) let viewWidthTouch = viewTouchPoint.x let viewPercentTouch = viewWidthTouch / oneWidthViewPercent let photoWidth = imageView.bounds.width let onePhotoPercent = photoWidth / 100 let needPoint = viewPercentTouch * onePhotoPercent var Y: CGFloat! if viewTouchPoint.y < view.bounds.height / 2 { Y = 0 } else { Y = imageView.bounds.height } let allPoint = CGPoint(x: needPoint, y: Y) return allPoint } func zoomRectForScrollViewWith(_ scale: CGFloat, touchPoint: CGPoint) -> CGRect { let w = frame.size.width / scale let h = frame.size.height / scale let x = touchPoint.x - (h / max(SKMesurement.screenScale, 2.0)) let y = touchPoint.y - (w / max(SKMesurement.screenScale, 2.0)) return CGRect(x: x, y: y, width: w, height: h) } }
mit
carlo-/ipolito
iPoliTO2/CareerViewController.swift
1
22755
// // GradesViewController.swift // iPoliTO2 // // Created by Carlo Rapisarda on 30/07/2016. // Copyright © 2016 crapisarda. All rights reserved. // import UIKit import Charts class CareerViewController: UITableViewController { var status: PTViewControllerStatus = .loggedOut { didSet { statusDidChange() } } var temporaryGrades: [PTTemporaryGrade] = [] { didSet { tableView.reloadData() } } var passedExams: [PTExam] = [] { didSet { examsDidChange() } } fileprivate var sortedExams: [PTExam] = [] fileprivate var currentSorting: PTExamSorting = PTExamSorting.defaultValue fileprivate var canShowCareerDetails: Bool { // Needs at least 1 exam return passedExams.count > 0 } fileprivate var canShowGraph: Bool { // Needs at least 1 numerical grade return passedExams.contains(where: { $0.grade != .passed }) } fileprivate var graphCell: PTGraphCell? fileprivate var detailsCell: PTCareerDetailsCell? @IBOutlet fileprivate var sortButton: UIBarButtonItem! override func viewDidLoad() { super.viewDidLoad() if #available(iOS 11.0, *) { // Disable use of 'large title' display mode navigationItem.largeTitleDisplayMode = .never } // Removes annoying row separators after the last cell tableView.tableFooterView = UIView() setupRefreshControl() reloadSpecialCells() } override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { super.viewWillTransition(to: size, with: coordinator) coordinator.animate(alongsideTransition: { _ in self.tableView.backgroundView?.setNeedsDisplay() }, completion: nil) } func statusDidChange() { if status != .fetching && status != .logginIn { refreshControl?.endRefreshing() } let isTableEmpty = temporaryGrades.isEmpty && passedExams.isEmpty if isTableEmpty { tableView.isScrollEnabled = false navigationItem.titleView = nil let refreshButton = UIButton(type: .system) refreshButton.addTarget(self, action: #selector(refreshButtonPressed), for: .touchUpInside) switch status { case .logginIn: tableView.backgroundView = PTLoadingTableBackgroundView(frame: view.bounds, title: ~"ls.generic.status.loggingIn") case .offline: refreshButton.setTitle(~"ls.generic.alert.retry", for: .normal) tableView.backgroundView = PTSimpleTableBackgroundView(frame: view.bounds, title: ~"ls.generic.status.offline", button: refreshButton) case .error: refreshButton.setTitle(~"ls.generic.alert.retry", for: .normal) tableView.backgroundView = PTSimpleTableBackgroundView(frame: view.bounds, title: ~"ls.generic.status.couldNotRetrieve", button: refreshButton) case .ready: refreshButton.setTitle(~"ls.generic.refresh", for: .normal) tableView.backgroundView = PTSimpleTableBackgroundView(frame: view.bounds, title: ~"ls.careerVC.status.emptyCareer", button: refreshButton) navigationItem.titleView = PTSession.shared.lastUpdateTitleView(title: ~"ls.careerVC.title") default: tableView.backgroundView = nil } } else { tableView.isScrollEnabled = true tableView.backgroundView = nil switch status { case .logginIn: navigationItem.titleView = PTLoadingTitleView(withTitle: ~"ls.generic.status.loggingIn") case .fetching: navigationItem.titleView = PTLoadingTitleView(withTitle: ~"ls.careerVC.status.loading") case .offline: navigationItem.titleView = PTSession.shared.lastUpdateTitleView(title: ~"ls.generic.status.offline") default: navigationItem.titleView = PTSession.shared.lastUpdateTitleView(title: ~"ls.careerVC.title") } } } func examsDidChange() { OperationQueue().addOperation { [unowned self] _ in self.resortExams() OperationQueue.main.addOperation { self.updateSortButton() self.reloadSpecialCells() self.tableView.reloadData() } } } func setupRefreshControl() { refreshControl = UIRefreshControl() refreshControl?.addTarget(self, action: #selector(refreshControlActuated), for: .valueChanged) } @objc func refreshControlActuated() { if PTSession.shared.isBusy { refreshControl?.endRefreshing() } else { (UIApplication.shared.delegate as! AppDelegate).login() } } @objc func refreshButtonPressed() { (UIApplication.shared.delegate as! AppDelegate).login() } private func reloadSpecialCells() { if detailsCell == nil { detailsCell = tableView.dequeueReusableCell(withIdentifier: PTCareerDetailsCell.identifier) as? PTCareerDetailsCell } if graphCell == nil { graphCell = tableView.dequeueReusableCell(withIdentifier: PTGraphCell.identifier) as? PTGraphCell graphCell?.setupChart() } detailsCell?.configure(withStudentInfo: PTSession.shared.studentInfo) graphCell?.configure(withExams: passedExams) } func handleTabBarItemSelection(wasAlreadySelected: Bool) { if wasAlreadySelected { if #available(iOS 11.0, *) { tableView.setContentOffset(CGPoint(x: 0, y: -64), animated: true) } else { tableView.setContentOffset(CGPoint(x: 0, y: -tableView.contentInset.top), animated: true) } } } private func updateSortButton() { sortButton.isEnabled = (passedExams.count > 0) } @IBAction func sortPressed(_ sender: UIBarButtonItem) { let actionSheet = UIAlertController(title: ~"ls.careerVC.sorting.sortBy", message: nil, preferredStyle: .actionSheet) actionSheet.addAction(UIAlertAction(title: ~"ls.careerVC.sorting.date", style: .default, handler: { _ in self.sortExams(.byDate) self.tableView.reloadData() })) actionSheet.addAction(UIAlertAction(title: ~"ls.careerVC.sorting.credits", style: .default, handler: { _ in self.sortExams(.byCredits) self.tableView.reloadData() })) actionSheet.addAction(UIAlertAction(title: ~"ls.careerVC.sorting.grade", style: .default, handler: { _ in self.sortExams(.byGrade) self.tableView.reloadData() })) actionSheet.addAction(UIAlertAction(title: ~"ls.careerVC.sorting.name", style: .default, handler: { _ in self.sortExams(.byName) self.tableView.reloadData() })) actionSheet.addAction(UIAlertAction(title: ~"ls.generic.alert.cancel", style: .cancel, handler: nil)) present(actionSheet, animated: true, completion: nil) } fileprivate func resortExams() { sortExams(currentSorting) } fileprivate func sortExams(_ sorting: PTExamSorting, remember: Bool = true) { switch sorting { case .byDate: sortedExams = passedExams.sorted() { $0.date > $1.date } case .byCredits: sortedExams = passedExams.sorted() { $0.credits > $1.credits } case .byGrade: sortedExams = passedExams.sorted() { $0.grade.rawValue > $1.grade.rawValue } case .byName: sortedExams = passedExams.sorted() { $0.name < $1.name } } currentSorting = sorting if remember { sorting.setAsDefault() } } override func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? { if tableView.cellForRow(at: indexPath)?.selectionStyle == .none { return nil } else { return indexPath } } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) } override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) { let section = indexPath.section let row = indexPath.row switch section { case 0: (cell as? PTTemporaryGradeCell)?.setTemporaryGrade(temporaryGrades[row]) case 1: (cell as? PTGradeCell)?.setExam(sortedExams[row]) default: return } } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let section = indexPath.section switch section { case 0: return tableView.dequeueReusableCell(withIdentifier: PTTemporaryGradeCell.identifier, for: indexPath) case 1: return tableView.dequeueReusableCell(withIdentifier: PTGradeCell.identifier, for: indexPath) case 2: return detailsCell! default: return graphCell! } } override func numberOfSections(in tableView: UITableView) -> Int { return 4 } override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { switch section { case 0: return temporaryGrades.count > 0 ? ~"ls.careerVC.section.tempGrades" : nil case 1: return sortedExams.count > 0 ? ~"ls.careerVC.section.grades" : nil case 2: return canShowCareerDetails ? ~"ls.careerVC.section.details" : nil case 3: return canShowGraph ? ~"ls.careerVC.section.overview" : nil default: return nil } } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { switch section { case 0: return temporaryGrades.count case 1: return sortedExams.count case 2: return canShowCareerDetails ? 1 : 0 case 3: return canShowGraph ? 1 : 0 default: return 0 } } override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { let section = indexPath.section switch section { case 0: return PTTemporaryGradeCell.estimatedHeight(temporaryGrade: temporaryGrades[indexPath.row], rowWidth: tableView.frame.width) case 1: return PTGradeCell.height case 2: return PTCareerDetailsCell.height default: return PTGraphCell.height } } } private enum PTExamSorting: Int { private static let udKey = "examSorting" case byName = 0, byGrade, byCredits, byDate static var defaultValue: PTExamSorting { let rawValue = UserDefaults().integer(forKey: PTExamSorting.udKey) return PTExamSorting(rawValue: rawValue) ?? .byName } func setAsDefault() { UserDefaults().set(self.rawValue, forKey: PTExamSorting.udKey) } } class PTGradeCell: UITableViewCell { @IBOutlet var subjectLabel: UILabel! @IBOutlet var gradeLabel: UILabel! @IBOutlet var subtitleLabel: UILabel! static let identifier = "PTGradeCell_id" static let height: CGFloat = 70 func setExam(_ exam: PTExam) { subjectLabel.text = exam.name gradeLabel.text = exam.grade.shortDescription let formatter = DateFormatter() formatter.timeZone = TimeZone.Turin formatter.dateStyle = DateFormatter.Style.medium let dateStr = formatter.string(from: exam.date) subtitleLabel.text = dateStr+" - \(exam.credits) "+(~"ls.generic.credits") } override func awakeFromNib() { super.awakeFromNib() self.selectionStyle = .none } } class PTCareerDetailsCell: UITableViewCell { @IBOutlet var weightedAvgLabel: UILabel! @IBOutlet var cleanAvgLabel: UILabel! @IBOutlet var creditsLabel: UILabel! static let identifier = "PTCareerDetailsCell_id" static let height: CGFloat = 76 func configure(withStudentInfo studentInfo: PTStudentInfo?) { let formatter = NumberFormatter() formatter.allowsFloats = true formatter.maximumFractionDigits = 2 let blackAttributes = [NSFontAttributeName: UIFont.systemFont(ofSize: 17.0), NSForegroundColorAttributeName: UIColor.iPoliTO.darkGray] let grayAttributes = [NSFontAttributeName: UIFont.systemFont(ofSize: 12.0), NSForegroundColorAttributeName: UIColor.lightGray] var weightedAvgStr: String? = nil if let weightedAvg = studentInfo?.weightedAverage { weightedAvgStr = formatter.string(from: NSNumber(floatLiteral: weightedAvg)) } var cleanAvgStr: String? = nil if let cleanAvg = studentInfo?.cleanWeightedAverage { cleanAvgStr = formatter.string(from: NSNumber(floatLiteral: cleanAvg)) } var graduationMarkStr: String? = nil if let graduationMark = studentInfo?.graduationMark { graduationMarkStr = formatter.string(from: NSNumber(floatLiteral: graduationMark)) } var cleanGraduationMarkStr: String? = nil if let cleanGraduationMark = studentInfo?.cleanGraduationMark { cleanGraduationMarkStr = formatter.string(from: NSNumber(floatLiteral: cleanGraduationMark)) } var totalCreditsStr: String? = nil if let totalCreditsVal = studentInfo?.totalCredits { totalCreditsStr = String(totalCreditsVal) } var obtainedCreditsStr: String? = nil if let obtainedCreditsVal = studentInfo?.obtainedCredits { obtainedCreditsStr = String(obtainedCreditsVal) } let weightedAvgAttrib = NSAttributedString(string: weightedAvgStr ?? "??", attributes: blackAttributes) let cleanAvgAttrib = NSAttributedString(string: cleanAvgStr ?? "??", attributes: blackAttributes) let graduationMarkAttrib = NSAttributedString(string: graduationMarkStr ?? "??", attributes: blackAttributes) let cleanGraduationMarkAttrib = NSAttributedString(string: cleanGraduationMarkStr ?? "??", attributes: blackAttributes) let obtainedCreditsAttrib = NSAttributedString(string: obtainedCreditsStr ?? "??", attributes: blackAttributes) let maximumAverage = NSAttributedString(string: "/30", attributes: grayAttributes) let maximumGradMark = NSAttributedString(string: "/110", attributes: grayAttributes) let spacesAttrib = NSAttributedString(string: " ", attributes: [NSFontAttributeName: UIFont.systemFont(ofSize: 17.0)]) let totalCreditsAttrib = NSAttributedString(string: "/"+(totalCreditsStr ?? "??"), attributes: grayAttributes) let weightedAvgLabelText = NSMutableAttributedString() weightedAvgLabelText.append(weightedAvgAttrib) weightedAvgLabelText.append(maximumAverage) weightedAvgLabelText.append(spacesAttrib) weightedAvgLabelText.append(graduationMarkAttrib) weightedAvgLabelText.append(maximumGradMark) let cleanAvgLabelText = NSMutableAttributedString() cleanAvgLabelText.append(cleanAvgAttrib) cleanAvgLabelText.append(maximumAverage) cleanAvgLabelText.append(spacesAttrib) cleanAvgLabelText.append(cleanGraduationMarkAttrib) cleanAvgLabelText.append(maximumGradMark) let creditsLabelText = NSMutableAttributedString() creditsLabelText.append(obtainedCreditsAttrib) creditsLabelText.append(totalCreditsAttrib) weightedAvgLabel.attributedText = weightedAvgLabelText cleanAvgLabel.attributedText = cleanAvgLabelText creditsLabel.attributedText = creditsLabelText } } class PTTemporaryGradeCell: UITableViewCell { @IBOutlet var subjectLabel: UILabel! @IBOutlet var gradeLabel: UILabel! @IBOutlet var subtitleLabel: UILabel! @IBOutlet var messageTextView: UITextView! static let identifier = "PTTemporaryGradeCell_id" func setTemporaryGrade(_ tempGrade: PTTemporaryGrade) { subjectLabel.text = tempGrade.subjectName gradeLabel.text = tempGrade.grade?.shortDescription ?? "" messageTextView.text = tempGrade.message ?? "" var details: [String] = [] let formatter = DateFormatter() formatter.timeZone = TimeZone.Turin formatter.dateStyle = DateFormatter.Style.medium let dateStr = formatter.string(from: tempGrade.date) details.append(dateStr) if tempGrade.absent { details.append(~"ls.careerVC.tempGrade.absent") } if tempGrade.failed { details.append(~"ls.careerVC.tempGrade.failed") } let stateStr = ~"ls.careerVC.tempGrade.state"+": "+tempGrade.state details.append(stateStr) subtitleLabel.text = details.joined(separator: " - ") } class func estimatedHeight(temporaryGrade: PTTemporaryGrade, rowWidth: CGFloat) -> CGFloat { let minimumHeight: CGFloat = 70.0 let textViewWidth = rowWidth-22.0 guard let bodyText = temporaryGrade.message else { return minimumHeight } let textView = UITextView() textView.text = bodyText textView.font = UIFont.systemFont(ofSize: 13) let textViewSize = textView.sizeThatFits(CGSize(width: textViewWidth, height: CGFloat.greatestFiniteMagnitude)) return minimumHeight + textViewSize.height + 10.0 } override func awakeFromNib() { super.awakeFromNib() self.selectionStyle = .none } } class PTGraphCell: UITableViewCell { static let identifier = "PTGraphCell_id" static let height: CGFloat = 300 private var pieChart: PieChartView? private var pieChartData: PieChartData? override func draw(_ rect: CGRect) { pieChart?.frame = CGRect(origin: rect.origin, size: CGSize(width: rect.width, height: (rect.height - 10))) } func setupChart() { if pieChart == nil { pieChart = PieChartView() pieChart?.noDataText = ~"ls.careerVC.chart.noData" pieChart?.descriptionText = "" pieChart?.drawEntryLabelsEnabled = false pieChart?.usePercentValuesEnabled = false pieChart?.transparentCircleRadiusPercent = 0.6 pieChart?.legend.horizontalAlignment = .center pieChart?.setExtraOffsets(left: 0, top: 0, right: 0, bottom: -10) pieChart?.isUserInteractionEnabled = false addSubview(pieChart!) } if let data = pieChartData { pieChart?.data = data } } func configure(withExams exams: [PTExam]) { guard !(exams.isEmpty) else { return; } var n18_20 = 0.0 var n21_23 = 0.0 var n24_26 = 0.0 var n27_30 = 0.0 var n30L = 0.0 for exam in exams { switch exam.grade { case .passed: continue case .honors: n30L += 1 case .numerical(let numb): if numb >= 18 && numb <= 20 { n18_20 += 1 } else if numb >= 21 && numb <= 23 { n21_23 += 1 } else if numb >= 24 && numb <= 26 { n24_26 += 1 } else if numb >= 27 && numb <= 30 { n27_30 += 1 } } } var entries: [PieChartDataEntry] = [] var colors: [UIColor] = [] if n18_20 > 0 { entries.append(PieChartDataEntry(value: n18_20, label: "18~20")) colors.append(#colorLiteral(red: 0.9372549057, green: 0.3490196168, blue: 0.1921568662, alpha: 1)) } if n21_23 > 0 { entries.append(PieChartDataEntry(value: n21_23, label: "21~23")) colors.append(#colorLiteral(red: 0.9568627477, green: 0.6588235497, blue: 0.5450980663, alpha: 1)) } if n24_26 > 0 { entries.append(PieChartDataEntry(value: n24_26, label: "24~26")) colors.append(#colorLiteral(red: 0.9764705896, green: 0.850980401, blue: 0.5490196347, alpha: 1)) } if n27_30 > 0 { entries.append(PieChartDataEntry(value: n27_30, label: "27~30")) colors.append(#colorLiteral(red: 0.721568644, green: 0.8862745166, blue: 0.5921568871, alpha: 1)) } if n30L > 0 { entries.append(PieChartDataEntry(value: n30L, label: "30L" )) colors.append(#colorLiteral(red: 0.4666666687, green: 0.7647058964, blue: 0.2666666806, alpha: 1)) } guard !(entries.isEmpty) else { return; } let set = PieChartDataSet(values: entries, label: nil) set.colors = colors let data = PieChartData(dataSet: set) let formatter = DefaultValueFormatter() formatter.decimals = 0 data.setValueFormatter(formatter) pieChartData = data pieChart?.data = data } }
gpl-3.0
Nickelfox/TemplateProject
ProjectFiles/Code/Helpers/Fonts.swift
1
301
// // Fonts.swift // TemplateProject // // Created by Ravindra Soni on 18/12/16. // Copyright © 2016 Nickelfox. All rights reserved. // import UIKit extension UIFont { //Example // class func robotoBlack(_ size: CGFloat) -> UIFont { // return UIFont(name: "Roboto-Black", size: size)! // } }
mit
victoraliss0n/FireRecord
FireRecord/Source/Extensions/Database/ModelType+Extension.swift
2
237
// // ModelType+Extension.swift // FireRecord // // Created by Victor Alisson on 22/10/17. // import Foundation public extension ModelType { public static var className: String { return String(describing: self) } }
mit
garriguv/graphql-swift
Sources/language/Parser.swift
1
14213
import Foundation enum Keyword: String { case On = "on", Fragment = "fragment", BoolTrue = "true", BoolFalse = "false", Null = "null", Implements = "implements" case Type = "type", Interface = "interface", Union = "union", Scalar, EnumType = "enum", Input = "input", Extend = "extend" case Query = "query", Mutation = "mutation", Subscription = "subscription" } enum ParserError: ErrorType { case UnexpectedToken(Token) case UnexpectedKeyword(Keyword, Token) case WrongTokenKind(TokenKind, TokenKind) } public class Parser { private let lexer: Lexer private var token: Token! init(source: String) { lexer = Lexer(source: source) } public func parse() throws -> Document { token = try lexer.next() return try parseDocument() } } extension Parser { private func parseDocument() throws -> Document { var definitions: [Definition] = [] repeat { definitions.append(try parseDefinition()) } while try !skip(.EOF) return Document(definitions: definitions) } private func parseDefinition() throws -> Definition { if peek(.BraceL) { return .Operation(try parseOperationDefinition()) } guard peek(.Name), let value = token.value, keyword = Keyword(rawValue: value) else { throw ParserError.UnexpectedToken(token) } switch keyword { case .Query, .Mutation, .Subscription: return .Operation(try parseOperationDefinition()) case .Fragment: return .Fragment(try parseFragmentDefinition()) case .Type, .Interface, .Union, .Scalar, .EnumType, .Input: return .Type(try parseTypeDefinition()) case .Extend: return .TypeExtension(try parseTypeExtensionDefinition()) default: throw ParserError.UnexpectedToken(token) } } } extension Parser { private func parseOperationDefinition() throws -> OperationDefinition { if peek(.BraceL) { return OperationDefinition( type: .Query, name: nil, variableDefinitions: [], directives: [], selectionSet: try parseSelectionSet()) } let operationToken = try expect(.Name) guard let typeString = operationToken.value, type = OperationType(rawValue: typeString) else { throw ParserError.UnexpectedToken(operationToken) } let name: Name? = peek(.Name) ? try parseName() : nil return OperationDefinition( type: type, name: name, variableDefinitions: try parseVariableDefinitions(), directives: try parseDirectives(), selectionSet: try parseSelectionSet()) } private func parseVariableDefinitions() throws -> [VariableDefinition] { return peek(.ParenL) ? try many(openKind: .ParenL, parseFn: parseVariableDefinition, closeKind: .ParenR) : [] } private func parseVariableDefinition() throws -> VariableDefinition { let variable = try parseVariable() try expect(.Colon) let type = try parseType() let defaultValue: Value? = try skip(.Equals) ? try parseValueLiteral(isConst: true) : nil return VariableDefinition(variable: variable, type: type, defaultValue: defaultValue) } private func parseVariable() throws -> Variable { try expect(.Dollar) return Variable(name: try parseName()) } private func parseSelectionSet() throws -> SelectionSet { return SelectionSet(selections: try many(openKind: .BraceL, parseFn: parseSelection, closeKind: .BraceR)) } private func parseSelection() throws -> Selection { return peek(.Spread) ? try parseFragment() : Selection.FieldSelection(try parseField()) } private func parseField() throws -> Field { let nameOrAlias = try parseName() let alias: Name? let name: Name if try skip(.Colon) { alias = nameOrAlias name = try parseName() } else { alias = nil name = nameOrAlias } return Field( alias: alias, name: name, arguments: try parseArguments(), directives: try parseDirectives(), selectionSet: peek(.BraceL) ? try parseSelectionSet() : nil) } private func parseArguments() throws -> [Argument] { return peek(.ParenL) ? try many(openKind: .ParenL, parseFn: parseArgument, closeKind: .ParenR) : [] } private func parseArgument() throws -> Argument { let name = try parseName() try expect(.Colon) let value = try parseValueLiteral(isConst: false) return Argument(name: name, value: value) } private func parseName() throws -> Name { let nameToken = try expect(.Name) return Name(value: nameToken.value) } } extension Parser { private func parseFragment() throws -> Selection { try expect(.Spread) if peek(.Name) && token.value != Keyword.On.rawValue { return .FragmentSpreadSelection(FragmentSpread( name: try parseFragmentName(), directives: try parseDirectives())) } let typeCondition: Type? if token.value == Keyword.On.rawValue { try advance() typeCondition = try parseNamedType() } else { typeCondition = nil } return .InlineFragmentSelection(InlineFragment( typeCondition: typeCondition, directives: try parseDirectives(), selectionSet: try parseSelectionSet())) } private func parseFragmentDefinition() throws -> FragmentDefinition { try expectKeyword(.Fragment) let name = try parseFragmentName() try expectKeyword(.On) let typeCondition = try parseNamedType() return FragmentDefinition( name: name, typeCondition: typeCondition, directives: try parseDirectives(), selectionSet: try parseSelectionSet() ) } private func parseFragmentName() throws -> Name { if token.value == Keyword.On.rawValue { throw ParserError.UnexpectedToken(token) } return try parseName() } } extension Parser { private func parseValueLiteral(isConst isConst: Bool) throws -> Value { switch token.kind { case .BracketL: return try parseList(isConst: isConst) case .BraceL: return try parseObject(isConst: isConst) case .Int: guard let value = token.value else { throw ParserError.UnexpectedToken(token) } try advance() return .IntValue(value) case .Float: guard let value = token.value else { throw ParserError.UnexpectedToken(token) } try advance() return .FloatValue(value) case .String: guard let value = token.value else { throw ParserError.UnexpectedToken(token) } try advance() return .StringValue(value) case .Name: if let value = token.value where (value == Keyword.BoolFalse.rawValue || value == Keyword.BoolTrue.rawValue) { try advance() return .BoolValue(value) } else if token.value != Keyword.Null.rawValue { guard let value = token.value else { throw ParserError.UnexpectedToken(token) } try advance() return .Enum(value) } case .Dollar: if !isConst { return .VariableValue(try parseVariable()) } default: throw ParserError.UnexpectedToken(token) } throw ParserError.UnexpectedToken(token) } private func parseList(isConst isConst: Bool) throws -> Value { return .List(try any(openKind: .BracketL, parseFn: { return try self.parseValueLiteral(isConst: isConst) }, closeKind: .BracketR)) } private func parseObject(isConst isConst: Bool) throws -> Value { try expect(.BraceL) var fields: [ObjectField] = [] while try !skip(.BraceR) { fields.append(try parseObjectField(isConst: isConst)) } return .Object(fields) } private func parseObjectField(isConst isConst: Bool) throws -> ObjectField { let name = try parseName() try expect(.Colon) let value = try parseValueLiteral(isConst: isConst) return ObjectField(name: name, value: value) } } extension Parser { private func parseDirectives() throws -> [Directive] { var directives: [Directive] = [] while peek(.At) { directives.append(try parseDirective()) } return directives } private func parseDirective() throws -> Directive { try expect(.At) return Directive(name: try parseName(), arguments: try parseArguments()) } } extension Parser { private func parseType() throws -> Type { let type: Type if try skip(.BracketL) { let listType = try parseType() try expect(.BracketR) type = .List(listType) } else { type = try parseNamedType() } if try skip(.Bang) { return .NonNull(type) } return type } private func parseNamedType() throws -> Type { return .Named(try parseName()) } } extension Parser { private func parseTypeDefinition() throws -> TypeDefinition { if !peek(.Name) { throw ParserError.UnexpectedToken(token) } guard let value = token.value, type = Keyword(rawValue: value) else { throw ParserError.UnexpectedToken(token) } switch type { case .Type: return .Object(try parseObjectTypeDefinition()) case .Interface: return .Interface(try parseInterfaceTypeDefinition()) case .Union: return .Union(try parseUnionTypeDefinition()) case .Scalar: return .Scalar(try parseScalarTypeDefinition()) case .EnumType: return .Enum(try parseEnumTypeDefinition()) case .Input: return .InputObject(try parseInputObjectTypeDefinition()) default: throw ParserError.UnexpectedToken(token) } } private func parseObjectTypeDefinition() throws -> ObjectTypeDefinition { try expectKeyword(.Type) return ObjectTypeDefinition( name: try parseName(), interfaces: try parseImplementsInterfaces(), fields: try any(openKind: .BraceL, parseFn: parseFieldDefinition, closeKind: .BraceR)) } private func parseImplementsInterfaces() throws -> [Type] { if token.value == Keyword.Implements.rawValue { try advance() var types: [Type] = [] repeat { types.append(try parseNamedType()) } while !peek(.BraceL) return types } return [] } private func parseFieldDefinition() throws -> FieldDefinition { let name = try parseName() let arguments = try parseArgumentDefinitions() try expect(.Colon) let type = try parseType() return FieldDefinition(name: name, arguments: arguments, type: type) } private func parseArgumentDefinitions() throws -> [InputValueDefinition] { if peek(.ParenL) { return try many(openKind: .ParenL, parseFn: parseInputValueDefinition, closeKind: .ParenR) } return [] } private func parseInputValueDefinition() throws -> InputValueDefinition { let name = try parseName() try expect(.Colon) let type = try parseType() let defaultValue: Value? = try skip(.Equals) ? try parseValueLiteral(isConst: true) : nil return InputValueDefinition(name: name, type: type, defaultValue: defaultValue) } private func parseInterfaceTypeDefinition() throws -> InterfaceTypeDefinition { try expectKeyword(.Interface) return InterfaceTypeDefinition( name: try parseName(), fields: try any(openKind: .BraceL, parseFn: parseFieldDefinition, closeKind: .BraceR)) } private func parseUnionTypeDefinition() throws -> UnionTypeDefinition { try expectKeyword(.Union) let name = try parseName() try expect(.Equals) let types = try parseUnionMembers() return UnionTypeDefinition(name: name, types: types) } private func parseUnionMembers() throws -> [Type] { var members: [Type] = [] repeat { members.append(try parseNamedType()) } while try skip(.Pipe) return members } private func parseScalarTypeDefinition() throws -> ScalarTypeDefinition { try expectKeyword(.Scalar) return ScalarTypeDefinition(name: try parseName()) } private func parseEnumTypeDefinition() throws -> EnumTypeDefinition { try expectKeyword(.EnumType) return EnumTypeDefinition( name: try parseName(), values: try many(openKind: .BraceL, parseFn: parseEnumValueDefinition, closeKind: .BraceR)) } private func parseEnumValueDefinition() throws -> EnumValueDefinition { return EnumValueDefinition(name: try parseName()) } private func parseInputObjectTypeDefinition() throws -> InputObjectTypeDefinition { try expectKeyword(.Input) return InputObjectTypeDefinition( name: try parseName(), fields: try any(openKind: .BraceL, parseFn: parseInputValueDefinition, closeKind: .BraceR)) } private func parseTypeExtensionDefinition() throws -> TypeExtensionDefinition { try expectKeyword(.Extend) return TypeExtensionDefinition(definition: try parseObjectTypeDefinition()) } } extension Parser { private func advance() throws { token = try lexer.next() } private func skip(kind: TokenKind) throws -> Bool { let match = token.kind == kind if match { try advance() } return match } private func peek(kind: TokenKind) -> Bool { return token.kind == kind } private func expect(kind: TokenKind) throws -> Token { let currentToken = token if currentToken.kind == kind { try advance() return currentToken } throw ParserError.WrongTokenKind(kind, currentToken.kind) } private func expectKeyword(keyword: Keyword) throws -> Token { let currentToken = token if token.kind == .Name && token.value == keyword.rawValue { try advance() return currentToken } throw ParserError.UnexpectedKeyword(keyword, currentToken) } private func any<T>(openKind openKind: TokenKind, parseFn: () throws -> T, closeKind: TokenKind) throws -> [T] { try expect(openKind) var nodes: [T] = [] while try !skip(closeKind) { nodes.append(try parseFn()) } return nodes } private func many<T>(openKind openKind: TokenKind, parseFn: () throws -> T, closeKind: TokenKind) throws -> [T] { try expect(openKind) var nodes = [try parseFn()] while try !skip(closeKind) { nodes.append(try parseFn()) } return nodes } } extension Parser { private func syntaxError(token: Token) throws { throw ParserError.UnexpectedToken(token) } }
mit
obrichak/discounts
discounts/Classes/DAO/DataObjects/CompanyObject/CompanyObject.swift
1
373
// // CompanyObject.swift // discounts // // Created by Alexandr Chernyy on 9/15/14. // Copyright (c) 2014 Alexandr Chernyy. All rights reserved. // import Foundation class CompanyObject { var companyId:Int = 0 var categoryId:Int = 0 var companyName:String = "" var discount:String = "" var imageName:String = "" var discountCode:String = "" }
gpl-3.0
squarefrog/enigma
Source/Extensions/Character+unicodeScalarValue.swift
1
220
import Foundation extension Character { func unicodeScalarValue() -> Int { let string = String(self) let scalars = string.unicodeScalars return Int(scalars[scalars.startIndex].value) } }
mit
aschwaighofer/swift
test/InterfaceHash/added_private_protocol_property-type-fingerprints.swift
2
2391
// REQUIRES: shell // Also uses awk: // XFAIL OS=windows // When adding a private protocol method, the interface hash should stay the same // The per-type fingerprint should change // RUN: %empty-directory(%t) // RUN: %{python} %utils/split_file.py -o %t %s // RUN: cp %t/{a,x}.swift // RUN: %target-swift-frontend -typecheck -enable-type-fingerprints -primary-file %t/x.swift -emit-reference-dependencies-path %t/x.swiftdeps -module-name main // RUN: %S/../Inputs/process_fine_grained_swiftdeps_with_fingerprints.sh <%t/x.swiftdeps >%t/a-processed.swiftdeps // RUN: cp %t/{b,x}.swift // RUN: %target-swift-frontend -typecheck -enable-type-fingerprints -primary-file %t/x.swift -emit-reference-dependencies-path %t/x.swiftdeps -module-name main // RUN: %S/../Inputs/process_fine_grained_swiftdeps_with_fingerprints.sh <%t/x.swiftdeps >%t/b-processed.swiftdeps // RUN: not diff %t/{a,b}-processed.swiftdeps >%t/diffs // BEGIN a.swift private protocol P { func f2() -> Int var y: Int { get set } } // BEGIN b.swift private protocol P { func f2() -> Int var x: Int { get set } var y: Int { get set } } // RUN: %FileCheck %s <%t/diffs -check-prefix=CHECK-SAME-INTERFACE-HASH // RUN: %FileCheck %s <%t/diffs -check-prefix=CHECK-DIFFERENT-TYPE-FINGERPRINT // CHECK-SAME-INTERFACE-HASH-NOT: sourceFileProvides // CHECK-DIFFERENT-TYPE-FINGERPRINT-DAG: < topLevel implementation '' P true // CHECK-DIFFERENT-TYPE-FINGERPRINT-DAG: < topLevel interface '' P true // CHECK-DIFFERENT-TYPE-FINGERPRINT-DAG: > topLevel implementation '' P true // CHECK-DIFFERENT-TYPE-FINGERPRINT-DAG: > topLevel interface '' P true // CHECK-DIFFERENT-TYPE-FINGERPRINT-DAG: < nominal implementation 4main1P{{[^ ]+}} '' true // CHECK-DIFFERENT-TYPE-FINGERPRINT-DAG: < nominal interface 4main1P{{[^ ]+}} '' true // CHECK-DIFFERENT-TYPE-FINGERPRINT-DAG: > nominal implementation 4main1P{{[^ ]+}} '' true // CHECK-DIFFERENT-TYPE-FINGERPRINT-DAG: > nominal interface 4main1P{{[^ ]+}} '' true // CHECK-DIFFERENT-TYPE-FINGERPRINT-DAG: < potentialMember implementation 4main1P{{[^ ]+}} '' true // CHECK-DIFFERENT-TYPE-FINGERPRINT-DAG: < potentialMember interface 4main1P{{[^ ]+}} '' true // CHECK-DIFFERENT-TYPE-FINGERPRINT-DAG: > potentialMember implementation 4main1P{{[^ ]+}} '' true // CHECK-DIFFERENT-TYPE-FINGERPRINT-DAG: > potentialMember interface 4main1P{{[^ ]+}} '' true
apache-2.0
natecook1000/swift
stdlib/public/SDK/Foundation/NSArray.swift
2
5307
//===----------------------------------------------------------------------===// // // 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 // //===----------------------------------------------------------------------===// @_exported import Foundation // Clang module //===----------------------------------------------------------------------===// // Arrays //===----------------------------------------------------------------------===// extension NSArray : ExpressibleByArrayLiteral { /// Create an instance initialized with `elements`. public required convenience init(arrayLiteral elements: Any...) { // Let bridging take care of it. self.init(array: elements) } } extension Array : _ObjectiveCBridgeable { /// Private initializer used for bridging. /// /// The provided `NSArray` will be copied to ensure that the copy can /// not be mutated by other code. internal init(_cocoaArray: NSArray) { assert(_isBridgedVerbatimToObjectiveC(Element.self), "Array can be backed by NSArray only when the element type can be bridged verbatim to Objective-C") // FIXME: We would like to call CFArrayCreateCopy() to avoid doing an // objc_msgSend() for instances of CoreFoundation types. We can't do that // today because CFArrayCreateCopy() copies array contents unconditionally, // resulting in O(n) copies even for immutable arrays. // // <rdar://problem/19773555> CFArrayCreateCopy() is >10x slower than // -[NSArray copyWithZone:] // // The bug is fixed in: OS X 10.11.0, iOS 9.0, all versions of tvOS // and watchOS. self = Array( _immutableCocoaArray: unsafeBitCast(_cocoaArray.copy() as AnyObject, to: _NSArrayCore.self)) } @_semantics("convertToObjectiveC") public func _bridgeToObjectiveC() -> NSArray { return unsafeBitCast(self._bridgeToObjectiveCImpl(), to: NSArray.self) } public static func _forceBridgeFromObjectiveC( _ source: NSArray, result: inout Array? ) { // If we have the appropriate native storage already, just adopt it. if let native = Array._bridgeFromObjectiveCAdoptingNativeStorageOf(source) { result = native return } if _fastPath(_isBridgedVerbatimToObjectiveC(Element.self)) { // Forced down-cast (possible deferred type-checking) result = Array(_cocoaArray: source) return } result = _arrayForceCast([AnyObject](_cocoaArray: source)) } public static func _conditionallyBridgeFromObjectiveC( _ source: NSArray, result: inout Array? ) -> Bool { // Construct the result array by conditionally bridging each element. let anyObjectArr = [AnyObject](_cocoaArray: source) result = _arrayConditionalCast(anyObjectArr) return result != nil } public static func _unconditionallyBridgeFromObjectiveC( _ source: NSArray? ) -> Array { // `nil` has historically been used as a stand-in for an empty // array; map it to an empty array instead of failing. if _slowPath(source == nil) { return Array() } // If we have the appropriate native storage already, just adopt it. if let native = Array._bridgeFromObjectiveCAdoptingNativeStorageOf(source!) { return native } if _fastPath(_isBridgedVerbatimToObjectiveC(Element.self)) { // Forced down-cast (possible deferred type-checking) return Array(_cocoaArray: source!) } return _arrayForceCast([AnyObject](_cocoaArray: source!)) } } extension NSArray : _HasCustomAnyHashableRepresentation { // Must be @nonobjc to avoid infinite recursion during bridging @nonobjc public func _toCustomAnyHashable() -> AnyHashable? { return AnyHashable(self as! Array<AnyHashable>) } } extension NSArray : Sequence { /// Return an *iterator* over the elements of this *sequence*. /// /// - Complexity: O(1). final public func makeIterator() -> NSFastEnumerationIterator { return NSFastEnumerationIterator(self) } } /* TODO: API review extension NSArray : Swift.Collection { final public var startIndex: Int { return 0 } final public var endIndex: Int { return count } } */ extension NSArray { // Overlay: - (instancetype)initWithObjects:(id)firstObj, ... public convenience init(objects elements: Any...) { self.init(array: elements) } } extension NSArray { /// Initializes a newly allocated array by placing in it the objects /// contained in a given array. /// /// - Returns: An array initialized to contain the objects in /// `anArray``. The returned object might be different than the /// original receiver. /// /// Discussion: After an immutable array has been initialized in /// this way, it cannot be modified. @nonobjc public convenience init(array anArray: NSArray) { self.init(array: anArray as Array) } } extension NSArray : CustomReflectable { public var customMirror: Mirror { return Mirror(reflecting: self as [AnyObject]) } } extension Array: CVarArg {}
apache-2.0
kstaring/swift
validation-test/compiler_crashers_fixed/27662-swift-valuedecl-settype.swift
11
462
// This source file is part of the Swift.org open source project // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -parse {==1 enum A{ class a<T where I:a{ struct B{ var _=a class a<a class a
apache-2.0
kstaring/swift
test/decl/enum/objc_enum_multi_file.swift
4
2040
// RUN: not %target-swift-frontend -module-name main %s -primary-file %S/Inputs/objc_enum_multi_file_helper.swift -parse -D NO_RAW_TYPE 2>&1 | %FileCheck -check-prefix=NO_RAW_TYPE %s // RUN: not %target-swift-frontend -module-name main %s -primary-file %S/Inputs/objc_enum_multi_file_helper.swift -parse -D BAD_RAW_TYPE 2>&1 | %FileCheck -check-prefix=BAD_RAW_TYPE %s // RUN: not %target-swift-frontend -module-name main %s -primary-file %S/Inputs/objc_enum_multi_file_helper.swift -parse -D NON_INT_RAW_TYPE 2>&1 | %FileCheck -check-prefix=NON_INT_RAW_TYPE %s // RUN: not %target-swift-frontend -module-name main %s -primary-file %S/Inputs/objc_enum_multi_file_helper.swift -parse -D NO_CASES 2>&1 | %FileCheck -check-prefix=NO_CASES %s // RUN: not %target-swift-frontend -module-name main %s -primary-file %S/Inputs/objc_enum_multi_file_helper.swift -parse -D DUPLICATE_CASES 2>&1 | %FileCheck -check-prefix=DUPLICATE_CASES %s // Note that the *other* file is the primary file in this test! #if NO_RAW_TYPE // NO_RAW_TYPE: :[[@LINE+1]]:12: error: '@objc' enum must declare an integer raw type @objc enum TheEnum { case A } #elseif BAD_RAW_TYPE // BAD_RAW_TYPE: :[[@LINE+1]]:22: error: '@objc' enum raw type 'Array<Int>' is not an integer type @objc enum TheEnum : Array<Int> { case A } #elseif NON_INT_RAW_TYPE // NON_INT_RAW_TYPE: :[[@LINE+1]]:22: error: '@objc' enum raw type 'Float' is not an integer type @objc enum TheEnum : Float { case A = 0.0 } #elseif NO_CASES // NO_CASES: :[[@LINE+1]]:22: error: an enum with no cases cannot declare a raw type @objc enum TheEnum : Int32 { static var A: TheEnum! { return nil } } #elseif DUPLICATE_CASES @objc enum TheEnum : Int32 { case A case B = 0 // DUPLICATE_CASES: :[[@LINE-1]]:12: error: raw value for enum case is not unique // DUPLICATE_CASES: :[[@LINE-3]]:8: note: raw value previously used here // DUPLICATE_CASES: :[[@LINE-4]]:8: note: raw value implicitly auto-incremented from zero } #else enum TheEnum: Invalid { // should never be hit case A } #endif
apache-2.0
grantmagdanz/InupiaqKeyboard
Keyboard/DirectionEnum.swift
2
1527
// // Direction.swift // TransliteratingKeyboard // // Created by Alexei Baboulevitch on 7/19/14. // Copyright (c) 2014 Apple. All rights reserved. // enum Direction: Int, CustomStringConvertible { case Left = 0 case Down = 3 case Right = 2 case Up = 1 var description: String { get { switch self { case Left: return "Left" case Right: return "Right" case Up: return "Up" case Down: return "Down" } } } func clockwise() -> Direction { switch self { case Left: return Up case Right: return Down case Up: return Right case Down: return Left } } func counterclockwise() -> Direction { switch self { case Left: return Down case Right: return Up case Up: return Left case Down: return Right } } func opposite() -> Direction { switch self { case Left: return Right case Right: return Left case Up: return Down case Down: return Up } } func horizontal() -> Bool { switch self { case Left, Right: return true default: return false } } }
bsd-3-clause
antlr/antlr4
runtime/Swift/Sources/Antlr4/atn/ProfilingATNSimulator.swift
7
9326
/// /// Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. /// Use of this file is governed by the BSD 3-clause license that /// can be found in the LICENSE.txt file in the project root. /// /// /// - 4.3 /// import Foundation public class ProfilingATNSimulator: ParserATNSimulator { private(set) var decisions: [DecisionInfo] internal var numDecisions: Int = 0 internal var _sllStopIndex: Int = 0 internal var _llStopIndex: Int = 0 internal var currentDecision: Int = 0 internal var currentState: DFAState? /// /// At the point of LL failover, we record how SLL would resolve the conflict so that /// we can determine whether or not a decision / input pair is context-sensitive. /// If LL gives a different result than SLL's predicted alternative, we have a /// context sensitivity for sure. The converse is not necessarily true, however. /// It's possible that after conflict resolution chooses minimum alternatives, /// SLL could get the same answer as LL. Regardless of whether or not the result indicates /// an ambiguity, it is not treated as a context sensitivity because LL prediction /// was not required in order to produce a correct prediction for this decision and input sequence. /// It may in fact still be a context sensitivity but we don't know by looking at the /// minimum alternatives for the current input. /// internal var conflictingAltResolvedBySLL: Int = 0 public init(_ parser: Parser) { decisions = [DecisionInfo]() super.init(parser, parser.getInterpreter().atn, parser.getInterpreter().decisionToDFA, parser.getInterpreter().sharedContextCache) numDecisions = atn.decisionToState.count for i in 0..<numDecisions { decisions[i] = DecisionInfo(i) } } override public func adaptivePredict(_ input: TokenStream, _ decision: Int,_ outerContext: ParserRuleContext?) throws -> Int { let outerContext = outerContext self._sllStopIndex = -1 self._llStopIndex = -1 self.currentDecision = decision let start: Int64 = Int64(Date().timeIntervalSince1970) //System.nanoTime(); // expensive but useful info let alt: Int = try super.adaptivePredict(input, decision, outerContext) let stop: Int64 = Int64(Date().timeIntervalSince1970) //System.nanoTime(); decisions[decision].timeInPrediction += (stop - start) decisions[decision].invocations += 1 let SLL_k: Int64 = Int64(_sllStopIndex - _startIndex + 1) decisions[decision].SLL_TotalLook += SLL_k decisions[decision].SLL_MinLook = decisions[decision].SLL_MinLook == 0 ? SLL_k : min(decisions[decision].SLL_MinLook, SLL_k) if SLL_k > decisions[decision].SLL_MaxLook { decisions[decision].SLL_MaxLook = SLL_k decisions[decision].SLL_MaxLookEvent = LookaheadEventInfo(decision, nil, input, _startIndex, _sllStopIndex, false) } if _llStopIndex >= 0 { let LL_k: Int64 = Int64(_llStopIndex - _startIndex + 1) decisions[decision].LL_TotalLook += LL_k decisions[decision].LL_MinLook = decisions[decision].LL_MinLook == 0 ? LL_k : min(decisions[decision].LL_MinLook, LL_k) if LL_k > decisions[decision].LL_MaxLook { decisions[decision].LL_MaxLook = LL_k decisions[decision].LL_MaxLookEvent = LookaheadEventInfo(decision, nil, input, _startIndex, _llStopIndex, true) } } defer { self.currentDecision = -1 } return alt } override internal func getExistingTargetState(_ previousD: DFAState, _ t: Int) -> DFAState? { // this method is called after each time the input position advances // during SLL prediction _sllStopIndex = _input.index() let existingTargetState: DFAState? = super.getExistingTargetState(previousD, t) if existingTargetState != nil { decisions[currentDecision].SLL_DFATransitions += 1 // count only if we transition over a DFA state if existingTargetState == ATNSimulator.ERROR { decisions[currentDecision].errors.append( ErrorInfo(currentDecision, previousD.configs, _input, _startIndex, _sllStopIndex, false) ) } } currentState = existingTargetState return existingTargetState } override internal func computeTargetState(_ dfa: DFA, _ previousD: DFAState, _ t: Int) throws -> DFAState { let state = try super.computeTargetState(dfa, previousD, t) currentState = state return state } override internal func computeReachSet(_ closure: ATNConfigSet, _ t: Int, _ fullCtx: Bool) throws -> ATNConfigSet? { if fullCtx { // this method is called after each time the input position advances // during full context prediction _llStopIndex = _input.index() } let reachConfigs = try super.computeReachSet(closure, t, fullCtx) if fullCtx { decisions[currentDecision].LL_ATNTransitions += 1 // count computation even if error if reachConfigs != nil { } else { // no reach on current lookahead symbol. ERROR. // TODO: does not handle delayed errors per getSynValidOrSemInvalidAltThatFinishedDecisionEntryRule() decisions[currentDecision].errors.append( ErrorInfo(currentDecision, closure, _input, _startIndex, _llStopIndex, true) ) } } else { decisions[currentDecision].SLL_ATNTransitions += 1 if reachConfigs != nil { } else { // no reach on current lookahead symbol. ERROR. decisions[currentDecision].errors.append( ErrorInfo(currentDecision, closure, _input, _startIndex, _sllStopIndex, false) ) } } return reachConfigs } override internal func evalSemanticContext(_ pred: SemanticContext, _ parserCallStack: ParserRuleContext, _ alt: Int, _ fullCtx: Bool) throws -> Bool { let result = try super.evalSemanticContext(pred, parserCallStack, alt, fullCtx) if !(pred is SemanticContext.PrecedencePredicate) { let fullContext = _llStopIndex >= 0 let stopIndex = fullContext ? _llStopIndex : _sllStopIndex decisions[currentDecision].predicateEvals.append( PredicateEvalInfo(currentDecision, _input, _startIndex, stopIndex, pred, result, alt, fullCtx) ) } return result } override internal func reportAttemptingFullContext(_ dfa: DFA, _ conflictingAlts: BitSet?, _ configs: ATNConfigSet, _ startIndex: Int, _ stopIndex: Int) { if let conflictingAlts = conflictingAlts { conflictingAltResolvedBySLL = conflictingAlts.firstSetBit() } else { let configAlts = configs.getAlts() conflictingAltResolvedBySLL = configAlts.firstSetBit() } decisions[currentDecision].LL_Fallback += 1 super.reportAttemptingFullContext(dfa, conflictingAlts, configs, startIndex, stopIndex) } override internal func reportContextSensitivity(_ dfa: DFA, _ prediction: Int, _ configs: ATNConfigSet, _ startIndex: Int, _ stopIndex: Int) { if prediction != conflictingAltResolvedBySLL { decisions[currentDecision].contextSensitivities.append( ContextSensitivityInfo(currentDecision, configs, _input, startIndex, stopIndex) ) } super.reportContextSensitivity(dfa, prediction, configs, startIndex, stopIndex) } override internal func reportAmbiguity(_ dfa: DFA, _ D: DFAState, _ startIndex: Int, _ stopIndex: Int, _ exact: Bool, _ ambigAlts: BitSet?, _ configs: ATNConfigSet) { var prediction: Int if let ambigAlts = ambigAlts { prediction = ambigAlts.firstSetBit() } else { let configAlts = configs.getAlts() prediction = configAlts.firstSetBit() } if configs.fullCtx && prediction != conflictingAltResolvedBySLL { // Even though this is an ambiguity we are reporting, we can // still detect some context sensitivities. Both SLL and LL // are showing a conflict, hence an ambiguity, but if they resolve // to different minimum alternatives we have also identified a // context sensitivity. decisions[currentDecision].contextSensitivities.append( ContextSensitivityInfo(currentDecision, configs, _input, startIndex, stopIndex) ) } decisions[currentDecision].ambiguities.append( AmbiguityInfo(currentDecision, configs, ambigAlts!, _input, startIndex, stopIndex, configs.fullCtx) ) super.reportAmbiguity(dfa, D, startIndex, stopIndex, exact, ambigAlts!, configs) } public func getDecisionInfo() -> [DecisionInfo] { return decisions } }
bsd-3-clause
yichizhang/JCTiledScrollView_Swift
Demo/Demo-Swift/Demo-Swift/ViewController.swift
1
7534
// // Copyright (c) 2015-present Yichi Zhang // https://github.com/yichizhang // zhang-yi-chi@hotmail.com // // This source code is licensed under MIT license found in the LICENSE file // in the root directory of this source tree. // Attribution can be found in the ATTRIBUTION file in the root directory // of this source tree. // import UIKit enum JCDemoType { case PDF case Image } let SkippingGirlImageName = "SkippingGirl" let SkippingGirlImageSize = CGSize(width: 432, height: 648) let ButtonTitleCancel = "Cancel" let ButtonTitleRemoveAnnotation = "Remove this Annotation" @objc class ViewController: UIViewController, JCTiledScrollViewDelegate, JCTileSource, UIAlertViewDelegate { let demoAnnotationViewReuseID = "DemoAnnotationView" var scrollView: JCTiledScrollView! var infoLabel: UILabel! var searchField: UITextField! var mode: JCDemoType! weak var selectedAnnotation: JCAnnotation? override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. if (mode == JCDemoType.PDF) { scrollView = JCTiledPDFScrollView( frame: self.view.bounds, URL: Bundle.main.url(forResource: "Map", withExtension: "pdf")! ) } else { scrollView = JCTiledScrollView(frame: self.view.bounds, contentSize: SkippingGirlImageSize) } scrollView.tiledScrollViewDelegate = self scrollView.zoomScale = 1.0 scrollView.dataSource = self scrollView.tiledScrollViewDelegate = self scrollView.tiledView.shouldAnnotateRect = true // totals 4 sets of tiles across all devices, retina devices will miss out on the first 1x set scrollView.levelsOfZoom = 3 scrollView.levelsOfDetail = 3 scrollView.translatesAutoresizingMaskIntoConstraints = false view.addSubview(scrollView) infoLabel = UILabel(frame: .zero) infoLabel.backgroundColor = UIColor.black infoLabel.textColor = UIColor.white infoLabel.textAlignment = NSTextAlignment.center infoLabel.translatesAutoresizingMaskIntoConstraints = false view.addSubview(infoLabel) view.addConstraints([ NSLayoutConstraint(item: scrollView, attribute: .width, relatedBy: .equal, toItem: view, attribute: .width, multiplier: 1, constant: 0), NSLayoutConstraint(item: scrollView, attribute: .height, relatedBy: .equal, toItem: view, attribute: .height, multiplier: 1, constant: 0), NSLayoutConstraint(item: scrollView, attribute: .top, relatedBy: .equal, toItem: view, attribute: .top, multiplier: 1, constant: 0), NSLayoutConstraint(item: scrollView, attribute: .leading, relatedBy: .equal, toItem: view, attribute: .leading, multiplier: 1, constant: 0), NSLayoutConstraint(item: infoLabel, attribute: .top, relatedBy: .equal, toItem: view, attribute: .top, multiplier: 1, constant: 20), NSLayoutConstraint(item: infoLabel, attribute: .centerX, relatedBy: .equal, toItem: view, attribute: .centerX, multiplier: 1, constant: 0), ]) addRandomAnnotations() scrollView.refreshAnnotations() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func addRandomAnnotations() { for number in 0 ... 8 { let annotation = DemoAnnotation(isSelectable: (number % 3 != 0)) let w = UInt32(UInt(scrollView.tiledView.bounds.width)) let h = UInt32(UInt(scrollView.tiledView.bounds.height)) annotation.contentPosition = CGPoint( x: CGFloat(UInt(arc4random_uniform(w))), y: CGFloat(UInt(arc4random_uniform(h))) ) scrollView.addAnnotation(annotation) } } // MARK: JCTiledScrollView Delegate func tiledScrollViewDidZoom(_ scrollView: JCTiledScrollView) { infoLabel.text = NSString(format: "zoomScale=%.2f", scrollView.zoomScale) as String } func tiledScrollView(_ scrollView: JCTiledScrollView, didReceiveSingleTap gestureRecognizer: UIGestureRecognizer) { let tapPoint: CGPoint = gestureRecognizer.location(in: scrollView.tiledView) infoLabel.text = NSString(format: "(%.2f, %.2f), zoomScale=%.2f", tapPoint.x, tapPoint.y, scrollView.zoomScale) as String } func tiledScrollView(_ scrollView: JCTiledScrollView, shouldSelectAnnotationView view: JCAnnotationView) -> Bool { if let annotation = view.annotation as? DemoAnnotation { return annotation.isSelectable } return true } func tiledScrollView(_ scrollView: JCTiledScrollView, didSelectAnnotationView view: JCAnnotationView) { guard let annotationView = view as? DemoAnnotationView, let annotation = annotationView.annotation as? DemoAnnotation else { return } let alertView = UIAlertView( title: "Annotation Selected", message: "You've selected an annotation. What would you like to do with it?", delegate: self, cancelButtonTitle: ButtonTitleCancel, otherButtonTitles: ButtonTitleRemoveAnnotation) alertView.show() selectedAnnotation = annotation annotation.isSelected = true annotationView.update(forAnnotation: annotation) } func tiledScrollView(_ scrollView: JCTiledScrollView, didDeselectAnnotationView view: JCAnnotationView) { guard let annotationView = view as? DemoAnnotationView, let annotation = annotationView.annotation as? DemoAnnotation else { return } selectedAnnotation = nil annotation.isSelected = false annotationView.update(forAnnotation: annotation) } func tiledScrollView(_ scrollView: JCTiledScrollView, viewForAnnotation annotation: JCAnnotation) -> JCAnnotationView { var annotationView: DemoAnnotationView! annotationView = (scrollView.dequeueReusableAnnotationViewWithReuseIdentifier(demoAnnotationViewReuseID) as? DemoAnnotationView) ?? DemoAnnotationView(frame: .zero, annotation: annotation, reuseIdentifier: demoAnnotationViewReuseID) annotationView.update(forAnnotation: annotation as? DemoAnnotation) return annotationView } func tiledScrollView(_ scrollView: JCTiledScrollView, imageForRow row: Int, column: Int, scale: Int) -> UIImage { let fileName = NSString(format: "%@_%dx_%d_%d.png", SkippingGirlImageName, scale, row, column) as String return UIImage(named: fileName)! } // MARK: UIAlertView Delegate func alertView(_ alertView: UIAlertView, clickedButtonAt buttonIndex: Int) { guard let buttonTitle = alertView.buttonTitle(at: buttonIndex) else { return } switch buttonTitle { case ButtonTitleCancel: break case ButtonTitleRemoveAnnotation: if let selectedAnnotation = self.selectedAnnotation { scrollView.removeAnnotation(selectedAnnotation) } default: break } } }
mit
ReactiveCocoa/ReactiveSwift
ReactiveSwift.playground/Pages/Property.xcplaygroundpage/Contents.swift
1
9388
/*: > # IMPORTANT: To use `ReactiveSwift.playground`, please: 1. Retrieve the project dependencies using one of the following terminal commands from the ReactiveSwift project root directory: - `git submodule update --init` **OR**, if you have [Carthage](https://github.com/Carthage/Carthage) installed - `carthage checkout` 1. Open `ReactiveSwift.xcworkspace` 1. Build `ReactiveSwift-macOS` scheme 1. Finally open the `ReactiveSwift.playground` 1. Choose `View > Show Debug Area` */ import ReactiveSwift import Foundation /*: ## Property A **property**, represented by the [`PropertyProtocol`](https://github.com/ReactiveCocoa/ReactiveSwift/blob/master/Sources/Property.swift) , stores a value and notifies observers about future changes to that value. - The current value of a property can be obtained from the `value` getter. - The `producer` getter returns a [signal producer](SignalProducer) that will send the property’s current value, followed by all changes over time. - The `signal` getter returns a [signal](Signal) that will send all changes over time, but not the initial value. */ scopedExample("Creation") { let mutableProperty = MutableProperty(1) // The value of the property can be accessed via its `value` attribute print("Property has initial value \(mutableProperty.value)") // The properties value can be observed via its `producer` or `signal attribute` // Note, how the `producer` immediately sends the initial value, but the `signal` only sends new values mutableProperty.producer.startWithValues { print("mutableProperty.producer received \($0)") } mutableProperty.signal.observeValues { print("mutableProperty.signal received \($0)") } print("---") print("Setting new value for mutableProperty: 2") mutableProperty.value = 2 print("---") // If a property should be exposed for readonly access, it can be wrapped in a Property let property = Property(mutableProperty) print("Reading value of readonly property: \(property.value)") property.signal.observeValues { print("property.signal received \($0)") } // Its not possible to set the value of a Property // readonlyProperty.value = 3 // But you can still change the value of the mutableProperty and observe its change on the property print("---") print("Setting new value for mutableProperty: 3") mutableProperty.value = 3 // Constant properties can be created by using the `Property(value:)` initializer let constant = Property(value: 1) // constant.value = 2 // The value of a constant property can not be changed } /*: ### Binding The `<~` operator can be used to bind properties in different ways. Note that in all cases, the target has to be a binding target, represented by the [`BindingTargetProvider`](https://github.com/ReactiveCocoa/ReactiveSwift/blob/master/Sources/UnidirectionalBinding.swift). All mutable property types, represented by the [`MutablePropertyProtocol`](https://github.com/ReactiveCocoa/ReactiveSwift/blob/master/Sources/Property.swift#L38), are inherently binding targets. * `property <~ signal` binds a [signal](Signal) to the property, updating the property’s value to the latest value sent by the signal. * `property <~ producer` starts the given [signal producer](SignalProducer), and binds the property’s value to the latest value sent on the started signal. * `property <~ otherProperty` binds one property to another, so that the destination property’s value is updated whenever the source property is updated. */ scopedExample("Binding from SignalProducer") { let producer = SignalProducer<Int, Never> { observer, _ in print("New subscription, starting operation") observer.send(value: 1) observer.send(value: 2) } let property = MutableProperty(0) property.producer.startWithValues { print("Property received \($0)") } // Notice how the producer will start the work as soon it is bound to the property property <~ producer } scopedExample("Binding from Signal") { let (signal, observer) = Signal<Int, Never>.pipe() let property = MutableProperty(0) property.producer.startWithValues { print("Property received \($0)") } property <~ signal print("Sending new value on signal: 1") observer.send(value: 1) print("Sending new value on signal: 2") observer.send(value: 2) } scopedExample("Binding from other Property") { let property = MutableProperty(0) property.producer.startWithValues { print("Property received \($0)") } let otherProperty = MutableProperty(0) // Notice how property receives another value of 0 as soon as the binding is established property <~ otherProperty print("Setting new value for otherProperty: 1") otherProperty.value = 1 print("Setting new value for otherProperty: 2") otherProperty.value = 2 } /*: ### Transformations Properties provide a number of transformations like `map`, `combineLatest` or `zip` for manipulation similar to [signal](Signal) and [signal producer](SignalProducer) */ scopedExample("`map`") { let property = MutableProperty(0) let mapped = property.map { $0 * 2 } mapped.producer.startWithValues { print("Mapped property received \($0)") } print("Setting new value for property: 1") property.value = 1 print("Setting new value for property: 2") property.value = 2 } scopedExample("`skipRepeats`") { let property = MutableProperty(0) let skipRepeatsProperty = property.skipRepeats() property.producer.startWithValues { print("Property received \($0)") } skipRepeatsProperty.producer.startWithValues { print("Skip-Repeats property received \($0)") } print("Setting new value for property: 0") property.value = 0 print("Setting new value for property: 1") property.value = 1 print("Setting new value for property: 1") property.value = 1 print("Setting new value for property: 0") property.value = 0 } scopedExample("`uniqueValues`") { let property = MutableProperty(0) let unique = property.uniqueValues() property.producer.startWithValues { print("Property received \($0)") } unique.producer.startWithValues { print("Unique values property received \($0)") } print("Setting new value for property: 0") property.value = 0 print("Setting new value for property: 1") property.value = 1 print("Setting new value for property: 1") property.value = 1 print("Setting new value for property: 0") property.value = 0 } scopedExample("`combineLatest`") { let propertyA = MutableProperty(0) let propertyB = MutableProperty("A") let combined = propertyA.combineLatest(with: propertyB) combined.producer.startWithValues { print("Combined property received \($0)") } print("Setting new value for propertyA: 1") propertyA.value = 1 print("Setting new value for propertyB: 'B'") propertyB.value = "B" print("Setting new value for propertyB: 'C'") propertyB.value = "C" print("Setting new value for propertyB: 'D'") propertyB.value = "D" print("Setting new value for propertyA: 2") propertyA.value = 2 } scopedExample("`zip`") { let propertyA = MutableProperty(0) let propertyB = MutableProperty("A") let zipped = propertyA.zip(with: propertyB) zipped.producer.startWithValues { print("Zipped property received \($0)") } print("Setting new value for propertyA: 1") propertyA.value = 1 print("Setting new value for propertyB: 'B'") propertyB.value = "B" // Observe that, in contrast to `combineLatest`, setting a new value for propertyB does not cause a new value for the zipped property until propertyA has a new value as well print("Setting new value for propertyB: 'C'") propertyB.value = "C" print("Setting new value for propertyB: 'D'") propertyB.value = "D" print("Setting new value for propertyA: 2") propertyA.value = 2 } scopedExample("`flatten`") { let property1 = MutableProperty("0") let property2 = MutableProperty("A") let property3 = MutableProperty("!") let property = MutableProperty(property1) // Try different merge strategies and see how the results change property.flatten(.latest).producer.startWithValues { print("Flattened property receive \($0)") } print("Sending new value on property1: 1") property1.value = "1" print("Sending new value on property: property2") property.value = property2 print("Sending new value on property1: 2") property1.value = "2" print("Sending new value on property2: B") property2.value = "B" print("Sending new value on property1: 3") property1.value = "3" print("Sending new value on property: property3") property.value = property3 print("Sending new value on property3: ?") property3.value = "?" print("Sending new value on property2: C") property2.value = "C" print("Sending new value on property1: 4") property1.value = "4" }
mit
huangboju/Moots
算法学习/LeetCode/LeetCode/EvalRPN.swift
1
989
// // EvalRPN.swift // LeetCode // // Created by 黄伯驹 on 2019/9/21. // Copyright © 2019 伯驹 黄. All rights reserved. // import Foundation // 逆波兰表达式 // https://zh.wikipedia.org/wiki/%E9%80%86%E6%B3%A2%E5%85%B0%E8%A1%A8%E7%A4%BA%E6%B3%95 // https://www.jianshu.com/p/f2c88d983ff5 func evalRPN(_ tokens: [String]) -> Int { let operators: Set<String> = ["*","+","/","-"] var stack = Array<Int>() for token in tokens { if operators.contains(token) { let num1 = stack.removeLast() let index = stack.count - 1 switch token { case "*": stack[index] *= num1 case "-": stack[index] -= num1 case "+": stack[index] += num1 case "/": stack[index] /= num1 default: break } continue } stack.append(Int(token)!) } return stack[0] }
mit
vanshg/MacAssistant
Pods/Magnet/Lib/Magnet/KeyCombo.swift
1
3115
// // KeyCombo.swift // Magnet // // Created by 古林俊佑 on 2016/03/09. // Copyright © 2016年 Shunsuke Furubayashi. All rights reserved. // import Cocoa import Carbon public final class KeyCombo: NSObject, NSCopying, NSCoding, Codable { // MARK: - Properties public let keyCode: Int public let modifiers: Int public let doubledModifiers: Bool public var characters: String { if doubledModifiers { return "" } return KeyCodeTransformer.shared.transformValue(keyCode, carbonModifiers: modifiers) } // MARK: - Initialize public init?(keyCode: Int, carbonModifiers: Int) { if keyCode < 0 || carbonModifiers < 0 { return nil } if KeyTransformer.containsFunctionKey(keyCode) { self.modifiers = Int(UInt(carbonModifiers) | NSEvent.ModifierFlags.function.rawValue) } else { self.modifiers = carbonModifiers } self.keyCode = keyCode self.doubledModifiers = false } public init?(keyCode: Int, cocoaModifiers: NSEvent.ModifierFlags) { if keyCode < 0 || !KeyTransformer.supportedCocoaFlags(cocoaModifiers) { return nil } if KeyTransformer.containsFunctionKey(keyCode) { self.modifiers = Int(UInt(KeyTransformer.carbonFlags(from: cocoaModifiers)) | NSEvent.ModifierFlags.function.rawValue) } else { self.modifiers = KeyTransformer.carbonFlags(from: cocoaModifiers) } self.keyCode = keyCode self.doubledModifiers = false } public init?(doubledCarbonModifiers modifiers: Int) { if !KeyTransformer.singleCarbonFlags(modifiers) { return nil } self.keyCode = 0 self.modifiers = modifiers self.doubledModifiers = true } public init?(doubledCocoaModifiers modifiers: NSEvent.ModifierFlags) { if !KeyTransformer.singleCocoaFlags(modifiers) { return nil } self.keyCode = 0 self.modifiers = KeyTransformer.carbonFlags(from: modifiers) self.doubledModifiers = true } public func copy(with zone: NSZone?) -> Any { if doubledModifiers { return KeyCombo(doubledCarbonModifiers: modifiers)! } else { return KeyCombo(keyCode: keyCode, carbonModifiers: modifiers)! } } public init?(coder aDecoder: NSCoder) { self.keyCode = aDecoder.decodeInteger(forKey: "keyCode") self.modifiers = aDecoder.decodeInteger(forKey: "modifiers") self.doubledModifiers = aDecoder.decodeBool(forKey: "doubledModifiers") } public func encode(with aCoder: NSCoder) { aCoder.encode(keyCode, forKey: "keyCode") aCoder.encode(modifiers, forKey: "modifiers") aCoder.encode(doubledModifiers, forKey: "doubledModifiers") } // MARK: - Equatable public override func isEqual(_ object: Any?) -> Bool { guard let keyCombo = object as? KeyCombo else { return false } return keyCode == keyCombo.keyCode && modifiers == keyCombo.modifiers && doubledModifiers == keyCombo.doubledModifiers } }
mit
brunomorgado/RxErrorTracker
Example/RxErrorTracker/AppDelegate.swift
1
2184
// // AppDelegate.swift // RxErrorTracker // // Created by Bruno Morgado on 08/03/2016. // Copyright (c) 2016 Bruno Morgado. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
mit
mightydeveloper/swift
test/Sema/object_literals.swift
9
501
// RUN: %target-parse-verify-swift struct S: _ColorLiteralConvertible { init(colorLiteralRed: Float, green: Float, blue: Float, alpha: Float) {} } let y: S = [#Color(colorLiteralRed: 1, green: 0, blue: 0, alpha: 1)#] struct I: _ImageLiteralConvertible { init(imageLiteral: String) {} } let z: I = [#Image(imageLiteral: "hello.png")#] struct Path: _FileReferenceLiteralConvertible { init(fileReferenceLiteral: String) {} } let p1: Path = [#FileReference(fileReferenceLiteral: "what.txt")#]
apache-2.0
swiftde/27-CoreLocation
CoreLocation-Tutorial/CoreLocation-TutorialTests/CoreLocation_TutorialTests.swift
2
951
// // CoreLocation_TutorialTests.swift // CoreLocation-TutorialTests // // Created by Benjamin Herzog on 06.09.14. // Copyright (c) 2014 Benjamin Herzog. All rights reserved. // import UIKit import XCTest class CoreLocation_TutorialTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // This is an example of a functional test case. XCTAssert(true, "Pass") } func testPerformanceExample() { // This is an example of a performance test case. self.measureBlock() { // Put the code you want to measure the time of here. } } }
gpl-2.0
ziaukhan/Swift-Big-Nerd-Ranch-Guide
chapter 6/Chap6/Chap6/BNRHypnosisView.swift
1
2729
// // BNRHypnosisView.swift // Chap4 // import UIKit class BNRHypnosisView: UIView { override init(frame: CGRect) { super.init(frame: frame) // Initialization code //All BNRHyponosisView starts with a clear background Color self.backgroundColor = UIColor.clearColor() var circleColor:UIColor = UIColor.lightGrayColor() } required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } var circleColor:UIColor = UIColor.lightGrayColor() override func drawRect(rect: CGRect) { var bounds = self.bounds //figure out the center of the bounds rectangle var center = CGPoint() center.x = (bounds.origin.x + bounds.size.width) / 2.0 center.y = (bounds.origin.y + bounds.size.height) / 2.0 /*//The circle will be the largest that will fit in the view var radius:CGFloat = hypot(bounds.size.width, bounds.size.height)/4.0 */ var path = UIBezierPath() /*//Add an arc to the path at center, with radius of radius, //from 0 to 2*PI randian (a circle) var startAngle:CGFloat = 0.0 path.addArcWithCenter(center, radius: radius, startAngle: startAngle, endAngle: Float(M_PI)*2.0, clockwise: true) */ var maxRadius = hypot(bounds.size.width, bounds.size.height)/2.0 for(var currentRadius = maxRadius; currentRadius > 0; currentRadius -= 20){ path.moveToPoint(CGPointMake(center.x + currentRadius, center.y)) var startAngle:CGFloat = 0.0 path.addArcWithCenter(center, radius:currentRadius, // Note this is currentRadius! startAngle: startAngle, endAngle: CGFloat(M_PI)*2.0, clockwise: true) } ///Congigure line width to 10 points path.lineWidth = 10 //Configure the drawing color to light gray self.circleColor.setStroke() //draw the line path.stroke() // --- END CHAPTER # 4 // } override func touchesBegan(touches: NSSet, withEvent event: UIEvent) { //get 3 random number b/w 0 and 1 var red:CGFloat = CGFloat(Float(arc4random()) % 100.0) / 100.0 var greenn:CGFloat = CGFloat(Float(arc4random()) % 100.0) / 100.0 var blue:CGFloat = CGFloat(Float(arc4random()) % 100.0) / 100.0 var randomColor = UIColor(red: red, green: greenn, blue: blue, alpha: 1.0) self.circleColor = randomColor self.setNeedsDisplay() } }
apache-2.0
cnoon/swift-compiler-crashes
crashes-duplicates/19617-swift-typechecker-validatedecl.swift
10
253
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing struct c<T where T:e{var d{struct c{enum A{enum A{struct c{enum b{{}class A{init(){a
mit
testpress/ios-app
ios-appTests/ViewController/PhoneVerification.swift
1
4785
// // PhoneVerification.swift // ios-appTests // // Created by Karthik on 28/12/18. // Copyright © 2018 Testpress. All rights reserved. // import XCTest @testable import ios_app import Hippolyte class PhoneVerification: XCTestCase { let appDelegate = AppDelegate(); var verifyPhoneViewController: VerifyPhoneViewController? override func setUp() { verifyPhoneViewController = VerifyPhoneViewController() verifyPhoneViewController!.initVerify(username:"demo", password: "password") } override func tearDown() { verifyPhoneViewController = nil Hippolyte.shared.stop() } func testUsernameAndPassword() { /* This tests username and password in the verifyPhoneViewController */ XCTAssertEqual(verifyPhoneViewController!.username, "demo") XCTAssertEqual(verifyPhoneViewController!.password, "password") } func testVerifyCode() { /* This tests the verify code button action and whether login view controller */ let url = URL(string: Constants.BASE_URL+"/api/v2.2/verify/")! var stub = StubRequest(method: .POST, url: url) var response = StubResponse() let body = "success".data(using: .utf8)! response.body = body stub.response = response Hippolyte.shared.add(stubbedRequest: stub) Hippolyte.shared.start() let label = UIButton() label.setTitle("button", for:UIControl.State.normal) verifyPhoneViewController!.verifyCodeButton = label let textField: UITextField = UITextField() textField.text = "12345" verifyPhoneViewController?.otpField = textField verifyPhoneViewController?.verifyCode(verifyPhoneViewController!.verifyCodeButton) XCTAssertNotEqual(UIApplication.topViewController(), VerifyPhoneViewController()) } func testAuthenticateFailure() { /* This tests for authentication failure */ let url = URL(string: Constants.BASE_URL+"/api/v2.2/auth-token/")! var stub = StubRequest(method: .POST, url: url) var response = StubResponse() response = StubResponse(statusCode: 400) let jsonObject: [String: Any] = [ "non_field_errors": "Unable to login with provided credentials", ] do { try response.body = JSONSerialization.data(withJSONObject: jsonObject,options: .prettyPrinted) } catch { response.body = "hello".data(using: .utf8) } stub.response = response Hippolyte.shared.add(stubbedRequest: stub) Hippolyte.shared.start() verifyPhoneViewController?.authenticate(username: "demo", password: "password", provider: .TESTPRESS) XCTAssertTrue(UIApplication.topViewController() is LoginViewController) } // func testAuthenticateSuccess() { // /* // This tests authentication success // */ // let url = URL(string: Constants.BASE_URL+"/api/v2.2/auth-token/")! // var stub = StubRequest(method: .POST, url: url) // var response = StubResponse() // response = StubResponse(statusCode: 200) // // let jsonObject: [String: Any] = [ // "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6MjY5LCJ1c2VyX2lkIjoyNjksImVtYWlsIjoia2FydGhpa0B0ZXN0cHJlc3MuaW4iLCJleHAiOjE1NDYwMDcyOTJ9.ux0YtD-pGOBXPN6K6hhlCstRCmAhCDJF4R2YBO8t5bM", // ] // // do { // try response.body = JSONSerialization.data(withJSONObject: jsonObject,options: .prettyPrinted) // } catch { // response.body = "hello".data(using: .utf8) // } // // stub.response = response // Hippolyte.shared.add(stubbedRequest: stub) // Hippolyte.shared.start() // // verifyPhoneViewController?.authenticate(username: "demo", password: "password", provider: .TESTPRESS) // // XCTAssertTrue(UIApplication.topViewController() is ActivityFeedTableViewController) // } func testInvalidOtpFieldValue() { /* This tests whether otp field accepts invalid value. */ let textField: UITextField = UITextField() textField.text = "Hello" verifyPhoneViewController?.otpField = textField XCTAssertFalse((verifyPhoneViewController?.validate())!) } func testValidOtpFieldValue() { /* This tests otp field for valid value. */ let textField: UITextField = UITextField() textField.text = "12345" verifyPhoneViewController?.otpField = textField XCTAssertTrue((verifyPhoneViewController?.validate())!) } }
mit
noppoMan/aws-sdk-swift
CodeGenerator/Sources/CodeGenerator/Glob.swift
1
1028
//===----------------------------------------------------------------------===// // // This source file is part of the Soto for AWS open source project // // Copyright (c) 2017-2020 the Soto project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of Soto project authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// import Darwin.C import Foundation public class Glob { public static func entries(pattern: String) -> [String] { var files = [String]() var gt = glob_t() let res = glob(pattern.cString(using: .utf8)!, 0, nil, &gt) if res != 0 { return files } for i in 0..<gt.gl_pathc { let x = gt.gl_pathv[Int(i)] let c = UnsafePointer<CChar>(x)! let s = String(cString: c) files.append(s) } globfree(&gt) return files } }
apache-2.0
barteljan/VISPER
VISPER-Redux/Classes/LogicFeature.swift
1
265
// // LogicFeature.swift // SwiftyVISPER // // Created by bartel on 18.11.17. // import Foundation import VISPER_Core /// A feature providing reducers for your Redux public protocol LogicFeature: Feature{ func injectReducers(container: ReducerContainer) }
mit
jpush/jchat-swift
JChat/Src/ChatModule/Input/InputView/Emoticon/JCEmoticonLine.swift
1
2742
// // JCEmoticonLine.swift // JChat // // Created by JIGUANG on 2017/3/9. // Copyright © 2017年 HXHG. All rights reserved. // import UIKit internal class JCEmoticonLine { func draw(in ctx: CGContext) { _ = emoticons.reduce(CGRect(origin: vaildRect.origin, size: itemSize)) { $1.draw(in: $0, in: ctx) return $0.offsetBy(dx: $0.width + minimumInteritemSpacing, dy: 0) } } func rect(at index: Int) -> CGRect? { guard index < emoticons.count else { return nil } let isp = minimumInteritemSpacing let nwidth = (itemSize.width + isp) * CGFloat(index) return CGRect(origin: CGPoint(x: vaildRect.minX + nwidth, y: vaildRect.minY), size: itemSize) } func addEmoticon(_ emoticon: JCEmoticon) -> Bool { let isp = minimumInteritemSpacing let nwidth = visableSize.width + isp + itemSize.width let nwidthWithDelete = visableSize.width + (isp + itemSize.width) * 2 let nheight = max(visableSize.height, itemSize.height) if floor(vaildRect.minX + nwidth) > floor(vaildRect.maxX) { return false } if itemType.isSmall && isLastLine && floor(vaildRect.minX + nwidthWithDelete) > floor(vaildRect.maxX) { return false } if floor(vaildRect.minY + nheight) > floor(vaildRect.maxY) { return false } if visableSize.height != nheight { _isLastLine = nil } visableSize.width = nwidth visableSize.height = nheight emoticons.append(emoticon) return true } var itemSize: CGSize var vaildRect: CGRect var visableSize: CGSize var itemType: JCEmoticonType var isLastLine: Bool { if let isLastLine = _isLastLine { return isLastLine } let isLastLine = floor(vaildRect.minY + visableSize.height + minimumLineSpacing + itemSize.height) > floor(vaildRect.maxY) _isLastLine = isLastLine return isLastLine } var minimumLineSpacing: CGFloat var minimumInteritemSpacing: CGFloat var emoticons: [JCEmoticon] var _isLastLine: Bool? init(_ first: JCEmoticon, _ itemSize: CGSize, _ rect: CGRect, _ lineSpacing: CGFloat, _ interitemSpacing: CGFloat, _ itemType: JCEmoticonType) { self.itemSize = itemSize self.itemType = itemType self.vaildRect = rect self.visableSize = itemSize minimumLineSpacing = lineSpacing minimumInteritemSpacing = interitemSpacing emoticons = [first] } }
mit
AlexChekanov/Gestalt
Gestalt/SupportingClasses/General classes Extensions/UIImage+alpha.swift
1
511
// // UIImage+alpha.swift // Gestalt // // Created by Alexey Chekanov on 6/25/17. // Copyright © 2017 Alexey Chekanov. All rights reserved. // import UIKit extension UIImage{ func alpha(_ value:CGFloat)->UIImage { UIGraphicsBeginImageContextWithOptions(size, false, scale) draw(at: CGPoint.zero, blendMode: .normal, alpha: value) let newImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return newImage! } }
apache-2.0
alessioros/mobilecodegenerator3
examples/BookShelf/ios/completed/BookShelf/BookShelf/AppDelegate.swift
1
4411
import UIKit import CoreData import Firebase @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. // Configure Firebase FirebaseApp.configure() return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } // MARK: - Core Data stack lazy var persistentContainer: NSPersistentContainer = { /* The persistent container for the application. This implementation creates and returns a container, having loaded the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. */ let container = NSPersistentContainer(name: "BookShelf") container.loadPersistentStores(completionHandler: { (storeDescription, error) in if let error = error as NSError? { // Replace this implementation with code to handle the error appropriately. // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. /* Typical reasons for an error here include: * The parent directory does not exist, cannot be created, or disallows writing. * The persistent store is not accessible, due to permissions or data protection when the device is locked. * The device is out of space. * The store could not be migrated to the current model version. Check the error message to determine what the actual problem was. */ fatalError("Unresolved error \(error), \(error.userInfo)") } }) return container }() // MARK: - Core Data Saving support func saveContext () { let context = persistentContainer.viewContext if context.hasChanges { do { try context.save() } catch { // Replace this implementation with code to handle the error appropriately. // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. let nserror = error as NSError fatalError("Unresolved error \(nserror), \(nserror.userInfo)") } } } }
gpl-3.0
RomainBoulay/SectionSpacingFlowLayout
CollectionViewCompactLayout/SectionPosition.swift
1
1690
import Foundation import UIKit struct SectionAttribute { let initialMinY: CGFloat let initialMaxY: CGFloat let itemsCount: Int private let spacingHeight: CGFloat private let previousAggregatedVerticalOffset: CGFloat init(minY: CGFloat, maxY: CGFloat, itemsCount: Int, spacingHeight: CGFloat, previousAggregatedVerticalOffset: CGFloat ) { self.initialMinY = minY self.initialMaxY = maxY self.itemsCount = itemsCount self.spacingHeight = spacingHeight self.previousAggregatedVerticalOffset = previousAggregatedVerticalOffset } static func empty(previousAggregatedVerticalOffset: CGFloat, sectionTopHeight: CGFloat, sectionBottomHeight: CGFloat) -> SectionAttribute { let verticalOffsetMinusHeaderFooter = previousAggregatedVerticalOffset - sectionTopHeight - sectionBottomHeight return SectionAttribute(minY: .nan, maxY: .nan, itemsCount: 0, spacingHeight: 0, previousAggregatedVerticalOffset: verticalOffsetMinusHeaderFooter) } var hasItems: Bool { return itemsCount > 0 } var aggregatedVerticalOffset: CGFloat { return previousAggregatedVerticalOffset + spacingHeight } var decorationViewMinY: CGFloat { return initialMinY + previousAggregatedVerticalOffset } var newMinY: CGFloat { return initialMinY + aggregatedVerticalOffset } var newMaxY: CGFloat { return initialMaxY + aggregatedVerticalOffset } }
mit
WTGrim/WTOfo_Swift
Ofo_Swift/Ofo_Swift/MoreViewController.swift
1
785
// // MoreViewController.swift // Ofo_Swift // // Created by Dwt on 2017/9/22. // Copyright © 2017年 Dwt. All rights reserved. // import UIKit import WebKit class MoreViewController: UIViewController , WKUIDelegate{ var webView : WKWebView! override func viewDidLoad() { super.viewDidLoad() title = "热门活动" let url = URL(string: "http://m.ofo.so/active.html")! let request = URLRequest(url: url as URL) webView = WKWebView(frame:CGRect(x:0, y:0, width:self.view.bounds.width, height:self.view.bounds.height)) webView.uiDelegate = self webView.load(request) view.addSubview(webView) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } }
mit