repo_name
stringlengths
6
91
path
stringlengths
8
968
copies
stringclasses
210 values
size
stringlengths
2
7
content
stringlengths
61
1.01M
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6
99.8
line_max
int64
12
1k
alpha_frac
float64
0.3
0.91
ratio
float64
2
9.89
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
filiroman/RFCircleView
RFCircleView/Classes/CircleView.swift
1
5958
// // CircleView.swift // CircleView // // Created by Roman Filippov on 13/09/2017. // Copyright © 2017 romanfilippov. All rights reserved. // import UIKit @IBDesignable public class CircleView: UIView { var circleLabel: UILabel! var panRecognizer: UIPanGestureRecognizer! @IBInspectable public var outlineColor: UIColor = UIColor.blue @IBInspectable public var outlineFillColor: UIColor = UIColor.blue @IBInspectable public var counterColor: UIColor = UIColor.orange @IBInspectable public var minValue: Int = 0 @IBInspectable public var maxValue: Int = 8 @IBInspectable public var lineWidth: CGFloat = 4.0 @IBInspectable public var arcWidth: CGFloat = 80.0 @IBInspectable public var arcAngle: Int = 270 public var useInternalGestureRecognizer: Bool = false { didSet { if (useInternalGestureRecognizer) { guard panRecognizer == nil else { print("Not possible nil!") return } panRecognizer = UIPanGestureRecognizer(target: self, action: #selector(handlePan(panGesture:))) self.addGestureRecognizer(panRecognizer) } else { guard panRecognizer != nil else { print("Not possible not nil!") return } panRecognizer.removeTarget(self, action: #selector(handlePan(panGesture:))) panRecognizer = nil } } } var _counter: Int = 0 { didSet { guard _counter >= minValue else { _counter = minValue return } guard _counter <= maxValue else { _counter = maxValue return } circleLabel.text = String(_counter) setNeedsDisplay() } } @IBInspectable public var counter: Int { get { return _counter } set (aNewValue) { if aNewValue != _counter { _counter = aNewValue } } } var radius: CGFloat { get { return max(bounds.width, bounds.height) } } var valuesCount: Int { get { return maxValue-minValue+1 } } override init(frame: CGRect) { super.init(frame: frame) createLabel() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) createLabel() } func createLabel() { circleLabel = UILabel(frame: CGRect.zero) circleLabel.text = "0" circleLabel.font = UIFont.systemFont(ofSize: 36) circleLabel.textAlignment = .center circleLabel.translatesAutoresizingMaskIntoConstraints = false self.addSubview(circleLabel) updateConstraints() } override public func updateConstraints() { let xCenter = NSLayoutConstraint(item: circleLabel, attribute: .centerX, relatedBy: .equal, toItem: self, attribute: .centerX, multiplier: 1, constant: 0) let yCenter = NSLayoutConstraint(item: circleLabel, attribute: .centerY, relatedBy: .equal, toItem: self, attribute: .centerY, multiplier: 1, constant: 0) NSLayoutConstraint.activate([xCenter, yCenter]) super.updateConstraints() } override public func draw(_ rect: CGRect) { guard lineWidth>0 else { return } guard maxValue>minValue else { return } guard arcWidth>0 && arcAngle>0 else { return } guard (minValue...maxValue) ~= counter else { return } let center = CGPoint(x: bounds.width / 2, y: bounds.height / 2) let arcAngleRadians = CGFloat(arcAngle.degreesToRadians) let startAngle: CGFloat = 3 * .pi/2 - arcAngleRadians/2 //let endAngle: CGFloat = 3 * .pi/2 + arcAngleRadians/2 /*let path = UIBezierPath(arcCenter: center, radius: radius/2 - arcWidth/2, startAngle: startAngle, endAngle: endAngle, clockwise: true) path.lineWidth = arcWidth counterColor.setStroke() path.stroke()*/ let arcLengthPerValue = arcAngleRadians / CGFloat(maxValue - minValue) let outlineEndAngle = arcLengthPerValue * CGFloat(counter - minValue) + startAngle // outer line /*let outlinePath = UIBezierPath(arcCenter: center, radius: (bounds.width - lineWidth)/2, startAngle: startAngle, endAngle: outlineEndAngle, clockwise: true)*/ let path = UIBezierPath(arcCenter: center, radius: radius/2 - arcWidth/2, startAngle: startAngle, endAngle: outlineEndAngle, clockwise: true) path.lineWidth = arcWidth counterColor.setStroke() path.stroke() //inner line /*outlinePath.addArc(withCenter: center, radius: bounds.width/2 - arcWidth + lineWidth/2, startAngle: outlineEndAngle, endAngle: startAngle, clockwise: false)*/ /*outlinePath.close() outlineColor.setStroke() outlineFillColor.setFill() outlinePath.lineWidth = lineWidth outlinePath.stroke()*/ } // MARK: - UIPanGestureRecognizer delegate func handlePan(panGesture:UIPanGestureRecognizer) { switch panGesture.state { case .began, .changed: let translation = panGesture.translation(in: self) let pointsPerValue = radius / CGFloat(valuesCount) var maxDelta: CGFloat = 0 if abs(translation.x) > abs(translation.y) { maxDelta = translation.x } else { maxDelta = -translation.y } counter = Int(maxDelta) / Int(pointsPerValue) case .ended: panGesture.setTranslation(CGPoint.zero, in: self) default: return } } }
mit
b429ab58ad258fd02ce339a4649b695a
25.127193
158
0.589055
5.035503
false
false
false
false
ethanneff/iOS-Swift-Drag-And-Drop-TableView-Cell-4
DragAndDropTableViewCell4/TableViewController.swift
1
2248
// // TableViewController.swift // DragAndDropTableViewCell4 // // Created by Ethan Neff on 2/28/16. // Copyright © 2016 Ethan Neff. All rights reserved. // import UIKit class TableViewController: UITableViewController { // MARK: - properties var items = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25] // MARK: - init override func viewDidLoad() { super.viewDidLoad() // reorder tableView = ReorderTableView(tableView: tableView) // nav controller properties navigationController?.navigationBarHidden = true // table properties tableView.contentInset = UIEdgeInsetsZero tableView.separatorInset = UIEdgeInsetsZero tableView.scrollIndicatorInsets = UIEdgeInsetsZero tableView.layoutMargins = UIEdgeInsetsZero tableView.tableFooterView = UIView(frame: CGRectZero) } // MARK: - reorder functions // (optional but needed to reorder your data behind the view) func reorderBefore(index: NSIndexPath) { // if you update the tableView before the reorder, you need to update the tableView.reorderInitalIndexPath } func reorderAfter(fromIndex: NSIndexPath, toIndex:NSIndexPath) { // update view data (reorder based on direction moved) let ascending = fromIndex.row < toIndex.row ? true : false let from = ascending ? fromIndex.row : fromIndex.row+1 let to = ascending ? toIndex.row+1 : toIndex.row items.insert(items[fromIndex.row], atIndex: to) items.removeAtIndex(from) print(items) } // MARK: - table view datasource override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return items.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) // cell properties cell.separatorInset = UIEdgeInsetsZero cell.layoutMargins = UIEdgeInsetsZero cell.selectionStyle = .None cell.textLabel?.text = String(items[indexPath.row]) return cell } }
mit
3e59068f3338cb5c4117d62e3e04b881
28.181818
116
0.70939
4.68125
false
false
false
false
jianghongbing/APIReferenceDemo
Swift/Syntax/Extension.playground/Contents.swift
1
4158
//: Playground - noun: a place where people can play import UIKit //Extendsion:扩展,为类,结构体,枚举扩展新的功能,如添加计算熟悉,下边,类型方法,实例方法等,通过关键字extension来扩展类,枚举,结构体 //1.添加计算型属性 struct Point { var x = 0.0 var y = 0.0 } struct Size { var width = 0.0 var height = 0.0 } struct Rect { var x = 0.0, y = 0.0, width = 0.0, height = 0.0 } extension Rect { //添加实例计算属性 var center: Point { return Point(x: x + width * 0.5, y: y + height * 0.5) } static var shape: Shape { return .rectangle } //2.添加方法 //添加类型方法 static func logShape() { print(shape) } //添加实例方法 func area() -> Double { return width * height } //3.扩展构造器,类类型之能扩展便利构造器 init(origin: Point, size: Size) { self.init(x: origin.x, y: origin.y, width: size.width, height: size.height) } //5.扩展嵌套类型 enum Shape { case circle, trangle, rectangle, square, other } } let rect = Rect(origin: Point(x: 10, y: 10), size: Size(width: 100.0, height: 100.0)) print(rect.area()) print(Rect.logShape()) print(rect.center) class User { var name: String = "" let id: String var age = 0 init(id: String) { self.id = id } } //为类类型扩展便利构造器 extension User { convenience init(id: String, name: String, age: Int) { self.init(id: id) self.name = name self.age = age } //4.扩展下标 subscript (valueForPropertyName: String) -> String? { set { if valueForPropertyName == "name" { self.name = newValue! }else if valueForPropertyName == "age" { self.age = Int(newValue!)! } } get { guard valueForPropertyName == "id" else{ guard valueForPropertyName == "name" else { guard valueForPropertyName == "age" else { return nil } return String(age) } return name } return id } } } protocol LoginService { func login() func loginout() } //6.通过扩展,让类型遵循协议 extension User: LoginService { func login() { print("name:\(name), id:\(id) login") } func loginout() { print("name:\(name), id:\(id) loginout") } } //7.扩展协议 //7.1:通过扩展协议,为协议中的方法提供默认实现 protocol UserInfo { func getId() -> String func logUserInfo() } protocol UserDetailInfo: UserInfo { func getName() -> String func getAge() -> Int } extension UserInfo { func logUserInfo() { print("userId:\(getId())") } } extension UserDetailInfo { func logUserInfo() { print("userId:\(getId()), userName:\(getName()), userAge:\(getAge())") } } extension User: UserDetailInfo { func getId() -> String { return id } func getName() -> String { return name } func getAge() -> Int { return age } } let xiaoming = User(id: "001", name: "xiaoming", age: 10) xiaoming.logUserInfo() xiaoming.login() xiaoming.loginout() //7.2:通过扩展协议,为符合条件的类型提供默认实现 protocol Animatable { func duration() -> Double func startAnimatino() func endAnimation() } protocol AnimationTiming { var duration: Double { set get } var beginTime: Double { set get } } extension Animatable where Self: AnimationTiming { func duration() -> Double { return duration } } struct Circle: AnimationTiming{ var r = 0.0 var center = Point(x: 0, y: 0) var duration = 0.25 var beginTime = 0.0 init(radius: Double, center: Point) { r = radius self.center = center } } extension Circle: Animatable { func startAnimatino() { print("start animation") } func endAnimation() { print("end animtion") } }
mit
77974811932ea1fc9e54a1164254ae6f
19.308511
85
0.555788
3.548327
false
false
false
false
maxgoedjen/M3U8
M3U8/ByteRange.swift
1
1639
// // ByteRange.swift // M3U8 // // Created by Max Goedjen on 8/10/15. // Copyright © 2015 Max Goedjen. All rights reserved. // import Foundation public struct ByteRange { private enum Mode { case FullRange(Range<Int>) case LengthOnly(Int) } private let value: Mode public init(range: Range<Int>) { value = .FullRange(range) } public init(start: Int, length: Int) { value = .FullRange(start..<(start+length)) } public init(length: Int) { value = .LengthOnly(length) } public init?(string: String) { let values = string.componentsSeparatedByString("@") guard let lengthString = values.first, let length = Int(lengthString) else { return nil } if values.count == 2, let start = Int(values[1]) { value = .FullRange(start..<(start+length)) } else { value = .LengthOnly(length) } } } extension ByteRange: CustomStringConvertible { public var description: String { switch value { case .FullRange(let range): return "\(range.endIndex-range.startIndex)@\(range.startIndex)" case .LengthOnly(let length): return "\(length)" } } } extension ByteRange: Equatable { } public func ==(lhs: ByteRange, rhs: ByteRange) -> Bool { switch (lhs.value, rhs.value) { case (.FullRange(let lRange), .FullRange(let rRange)): return lRange == rRange case (.LengthOnly(let lLength), .LengthOnly(let rLength)): return lLength == rLength default: return false } }
mit
976eca502c7a3b8f6d06e4cdd6033e2c
22.73913
97
0.586691
4.084788
false
false
false
false
mozilla-mobile/firefox-ios
Client/Frontend/Browser/SearchSuggestClient.swift
2
3136
// This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0 import Foundation import Shared let SearchSuggestClientErrorDomain = "org.mozilla.firefox.SearchSuggestClient" let SearchSuggestClientErrorInvalidEngine = 0 let SearchSuggestClientErrorInvalidResponse = 1 /* * Clients of SearchSuggestionClient should retain the object during the * lifetime of the search suggestion query, as requests are canceled during destruction. * * Query callbacks that must run even if they are cancelled should wrap their contents in `withExtendendLifetime`. */ class SearchSuggestClient { fileprivate let searchEngine: OpenSearchEngine fileprivate let userAgent: String fileprivate var task: URLSessionTask? lazy fileprivate var urlSession: URLSession = makeURLSession(userAgent: self.userAgent, configuration: URLSessionConfiguration.ephemeral) init(searchEngine: OpenSearchEngine, userAgent: String) { self.searchEngine = searchEngine self.userAgent = userAgent } func query(_ query: String, callback: @escaping (_ response: [String]?, _ error: NSError?) -> Void) { let url = searchEngine.suggestURLForQuery(query) if url == nil { let error = NSError(domain: SearchSuggestClientErrorDomain, code: SearchSuggestClientErrorInvalidEngine, userInfo: nil) callback(nil, error) return } task = urlSession.dataTask(with: url!) { (data, response, error) in if let error = error { callback(nil, error as NSError?) return } guard let data = data, validatedHTTPResponse(response, statusCode: 200..<300) != nil else { let error = NSError(domain: SearchSuggestClientErrorDomain, code: SearchSuggestClientErrorInvalidResponse, userInfo: nil) callback(nil, error as NSError?) return } let json = try? JSONSerialization.jsonObject(with: data, options: .fragmentsAllowed) let array = json as? [Any] // The response will be of the following format: // ["foobar",["foobar","foobar2000 mac","foobar skins",...]] // That is, an array of at least two elements: the search term and an array of suggestions. if array?.count ?? 0 < 2 { let error = NSError(domain: SearchSuggestClientErrorDomain, code: SearchSuggestClientErrorInvalidResponse, userInfo: nil) callback(nil, error) return } guard let suggestions = array?[1] as? [String] else { let error = NSError(domain: SearchSuggestClientErrorDomain, code: SearchSuggestClientErrorInvalidResponse, userInfo: nil) callback(nil, error) return } callback(suggestions, nil) } task?.resume() } func cancelPendingRequest() { task?.cancel() } }
mpl-2.0
46fcc9bf06d1337683b3db0b40008575
38.696203
141
0.64764
5.049919
false
false
false
false
vibinkundukulam/Bard
Bard/KeyboardViewController.swift
1
2146
// // KeyboardViewController.swift // Bard // // Created by Test Account on 7/6/15. // Copyright (c) 2015 Vibin Kundukulam. All rights reserved. // import UIKit class KeyboardViewController: UIInputViewController { var capsLockOn = true @IBOutlet weak var table: UITableView! override func viewDidLoad() { super.viewDidLoad() let nib = UINib(nibName: "KeyboardView", bundle: nil) let objects = nib.instantiateWithOwner(self, options: nil) view = objects[0] as! UIView; } @IBAction func nextKeyboardPressed(button: UIButton) { advanceToNextInputMode() } @IBAction func capsLockPressed(button: UIButton) { capsLockOn = !capsLockOn } @IBAction func keyPressed(button: UIButton) { var string = button.titleLabel!.text (textDocumentProxy as! UIKeyInput).insertText("\(string!)") UIView.animateWithDuration(0.2, animations: { button.transform = CGAffineTransformScale(CGAffineTransformIdentity,2.0,2.0)} , completion: {(_) -> Void in button.transform = CGAffineTransformScale(CGAffineTransformIdentity, 1,1) }) } @IBAction func backSpacePressed(button: UIButton) { (textDocumentProxy as! UIKeyInput).deleteBackward() } @IBAction func spacePressed(button: UIButton) { (textDocumentProxy as! UIKeyInput).insertText(" ") } @IBAction func returnPressed(button: UIButton) { (textDocumentProxy as! UIKeyInput).insertText("\n") } func changeCaps(containerView: UIView) { for view in containerView.subviews { if let button = view as? UIButton { let buttonTitle = button.titleLabel!.text if capsLockOn { let text = buttonTitle!.uppercaseString button.setTitle("\(text)", forState:.Normal) } else { let text = buttonTitle!.lowercaseString button.setTitle("\(text)", forState: .Normal) } } } } }
apache-2.0
b6c1cdd1e50610eb4253cd4aa445da1b
29.657143
89
0.598788
5.014019
false
false
false
false
Digipolitan/perfect-middleware-swift
Sources/PerfectMiddleware/MiddlewareIterator.swift
1
1485
import PerfectHTTP /** * Internal RouteContext implementation * This implementation iterate over all middlewares one by one * @author Benoit BRIATTE http://www.digipolitan.com * @copyright 2017 Digipolitan. All rights reserved. */ internal class MiddlewareIterator: RouteContext { public let request: HTTPRequest public let response: HTTPResponse private let middlewares: [Middleware] private let errorHandler: ErrorHandler? private var userInfo: [String: Any] private var current: Int public init(request: HTTPRequest, response: HTTPResponse, middlewares: [Middleware], errorHandler: ErrorHandler?) { self.request = request self.response = response self.middlewares = middlewares self.errorHandler = errorHandler self.userInfo = [String: Any]() self.current = 0 } public func next() { if self.current < self.middlewares.count { let cur = self.current self.current = cur + 1 do { try self.middlewares[cur].handle(context: self) } catch { self.current = self.middlewares.count if self.errorHandler != nil { self.errorHandler!(error, self) } } } } public subscript(key: String) -> Any? { get { return self.userInfo[key] } set { self.userInfo[key] = newValue } } }
bsd-3-clause
79b47b87a8b05b088de2b1060030d0cd
28.117647
119
0.599327
4.837134
false
false
false
false
alskipp/Monoid
Monoid/Monoids/ProductMonoid.swift
1
767
// Copyright © 2016 Al Skipp. All rights reserved. public struct Product<T: NumberType> { public let value: T public init(_ v: T) { value = v } } extension Product: Monoid { public static var mempty: Product { return Product(T.one) } public static func combine(_ a: Product, _ b: Product) -> Product { return Product(a.value * b.value) } } extension Product: CustomStringConvertible { public var description: String { return "Product(\(value))" } } extension Product: Equatable, Comparable, Orderable { public static func == <N: NumberType>(x: Product<N>, y: Product<N>) -> Bool { return x.value == y.value } public static func < <N: NumberType>(x: Product<N>, y: Product<N>) -> Bool { return x.value < y.value } }
mit
8e0d73b3d05f656e888f7cbf21465df3
22.9375
79
0.651436
3.529954
false
false
false
false
ReactiveCocoa/ReactiveSwift
Sources/Observers/TakeFirst.swift
1
626
extension Operators { internal final class TakeFirst<Value, Error: Swift.Error>: Observer<Value, Error> { let downstream: Observer<Value, Error> let count: Int var taken: Int = 0 init(downstream: Observer<Value, Error>, count: Int) { precondition(count >= 1) self.downstream = downstream self.count = count } override func receive(_ value: Value) { if taken < count { taken += 1 downstream.receive(value) } if taken == count { downstream.terminate(.completed) } } override func terminate(_ termination: Termination<Error>) { downstream.terminate(termination) } } }
mit
0eb7c7bb415da2edd66b77f21eca10e1
20.586207
84
0.670927
3.497207
false
false
false
false
mightydeveloper/swift
test/NameBinding/Inputs/accessibility_other.swift
10
586
import has_accessibility public let a = 0 internal let b = 0 private let c = 0 extension Foo { public static func a() {} internal static func b() {} private static func c() {} } struct PrivateInit { private init() {} } extension Foo { private func method() {} private typealias TheType = Float } extension OriginallyEmpty { func method() {} typealias TheType = Float } private func privateInBothFiles() {} func privateInPrimaryFile() {} // expected-note {{previously declared here}} private func privateInOtherFile() {} // expected-error {{invalid redeclaration}}
apache-2.0
845ecd935454003797c7f2dab885b628
19.206897
80
0.704778
4.013699
false
false
false
false
SRandazzo/Moya
Source/ReactiveCocoa/Moya+ReactiveCocoa.swift
1
3176
import Foundation import ReactiveCocoa import Alamofire /// Subclass of MoyaProvider that returns SignalProducer instances when requests are made. Much better than using completion closures. public class ReactiveCocoaMoyaProvider<Target where Target: MoyaTarget>: MoyaProvider<Target> { private let stubScheduler: DateSchedulerType? /// Initializes a reactive provider. public init(endpointClosure: EndpointClosure = MoyaProvider.DefaultEndpointMapping, requestClosure: RequestClosure = MoyaProvider.DefaultRequestMapping, stubClosure: StubClosure = MoyaProvider.NeverStub, manager: Manager = Alamofire.Manager.sharedInstance, plugins: [Plugin<Target>] = [], stubScheduler: DateSchedulerType? = nil) { self.stubScheduler = stubScheduler super.init(endpointClosure: endpointClosure, requestClosure: requestClosure, stubClosure: stubClosure, manager: manager, plugins: plugins) } /// Designated request-making method. public func request(token: Target) -> SignalProducer<Response, Error> { // Creates a producer that starts a request each time it's started. return SignalProducer { [weak self] observer, requestDisposable in let cancellableToken = self?.request(token) { result in switch result { case let .Success(response): observer.sendNext(response) observer.sendCompleted() break case let .Failure(error): observer.sendFailed(error) } } requestDisposable.addDisposable { // Cancel the request cancellableToken?.cancel() } } } override func stubRequest(target: Target, request: NSURLRequest, completion: Moya.Completion, endpoint: Endpoint<Target>, stubBehavior: Moya.StubBehavior) -> CancellableToken { guard let stubScheduler = self.stubScheduler else { return super.stubRequest(target, request: request, completion: completion, endpoint: endpoint, stubBehavior: stubBehavior) } notifyPluginsOfImpendingStub(request, target: target) var dis: Disposable? = .None let token = CancellableToken { dis?.dispose() } let stub = createStubFunction(token, forTarget: target, withCompletion: completion, endpoint: endpoint, plugins: plugins) switch stubBehavior { case .Immediate: dis = stubScheduler.schedule(stub) case .Delayed(let seconds): let date = NSDate(timeIntervalSinceNow: seconds) dis = stubScheduler.scheduleAfter(date, action: stub) case .Never: fatalError("Attempted to stub request when behavior requested was never stub!") } return token } @available(*, deprecated, message="This will be removed when ReactiveCocoa 4 becomes final. Please visit https://github.com/Moya/Moya/issues/298 for more information.") public func request(token: Target) -> RACSignal { return toRACSignal(request(token)) } }
mit
42a8b701110355bcfa44cfe840a877e7
45.705882
180
0.659635
5.681574
false
false
false
false
huonw/swift
test/Interpreter/algorithms.swift
32
1041
// RUN: %target-run-simple-swift | %FileCheck %s // REQUIRES: executable_test func fib() { var (a, b) = (0, 1) while b < 10 { print(b) (a, b) = (b, a+b) } } fib() // CHECK: 1 // CHECK: 1 // CHECK: 2 // CHECK: 3 // CHECK: 5 // CHECK: 8 // From: <rdar://problem/17796401> // FIXME: <rdar://problem/21993692> type checker too slow let two_oneA = [1, 2, 3, 4].lazy.reversed() let two_one = Array(two_oneA.filter { $0 % 2 == 0 }.map { $0 / 2 }) print(two_one) // CHECK: [2, 1] // rdar://problem/18208283 func flatten<Element, Seq: Sequence, InnerSequence: Sequence where Seq.Iterator.Element == InnerSequence, InnerSequence.Iterator.Element == Element> (_ outerSequence: Seq) -> [Element] { var result = [Element]() for innerSequence in outerSequence { result.append(contentsOf: innerSequence) } return result } // CHECK: [1, 2, 3, 4, 5, 6] let flat = flatten([[1,2,3], [4,5,6]]) print(flat) // rdar://problem/19416848 func observe<T:Sequence, V where V == T.Iterator.Element>(_ g:T) { } observe(["a":1])
apache-2.0
e946bcb9f5cf025e53ae0aa26e53c905
22.133333
132
0.615754
2.790885
false
false
false
false
linhaosunny/smallGifts
小礼品/小礼品/Classes/Module/Me/Controllers/SettingViewController.swift
1
3260
// // SettingViewController.swift // 小礼品 // // Created by 李莎鑫 on 2017/4/25. // Copyright © 2017年 李莎鑫. All rights reserved. // import UIKit import SnapKit class SettingViewController: UIViewController { //MARK: 属性 fileprivate let setIdentifier = "settingCell" //MARK: 懒加载 lazy var footerView:SettingFooterView = SettingFooterView(frame: CGRect(x: 0, y: 0, width: ScreenWidth, height: 200)) lazy var tableView:UITableView = { () -> UITableView in let view = UITableView(frame: CGRect.zero, style: .grouped) view.delegate = self view.dataSource = self view.showsVerticalScrollIndicator = false view.showsHorizontalScrollIndicator = false view.register(UITableViewCell.self, forCellReuseIdentifier: self.setIdentifier) return view }() //MARK: 系统方法 override func viewDidLoad() { super.viewDidLoad() setupSettingView() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() setupSettingViewSubView() } //MARK: 私有方法 private func setupSettingView() { title = "设置" view.backgroundColor = SystemGlobalBackgroundColor //: 如果登录了显示退出按钮 if AccountModel.isLogin() { tableView.tableFooterView = footerView footerView.delegate = self } view.addSubview(tableView) } private func setupSettingViewSubView() { tableView.snp.makeConstraints { (make) in make.edges.equalToSuperview().inset(UIEdgeInsets.zero) } } } //MARK: 代理方法 extension SettingViewController:UITableViewDelegate,UITableViewDataSource { func numberOfSections(in tableView: UITableView) -> Int { return 3 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 2 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: setIdentifier, for: indexPath) cell.textLabel?.text = "关于作者" return cell } } extension SettingViewController:SettingFooterViewDelegate { func settingFooterViewLogoutButtonClick() { let alert = UIAlertController(title: "确定注销登录状态?", message: nil, preferredStyle: .actionSheet) let actionSure = UIAlertAction(title: "确定", style: .destructive) { (_) in AccountModel.logout() ProgressHUD.showSuccess(withStatus: "退出成功") _ = self.navigationController?.popViewController(animated: true) } let actionCancel = UIAlertAction(title: "取消", style: .cancel) { (_) in } alert.addAction(actionSure) alert.addAction(actionCancel) present(alert, animated: true, completion: nil) } }
mit
65ea3a0b5757c3a54d10cf93ea148460
28.59434
121
0.629264
5.185124
false
false
false
false
Paladinfeng/leetcode
leetcode/Valid Parentheses/main.swift
1
1135
// // main.swift // Valid Parentheses // // Created by xuezhaofeng on 14/08/2017. // Copyright © 2017 paladinfeng. All rights reserved. // import Foundation class Solution { func isValid(_ s: String) -> Bool { if s.characters.count % 2 != 0 { return false } var stack = [Character]() for value in s.characters { switch value { case "{", "[", "(": stack.append(value) break case "}": if stack.count == 0 || stack.removeLast() != "{" { return false } break case "]": if stack.count == 0 || stack.removeLast() != "[" { return false } break case ")": if stack.count == 0 || stack.removeLast() != "(" { return false } break default: continue } } return stack.isEmpty } } let result = Solution().isValid("[(){}]") print(result)
mit
91f4e8b51f3eae7af03fbf6644b36130
23.12766
66
0.409171
4.951965
false
false
false
false
atrick/swift
test/Distributed/Runtime/distributed_actor_init_local.swift
1
9001
// RUN: %target-run-simple-swift( -Xfrontend -disable-availability-checking -parse-as-library) | %FileCheck %s // REQUIRES: executable_test // REQUIRES: concurrency // REQUIRES: distributed // rdar://76038845 // UNSUPPORTED: use_os_stdlib // UNSUPPORTED: back_deployment_runtime import Distributed enum MyError: Error { case test } distributed actor PickATransport1 { init(kappa system: FakeActorSystem, other: Int) { self.actorSystem = system } } distributed actor PickATransport2 { init(other: Int, theSystem: FakeActorSystem) async { self.actorSystem = theSystem } } distributed actor LocalWorker { init(system: FakeActorSystem) { self.actorSystem = system } } distributed actor Bug_CallsReadyTwice { var x: Int init(system: FakeActorSystem, wantBug: Bool) async { self.actorSystem = system if wantBug { self.x = 1 } self.x = 2 } } distributed actor Throwy { init(system: FakeActorSystem, doThrow: Bool) throws { self.actorSystem = system if doThrow { throw MyError.test } } } distributed actor ThrowBeforeFullyInit { var x: Int init(system: FakeActorSystem, doThrow: Bool) throws { self.actorSystem = system if doThrow { throw MyError.test } self.x = 0 } } distributed actor ThrowingAssign { init(_ getSystem: @Sendable () throws -> FakeActorSystem) throws { self.actorSystem = try getSystem() } } distributed actor MaybeSystem { init?(_ sys: FakeActorSystem?) { if let system = sys { self.actorSystem = system return } return nil } } distributed actor MaybeAfterAssign { var x: Int init?(fail: Bool) { actorSystem = FakeActorSystem() if fail { return nil } x = 100 } } // ==== Fake Transport --------------------------------------------------------- struct ActorAddress: Sendable, Hashable, Codable { let address: String init(parse address: String) { self.address = address } } // global to track available IDs var nextID: Int = 1 struct FakeActorSystem: DistributedActorSystem { public typealias ActorID = ActorAddress public typealias InvocationDecoder = FakeInvocationDecoder public typealias InvocationEncoder = FakeInvocationEncoder public typealias SerializationRequirement = Codable public typealias ResultHandler = FakeResultHandler init() { print("Initialized new FakeActorSystem") } public func resolve<Act>(id: ActorID, as actorType: Act.Type) throws -> Act? where Act: DistributedActor, Act.ID == ActorID { fatalError("not implemented:\(#function)") } func assignID<Act>(_ actorType: Act.Type) -> ActorID where Act: DistributedActor { let id = ActorAddress(parse: "\(nextID)") nextID += 1 print("assign type:\(actorType), id:\(id)") return id } func actorReady<Act>(_ actor: Act) where Act: DistributedActor, Act.ID == ActorID { print("ready actor:\(actor), id:\(actor.id)") } func resignID(_ id: ActorID) { print("resign id:\(id)") } func makeInvocationEncoder() -> InvocationEncoder { .init() } func remoteCall<Act, Err, Res>( on actor: Act, target: RemoteCallTarget, invocation: inout InvocationEncoder, throwing: Err.Type, returning: Res.Type ) async throws -> Res where Act: DistributedActor, Act.ID == ActorID, Err: Error, Res: SerializationRequirement { throw ExecuteDistributedTargetError(message: "Not implemented") } func remoteCallVoid<Act, Err>( on actor: Act, target: RemoteCallTarget, invocation: inout InvocationEncoder, throwing: Err.Type ) async throws where Act: DistributedActor, Act.ID == ActorID, Err: Error { throw ExecuteDistributedTargetError(message: "Not implemented") } } // === Sending / encoding ------------------------------------------------- struct FakeInvocationEncoder: DistributedTargetInvocationEncoder { typealias SerializationRequirement = Codable mutating func recordGenericSubstitution<T>(_ type: T.Type) throws {} mutating func recordArgument<Value: SerializationRequirement>(_ argument: RemoteCallArgument<Value>) throws {} mutating func recordReturnType<R: SerializationRequirement>(_ type: R.Type) throws {} mutating func recordErrorType<E: Error>(_ type: E.Type) throws {} mutating func doneRecording() throws {} } // === Receiving / decoding ------------------------------------------------- class FakeInvocationDecoder : DistributedTargetInvocationDecoder { typealias SerializationRequirement = Codable func decodeGenericSubstitutions() throws -> [Any.Type] { [] } func decodeNextArgument<Argument: SerializationRequirement>() throws -> Argument { fatalError() } func decodeReturnType() throws -> Any.Type? { nil } func decodeErrorType() throws -> Any.Type? { nil } } public struct FakeResultHandler: DistributedTargetInvocationResultHandler { public typealias SerializationRequirement = Codable public func onReturn<Success: SerializationRequirement>(value: Success) async throws { fatalError("Not implemented: \(#function)") } public func onReturnVoid() async throws { fatalError("Not implemented: \(#function)") } public func onThrow<Err: Error>(error: Err) async throws { fatalError("Not implemented: \(#function)") } } typealias DefaultDistributedActorSystem = FakeActorSystem // ==== Execute ---------------------------------------------------------------- func test() async { let system = DefaultDistributedActorSystem() // NOTE: All allocated distributed actors should be saved in this array, so // that they will be deallocated together at the end of this test! // This convention helps ensure that the test is not flaky. var test: [(any DistributedActor)?] = [] test.append(LocalWorker(system: system)) // CHECK: assign type:LocalWorker, id:ActorAddress(address: "[[ID1:.*]]") // CHECK: ready actor:main.LocalWorker, id:ActorAddress(address: "[[ID1]]") test.append(PickATransport1(kappa: system, other: 0)) // CHECK: assign type:PickATransport1, id:ActorAddress(address: "[[ID2:.*]]") // CHECK: ready actor:main.PickATransport1, id:ActorAddress(address: "[[ID2]]") test.append(try? Throwy(system: system, doThrow: false)) // CHECK: assign type:Throwy, id:ActorAddress(address: "[[ID3:.*]]") // CHECK: ready actor:main.Throwy, id:ActorAddress(address: "[[ID3]]") test.append(try? Throwy(system: system, doThrow: true)) // CHECK: assign type:Throwy, id:ActorAddress(address: "[[ID4:.*]]") // CHECK-NOT: ready // CHECK: resign id:ActorAddress(address: "[[ID4]]") test.append(try? ThrowBeforeFullyInit(system: system, doThrow: true)) // CHECK: assign type:ThrowBeforeFullyInit, id:ActorAddress(address: "[[ID5:.*]]") // CHECK-NOT: ready // CHECK: resign id:ActorAddress(address: "[[ID5]]") test.append(await PickATransport2(other: 1, theSystem: system)) // CHECK: assign type:PickATransport2, id:ActorAddress(address: "[[ID6:.*]]") // CHECK: ready actor:main.PickATransport2, id:ActorAddress(address: "[[ID6]]") test.append(await Bug_CallsReadyTwice(system: system, wantBug: true)) // CHECK: assign type:Bug_CallsReadyTwice, id:ActorAddress(address: "[[ID7:.*]]") // CHECK: ready actor:main.Bug_CallsReadyTwice, id:ActorAddress(address: "[[ID7]]") // CHECK-NEXT: ready actor:main.Bug_CallsReadyTwice, id:ActorAddress(address: "[[ID7]]") test.append(MaybeSystem(system)) // CHECK: assign type:MaybeSystem, id:ActorAddress(address: "[[ID8:.*]]") // CHECK: ready actor:main.MaybeSystem, id:ActorAddress(address: "[[ID8]]") test.append(MaybeAfterAssign(fail: true)) // CHECK: assign type:MaybeAfterAssign, id:ActorAddress(address: "[[ID9:.*]]") // CHECK-NOT: ready // CHECK-NEXT: resign id:ActorAddress(address: "[[ID9]]") test.append(MaybeAfterAssign(fail: false)) // CHECK: assign type:MaybeAfterAssign, id:ActorAddress(address: "[[ID10:.*]]") // CHECK-NEXT: ready actor:main.MaybeAfterAssign, id:ActorAddress(address: "[[ID10]]") // the following tests fail to initialize the actor's identity. print("-- start of no-assign tests --") test.append(MaybeSystem(nil)) test.append(try? ThrowingAssign { throw MyError.test }) print("-- end of no-assign tests --") // CHECK: -- start of no-assign tests -- // CHECK-NOT: assign // CHECK: -- end of no-assign tests -- // resigns that come out of the deinits: // CHECK-DAG: resign id:ActorAddress(address: "[[ID1]]") // CHECK-DAG: resign id:ActorAddress(address: "[[ID2]]") // CHECK-DAG: resign id:ActorAddress(address: "[[ID3]]") // CHECK-DAG: resign id:ActorAddress(address: "[[ID6]]") // CHECK-DAG: resign id:ActorAddress(address: "[[ID7]]") // CHECK-DAG: resign id:ActorAddress(address: "[[ID8]]") // CHECK-DAG: resign id:ActorAddress(address: "[[ID10]]") } @main struct Main { static func main() async { await test() } }
apache-2.0
5c168b98f687c6cae641d90a1c3b35ed
29.825342
112
0.670037
3.961708
false
true
false
false
u10int/Kinetic
Pod/Classes/Animator.swift
1
7221
// // Animator.swift // Pods // // Created by Nicholas Shipes on 5/14/16. // // import Foundation extension Interpolatable { public func interpolator(to: Self, duration: TimeInterval, function: TimingFunction, apply: @escaping ((Self) -> Void)) -> Interpolator { return Interpolator(from: self, to: to, duration: duration, function: function, apply: { (value) in apply(value) }) } } public class Interpolator : Subscriber { public var id: UInt32 = 0 public var progress: CGFloat = 0.0 { didSet { progress = max(0, min(progress, 1.0)) var adjustedProgress: Double = Double(progress) if let spring = spring { spring.proceed(Double(progress)) adjustedProgress = spring.current } else { adjustedProgress = timingFunction.solve(Double(progress)) } current = from.interpolate(to: to, progress: adjustedProgress) apply?(current.toInterpolatable()) } } var spring: Spring? public var finished: Bool { if let spring = spring { return spring.ended } return (!reversed && elapsed >= duration) || (reversed && elapsed <= 0) } fileprivate var current: InterpolatableValue fileprivate var from: InterpolatableValue fileprivate var to: InterpolatableValue fileprivate var duration: TimeInterval fileprivate var timingFunction: TimingFunction fileprivate var elapsed: TimeInterval = 0.0 fileprivate var reversed = false fileprivate var apply: ((Interpolatable) -> Void)? public init<T: Interpolatable>(from: T, to: T, duration: TimeInterval, function: TimingFunction, apply: @escaping ((T) -> Void)) { self.from = InterpolatableValue(value: from.vectorize()) self.to = InterpolatableValue(value: to.vectorize()) self.current = InterpolatableValue(value: self.from) self.duration = duration self.timingFunction = function self.apply = { let _ = ($0 as? T).flatMap(apply) } } public func run() { Scheduler.shared.add(self) } public func seek(_ time: TimeInterval) { elapsed = time advance(0) } public func reset() { current = from if let spring = spring { spring.reset() } // only force target presentation update if we've elapsed past 0 if elapsed > 0 { apply?(current.toInterpolatable()) } elapsed = 0 } internal func advance(_ time: TimeInterval) { let direction: CGFloat = reversed ? -1.0 : 1.0 elapsed += time elapsed = max(0, elapsed) reversed = time < 0 progress = CGFloat(elapsed / duration) * direction if (direction > 0 && progress >= 1.0) || (direction < 0 && progress <= -1.0) { kill() } } func kill() { Scheduler.shared.remove(self) } func time() -> TimeInterval { return elapsed } func canSubscribe() -> Bool { return true } } final public class Animator: Equatable { fileprivate (set) public var from: Property fileprivate (set) public var to: Property fileprivate (set) public var duration: Double fileprivate (set) public var key: String public var timingFunction: TimingFunction = Linear().timingFunction public var anchorPoint: CGPoint = CGPoint(x: 0.5, y: 0.5) public var additive: Bool = true public var changed: ((Animator, Property) -> Void)? public var finished: Bool { if let spring = spring { return spring.ended } return (!reversed && elapsed >= duration) || (reversed && elapsed <= 0) } internal var spring: Spring? fileprivate (set) public var current: Property fileprivate var elapsed: Double = 0.0 fileprivate var reversed = false fileprivate var presentation: ((Property) -> Property?)? public init(from: Property, to: Property, duration: Double, timingFunction: TimingFunction) { self.from = from self.to = to self.duration = duration self.timingFunction = timingFunction self.current = from self.key = from.key } // MARK: Public Methods public func seek(_ time: Double) { elapsed = time // advance(0) render(time) } public func reset() { current = from if let spring = spring { spring.reset() } changed?(self, current) elapsed = 0 } public func render(_ time: Double, advance: TimeInterval = 0) { // elapsed += time // elapsed = max(0, min(elapsed, duration)) let elapsed = max(0, min(time, duration)) if elapsed == self.elapsed { return } self.elapsed = elapsed reversed = time < 0 var progress = elapsed / duration progress = max(progress, 0.0) progress = min(progress, 1.0) var adjustedProgress = progress if let spring = spring { if time == 0 { spring.reset() } else { spring.proceed(advance / duration) } adjustedProgress = spring.current } else { adjustedProgress = timingFunction.solve(progress) } var presentationValue: Property = current if let from = from as? Transform, let to = to as? Transform, var value = current as? Transform { let scale = from.scale.value.interpolate(to: to.scale.value, progress: adjustedProgress) let rotation = from.rotation.value.interpolate(to: to.rotation.value, progress: adjustedProgress) let translation = from.translation.value.interpolate(to: to.translation.value, progress: adjustedProgress) value.scale.apply(scale) value.rotation.apply(rotation) value.translation.apply(translation) self.current = value presentationValue = value } else { let interpolatedValue = from.value.interpolate(to: to.value, progress: adjustedProgress) current.apply(interpolatedValue) if additive { // when an animation is additive, its presentation value needs to be adjusted so the transition is smooth presentationValue = adjustForAdditive(prop: presentationValue, interpolatable: interpolatedValue) } else { presentationValue = current } } // print("animator \(key) - progress: \(progress), current: \(current.value.vectors), presentation: \(presentationValue.value.vectors), from: \(from.value.vectors), to: \(to.value.vectors)") changed?(self, presentationValue) } public func onChange(_ block: ((Animator, Property) -> Void)?) { changed = block } public func setPresentation(_ block: ((Property) -> Property?)?) { presentation = block } /* An additive animation requires the linearly-interpolated value (LERP) to be updated to equal the sum of the display object's current presentation value and the delta between the animation's current and previous interpolated values. This should only be applied to the display object, *not* to the animation's current interpolated value. presentation = presentation + (current - previous) */ private func adjustForAdditive(prop: Property, interpolatable: InterpolatableValue) -> Property { if let pres = presentation?(prop) { var adjustedValue = prop var vectors = interpolatable.vectors let current = prop.value.vectors let pcurrent = pres.value.vectors for i in 0..<vectors.count { let delta = vectors[i] - current[i] vectors[i] = pcurrent[i] + delta } let intepolatable = InterpolatableValue(type: interpolatable.type, vectors: vectors) adjustedValue.apply(intepolatable) return adjustedValue } return prop } } public func ==(lhs: Animator, rhs: Animator) -> Bool { return ObjectIdentifier(lhs) == ObjectIdentifier(rhs) }
mit
b7e10e99f1a52ce006f85b1ced7c345d
26.880309
191
0.695749
3.691718
false
false
false
false
sm00th1980/compass
compass/Views/TopLabelViewController.swift
1
1088
// // TopLabelViewController.swift // compass // // Created by Ruslan Deyarov on 22/04/17. // Copyright © 2017 youct.ru. All rights reserved. // let HEIGHT = 59.0 import UIKit class TopLabelViewController: NSObject { class func setup(superView: UIView) -> CGFloat { let y = Double(UIApplication.shared.statusBarFrame.size.height) let label = UILabel(frame: CGRect(x: 0.0, y: y, width: Double(superView.bounds.width), height: height())) label.textAlignment = .center label.text = "YOUR DIRECTION" label.font = UIFont.systemFont(ofSize: 26.0, weight: UIFontWeightLight) label.textColor = UIColor(red: 28.0/255.0, green: 34.0/255.0, blue: 43.0/255.0, alpha: 1.0) // label.layer.borderWidth = 1 // label.layer.borderColor = UIColor.red.cgColor superView.addSubview(label) return label.frame.maxY } class func height() -> Double { if DeviceManager.iPhone4() { return HEIGHT / 1.5 } return HEIGHT } }
mit
29114c6ed01b94004429e117074b13a7
26.871795
113
0.606256
3.800699
false
false
false
false
vlas-voloshin/CustomAnimationsPlayground
CustomAnimations/BezierCurveView.swift
1
3079
// // BezierCurveView.swift // CustomAnimations // // Created by Vlas Voloshin on 9/08/2015. // Copyright (c) 2015 Vlas Voloshin. All rights reserved. // import UIKit final class BezierCurveView: UIView { var function: CAMediaTimingFunction? { didSet { self.setNeedsLayout() } } var strokeColor = UIColor.black { didSet { self.shapeLayer.strokeColor = self.strokeColor.cgColor self.tangentsLayer.strokeColor = self.strokeColor.cgColor } } override init(frame: CGRect) { super.init(frame: frame) self.commonInit() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.commonInit() } override func layoutSubviews() { super.layoutSubviews() let ownBounds = self.bounds self.shapeLayer.bounds = ownBounds self.tangentsLayer.bounds = ownBounds if let function = self.function { let controlPoints = (0..<4).map { (index: Int) -> CGPoint in let valuesArray = UnsafeMutablePointer<Float>.allocate(capacity: 2) function.getControlPoint(at: index, values: valuesArray) let normalizedPoint = CGPoint(x: CGFloat(valuesArray[0]), y: CGFloat(1 - valuesArray[1])) let denormalizedPoint = CGPoint(x: normalizedPoint.x * ownBounds.size.width, y: normalizedPoint.y * ownBounds.size.height) return denormalizedPoint } let curve = UIBezierPath() curve.move(to: controlPoints[0]) curve.addCurve(to: controlPoints[3], controlPoint1: controlPoints[1], controlPoint2: controlPoints[2]) self.shapeLayer.path = curve.cgPath let tangents = UIBezierPath() tangents.move(to: controlPoints[0]) tangents.addLine(to: controlPoints[1]) tangents.move(to: controlPoints[3]) tangents.addLine(to: controlPoints[2]) self.tangentsLayer.path = tangents.cgPath } else { self.shapeLayer.path = nil self.tangentsLayer.path = nil } } // MARK: - Private private let shapeLayer: CAShapeLayer = { let shapeLayer = CAShapeLayer() shapeLayer.fillColor = nil shapeLayer.anchorPoint = CGPoint.zero return shapeLayer }() private let tangentsLayer: CAShapeLayer = { let tangentsLayer = CAShapeLayer() tangentsLayer.fillColor = nil tangentsLayer.anchorPoint = CGPoint.zero tangentsLayer.lineDashPattern = [5, 2] return tangentsLayer }() private func commonInit() { self.shapeLayer.strokeColor = self.strokeColor.cgColor self.layer.addSublayer(self.shapeLayer) self.layer.addSublayer(self.tangentsLayer) self.tangentsLayer.strokeColor = self.strokeColor.cgColor } }
mit
71abda3da034da81077d143a7a7a517f
30.418367
114
0.591751
4.616192
false
false
false
false
joshuamcshane/nessie-ios-sdk-swift2
Nessie-iOS-Wrapper/ATM.swift
1
5744
// // ATM.swift // Nessie-iOS-Wrapper // // Created by Mecklenburg, William on 4/3/15. // Copyright (c) 2015 Nessie. All rights reserved. // import Foundation import CoreLocation public class ATMRequestBuilder { public var requestType: HTTPType? public var atmId: String! public var radius: String? public var latitude: Float? public var longitude: Float? } public class ATMRequest { private var request: NSMutableURLRequest? private var builder: ATMRequestBuilder! public convenience init?(block: (ATMRequestBuilder -> Void)) { let initializingBuilder = ATMRequestBuilder() block(initializingBuilder) self.init(builder: initializingBuilder) } private init?(builder: ATMRequestBuilder) { self.builder = builder if (builder.requestType != HTTPType.GET) { NSLog("You can only make a GET request for ATMs") return nil } let requestString = buildRequestUrl(); buildRequest(requestString); } //Methods for building the request. private func buildRequestUrl() -> String { var requestString = "\(baseString)/atms" if (builder.atmId != nil) { requestString += "/\(builder.atmId)?" } requestString += validateLocationSearchParameters() requestString += "key=\(NSEClient.sharedInstance.getKey())" return requestString } private func validateLocationSearchParameters() -> String { if (builder.latitude != nil && builder.longitude != nil && builder.radius != nil) { let locationSearchParameters = "lat=\(builder.latitude!)&lng=\(builder.longitude!)&rad=\(builder.radius!)" return "?"+locationSearchParameters+"&" } else if !(builder.latitude == nil && builder.longitude == nil && builder.radius == nil) { NSLog("To search for ATMs by location, you must provide latitude, longitude, and radius.") NSLog("You provided lat:\(builder.latitude) long:\(builder.longitude) radius:\(builder.radius)") } return "" } private func buildRequest(url: String) -> NSMutableURLRequest { self.request = NSMutableURLRequest(URL: NSURL(string: url)!) self.request!.HTTPMethod = builder.requestType!.rawValue self.request!.setValue("application/json", forHTTPHeaderField: "content-type") return request! } //Method for sending the request public func send(completion: ((ATMResult) -> Void)?) { NSURLSession.sharedSession().dataTaskWithRequest(request!, completionHandler:{(data, response, error) -> Void in if error != nil { NSLog(error!.description) return } if (completion == nil) { return } let result = ATMResult(data: data!) completion!(result) }).resume() } } public struct ATMResult { private var dataItem:ATM? private var dataArray:Array<ATM>? private init(data:NSData) { let parsedObject: AnyObject? = try! NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions()) as? Dictionary<String,AnyObject> if let results = parsedObject as? NSDictionary { if let atmsDict = results["data"] as? [Dictionary<String, AnyObject>] { dataArray = [] dataItem = nil for atm in atmsDict { dataArray?.append(ATM(data: atm)) } } else { dataArray = nil //If there is an error message, the json will parse to a dictionary, not an array if let message:AnyObject = results["message"] { NSLog(message.description!) if let reason:AnyObject = results["culprit"] { NSLog("Reasons:\(reason.description)") return } else { return } } dataItem = ATM(data: results as! Dictionary<String, AnyObject>) } } } public func getATM() -> ATM? { if (dataItem == nil) { NSLog("No single data item found. If you were intending to get multiple items, try getAllATMs()"); } return dataItem } public func getAllATMs() -> Array<ATM>? { if (dataArray == nil) { NSLog("No array of data items found. If you were intending to get one single item, try getATM()"); } return dataArray } } public class ATM { public let atmId:String public let name:String public let languageList:Array<String> public let address:Address public let geocode:CLLocation public let amountLeft:Int public let accessibility: Bool public let hours: Array<String> internal init(data:Dictionary<String,AnyObject>) { self.atmId = data["_id"] as! String self.name = data["name"] as! String self.languageList = data["language_list"] as! Array<String> self.address = Address(data:data["address"] as! Dictionary<String,AnyObject>) self.amountLeft = data["amount_left"] as! Int self.accessibility = data["accessibility"] as! Bool self.hours = data["hours"] as! Array<String> var geocodeDict = data["geocode"] as! Dictionary<String, Double> self.geocode = CLLocation(latitude: geocodeDict["lat"]!, longitude: geocodeDict["lng"]!) } }
mit
521ad5e69f4db239fdf41d6ed1a6c8a2
32.011494
154
0.579909
4.947459
false
false
false
false
Ricky-Choi/AppcidCocoaUtil
ACUSample/AppDelegate.swift
1
3329
// // AppDelegate.swift // ACUSample // // Created by Jae Young Choi on 2017. 2. 2.. // Copyright © 2017년 Appcid. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate, UISplitViewControllerDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. let splitViewController = self.window!.rootViewController as! UISplitViewController let navigationController = splitViewController.viewControllers[splitViewController.viewControllers.count-1] as! UINavigationController navigationController.topViewController!.navigationItem.leftBarButtonItem = splitViewController.displayModeButtonItem splitViewController.delegate = self return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } // MARK: - Split view func splitViewController(_ splitViewController: UISplitViewController, collapseSecondary secondaryViewController:UIViewController, onto primaryViewController:UIViewController) -> Bool { guard let secondaryAsNavController = secondaryViewController as? UINavigationController else { return false } guard let topAsDetailController = secondaryAsNavController.topViewController as? DetailViewController else { return false } if topAsDetailController.detailItem == nil { // Return true to indicate that we have handled the collapse by doing nothing; the secondary controller will be discarded. return true } return false } }
mit
318f7c2573bc8d1c0bf793499b686231
53.52459
285
0.760673
6.182156
false
false
false
false
TerryCK/GogoroBatteryMap
GogoroMap/BackupPage/Views/SupplementaryCell.swift
1
1468
// // SupplementaryCell.swift // GogoroMap // // Created by Terry Chen on 2019/4/8. // Copyright © 2019 陳 冠禎. All rights reserved. // import UIKit final class SupplementaryCell: UIView { override init(frame: CGRect) { super.init(frame: frame) setupView() } init(title: String? = nil, subtitle: String? = nil, titleTextAlignment: NSTextAlignment = .natural) { self.init() titleLabel.text = title subtitleLabel.text = subtitle titleLabel.textAlignment = titleTextAlignment } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setupView() } lazy var titleLabel = UILabel { $0.font = .systemFont(ofSize: 16) $0.textColor = .gray } lazy var subtitleLabel = UILabel { $0.font = .systemFont(ofSize: 16) $0.numberOfLines = 0 $0.textColor = .lightGray } func setupView() { [titleLabel, subtitleLabel].forEach(addSubview) titleLabel.anchor(top: topAnchor, left: leftAnchor, bottom: nil, right: rightAnchor, topPadding: 12, leftPadding: 20, bottomPadding: 0, rightPadding: 10, width: 0, height: 22) subtitleLabel.anchor(top: titleLabel.bottomAnchor, left: titleLabel.leftAnchor, bottom: bottomAnchor, right: titleLabel.rightAnchor, topPadding: 0, leftPadding: 0, bottomPadding: 0, rightPadding: 0, width: 0, height: 0) } }
mit
a40811773ce5f29e276251f2f90ebe07
29.4375
227
0.631759
4.247093
false
false
false
false
blockchain/My-Wallet-V3-iOS
Modules/FeatureNFT/Sources/FeatureNFTDomain/Models/Asset.swift
1
4520
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import Foundation import ToolKit public struct AssetPageResponse { public let next: String? public let assets: [Asset] public init( next: String?, assets: [Asset] ) { self.next = next self.assets = assets } } public struct Asset: Equatable, Identifiable { public var id: String { identifier } public var url: URL { let network = network.openseaDescription var components = URLComponents() components.scheme = "https" components.host = "opensea.io" components.path = "/assets/\(network)/\(contractId)/\(tokenID)" return components.url ?? "https://www.opensea.io" } public var creatorDisplayValue: String { if creator.contains("0x") { // Abridge the address to match OpenSea's UX return creator .dropFirst(2) .prefix(6) .uppercased() } else { return creator } } public let name: String public let creator: String public let tokenID: String public let nftDescription: String public let identifier: String public let contractId: String public let collection: Collection public let media: Media public let network: Network public let traits: [Trait] public enum Network { case ethereum case polygon var openseaDescription: String { switch self { case .ethereum: return "ethereum" case .polygon: return "matic" } } } public struct Trait: Equatable, Identifiable { public var id: String { "\(type).\(description)" } public let type: String public let description: String public init(type: String, description: String) { self.type = type self.description = description } } public struct Collection: Equatable { public let name: String public let isVerified: Bool public let bannerImageURL: String? public let collectionImageUrl: String? public let collectionDescription: String? public init( name: String, isVerified: Bool, bannerImageURL: String? = nil, collectionImageURL: String? = nil, collectionDescription: String? = nil ) { self.name = name self.isVerified = isVerified self.bannerImageURL = bannerImageURL collectionImageUrl = collectionImageURL self.collectionDescription = collectionDescription } } public struct Media: Equatable { public let backgroundColor: String? public let bannerImageURL: String? public let animationURL: String? public let collectionImageUrl: String? public let imageOriginalURL: String? public let imagePreviewURL: String public let imageThumbnailURL: String public let imageURL: String? public init( backgroundColor: String?, animationURL: String?, bannerImageURL: String?, collectionImageUrl: String?, imageOriginalURL: String?, imagePreviewURL: String, imageThumbnailURL: String, imageURL: String? ) { self.backgroundColor = backgroundColor self.animationURL = animationURL self.collectionImageUrl = collectionImageUrl self.bannerImageURL = bannerImageURL self.imageOriginalURL = imageOriginalURL self.imagePreviewURL = imagePreviewURL self.imageThumbnailURL = imageThumbnailURL self.imageURL = imageURL } } public init( name: String, creator: String, tokenID: String, nftDescription: String, identifier: String, contractId: String, collection: Collection, network: Network, media: Media, traits: [Trait] ) { self.name = name self.collection = collection self.creator = creator self.tokenID = tokenID self.network = network self.contractId = contractId self.nftDescription = nftDescription self.identifier = identifier self.media = media self.traits = traits } }
lgpl-3.0
4c2f5a88ccec320bef8d82912d7545b6
26.895062
71
0.585306
5.254651
false
false
false
false
PJayRushton/stats
Stats/Component.swift
1
1807
// // ......... ......... // ...... ........... ..... // ... ..... .... // ... .... ... // ... ........ ... // .... .... .... ... // ... .... .... ... // ..... ....... .... // ... ..... .... // .... .... // .... .... // ..... ..... // ..... .... // ....... // ... import UIKit import Presentr class Component: UIViewController, Subscriber { var core = App.core let alertPresenter: Presentr = { let presenter = Presentr(presentationType: .alert) presenter.transitionType = TransitionType.coverHorizontalFromRight return presenter }() override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) core.add(subscriber: self) } override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) core.remove(subscriber: self) } func update(with: AppState) { // override me } func modalPresenter(withTransitionType transitionType: TransitionType = .coverHorizontalFromRight) -> Presentr { let customPresentation = PresentationType.custom(width: .half, height: .half, center: .center) let modalPresentation = PresentationType.popup let presentationType = UIDevice.current.userInterfaceIdiom == .pad ? customPresentation : modalPresentation let presenter = Presentr(presentationType: presentationType) presenter.transitionType = transitionType presenter.dismissTransitionType = TransitionType.coverHorizontalFromRight return presenter } }
mit
f1a560896458de01f4f0166cf4ad3017
30.701754
116
0.50083
5.252907
false
false
false
false
pyanfield/ataturk_olympic
swift_programming_subscripts_inheritance.playground/section-1.swift
1
5299
// Playground - noun: a place where people can play import UIKit // 2.12 // 下标脚本(Subscripts) // 下标脚本是定义在类(Class)、结构体(structure)和枚举(enumeration)中,是访问对象、集合或序列的快捷方式,不需要再调用实例的特定的赋值和访问方法。 // 对于同一个目标可以定义多个下标脚本,通过索引值类型的不同来进行重载,而且索引值的个数可以是多个。 // 下标脚本允许你通过在实例后面的方括号中传入一个或者多个的索引值来对实例进行访问和赋值。 struct TimesTable { let multiplier: Int // 使用 subscript 关键字来修饰 subscript(index: Int) -> Int { return multiplier * index } } let threeTimesTable = TimesTable(multiplier: 3) // 像访问数组中的某个值一样, subscript 在访问的时候也是用方括号的方式来实现 println("3的6倍是\(threeTimesTable[6])") // 输出 "3的6倍是18" // 通常下标脚本是用来访问集合(collection),列表(list)或序列(sequence)中元素的快捷方式。你可以在你自己特定的类或结构体中自由的实现下标脚本来提供合适的功能。 // 下标脚本允许任意数量的入参索引,并且每个入参类型也没有限制。下标脚本的返回值也可以是任何类型。 // 下标脚本可以使用变量参数和可变参数,但使用写入读出(in-out)参数或给参数设置默认值都是不允许的。 struct Matrix { let rows: Int, columns: Int var grid: [Double] init(rows: Int, columns: Int) { self.rows = rows self.columns = columns grid = Array(count: rows * columns, repeatedValue: 0.0) } func indexIsValidForRow(row: Int, column: Int) -> Bool { return row >= 0 && row < rows && column >= 0 && column < columns } // 关键字实现下标脚本,可以实现 get / set 方法 subscript(row: Int, column: Int) -> Double { get { assert(indexIsValidForRow(row, column: column), "Index out of range") return grid[(row * columns) + column] } set { assert(indexIsValidForRow(row, column: column), "Index out of range") grid[(row * columns) + column] = newValue } } } var matrix = Matrix(rows: 2, columns: 2) matrix[1,1] = 1.5 matrix[1,1] // 2.13 // 继承 Inheritance // 在 Swift 中,继承是区分「类」与其它类型的一个基本特征。 // 在 Swift 中,类可以调用和访问超类的方法,属性和下标脚本(subscripts),并且可以重写(override)这些方法,属性和下标脚本来优化或修改它们的行为。 // 可以为类中继承来的属性添加属性观察器(property observer),这样一来,当属性值改变时,类就会被通知到。 // 可以为任何属性添加属性观察器,无论它原本被定义为存储型属性(stored property)还是计算型属性(computed property) // 子类可以为继承来的实例方法(instance method),类方法(class method),实例属性(instance property),或下标脚本(subscript)提供自己定制的实现(implementation)。我们把这种行为叫重写(overriding)。 // 如果要重写某个特性,你需要在重写定义的前面加上 override 关键字。 // 通过使用super前缀来访问超类版本的方法,属性或下标脚本. // 在属性someProperty的 getter 或 setter 的重写实现中,可以通过super.someProperty来访问超类版本的someProperty属性。 // 在下标脚本的重写实现中,可以通过super[someIndex]来访问超类版本中的相同下标脚本。 // 子类并不知道继承来的属性是存储型的还是计算型的,它只知道继承来的属性会有一个名字和类型。你在重写一个属性时,必需将它的名字和类型都写出来。 // 这样才能使编译器去检查你重写的属性是与超类中同名同类型的属性相匹配的。 // 可以将一个继承来的只读属性重写为一个读写属性,只需要你在重写版本的属性里提供 getter 和 setter 即可。但是,你不可以将一个继承来的读写属性重写为一个只读属性。 // 如果你在重写属性中提供了 setter,那么你也一定要提供 getter。 // 如果你不想在重写版本中的 getter 里修改继承来的属性值,你可以直接通过super.someProperty来返回继承来的值,其中someProperty是你要重写的属性的名字。 // 你不可以同时提供重写的 setter 和重写的属性观察器。如果你想观察属性值的变化,并且你已经为那个属性提供了定制的 setter,那么你在 setter 中就可以观察到任何值变化了。 // 不可以为继承来的常量存储型属性或继承来的只读计算型属性添加属性观察器。 // 可以通过把方法,属性或下标脚本标记为final来防止它们被重写,只需要在声明关键字前加上@final特性即可。(例如:final var, final func, final class func, 以及 final subscript) // 通过在关键字class前添加final特性(final class)来将整个类标记为 final 的,这样的类是不可被继承的,否则会报编译错误。
mit
a55f495897a91dea9eda6953b75fb74d
34.722892
141
0.738954
2.547251
false
false
false
false
PomTTcat/SourceCodeGuideRead_JEFF
RxSwiftGuideRead/RxSwift-master/Rx.playground/Pages/Introduction.xcplaygroundpage/Contents.swift
5
4448
/*: > # IMPORTANT: To use **Rx.playground**: 1. Open **Rx.xcworkspace**. 1. Build the **RxExample-macOS** scheme (**Product** → **Build**). 1. Open **Rx** playground in the **Project navigator** (under RxExample project). 1. Show the Debug Area (**View** → **Debug Area** → **Show Debug Area**). ---- [Previous](@previous) */ import RxSwift /*: # Introduction ## Why use RxSwift? A vast majority of the code we write involves responding to external events. When a user manipulates a control, we need to write an `@IBAction` handler to respond. We need to observe notifications to detect when the keyboard changes position. We must provide closures to execute when URL sessions respond with data. And we use KVO to detect changes to variables. All of these various systems makes our code needlessly complex. Wouldn't it be better if there was one consistent system that handled all of our call/response code? Rx is such a system. RxSwift is the official implementation of [Reactive Extensions](http://reactivex.io) (aka Rx), which exist for [most major languages and platforms](http://reactivex.io/languages.html). */ /*: ## Concepts **Every `Observable` instance is just a sequence.** The key advantage for an `Observable` sequence vs. Swift's `Sequence` is that it can also receive elements asynchronously. _This is the essence of RxSwift._ Everything else expands upon this concept. * An `Observable` (`ObservableType`) is equivalent to a `Sequence`. * The `ObservableType.subscribe(_:)` method is equivalent to `Sequence.makeIterator()`. * `ObservableType.subscribe(_:)` takes an observer (`ObserverType`) parameter, which will be subscribed to automatically receive sequence events and elements emitted by the `Observable`, instead of manually calling `next()` on the returned generator. */ /*: If an `Observable` emits a next event (`Event.next(Element)`), it can continue to emit more events. However, if the `Observable` emits either an error event (`Event.error(ErrorType)`) or a completed event (`Event.completed`), the `Observable` sequence cannot emit additional events to the subscriber. Sequence grammar explains this more concisely: `next* (error | completed)?` And this can also be explained more visually using diagrams: `--1--2--3--4--5--6--|----> // "|" = Terminates normally` `--a--b--c--d--e--f--X----> // "X" = Terminates with an error` `--tap--tap----------tap--> // "|" = Continues indefinitely, such as a sequence of button taps` > These diagrams are called marble diagrams. You can learn more about them at [RxMarbles.com](http://rxmarbles.com). */ /*: ### Observables and observers (aka subscribers) `Observable`s will not execute their subscription closure unless there is a subscriber. In the following example, the closure of the `Observable` will never be executed, because there are no subscribers: */ example("Observable with no subscribers") { _ = Observable<String>.create { observerOfString -> Disposable in print("This will never be printed") observerOfString.on(.next("😬")) observerOfString.on(.completed) return Disposables.create() } } /*: ---- In the following example, the closure will be executed when `subscribe(_:)` is called: */ example("Observable with subscriber") { _ = Observable<String>.create { observerOfString in print("Observable created") observerOfString.on(.next("😉")) observerOfString.on(.completed) return Disposables.create() } .subscribe { event in print(event) } } /*: > Don't concern yourself with the details of how these `Observable`s were created in these examples. We'll get into that [next](@next). # > `subscribe(_:)` returns a `Disposable` instance that represents a disposable resource such as a subscription. It was ignored in the previous simple example, but it should normally be properly handled. This usually means adding it to a `DisposeBag` instance. All examples going forward will include proper handling, because, well, practice makes _permanent_ 🙂. You can learn more about this in the [Disposing section](https://github.com/ReactiveX/RxSwift/blob/master/Documentation/GettingStarted.md#disposing) of the [Getting Started guide](https://github.com/ReactiveX/RxSwift/blob/master/Documentation/GettingStarted.md). */ //: [Next](@next) - [Table of Contents](Table_of_Contents)
mit
8b98e37afbbe31184892e4a33ff54c08
51.152941
625
0.715768
4.389109
false
false
false
false
jeroendesloovere/examples-swift
Swift-Playgrounds/SwiftStanardLibrary/String.playground/section-1.swift
1
1934
// Swift Standard Library - Types - String // A String represents an ordered collection of characters. // Creating a String let emptyString = String() let equivilentString = "" let repeatedString = String(count: 5, repeatedValue: Character("a")) // Querying a String var string = "Hello, world!" let firstCheck = string.isEmpty string = "" let secondCheck = string.isEmpty string = "Hello, world!" let hasPrefixFirstCheck = string.hasPrefix("Hello") let hasPrefixSecondCheck = string.hasPrefix("hello") let hasSuffixFirstCheck = string.hasSuffix("world!") let hasSuffixSecondCheck = string.hasSuffix("World!") // Changing and Converting Strings string = "42" if let number = string.toInt() { println("Got the number: \(number)") } else { println("Couldn't convert to a number") } // Operators // Concatinate + let combination = "Hello " + "world" // You can use the + operator with two strings as shown in the combination example, or with a string and a character in either order: let exclamationPoint: Character = "!" var charCombo = combination charCombo.append(exclamationPoint) //var extremeCombo: String = exclamationPoint //extremeCombo.append(charCombo) // Append += string = "Hello " string += "world" string.append(exclamationPoint) string // Equality == let string1 = "Hello world!" let string2 = "Hello" + " " + "world" + "!" let equality = string1 == string2 // Less than < let stringGreater = "Number 3" let stringLesser = "Number 2" let resulNotLessThan = stringGreater < stringLesser let resultIsLessThan = stringLesser < stringGreater // What is missing from this chapter? // - How does the less than operator work? "abc" < "def" "def" < "abc" "Number 2" < "number 1" // It just looks at the ordinal valu of the first character??? // - Does the greater than symbol work? "abc" > "def" "def" > "abc" "Number 2" > "number 1" // - How do you access the rodinal values of Characters?
mit
86bc99dfdabfdd5022e5229a18e158b5
21.229885
133
0.711479
3.676806
false
false
false
false
tjw/swift
test/Compatibility/tuple_arguments_3.swift
2
44410
// RUN: %target-typecheck-verify-swift -swift-version 3 // Tests for tuple argument behavior in Swift 3, which was broken. // The Swift 4 test is in test/Compatibility/tuple_arguments_4.swift. // The test for the most recent version is in test/Constraints/tuple_arguments.swift. // Key: // - "Crashes in actual Swift 3" -- snippets which crashed in Swift 3.0.1. // These don't have well-defined semantics in Swift 3 mode and don't // matter for source compatibility purposes. // // - "Does not diagnose in Swift 3 mode" -- snippets which failed to typecheck // in Swift 3.0.1, but now typecheck. This is fine. // // - "Diagnoses in Swift 3 mode" -- snippets which typechecked in Swift 3.0.1, // but now fail to typecheck. These are bugs in Swift 3 mode that should be // fixed. // // - "Crashes in Swift 3 mode" -- snippets which did not crash Swift 3.0.1, // but now crash. These are bugs in Swift 3 mode that should be fixed. func concrete(_ x: Int) {} func concreteLabeled(x: Int) {} func concreteTwo(_ x: Int, _ y: Int) {} // expected-note 3 {{'concreteTwo' declared here}} func concreteTuple(_ x: (Int, Int)) {} do { concrete(3) concrete((3)) concreteLabeled(x: 3) concreteLabeled(x: (3)) concreteLabeled((x: 3)) // expected-error {{missing argument label 'x:' in call}} concreteTwo(3, 4) concreteTwo((3, 4)) // expected-error {{missing argument for parameter #2 in call}} concreteTuple(3, 4) // expected-error {{global function 'concreteTuple' expects a single parameter of type '(Int, Int)'}} {{17-17=(}} {{21-21=)}} concreteTuple((3, 4)) } do { let a = 3 let b = 4 let c = (3) let d = (a, b) concrete(a) concrete((a)) concrete(c) concreteTwo(a, b) concreteTwo((a, b)) concreteTwo(d) // expected-error {{passing 2 arguments to a callee as a single tuple value has been removed in Swift 3}} concreteTuple(a, b) concreteTuple((a, b)) concreteTuple(d) } do { var a = 3 var b = 4 var c = (3) var d = (a, b) concrete(a) concrete((a)) concrete(c) concreteTwo(a, b) concreteTwo((a, b)) // expected-error {{missing argument for parameter #2 in call}} concreteTwo(d) // expected-error {{missing argument for parameter #2 in call}} concreteTuple(a, b) // expected-error {{global function 'concreteTuple' expects a single parameter of type '(Int, Int)'}} {{17-17=(}} {{21-21=)}} concreteTuple((a, b)) concreteTuple(d) } func generic<T>(_ x: T) {} func genericLabeled<T>(x: T) {} func genericTwo<T, U>(_ x: T, _ y: U) {} // expected-note 5 {{'genericTwo' declared here}} func genericTuple<T, U>(_ x: (T, U)) {} do { generic(3) generic(3, 4) generic((3)) generic((3, 4)) genericLabeled(x: 3) genericLabeled(x: 3, 4) // expected-error {{extra argument in call}} genericLabeled(x: (3)) genericLabeled(x: (3, 4)) genericTwo(3, 4) genericTwo((3, 4)) // expected-error {{missing argument for parameter #2 in call}} genericTuple(3, 4) // expected-error {{global function 'genericTuple' expects a single parameter of type '(T, U)'}} {{16-16=(}} {{20-20=)}} genericTuple((3, 4)) } do { let a = 3 let b = 4 let c = (3) let d = (a, b) generic(a) generic(a, b) generic((a)) generic(c) generic((a, b)) generic(d) genericTwo(a, b) genericTwo((a, b)) // expected-error {{missing argument for parameter #2 in call}} genericTwo(d) // expected-error {{missing argument for parameter #2 in call}} genericTuple(a, b) // expected-error {{global function 'genericTuple' expects a single parameter of type '(T, U)'}} {{16-16=(}} {{20-20=)}} genericTuple((a, b)) genericTuple(d) } do { var a = 3 var b = 4 var c = (3) var d = (a, b) generic(a) // generic(a, b) // Crashes in actual Swift 3 generic((a)) generic(c) generic((a, b)) generic(d) genericTwo(a, b) genericTwo((a, b)) // expected-error {{missing argument for parameter #2 in call}} genericTwo(d) // expected-error {{missing argument for parameter #2 in call}} genericTuple(a, b) // expected-error {{global function 'genericTuple' expects a single parameter of type '(T, U)'}} {{16-16=(}} {{20-20=)}} genericTuple((a, b)) genericTuple(d) } var function: (Int) -> () var functionTwo: (Int, Int) -> () // expected-note 3 {{'functionTwo' declared here}} var functionTuple: ((Int, Int)) -> () do { function(3) function((3)) functionTwo(3, 4) functionTwo((3, 4)) // expected-error {{missing argument for parameter #2 in call}} functionTuple(3, 4) // expected-error {{var 'functionTuple' expects a single parameter of type '(Int, Int)'}} {{17-17=(}} {{21-21=)}} functionTuple((3, 4)) } do { let a = 3 let b = 4 let c = (3) let d = (a, b) function(a) function((a)) function(c) functionTwo(a, b) functionTwo((a, b)) functionTwo(d) // expected-error {{passing 2 arguments to a callee as a single tuple value has been removed in Swift 3}} functionTuple(a, b) functionTuple((a, b)) functionTuple(d) } do { var a = 3 var b = 4 var c = (3) var d = (a, b) function(a) function((a)) function(c) functionTwo(a, b) functionTwo((a, b)) // expected-error {{missing argument for parameter #2 in call}} functionTwo(d) // expected-error {{missing argument for parameter #2 in call}} functionTuple(a, b) // expected-error {{var 'functionTuple' expects a single parameter of type '(Int, Int)'}} {{17-17=(}} {{21-21=)}} functionTuple((a, b)) functionTuple(d) } struct Concrete {} extension Concrete { func concrete(_ x: Int) {} func concreteTwo(_ x: Int, _ y: Int) {} // expected-note 3 {{'concreteTwo' declared here}} func concreteTuple(_ x: (Int, Int)) {} } do { let s = Concrete() s.concrete(3) s.concrete((3)) s.concreteTwo(3, 4) s.concreteTwo((3, 4)) // expected-error {{missing argument for parameter #2 in call}} s.concreteTuple(3, 4) // expected-error {{instance method 'concreteTuple' expects a single parameter of type '(Int, Int)'}} {{19-19=(}} {{23-23=)}} s.concreteTuple((3, 4)) } do { let s = Concrete() let a = 3 let b = 4 let c = (3) let d = (a, b) s.concrete(a) s.concrete((a)) s.concrete(c) s.concreteTwo(a, b) s.concreteTwo((a, b)) s.concreteTwo(d) // expected-error {{passing 2 arguments to a callee as a single tuple value has been removed in Swift 3}} s.concreteTuple(a, b) s.concreteTuple((a, b)) s.concreteTuple(d) } do { var s = Concrete() var a = 3 var b = 4 var c = (3) var d = (a, b) s.concrete(a) s.concrete((a)) s.concrete(c) s.concreteTwo(a, b) s.concreteTwo((a, b)) // expected-error {{missing argument for parameter #2 in call}} s.concreteTwo(d) // expected-error {{missing argument for parameter #2 in call}} s.concreteTuple(a, b) // expected-error {{instance method 'concreteTuple' expects a single parameter of type '(Int, Int)'}} {{19-19=(}} {{23-23=)}} s.concreteTuple((a, b)) s.concreteTuple(d) } extension Concrete { func generic<T>(_ x: T) {} func genericLabeled<T>(x: T) {} func genericTwo<T, U>(_ x: T, _ y: U) {} // expected-note 5 {{'genericTwo' declared here}} func genericTuple<T, U>(_ x: (T, U)) {} } do { let s = Concrete() s.generic(3) s.generic(3, 4) s.generic((3)) s.generic((3, 4)) s.genericLabeled(x: 3) s.genericLabeled(x: 3, 4) // expected-error {{extra argument in call}} s.genericLabeled(x: (3)) s.genericLabeled(x: (3, 4)) s.genericTwo(3, 4) s.genericTwo((3, 4)) // expected-error {{missing argument for parameter #2 in call}} s.genericTuple(3, 4) // expected-error {{instance method 'genericTuple' expects a single parameter of type '(T, U)'}} {{18-18=(}} {{22-22=)}} s.genericTuple((3, 4)) } do { let s = Concrete() let a = 3 let b = 4 let c = (3) let d = (a, b) s.generic(a) s.generic(a, b) s.generic((a)) s.generic((a, b)) s.generic(d) s.genericTwo(a, b) s.genericTwo((a, b)) // expected-error {{missing argument for parameter #2 in call}} s.genericTwo(d) // expected-error {{missing argument for parameter #2 in call}} s.genericTuple(a, b) // expected-error {{instance method 'genericTuple' expects a single parameter of type '(T, U)'}} {{18-18=(}} {{22-22=)}} s.genericTuple((a, b)) s.genericTuple(d) } do { var s = Concrete() var a = 3 var b = 4 var c = (3) var d = (a, b) s.generic(a) // s.generic(a, b) // Crashes in actual Swift 3 s.generic((a)) s.generic((a, b)) s.generic(d) s.genericTwo(a, b) s.genericTwo((a, b)) // expected-error {{missing argument for parameter #2 in call}} s.genericTwo(d) // expected-error {{missing argument for parameter #2 in call}} s.genericTuple(a, b) // expected-error {{instance method 'genericTuple' expects a single parameter of type '(T, U)'}} {{18-18=(}} {{22-22=)}} s.genericTuple((a, b)) s.genericTuple(d) } extension Concrete { mutating func mutatingConcrete(_ x: Int) {} mutating func mutatingConcreteTwo(_ x: Int, _ y: Int) {} // expected-note 3 {{'mutatingConcreteTwo' declared here}} mutating func mutatingConcreteTuple(_ x: (Int, Int)) {} } do { var s = Concrete() s.mutatingConcrete(3) s.mutatingConcrete((3)) s.mutatingConcreteTwo(3, 4) s.mutatingConcreteTwo((3, 4)) // expected-error {{missing argument for parameter #2 in call}} s.mutatingConcreteTuple(3, 4) // expected-error {{instance method 'mutatingConcreteTuple' expects a single parameter of type '(Int, Int)'}} {{27-27=(}} {{31-31=)}} s.mutatingConcreteTuple((3, 4)) } do { var s = Concrete() let a = 3 let b = 4 let c = (3) let d = (a, b) s.mutatingConcrete(a) s.mutatingConcrete((a)) s.mutatingConcrete(c) s.mutatingConcreteTwo(a, b) s.mutatingConcreteTwo((a, b)) s.mutatingConcreteTwo(d) // expected-error {{passing 2 arguments to a callee as a single tuple value has been removed in Swift 3}} s.mutatingConcreteTuple(a, b) s.mutatingConcreteTuple((a, b)) s.mutatingConcreteTuple(d) } do { var s = Concrete() var a = 3 var b = 4 var c = (3) var d = (a, b) s.mutatingConcrete(a) s.mutatingConcrete((a)) s.mutatingConcrete(c) s.mutatingConcreteTwo(a, b) s.mutatingConcreteTwo((a, b)) // expected-error {{missing argument for parameter #2 in call}} s.mutatingConcreteTwo(d) // expected-error {{missing argument for parameter #2 in call}} s.mutatingConcreteTuple(a, b) // expected-error {{instance method 'mutatingConcreteTuple' expects a single parameter of type '(Int, Int)'}} {{27-27=(}} {{31-31=)}} s.mutatingConcreteTuple((a, b)) s.mutatingConcreteTuple(d) } extension Concrete { mutating func mutatingGeneric<T>(_ x: T) {} mutating func mutatingGenericLabeled<T>(x: T) {} mutating func mutatingGenericTwo<T, U>(_ x: T, _ y: U) {} // expected-note 5 {{'mutatingGenericTwo' declared here}} mutating func mutatingGenericTuple<T, U>(_ x: (T, U)) {} } do { var s = Concrete() s.mutatingGeneric(3) s.mutatingGeneric(3, 4) s.mutatingGeneric((3)) s.mutatingGeneric((3, 4)) s.mutatingGenericLabeled(x: 3) s.mutatingGenericLabeled(x: 3, 4) // expected-error {{extra argument in call}} s.mutatingGenericLabeled(x: (3)) s.mutatingGenericLabeled(x: (3, 4)) s.mutatingGenericTwo(3, 4) s.mutatingGenericTwo((3, 4)) // expected-error {{missing argument for parameter #2 in call}} s.mutatingGenericTuple(3, 4) // expected-error {{instance method 'mutatingGenericTuple' expects a single parameter of type '(T, U)'}} {{26-26=(}} {{30-30=)}} s.mutatingGenericTuple((3, 4)) } do { var s = Concrete() let a = 3 let b = 4 let c = (3) let d = (a, b) s.mutatingGeneric(a) s.mutatingGeneric(a, b) s.mutatingGeneric((a)) s.mutatingGeneric((a, b)) s.mutatingGeneric(d) s.mutatingGenericTwo(a, b) s.mutatingGenericTwo((a, b)) // expected-error {{missing argument for parameter #2 in call}} s.mutatingGenericTwo(d) // expected-error {{missing argument for parameter #2 in call}} s.mutatingGenericTuple(a, b) // expected-error {{instance method 'mutatingGenericTuple' expects a single parameter of type '(T, U)'}} {{26-26=(}} {{30-30=)}} s.mutatingGenericTuple((a, b)) s.mutatingGenericTuple(d) } do { var s = Concrete() var a = 3 var b = 4 var c = (3) var d = (a, b) s.mutatingGeneric(a) // s.mutatingGeneric(a, b) // Crashes in actual Swift 3 s.mutatingGeneric((a)) s.mutatingGeneric((a, b)) s.mutatingGeneric(d) s.mutatingGenericTwo(a, b) s.mutatingGenericTwo((a, b)) // expected-error {{missing argument for parameter #2 in call}} s.mutatingGenericTwo(d) // expected-error {{missing argument for parameter #2 in call}} s.mutatingGenericTuple(a, b) // expected-error {{instance method 'mutatingGenericTuple' expects a single parameter of type '(T, U)'}} {{26-26=(}} {{30-30=)}} s.mutatingGenericTuple((a, b)) s.mutatingGenericTuple(d) } extension Concrete { var function: (Int) -> () { return concrete } var functionTwo: (Int, Int) -> () { return concreteTwo } var functionTuple: ((Int, Int)) -> () { return concreteTuple } } do { let s = Concrete() s.function(3) s.function((3)) s.functionTwo(3, 4) s.functionTwo((3, 4)) // expected-error {{missing argument for parameter #2 in call}} s.functionTuple(3, 4) // expected-error {{single parameter of type '(Int, Int)' is expected in call}} {{19-19=(}} {{23-23=)}} s.functionTuple((3, 4)) } do { let s = Concrete() let a = 3 let b = 4 let c = (3) let d = (a, b) s.function(a) s.function((a)) s.function(c) s.functionTwo(a, b) s.functionTwo((a, b)) s.functionTwo(d) // expected-error {{passing 2 arguments to a callee as a single tuple value has been removed in Swift 3}} s.functionTuple(a, b) s.functionTuple((a, b)) s.functionTuple(d) } do { var s = Concrete() var a = 3 var b = 4 var c = (3) var d = (a, b) s.function(a) s.function((a)) s.function(c) s.functionTwo(a, b) s.functionTwo((a, b)) // expected-error {{missing argument for parameter #2 in call}} s.functionTwo(d) // expected-error {{missing argument for parameter #2 in call}} s.functionTuple(a, b) // expected-error {{single parameter of type '(Int, Int)' is expected in call}} {{19-19=(}} {{23-23=)}} s.functionTuple((a, b)) s.functionTuple(d) } struct InitTwo { init(_ x: Int, _ y: Int) {} // expected-note 3 {{'init' declared here}} } struct InitTuple { init(_ x: (Int, Int)) {} } struct InitLabeledTuple { init(x: (Int, Int)) {} } do { _ = InitTwo(3, 4) _ = InitTwo((3, 4)) // expected-error {{missing argument for parameter #2 in call}} _ = InitTuple(3, 4) // expected-error {{initializer expects a single parameter of type '(Int, Int)'}} {{17-17=(}} {{21-21=)}} _ = InitTuple((3, 4)) _ = InitLabeledTuple(x: 3, 4) // expected-error {{initializer expects a single parameter of type '(Int, Int)'}} _ = InitLabeledTuple(x: (3, 4)) } do { let a = 3 let b = 4 let c = (a, b) _ = InitTwo(a, b) _ = InitTwo((a, b)) _ = InitTwo(c) // expected-error {{passing 2 arguments to a callee as a single tuple value has been removed in Swift 3}} _ = InitTuple(a, b) _ = InitTuple((a, b)) _ = InitTuple(c) } do { var a = 3 var b = 4 var c = (a, b) _ = InitTwo(a, b) _ = InitTwo((a, b)) // expected-error {{missing argument for parameter #2 in call}} _ = InitTwo(c) // expected-error {{missing argument for parameter #2 in call}} _ = InitTuple(a, b) // expected-error {{initializer expects a single parameter of type '(Int, Int)'}} {{17-17=(}} {{21-21=)}} _ = InitTuple((a, b)) _ = InitTuple(c) } struct SubscriptTwo { subscript(_ x: Int, _ y: Int) -> Int { get { return 0 } set { } } // expected-note 3 {{'subscript' declared here}} } struct SubscriptTuple { subscript(_ x: (Int, Int)) -> Int { get { return 0 } set { } } } struct SubscriptLabeledTuple { subscript(x x: (Int, Int)) -> Int { get { return 0 } set { } } } do { let s1 = SubscriptTwo() _ = s1[3, 4] _ = s1[(3, 4)] // expected-error {{missing argument for parameter #2 in call}} let s2 = SubscriptTuple() _ = s2[3, 4] // expected-error {{subscript expects a single parameter of type '(Int, Int)'}} {{10-10=(}} {{14-14=)}} _ = s2[(3, 4)] let s3 = SubscriptLabeledTuple() _ = s3[x: 3, 4] // expected-error {{subscript expects a single parameter of type '(Int, Int)'}} _ = s3[x: (3, 4)] } do { let a = 3 let b = 4 let d = (a, b) let s1 = SubscriptTwo() _ = s1[a, b] _ = s1[(a, b)] _ = s1[d] let s2 = SubscriptTuple() _ = s2[a, b] _ = s2[(a, b)] _ = s2[d] } do { // TODO: Restore regressed diagnostics rdar://problem/31724211 var a = 3 var b = 4 var d = (a, b) var s1 = SubscriptTwo() _ = s1[a, b] _ = s1[(a, b)] // expected-error {{missing argument for parameter #2 in call}} _ = s1[d] // expected-error {{missing argument for parameter #2 in call}} var s2 = SubscriptTuple() _ = s2[a, b] // expected-error {{subscript expects a single parameter of type '(Int, Int)'}} {{10-10=(}} {{14-14=)}} _ = s2[(a, b)] _ = s2[d] } enum Enum { case two(Int, Int) // expected-note 3 {{'two' declared here}} case tuple((Int, Int)) case labeledTuple(x: (Int, Int)) } do { _ = Enum.two(3, 4) _ = Enum.two((3, 4)) // expected-error {{missing argument for parameter #2 in call}} _ = Enum.tuple(3, 4) // expected-error {{enum element 'tuple' expects a single parameter of type '(Int, Int)'}} {{18-18=(}} {{22-22=)}} _ = Enum.tuple((3, 4)) _ = Enum.labeledTuple(x: 3, 4) // expected-error {{enum element 'labeledTuple' expects a single parameter of type '(Int, Int)'}} _ = Enum.labeledTuple(x: (3, 4)) } do { let a = 3 let b = 4 let c = (a, b) _ = Enum.two(a, b) _ = Enum.two((a, b)) _ = Enum.two(c) // expected-error {{passing 2 arguments to a callee as a single tuple value has been removed in Swift 3}} _ = Enum.tuple(a, b) _ = Enum.tuple((a, b)) _ = Enum.tuple(c) } do { var a = 3 var b = 4 var c = (a, b) _ = Enum.two(a, b) _ = Enum.two((a, b)) // expected-error {{missing argument for parameter #2 in call}} _ = Enum.two(c) // expected-error {{missing argument for parameter #2 in call}} _ = Enum.tuple(a, b) // expected-error {{enum element 'tuple' expects a single parameter of type '(Int, Int)'}} {{18-18=(}} {{22-22=)}} _ = Enum.tuple((a, b)) _ = Enum.tuple(c) } struct Generic<T> {} extension Generic { func generic(_ x: T) {} func genericLabeled(x: T) {} func genericTwo(_ x: T, _ y: T) {} // expected-note 2 {{'genericTwo' declared here}} func genericTuple(_ x: (T, T)) {} } do { let s = Generic<Double>() s.generic(3.0) s.generic((3.0)) s.genericLabeled(x: 3.0) s.genericLabeled(x: (3.0)) s.genericTwo(3.0, 4.0) s.genericTwo((3.0, 4.0)) // expected-error {{missing argument for parameter #2 in call}} s.genericTuple(3.0, 4.0) // expected-error {{instance method 'genericTuple' expects a single parameter of type '(Double, Double)'}} {{18-18=(}} {{26-26=)}} s.genericTuple((3.0, 4.0)) let sTwo = Generic<(Double, Double)>() sTwo.generic(3.0, 4.0) // expected-error {{instance method 'generic' expects a single parameter of type '(Double, Double)'}} {{16-16=(}} {{24-24=)}} sTwo.generic((3.0, 4.0)) sTwo.genericLabeled(x: 3.0, 4.0) // expected-error {{instance method 'genericLabeled' expects a single parameter of type '(Double, Double)'}} sTwo.genericLabeled(x: (3.0, 4.0)) } do { let s = Generic<Double>() let a = 3.0 let b = 4.0 let c = (3.0) let d = (a, b) s.generic(a) s.generic((a)) s.generic(c) s.genericTwo(a, b) s.genericTwo((a, b)) s.genericTuple(a, b) s.genericTuple((a, b)) let sTwo = Generic<(Double, Double)>() sTwo.generic(a, b) sTwo.generic((a, b)) sTwo.generic(d) } do { var s = Generic<Double>() var a = 3.0 var b = 4.0 var c = (3.0) var d = (a, b) s.generic(a) s.generic((a)) s.generic(c) s.genericTwo(a, b) s.genericTwo((a, b)) // expected-error {{missing argument for parameter #2 in call}} s.genericTuple(a, b) // expected-error {{instance method 'genericTuple' expects a single parameter of type '(Double, Double)'}} {{18-18=(}} {{22-22=)}} s.genericTuple((a, b)) var sTwo = Generic<(Double, Double)>() sTwo.generic(a, b) // expected-error {{instance method 'generic' expects a single parameter of type '(Double, Double)'}} {{16-16=(}} {{20-20=)}} sTwo.generic((a, b)) sTwo.generic(d) } extension Generic { mutating func mutatingGeneric(_ x: T) {} mutating func mutatingGenericLabeled(x: T) {} mutating func mutatingGenericTwo(_ x: T, _ y: T) {} // expected-note 2 {{'mutatingGenericTwo' declared here}} mutating func mutatingGenericTuple(_ x: (T, T)) {} } do { var s = Generic<Double>() s.mutatingGeneric(3.0) s.mutatingGeneric((3.0)) s.mutatingGenericLabeled(x: 3.0) s.mutatingGenericLabeled(x: (3.0)) s.mutatingGenericTwo(3.0, 4.0) s.mutatingGenericTwo((3.0, 4.0)) // expected-error {{missing argument for parameter #2 in call}} s.mutatingGenericTuple(3.0, 4.0) // expected-error {{instance method 'mutatingGenericTuple' expects a single parameter of type '(Double, Double)'}} {{26-26=(}} {{34-34=)}} s.mutatingGenericTuple((3.0, 4.0)) var sTwo = Generic<(Double, Double)>() sTwo.mutatingGeneric(3.0, 4.0) // expected-error {{instance method 'mutatingGeneric' expects a single parameter of type '(Double, Double)'}} {{24-24=(}} {{32-32=)}} sTwo.mutatingGeneric((3.0, 4.0)) sTwo.mutatingGenericLabeled(x: 3.0, 4.0) // expected-error {{instance method 'mutatingGenericLabeled' expects a single parameter of type '(Double, Double)'}} sTwo.mutatingGenericLabeled(x: (3.0, 4.0)) } do { var s = Generic<Double>() let a = 3.0 let b = 4.0 let c = (3.0) let d = (a, b) s.mutatingGeneric(a) s.mutatingGeneric((a)) s.mutatingGeneric(c) s.mutatingGenericTwo(a, b) s.mutatingGenericTwo((a, b)) s.mutatingGenericTuple(a, b) s.mutatingGenericTuple((a, b)) var sTwo = Generic<(Double, Double)>() sTwo.mutatingGeneric(a, b) sTwo.mutatingGeneric((a, b)) sTwo.mutatingGeneric(d) } do { var s = Generic<Double>() var a = 3.0 var b = 4.0 var c = (3.0) var d = (a, b) s.mutatingGeneric(a) s.mutatingGeneric((a)) s.mutatingGeneric(c) s.mutatingGenericTwo(a, b) s.mutatingGenericTwo((a, b)) // expected-error {{missing argument for parameter #2 in call}} s.mutatingGenericTuple(a, b) // expected-error {{instance method 'mutatingGenericTuple' expects a single parameter of type '(Double, Double)'}} {{26-26=(}} {{30-30=)}} s.mutatingGenericTuple((a, b)) var sTwo = Generic<(Double, Double)>() sTwo.mutatingGeneric(a, b) // expected-error {{instance method 'mutatingGeneric' expects a single parameter of type '(Double, Double)'}} {{24-24=(}} {{28-28=)}} sTwo.mutatingGeneric((a, b)) sTwo.mutatingGeneric(d) } extension Generic { var genericFunction: (T) -> () { return generic } var genericFunctionTwo: (T, T) -> () { return genericTwo } var genericFunctionTuple: ((T, T)) -> () { return genericTuple } } do { let s = Generic<Double>() s.genericFunction(3.0) s.genericFunction((3.0)) s.genericFunctionTwo(3.0, 4.0) s.genericFunctionTwo((3.0, 4.0)) // expected-error {{missing argument for parameter #2 in call}} s.genericFunctionTuple(3.0, 4.0) // expected-error {{single parameter of type '(Double, Double)' is expected in call}} {{26-26=(}} {{34-34=)}} s.genericFunctionTuple((3.0, 4.0)) let sTwo = Generic<(Double, Double)>() sTwo.genericFunction(3.0, 4.0) sTwo.genericFunction((3.0, 4.0)) // Does not diagnose in Swift 3 mode } do { let s = Generic<Double>() let a = 3.0 let b = 4.0 let c = (3.0) let d = (a, b) s.genericFunction(a) s.genericFunction((a)) s.genericFunction(c) s.genericFunctionTwo(a, b) s.genericFunctionTwo((a, b)) s.genericFunctionTuple(a, b) s.genericFunctionTuple((a, b)) let sTwo = Generic<(Double, Double)>() sTwo.genericFunction(a, b) sTwo.genericFunction((a, b)) sTwo.genericFunction(d) // Does not diagnose in Swift 3 mode } do { var s = Generic<Double>() var a = 3.0 var b = 4.0 var c = (3.0) var d = (a, b) s.genericFunction(a) s.genericFunction((a)) s.genericFunction(c) s.genericFunctionTwo(a, b) s.genericFunctionTwo((a, b)) // expected-error {{missing argument for parameter #2 in call}} s.genericFunctionTuple(a, b) // expected-error {{single parameter of type '(Double, Double)' is expected in call}} {{26-26=(}} {{30-30=)}} s.genericFunctionTuple((a, b)) var sTwo = Generic<(Double, Double)>() sTwo.genericFunction(a, b) sTwo.genericFunction((a, b)) // Does not diagnose in Swift 3 mode sTwo.genericFunction(d) // Does not diagnose in Swift 3 mode } struct GenericInit<T> { // expected-note 2 {{'T' declared as parameter to type 'GenericInit'}} init(_ x: T) {} } struct GenericInitLabeled<T> { init(x: T) {} } struct GenericInitTwo<T> { init(_ x: T, _ y: T) {} // expected-note 8 {{'init' declared here}} } struct GenericInitTuple<T> { init(_ x: (T, T)) {} } struct GenericInitLabeledTuple<T> { init(x: (T, T)) {} } do { _ = GenericInit(3, 4) _ = GenericInit((3, 4)) _ = GenericInitLabeled(x: 3, 4) // expected-error {{extra argument in call}} _ = GenericInitLabeled(x: (3, 4)) _ = GenericInitTwo(3, 4) _ = GenericInitTwo((3, 4)) // expected-error {{missing argument for parameter #2 in call}} _ = GenericInitTuple(3, 4) // expected-error {{initializer expects a single parameter of type '(T, T)'}} {{24-24=(}} {{28-28=)}} _ = GenericInitTuple((3, 4)) _ = GenericInitLabeledTuple(x: 3, 4) // expected-error {{initializer expects a single parameter of type '(T, T)'}} _ = GenericInitLabeledTuple(x: (3, 4)) } do { _ = GenericInit<(Int, Int)>(3, 4) _ = GenericInit<(Int, Int)>((3, 4)) // expected-error {{expression type 'GenericInit<(Int, Int)>' is ambiguous without more context}} _ = GenericInitLabeled<(Int, Int)>(x: 3, 4) // expected-error {{extra argument in call}} _ = GenericInitLabeled<(Int, Int)>(x: (3, 4)) _ = GenericInitTwo<Int>(3, 4) _ = GenericInitTwo<Int>((3, 4)) // expected-error {{missing argument for parameter #2 in call}} _ = GenericInitTuple<Int>(3, 4) // expected-error {{initializer expects a single parameter of type '(T, T)'}} {{29-29=(}} {{33-33=)}} _ = GenericInitTuple<Int>((3, 4)) _ = GenericInitLabeledTuple<Int>(x: 3, 4) // expected-error {{initializer expects a single parameter of type '(T, T)'}} _ = GenericInitLabeledTuple<Int>(x: (3, 4)) } do { let a = 3 let b = 4 let c = (a, b) _ = GenericInit(a, b) _ = GenericInit((a, b)) _ = GenericInit(c) _ = GenericInitTwo(a, b) _ = GenericInitTwo((a, b)) // expected-error {{missing argument for parameter #2 in call}} _ = GenericInitTwo(c) // expected-error {{missing argument for parameter #2 in call}} _ = GenericInitTuple(a, b) // expected-error {{initializer expects a single parameter of type '(T, T)'}} {{24-24=(}} {{28-28=)}} _ = GenericInitTuple((a, b)) _ = GenericInitTuple(c) } do { let a = 3 let b = 4 let c = (a, b) _ = GenericInit<(Int, Int)>(a, b) _ = GenericInit<(Int, Int)>((a, b)) _ = GenericInit<(Int, Int)>(c) _ = GenericInitTwo<Int>(a, b) _ = GenericInitTwo<Int>((a, b)) // Does not diagnose in Swift 3 mode _ = GenericInitTwo<Int>(c) // expected-error {{passing 2 arguments to a callee as a single tuple value has been removed in Swift 3}} _ = GenericInitTuple<Int>(a, b) // Does not diagnose in Swift 3 mode _ = GenericInitTuple<Int>((a, b)) _ = GenericInitTuple<Int>(c) } do { var a = 3 var b = 4 var c = (a, b) _ = GenericInit(a, b) // expected-error {{extra argument in call}} _ = GenericInit((a, b)) // expected-error {{generic parameter 'T' could not be inferred}} // expected-note {{explicitly specify the generic arguments to fix this issue}} _ = GenericInit(c) // expected-error {{generic parameter 'T' could not be inferred}} // expected-note {{explicitly specify the generic arguments to fix this issue}} _ = GenericInitTwo(a, b) _ = GenericInitTwo((a, b)) // expected-error {{missing argument for parameter #2 in call}} _ = GenericInitTwo(c) // expected-error {{missing argument for parameter #2 in call}} _ = GenericInitTuple(a, b) // expected-error {{initializer expects a single parameter of type '(T, T)'}} {{24-24=(}} {{28-28=)}} _ = GenericInitTuple((a, b)) _ = GenericInitTuple(c) } do { var a = 3 var b = 4 var c = (a, b) // _ = GenericInit<(Int, Int)>(a, b) // Crashes in Swift 3 _ = GenericInit<(Int, Int)>((a, b)) // expected-error {{expression type 'GenericInit<(Int, Int)>' is ambiguous without more context}} _ = GenericInit<(Int, Int)>(c) // expected-error {{expression type 'GenericInit<(Int, Int)>' is ambiguous without more context}} _ = GenericInitTwo<Int>(a, b) _ = GenericInitTwo<Int>((a, b)) // expected-error {{missing argument for parameter #2 in call}} _ = GenericInitTwo<Int>(c) // expected-error {{missing argument for parameter #2 in call}} _ = GenericInitTuple<Int>(a, b) // expected-error {{initializer expects a single parameter of type '(T, T)'}} {{29-29=(}} {{33-33=)}} _ = GenericInitTuple<Int>((a, b)) _ = GenericInitTuple<Int>(c) } struct GenericSubscript<T> { // TODO: Restore regressed diagnostics rdar://problem/31724211 subscript(_ x: T) -> Int { get { return 0 } set { } } // expected-note* {{}} } struct GenericSubscriptLabeled<T> { subscript(x x: T) -> Int { get { return 0 } set { } } } struct GenericSubscriptTwo<T> { subscript(_ x: T, _ y: T) -> Int { get { return 0 } set { } } // expected-note 3 {{'subscript' declared here}} } struct GenericSubscriptTuple<T> { subscript(_ x: (T, T)) -> Int { get { return 0 } set { } } } struct GenericSubscriptLabeledTuple<T> { subscript(x x: (T, T)) -> Int { get { return 0 } set { } } } do { let s1 = GenericSubscript<(Double, Double)>() _ = s1[3.0, 4.0] // TODO: Restore regressed diagnostics rdar://problem/31724211 _ = s1[(3.0, 4.0)] // expected-error {{}} let s1a = GenericSubscriptLabeled<(Double, Double)>() _ = s1a [x: 3.0, 4.0] // expected-error {{extra argument in call}} _ = s1a [x: (3.0, 4.0)] let s2 = GenericSubscriptTwo<Double>() _ = s2[3.0, 4.0] _ = s2[(3.0, 4.0)] // expected-error {{missing argument for parameter #2 in call}} let s3 = GenericSubscriptTuple<Double>() _ = s3[3.0, 4.0] // expected-error {{subscript expects a single parameter of type '(T, T)'}} {{10-10=(}} {{18-18=)}} _ = s3[(3.0, 4.0)] let s3a = GenericSubscriptLabeledTuple<Double>() _ = s3a[x: 3.0, 4.0] // expected-error {{subscript expects a single parameter of type '(T, T)'}} _ = s3a[x: (3.0, 4.0)] } do { let a = 3.0 let b = 4.0 let d = (a, b) let s1 = GenericSubscript<(Double, Double)>() _ = s1[a, b] _ = s1[(a, b)] _ = s1[d] let s2 = GenericSubscriptTwo<Double>() _ = s2[a, b] _ = s2[(a, b)] // Does not diagnose in Swift 3 mode _ = s2[d] // Does not diagnose in Swift 3 mode let s3 = GenericSubscriptTuple<Double>() _ = s3[a, b] // Does not diagnose in Swift 3 mode _ = s3[(a, b)] _ = s3[d] } do { // TODO: Restore regressed diagnostics rdar://problem/31724211 var a = 3.0 var b = 4.0 var d = (a, b) var s1 = GenericSubscript<(Double, Double)>() _ = s1[a, b] // TODO: Restore regressed diagnostics rdar://problem/31724211 // These two lines give different regressed behavior in S3 and S4 mode // _ = s1[(a, b)] // e/xpected-error {{expression type '@lvalue Int' is ambiguous without more context}} // _ = s1[d] // e/xpected-error {{expression type '@lvalue Int' is ambiguous without more context}} var s2 = GenericSubscriptTwo<Double>() _ = s2[a, b] _ = s2[(a, b)] // expected-error {{missing argument for parameter #2 in call}} _ = s2[d] // expected-error {{missing argument for parameter #2 in call}} var s3 = GenericSubscriptTuple<Double>() _ = s3[a, b] // expected-error {{subscript expects a single parameter of type '(T, T)'}} {{10-10=(}} {{14-14=)}} _ = s3[(a, b)] _ = s3[d] } enum GenericEnum<T> { case one(T) case labeled(x: T) case two(T, T) // expected-note 8 {{'two' declared here}} case tuple((T, T)) } do { _ = GenericEnum.one(3, 4) _ = GenericEnum.one((3, 4)) _ = GenericEnum.labeled(x: 3, 4) // expected-error {{extra argument in call}} _ = GenericEnum.labeled(x: (3, 4)) _ = GenericEnum.labeled(3, 4) // expected-error {{extra argument in call}} _ = GenericEnum.labeled((3, 4)) // expected-error {{missing argument label 'x:' in call}} _ = GenericEnum.two(3, 4) _ = GenericEnum.two((3, 4)) // expected-error {{missing argument for parameter #2 in call}} _ = GenericEnum.tuple(3, 4) // expected-error {{enum element 'tuple' expects a single parameter of type '(T, T)'}} {{25-25=(}} {{29-29=)}} _ = GenericEnum.tuple((3, 4)) } do { _ = GenericEnum<(Int, Int)>.one(3, 4) _ = GenericEnum<(Int, Int)>.one((3, 4)) // Does not diagnose in Swift 3 mode _ = GenericEnum<(Int, Int)>.labeled(x: 3, 4) // expected-error {{enum element 'labeled' expects a single parameter of type '(Int, Int)'}} _ = GenericEnum<(Int, Int)>.labeled(x: (3, 4)) _ = GenericEnum<(Int, Int)>.labeled(3, 4) // expected-error {{enum element 'labeled' expects a single parameter of type '(Int, Int)'}} _ = GenericEnum<(Int, Int)>.labeled((3, 4)) // expected-error {{missing argument label 'x:' in call}} _ = GenericEnum<Int>.two(3, 4) _ = GenericEnum<Int>.two((3, 4)) // expected-error {{missing argument for parameter #2 in call}} _ = GenericEnum<Int>.tuple(3, 4) // expected-error {{enum element 'tuple' expects a single parameter of type '(Int, Int)'}} {{30-30=(}} {{34-34=)}} _ = GenericEnum<Int>.tuple((3, 4)) } do { let a = 3 let b = 4 let c = (a, b) _ = GenericEnum.one(a, b) _ = GenericEnum.one((a, b)) _ = GenericEnum.one(c) _ = GenericEnum.two(a, b) _ = GenericEnum.two((a, b)) // expected-error {{missing argument for parameter #2 in call}} _ = GenericEnum.two(c) // expected-error {{missing argument for parameter #2 in call}} _ = GenericEnum.tuple(a, b) // expected-error {{enum element 'tuple' expects a single parameter of type '(T, T)'}} {{25-25=(}} {{29-29=)}} _ = GenericEnum.tuple((a, b)) _ = GenericEnum.tuple(c) } do { let a = 3 let b = 4 let c = (a, b) _ = GenericEnum<(Int, Int)>.one(a, b) _ = GenericEnum<(Int, Int)>.one((a, b)) _ = GenericEnum<(Int, Int)>.one(c) _ = GenericEnum<Int>.two(a, b) _ = GenericEnum<Int>.two((a, b)) _ = GenericEnum<Int>.two(c) // expected-error {{passing 2 arguments to a callee as a single tuple value has been removed in Swift 3}} _ = GenericEnum<Int>.tuple(a, b) _ = GenericEnum<Int>.tuple((a, b)) _ = GenericEnum<Int>.tuple(c) } do { var a = 3 var b = 4 var c = (a, b) // _ = GenericEnum.one(a, b) // Crashes in actual Swift 3 _ = GenericEnum.one((a, b)) // Does not diagnose in Swift 3 mode _ = GenericEnum.one(c) // Does not diagnose in Swift 3 mode _ = GenericEnum.two(a, b) _ = GenericEnum.two((a, b)) // expected-error {{missing argument for parameter #2 in call}} _ = GenericEnum.two(c) // expected-error {{missing argument for parameter #2 in call}} _ = GenericEnum.tuple(a, b) // expected-error {{enum element 'tuple' expects a single parameter of type '(T, T)'}} {{25-25=(}} {{29-29=)}} _ = GenericEnum.tuple((a, b)) _ = GenericEnum.tuple(c) } do { var a = 3 var b = 4 var c = (a, b) // _ = GenericEnum<(Int, Int)>.one(a, b) // Crashes in actual Swift 3 _ = GenericEnum<(Int, Int)>.one((a, b)) // Does not diagnose in Swift 3 mode _ = GenericEnum<(Int, Int)>.one(c) // Does not diagnose in Swift 3 mode _ = GenericEnum<Int>.two(a, b) _ = GenericEnum<Int>.two((a, b)) // expected-error {{missing argument for parameter #2 in call}} _ = GenericEnum<Int>.two(c) // expected-error {{missing argument for parameter #2 in call}} _ = GenericEnum<Int>.tuple(a, b) // expected-error {{enum element 'tuple' expects a single parameter of type '(Int, Int)'}} {{30-30=(}} {{34-34=)}} _ = GenericEnum<Int>.tuple((a, b)) _ = GenericEnum<Int>.tuple(c) } protocol Protocol { associatedtype Element } extension Protocol { func requirement(_ x: Element) {} func requirementLabeled(x: Element) {} func requirementTwo(_ x: Element, _ y: Element) {} // expected-note 2 {{'requirementTwo' declared here}} func requirementTuple(_ x: (Element, Element)) {} } struct GenericConforms<T> : Protocol { typealias Element = T } do { let s = GenericConforms<Double>() s.requirement(3.0) s.requirement((3.0)) s.requirementLabeled(x: 3.0) s.requirementLabeled(x: (3.0)) s.requirementTwo(3.0, 4.0) s.requirementTwo((3.0, 4.0)) // expected-error {{missing argument for parameter #2 in call}} s.requirementTuple(3.0, 4.0) // expected-error {{instance method 'requirementTuple' expects a single parameter of type '(Double, Double)'}} {{22-22=(}} {{30-30=)}} s.requirementTuple((3.0, 4.0)) let sTwo = GenericConforms<(Double, Double)>() sTwo.requirement(3.0, 4.0) // expected-error {{instance method 'requirement' expects a single parameter of type '(Double, Double)'}} {{20-20=(}} {{28-28=)}} sTwo.requirement((3.0, 4.0)) sTwo.requirementLabeled(x: 3.0, 4.0) // expected-error {{instance method 'requirementLabeled' expects a single parameter of type '(Double, Double)'}} sTwo.requirementLabeled(x: (3.0, 4.0)) } do { let s = GenericConforms<Double>() let a = 3.0 let b = 4.0 let c = (3.0) let d = (a, b) s.requirement(a) s.requirement((a)) s.requirement(c) s.requirementTwo(a, b) s.requirementTwo((a, b)) // Does not diagnose in Swift 3 mode s.requirementTuple(a, b) // Does not diagnose in Swift 3 mode s.requirementTuple((a, b)) let sTwo = GenericConforms<(Double, Double)>() sTwo.requirement(a, b) sTwo.requirement((a, b)) sTwo.requirement(d) } do { var s = GenericConforms<Double>() var a = 3.0 var b = 4.0 var c = (3.0) var d = (a, b) s.requirement(a) s.requirement((a)) s.requirement(c) s.requirementTwo(a, b) s.requirementTwo((a, b)) // expected-error {{missing argument for parameter #2 in call}} s.requirementTuple(a, b) // expected-error {{instance method 'requirementTuple' expects a single parameter of type '(Double, Double)'}} {{22-22=(}} {{26-26=)}} s.requirementTuple((a, b)) var sTwo = GenericConforms<(Double, Double)>() sTwo.requirement(a, b) // expected-error {{instance method 'requirement' expects a single parameter of type '(Double, Double)'}} {{20-20=(}} {{24-24=)}} sTwo.requirement((a, b)) sTwo.requirement(d) } extension Protocol { func takesClosure(_ fn: (Element) -> ()) {} func takesClosureTwo(_ fn: (Element, Element) -> ()) {} func takesClosureTuple(_ fn: ((Element, Element)) -> ()) {} } do { let s = GenericConforms<Double>() s.takesClosure({ _ = $0 }) s.takesClosure({ x in }) s.takesClosure({ (x: Double) in }) s.takesClosureTwo({ _ = $0 }) s.takesClosureTwo({ x in }) s.takesClosureTwo({ (x: (Double, Double)) in }) s.takesClosureTwo({ _ = $0; _ = $1 }) s.takesClosureTwo({ (x, y) in }) s.takesClosureTwo({ (x: Double, y:Double) in }) s.takesClosureTuple({ _ = $0 }) s.takesClosureTuple({ x in }) s.takesClosureTuple({ (x: (Double, Double)) in }) s.takesClosureTuple({ _ = $0; _ = $1 }) s.takesClosureTuple({ (x, y) in }) s.takesClosureTuple({ (x: Double, y:Double) in }) let sTwo = GenericConforms<(Double, Double)>() sTwo.takesClosure({ _ = $0 }) sTwo.takesClosure({ x in }) sTwo.takesClosure({ (x: (Double, Double)) in }) sTwo.takesClosure({ _ = $0; _ = $1 }) sTwo.takesClosure({ (x, y) in }) sTwo.takesClosure({ (x: Double, y: Double) in }) } do { let _: ((Int, Int)) -> () = { _ = $0 } let _: ((Int, Int)) -> () = { _ = ($0.0, $0.1) } let _: ((Int, Int)) -> () = { t in _ = (t.0, t.1) } let _: ((Int, Int)) -> () = { _ = ($0, $1) } let _: ((Int, Int)) -> () = { t, u in _ = (t, u) } let _: (Int, Int) -> () = { _ = $0 } let _: (Int, Int) -> () = { _ = ($0.0, $0.1) } let _: (Int, Int) -> () = { t in _ = (t.0, t.1) } let _: (Int, Int) -> () = { _ = ($0, $1) } let _: (Int, Int) -> () = { t, u in _ = (t, u) } } // rdar://problem/28952837 - argument labels ignored when calling function // with single 'Any' parameter func takesAny(_: Any) {} enum HasAnyCase { case any(_: Any) } do { let fn: (Any) -> () = { _ in } fn(123) fn(data: 123) takesAny(123) takesAny(data: 123) _ = HasAnyCase.any(123) _ = HasAnyCase.any(data: 123) } // rdar://problem/29739905 - protocol extension methods on Array had // ParenType sugar stripped off the element type typealias BoolPair = (Bool, Bool) func processArrayOfFunctions(f1: [((Bool, Bool)) -> ()], f2: [(Bool, Bool) -> ()], c: Bool) { let p = (c, c) f1.forEach { block in block(p) block((c, c)) block(c, c) } f2.forEach { block in block(p) // expected-error {{passing 2 arguments to a callee as a single tuple value has been removed in Swift 3}} block((c, c)) block(c, c) } f2.forEach { (block: ((Bool, Bool)) -> ()) in block(p) block((c, c)) block(c, c) } f2.forEach { (block: (Bool, Bool) -> ()) in block(p) // expected-error {{passing 2 arguments to a callee as a single tuple value has been removed in Swift 3}} block((c, c)) block(c, c) } } // expected-error@+1 {{cannot create a single-element tuple with an element label}} func singleElementTupleArgument(completion: ((didAdjust: Bool)) -> Void) { // TODO: Error could be improved. // expected-error@+1 {{cannot convert value of type '(didAdjust: Bool)' to expected argument type 'Bool'}} completion((didAdjust: true)) } // SR-4378 -- FIXME -- this should type check, it used to work in Swift 3.0 final public class MutableProperty<Value> { public init(_ initialValue: Value) {} } enum DataSourcePage<T> { case notLoaded } let pages1: MutableProperty<(data: DataSourcePage<Int>, totalCount: Int)> = MutableProperty(( // expected-error@-1 {{expression type 'MutableProperty<(data: DataSourcePage<Int>, totalCount: Int)>' is ambiguous without more context}} data: .notLoaded, totalCount: 0 )) let pages2: MutableProperty<(data: DataSourcePage<Int>, totalCount: Int)> = MutableProperty(( // expected-error@-1 {{cannot convert value of type 'MutableProperty<(data: DataSourcePage<_>, totalCount: Int)>' to specified type 'MutableProperty<(data: DataSourcePage<Int>, totalCount: Int)>'}} data: DataSourcePage.notLoaded, totalCount: 0 )) let pages3: MutableProperty<(data: DataSourcePage<Int>, totalCount: Int)> = MutableProperty(( // expected-error@-1 {{expression type 'MutableProperty<(data: DataSourcePage<Int>, totalCount: Int)>' is ambiguous without more context}} data: DataSourcePage<Int>.notLoaded, totalCount: 0 )) // rdar://problem/32301091 - Make sure that in Swift 3 mode following expressions still compile just fine func rdar32301091_1(_ :((Int, Int) -> ())!) {} rdar32301091_1 { _ in } // Ok in Swift 3 func rdar32301091_2(_ :(Int, Int) -> ()) {} rdar32301091_2 { _ in } // Ok in Swift 3 // rdar://problem/35198459 - source-compat-suite failure: Moya (toType->hasUnresolvedType() && "Should have handled this above") do { func foo(_: (() -> Void)?) {} func bar() -> ((()) -> Void)? { return nil } foo(bar()) // OK in Swift 3 mode } // https://bugs.swift.org/browse/SR-6509 public extension Optional { public func apply<Result>(_ transform: ((Wrapped) -> Result)?) -> Result? { return self.flatMap { value in transform.map { $0(value) } } } public func apply<Value, Result>(_ value: Value?) -> Result? where Wrapped == (Value) -> Result { return value.apply(self) } } // https://bugs.swift.org/browse/SR-6837 do { func takeFn(fn: (_ i: Int, _ j: Int?) -> ()) {} func takePair(_ pair: (Int, Int?)) {} takeFn(fn: takePair) takeFn(fn: { (pair: (Int, Int?)) in } ) takeFn { (pair: (Int, Int?)) in } } // https://bugs.swift.org/browse/SR-6796 do { func f(a: (() -> Void)? = nil) {} func log<T>() -> ((T) -> Void)? { return nil } f(a: log() as ((()) -> Void)?) // Allow ((()) -> Void)? to be passed in place of (() -> Void)? func logNoOptional<T>() -> (T) -> Void { } f(a: logNoOptional() as ((()) -> Void)) // Also allow the optional-injected form. func g() {} g(()) func h(_: ()) {} h() }
apache-2.0
a0ca02628cf0782e12da1a049e89695a
27.91276
201
0.623846
3.261604
false
false
false
false
brianpartridge/Life
Life/Game+Sequence.swift
1
870
// // Game+Sequence.swift // Life // // Created by Brian Partridge on 10/27/15. // Copyright © 2015 PearTreeLabs. All rights reserved. // import Foundation extension Game: SequenceType { public typealias Generator = AnyGenerator<Generation> public func generate() -> Generator { var game = self var hasReturnedInitialValue = false return anyGenerator { if !hasReturnedInitialValue { hasReturnedInitialValue = true return game.currentGeneration } let previousBoard = game.currentGeneration.board game.tick() let generatedBoard = game.currentGeneration.board if previousBoard != generatedBoard { return game.currentGeneration } return nil } } }
mit
1d988c75bc44a930c8d6827e84a6d546
24.558824
61
0.581128
5.29878
false
false
false
false
WhisperSystems/Signal-iOS
SignalServiceKit/src/Storage/Jobs/OWSSessionResetJobRecord+SDS.swift
1
2980
// // Copyright (c) 2019 Open Whisper Systems. All rights reserved. // import Foundation import GRDB import SignalCoreKit // NOTE: This file is generated by /Scripts/sds_codegen/sds_generate.py. // Do not manually edit it, instead run `sds_codegen.sh`. // MARK: - Typed Convenience Methods @objc public extension OWSSessionResetJobRecord { // NOTE: This method will fail if the object has unexpected type. class func anyFetchSessionResetJobRecord(uniqueId: String, transaction: SDSAnyReadTransaction) -> OWSSessionResetJobRecord? { assert(uniqueId.count > 0) guard let object = anyFetch(uniqueId: uniqueId, transaction: transaction) else { return nil } guard let instance = object as? OWSSessionResetJobRecord else { owsFailDebug("Object has unexpected type: \(type(of: object))") return nil } return instance } // NOTE: This method will fail if the object has unexpected type. func anyUpdateSessionResetJobRecord(transaction: SDSAnyWriteTransaction, block: (OWSSessionResetJobRecord) -> Void) { anyUpdate(transaction: transaction) { (object) in guard let instance = object as? OWSSessionResetJobRecord else { owsFailDebug("Object has unexpected type: \(type(of: object))") return } block(instance) } } } // MARK: - SDSSerializer // The SDSSerializer protocol specifies how to insert and update the // row that corresponds to this model. class OWSSessionResetJobRecordSerializer: SDSSerializer { private let model: OWSSessionResetJobRecord public required init(model: OWSSessionResetJobRecord) { self.model = model } // MARK: - Record func asRecord() throws -> SDSRecord { let id: Int64? = model.sortId > 0 ? Int64(model.sortId) : nil let recordType: SDSRecordType = .sessionResetJobRecord let uniqueId: String = model.uniqueId // Base class properties let failureCount: UInt = model.failureCount let label: String = model.label let status: SSKJobRecordStatus = model.status // Subclass properties let attachmentIdMap: Data? = nil let contactThreadId: String? = model.contactThreadId let envelopeData: Data? = nil let invisibleMessage: Data? = nil let messageId: String? = nil let removeMessageAfterSending: Bool? = nil let threadId: String? = nil return JobRecordRecord(id: id, recordType: recordType, uniqueId: uniqueId, failureCount: failureCount, label: label, status: status, attachmentIdMap: attachmentIdMap, contactThreadId: contactThreadId, envelopeData: envelopeData, invisibleMessage: invisibleMessage, messageId: messageId, removeMessageAfterSending: removeMessageAfterSending, threadId: threadId) } }
gpl-3.0
3609ea68472bec3aa97cfd99599efe1b
36.721519
368
0.665772
5.016835
false
false
false
false
xedin/swift
test/SILGen/struct_resilience.swift
8
13523
// RUN: %empty-directory(%t) // RUN: %target-swift-frontend -emit-module -enable-library-evolution -emit-module-path=%t/resilient_struct.swiftmodule %S/../Inputs/resilient_struct.swift // RUN: %target-swift-emit-silgen -I %t -enable-library-evolution %s | %FileCheck %s import resilient_struct // Resilient structs from outside our resilience domain are always address-only // CHECK-LABEL: sil hidden [ossa] @$s17struct_resilience26functionWithResilientTypes_1f010resilient_A04SizeVAF_A2FXEtF : $@convention(thin) (@in_guaranteed Size, @noescape @callee_guaranteed (@in_guaranteed Size) -> @out Size) -> @out Size // CHECK: bb0(%0 : $*Size, %1 : $*Size, %2 : $@noescape @callee_guaranteed (@in_guaranteed Size) -> @out Size): func functionWithResilientTypes(_ s: Size, f: (Size) -> Size) -> Size { // Stored properties of resilient structs from outside our resilience // domain are accessed through accessors // CHECK: copy_addr %1 to [initialization] [[OTHER_SIZE_BOX:%[0-9]*]] : $*Size var s2 = s // CHECK: copy_addr %1 to [initialization] [[SIZE_BOX:%.*]] : $*Size // CHECK: [[GETTER:%.*]] = function_ref @$s16resilient_struct4SizeV1wSivg : $@convention(method) (@in_guaranteed Size) -> Int // CHECK: [[RESULT:%.*]] = apply [[GETTER]]([[SIZE_BOX]]) // CHECK: [[WRITE:%.*]] = begin_access [modify] [unknown] [[OTHER_SIZE_BOX]] : $*Size // CHECK: [[SETTER:%.*]] = function_ref @$s16resilient_struct4SizeV1wSivs : $@convention(method) (Int, @inout Size) -> () // CHECK: apply [[SETTER]]([[RESULT]], [[WRITE]]) s2.w = s.w // CHECK: copy_addr %1 to [initialization] [[SIZE_BOX:%.*]] : $*Size // CHECK: [[FN:%.*]] = function_ref @$s16resilient_struct4SizeV1hSivg : $@convention(method) (@in_guaranteed Size) -> Int // CHECK: [[RESULT:%.*]] = apply [[FN]]([[SIZE_BOX]]) _ = s.h // CHECK: apply %2(%0, %1) // CHECK-NOT: destroy_value %2 // CHECK: return return f(s) } // Use modify for inout access of properties in resilient structs // from a different resilience domain public func inoutFunc(_ x: inout Int) {} // CHECK-LABEL: sil hidden [ossa] @$s17struct_resilience18resilientInOutTestyy0c1_A04SizeVzF : $@convention(thin) (@inout Size) -> () func resilientInOutTest(_ s: inout Size) { // CHECK: function_ref @$s16resilient_struct4SizeV1wSivM // CHECK: function_ref @$s17struct_resilience9inoutFuncyySizF inoutFunc(&s.w) // CHECK: return } // Fixed-layout structs may be trivial or loadable // CHECK-LABEL: sil hidden [ossa] @$s17struct_resilience28functionWithFixedLayoutTypes_1f010resilient_A05PointVAF_A2FXEtF : $@convention(thin) (Point, @noescape @callee_guaranteed (Point) -> Point) -> Point // CHECK: bb0(%0 : $Point, %1 : $@noescape @callee_guaranteed (Point) -> Point): func functionWithFixedLayoutTypes(_ p: Point, f: (Point) -> Point) -> Point { // Stored properties of fixed layout structs are accessed directly var p2 = p // CHECK: [[RESULT:%.*]] = struct_extract %0 : $Point, #Point.x // CHECK: [[DEST:%.*]] = struct_element_addr [[POINT_BOX:%[0-9]*]] : $*Point, #Point.x // CHECK: assign [[RESULT]] to [[DEST]] : $*Int p2.x = p.x // CHECK: [[RESULT:%.*]] = struct_extract %0 : $Point, #Point.y _ = p.y // CHECK: [[NEW_POINT:%.*]] = apply %1(%0) // CHECK: return [[NEW_POINT]] return f(p) } // Fixed-layout struct with resilient stored properties is still address-only // CHECK-LABEL: sil hidden [ossa] @$s17struct_resilience39functionWithFixedLayoutOfResilientTypes_1f010resilient_A09RectangleVAF_A2FXEtF : $@convention(thin) (@in_guaranteed Rectangle, @noescape @callee_guaranteed (@in_guaranteed Rectangle) -> @out Rectangle) -> @out Rectangle // CHECK: bb0(%0 : $*Rectangle, %1 : $*Rectangle, %2 : $@noescape @callee_guaranteed (@in_guaranteed Rectangle) -> @out Rectangle): func functionWithFixedLayoutOfResilientTypes(_ r: Rectangle, f: (Rectangle) -> Rectangle) -> Rectangle { return f(r) } // Make sure we generate getters and setters for stored properties of // resilient structs public struct MySize { // Static computed property // CHECK-LABEL: sil [ossa] @$s17struct_resilience6MySizeV10expirationSivgZ : $@convention(method) (@thin MySize.Type) -> Int // CHECK-LABEL: sil [ossa] @$s17struct_resilience6MySizeV10expirationSivsZ : $@convention(method) (Int, @thin MySize.Type) -> () // CHECK-LABEL: sil [ossa] @$s17struct_resilience6MySizeV10expirationSivMZ : $@yield_once @convention(method) (@thin MySize.Type) -> @yields @inout Int public static var expiration: Int { get { return copyright + 70 } set { copyright = newValue - 70 } } // Instance computed property // CHECK-LABEL: sil [ossa] @$s17struct_resilience6MySizeV1dSivg : $@convention(method) (@in_guaranteed MySize) -> Int // CHECK-LABEL: sil [ossa] @$s17struct_resilience6MySizeV1dSivs : $@convention(method) (Int, @inout MySize) -> () // CHECK-LABEL: sil [ossa] @$s17struct_resilience6MySizeV1dSivM : $@yield_once @convention(method) (@inout MySize) -> @yields @inout Int public var d: Int { get { return 0 } set { } } // Instance stored property // CHECK-LABEL: sil [ossa] @$s17struct_resilience6MySizeV1wSivg : $@convention(method) (@in_guaranteed MySize) -> Int // CHECK-LABEL: sil [ossa] @$s17struct_resilience6MySizeV1wSivs : $@convention(method) (Int, @inout MySize) -> () // CHECK-LABEL: sil [ossa] @$s17struct_resilience6MySizeV1wSivM : $@yield_once @convention(method) (@inout MySize) -> @yields @inout Int public var w: Int // Read-only instance stored property // CHECK-LABEL: sil [ossa] @$s17struct_resilience6MySizeV1hSivg : $@convention(method) (@in_guaranteed MySize) -> Int public let h: Int // Weak property // CHECK-LABEL: sil [ossa] @$s17struct_resilience6MySizeV1iyXlSgvg : $@convention(method) (@in_guaranteed MySize) -> @owned Optional<AnyObject> public weak var i: AnyObject? // Static stored property // CHECK-LABEL: sil [ossa] @$s17struct_resilience6MySizeV9copyrightSivgZ : $@convention(method) (@thin MySize.Type) -> Int // CHECK-LABEL: sil [ossa] @$s17struct_resilience6MySizeV9copyrightSivsZ : $@convention(method) (Int, @thin MySize.Type) -> () // CHECK-LABEL: sil [ossa] @$s17struct_resilience6MySizeV9copyrightSivMZ : $@yield_once @convention(method) (@thin MySize.Type) -> @yields @inout Int public static var copyright: Int = 0 } // CHECK-LABEL: sil [ossa] @$s17struct_resilience28functionWithMyResilientTypes_1fAA0E4SizeVAE_A2EXEtF : $@convention(thin) (@in_guaranteed MySize, @noescape @callee_guaranteed (@in_guaranteed MySize) -> @out MySize) -> @out MySize public func functionWithMyResilientTypes(_ s: MySize, f: (MySize) -> MySize) -> MySize { // Stored properties of resilient structs from inside our resilience // domain are accessed directly // CHECK: copy_addr %1 to [initialization] [[SIZE_BOX:%[0-9]*]] : $*MySize var s2 = s // CHECK: [[SRC_ADDR:%.*]] = struct_element_addr %1 : $*MySize, #MySize.w // CHECK: [[SRC:%.*]] = load [trivial] [[SRC_ADDR]] : $*Int // CHECK: [[WRITE:%.*]] = begin_access [modify] [unknown] [[SIZE_BOX]] : $*MySize // CHECK: [[DEST_ADDR:%.*]] = struct_element_addr [[WRITE]] : $*MySize, #MySize.w // CHECK: assign [[SRC]] to [[DEST_ADDR]] : $*Int s2.w = s.w // CHECK: [[RESULT_ADDR:%.*]] = struct_element_addr %1 : $*MySize, #MySize.h // CHECK: [[RESULT:%.*]] = load [trivial] [[RESULT_ADDR]] : $*Int _ = s.h // CHECK: apply %2(%0, %1) // CHECK-NOT: destroy_value %2 // CHECK: return return f(s) } // CHECK-LABEL: sil [transparent] [serialized] [ossa] @$s17struct_resilience25publicTransparentFunctionySiAA6MySizeVF : $@convention(thin) (@in_guaranteed MySize) -> Int @_transparent public func publicTransparentFunction(_ s: MySize) -> Int { // Since the body of a public transparent function might be inlined into // other resilience domains, we have to use accessors // CHECK: [[SELF:%.*]] = alloc_stack $MySize // CHECK-NEXT: copy_addr %0 to [initialization] [[SELF]] // CHECK: [[GETTER:%.*]] = function_ref @$s17struct_resilience6MySizeV1wSivg // CHECK-NEXT: [[RESULT:%.*]] = apply [[GETTER]]([[SELF]]) // CHECK-NEXT: destroy_addr [[SELF]] // CHECK-NEXT: dealloc_stack [[SELF]] // CHECK-NEXT: return [[RESULT]] return s.w } // CHECK-LABEL: sil [transparent] [serialized] [ossa] @$s17struct_resilience30publicTransparentLocalFunctionySiycAA6MySizeVF : $@convention(thin) (@in_guaranteed MySize) -> @owned @callee_guaranteed () -> Int @_transparent public func publicTransparentLocalFunction(_ s: MySize) -> () -> Int { // CHECK-LABEL: sil shared [serialized] [ossa] @$s17struct_resilience30publicTransparentLocalFunctionySiycAA6MySizeVFSiycfU_ : $@convention(thin) (@guaranteed { var MySize }) -> Int // CHECK: function_ref @$s17struct_resilience6MySizeV1wSivg : $@convention(method) (@in_guaranteed MySize) -> Int // CHECK: return {{.*}} : $Int return { s.w } } // CHECK-LABEL: sil hidden [transparent] [ossa] @$s17struct_resilience27internalTransparentFunctionySiAA6MySizeVF : $@convention(thin) (@in_guaranteed MySize) -> Int // CHECK: bb0([[ARG:%.*]] : $*MySize): @_transparent func internalTransparentFunction(_ s: MySize) -> Int { // The body of an internal transparent function will not be inlined into // other resilience domains, so we can access storage directly // CHECK: [[W_ADDR:%.*]] = struct_element_addr [[ARG]] : $*MySize, #MySize.w // CHECK-NEXT: [[RESULT:%.*]] = load [trivial] [[W_ADDR]] : $*Int // CHECK-NEXT: return [[RESULT]] return s.w } // CHECK-LABEL: sil [serialized] [ossa] @$s17struct_resilience23publicInlinableFunctionySiAA6MySizeVF : $@convention(thin) (@in_guaranteed MySize) -> Int @inlinable public func publicInlinableFunction(_ s: MySize) -> Int { // Since the body of a public transparent function might be inlined into // other resilience domains, we have to use accessors // CHECK: [[SELF:%.*]] = alloc_stack $MySize // CHECK-NEXT: copy_addr %0 to [initialization] [[SELF]] // CHECK: [[GETTER:%.*]] = function_ref @$s17struct_resilience6MySizeV1wSivg // CHECK-NEXT: [[RESULT:%.*]] = apply [[GETTER]]([[SELF]]) // CHECK-NEXT: destroy_addr [[SELF]] // CHECK-NEXT: dealloc_stack [[SELF]] // CHECK-NEXT: return [[RESULT]] return s.w } // Make sure that @usableFromInline entities can be resilient @usableFromInline struct VersionedResilientStruct { @usableFromInline let x: Int @usableFromInline let y: Int @usableFromInline init(x: Int, y: Int) { self.x = x self.y = y } // Non-inlinable initializer, assigns to self -- treated as a root initializer // CHECK-LABEL: sil [ossa] @$s17struct_resilience24VersionedResilientStructV5otherA2C_tcfC : $@convention(method) (@in VersionedResilientStruct, @thin VersionedResilientStruct.Type) -> @out VersionedResilientStruct // CHECK: [[SELF_BOX:%.*]] = alloc_box ${ var VersionedResilientStruct } // CHECK-NEXT: [[SELF_UNINIT:%.*]] = mark_uninitialized [rootself] [[SELF_BOX]] // CHECK: return @usableFromInline init(other: VersionedResilientStruct) { self = other } // Inlinable initializer, assigns to self -- treated as a delegating initializer // CHECK-LABEL: sil [serialized] [ossa] @$s17struct_resilience24VersionedResilientStructV6other2A2C_tcfC : $@convention(method) (@in VersionedResilientStruct, @thin VersionedResilientStruct.Type) -> @out VersionedResilientStruct // CHECK: [[SELF_BOX:%.*]] = alloc_box ${ var VersionedResilientStruct } // CHECK-NEXT: [[SELF_UNINIT:%.*]] = mark_uninitialized [delegatingself] [[SELF_BOX]] // CHECK: return @usableFromInline @inlinable init(other2: VersionedResilientStruct) { self = other2 } } // CHECK-LABEL: sil [transparent] [serialized] [ossa] @$s17struct_resilience27useVersionedResilientStructyAA0deF0VADF : $@convention(thin) (@in_guaranteed VersionedResilientStruct) -> @out VersionedResilientStruct @usableFromInline @_transparent func useVersionedResilientStruct(_ s: VersionedResilientStruct) -> VersionedResilientStruct { // CHECK: function_ref @$s17struct_resilience24VersionedResilientStructV1ySivg // CHECK: function_ref @$s17struct_resilience24VersionedResilientStructV1xSivg // CHECK: function_ref @$s17struct_resilience24VersionedResilientStructV1x1yACSi_SitcfC return VersionedResilientStruct(x: s.y, y: s.x) // CHECK: return } // CHECK-LABEL: sil [serialized] [ossa] @$s17struct_resilience18inlinableInoutTestyyAA6MySizeVzF : $@convention(thin) (@inout MySize) -> () @inlinable public func inlinableInoutTest(_ s: inout MySize) { // Inlinable functions can be inlined in other resiliene domains. // // Make sure we use modify for an inout access of a resilient struct // property inside an inlinable function. // CHECK: function_ref @$s17struct_resilience6MySizeV1wSivM inoutFunc(&s.w) // CHECK: return } // Initializers for resilient structs extension Size { // CHECK-LABEL: sil hidden [ossa] @$s16resilient_struct4SizeV0B11_resilienceE5otherA2C_tcfC : $@convention(method) (@in Size, @thin Size.Type) -> @out Size // CHECK: [[SELF_BOX:%.*]] = alloc_box ${ var Size } // CHECK-NEXT: [[SELF_UNINIT:%.*]] = mark_uninitialized [delegatingself] [[SELF_BOX]] : ${ var Size } // CHECK: return init(other: Size) { self = other } }
apache-2.0
14efcc6ef3df937151d6b7300111fb07
45.954861
277
0.679213
3.637171
false
false
false
false
zpz1237/NirBillBoard
NirBillboard/OnboardingContentViewController.swift
1
5571
// // OnboardingContentViewController.swift // OnboardSwift // // Created by Mike on 9/11/14. // Copyright (c) 2014 Mike Amaral. All rights reserved. // import UIKit class OnboardingContentViewController: UIViewController { let kDefaultOnboardingFont: String = "Helvetica-Light" let kDefaultTextColor: UIColor = UIColor.whiteColor() let kContentWidthMultiplier: CGFloat = 0.9 let kDefaultImageViewSize: CGFloat = 100 let kDefaultTopPadding: CGFloat = 60 let kDefaultUnderIconPadding: CGFloat = 30 let kDefaultUnderTitlePadding: CGFloat = 30 let kDefaultBottomPadding: CGFloat = 0; let kDefaultTitleFontSize: CGFloat = 38 let kDefaultBodyFontSize: CGFloat = 28 let kDefaultActionButtonHeight: CGFloat = 50 let kDefaultMainPageControlHeight: CGFloat = 35 let titleText: String let body: String let image: UIImage let buttonText: String let action: dispatch_block_t? var iconSize: CGFloat var fontName: String var titleFontSize: CGFloat var bodyFontSize: CGFloat var topPadding: CGFloat var underIconPadding: CGFloat var underTitlePadding: CGFloat var bottomPadding: CGFloat var titleTextColor: UIColor var bodyTextColor: UIColor var buttonTextColor: UIColor init(title: String?, body: String?, image: UIImage?, buttonText: String?, action: dispatch_block_t?) { // setup the optional initializer parameters if they were passed in or not self.titleText = title != nil ? title! : String() self.body = body != nil ? body! : String() self.image = image != nil ? image! : UIImage() self.buttonText = buttonText != nil ? buttonText! : String() self.action = action != nil ? action : {} // setup the initial default properties self.iconSize = kDefaultImageViewSize; self.fontName = kDefaultOnboardingFont; self.titleFontSize = kDefaultTitleFontSize; self.bodyFontSize = kDefaultBodyFontSize; self.topPadding = kDefaultTopPadding; self.underIconPadding = kDefaultUnderIconPadding; self.underTitlePadding = kDefaultUnderTitlePadding; self.bottomPadding = kDefaultBottomPadding; self.titleTextColor = kDefaultTextColor; self.bodyTextColor = kDefaultTextColor; self.buttonTextColor = kDefaultTextColor; super.init(nibName: nil, bundle: nil) } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() generateView() } func generateView() { // the background of each content page will be clear to be able to // see through to the background image of the master view controller self.view.backgroundColor = UIColor.clearColor() // do some calculation for some values we'll need to reuse, namely the width of the view, // the center of the width, and the content width we want to fill up, which is some // fraction of the view width we set in the multipler constant let viewWidth: CGFloat = CGRectGetWidth(self.view.frame) let horizontalCenter: CGFloat = viewWidth / 2 let contentWidth: CGFloat = viewWidth * kContentWidthMultiplier // create the image view with the appropriate image, size, and center in on screen var imageView: UIImageView = UIImageView(image: self.image) imageView.frame = CGRectMake(horizontalCenter - (self.iconSize / 2), self.topPadding, self.iconSize, self.iconSize) self.view.addSubview(imageView) var titleLabel: UILabel = UILabel(frame: CGRectMake(0, CGRectGetMaxY(imageView.frame) + self.underIconPadding, contentWidth, 0)) titleLabel.text = self.titleText titleLabel.font = UIFont(name: self.fontName, size: self.titleFontSize) titleLabel.textColor = self.titleTextColor titleLabel.numberOfLines = 0 titleLabel.textAlignment = .Center titleLabel.sizeToFit() titleLabel.center = CGPointMake(horizontalCenter, titleLabel.center.y) self.view.addSubview(titleLabel) var bodyLabel: UILabel = UILabel(frame: CGRectMake(0, CGRectGetMaxY(titleLabel.frame) + self.underTitlePadding, contentWidth, 0)) bodyLabel.text = self.body bodyLabel.font = UIFont(name: self.fontName, size: self.bodyFontSize) bodyLabel.textColor = self.titleTextColor bodyLabel.numberOfLines = 0 bodyLabel.textAlignment = .Center bodyLabel.sizeToFit() bodyLabel.center = CGPointMake(horizontalCenter, bodyLabel.center.y) self.view.addSubview(bodyLabel) if ( NSString(string: self.buttonText).length != 0) { var actionButton: UIButton = UIButton(frame: CGRectMake((CGRectGetMaxX(self.view.frame) / 2) - (contentWidth / 2), CGRectGetMaxY(self.view.frame) - kDefaultMainPageControlHeight - kDefaultActionButtonHeight - self.bottomPadding, contentWidth, kDefaultActionButtonHeight)) actionButton.titleLabel?.font = UIFont .systemFontOfSize(24) actionButton.setTitle(self.buttonText, forState: .Normal) actionButton.setTitleColor(self.buttonTextColor, forState: .Normal) actionButton.addTarget(self, action: "handleButtonPressed", forControlEvents: .TouchUpInside) self.view.addSubview(actionButton) } } func handleButtonPressed() { self.action!() } }
mit
ac89618433318a56458e3efcd1b7a10b
42.523438
283
0.689104
4.934455
false
false
false
false
XWJACK/Music
Music/Universal/ViewControllers/MusicTableViewController.swift
1
2292
// // MusicTableViewController.swift // Music // // Created by Jack on 5/4/17. // Copyright © 2017 Jack. All rights reserved. // import UIKit class MusicTableViewController: MusicViewController, UITableViewDataSource, UITableViewDelegate { let backgroundImageView = UIImageView(image: #imageLiteral(resourceName: "background_default_dark-ip5")) var effectView: UIVisualEffectView? let tableView = UITableView(frame: .zero, style: .grouped) override func viewDidLoad() { view.addSubview(backgroundImageView) effectView = view.addBlurEffect(style: .light) view.addSubview(tableView) effectView?.alpha = 0.6 tableView.dataSource = self tableView.delegate = self tableView.backgroundColor = .clear tableView.separatorStyle = .none backgroundImageView.snp.makeConstraints { (make) in make.edges.equalToSuperview() } effectView?.snp.makeConstraints { (make) in make.width.height.equalTo(backgroundImageView) } tableView.snp.makeConstraints { (make) in make.top.equalToSuperview().offset(64) make.left.right.equalToSuperview() make.bottom.equalTo(bottomLayoutGuide.snp.top) } super.viewDidLoad() } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 44 } func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 0 } func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return .leastNonzeroMagnitude } func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { return .leastNonzeroMagnitude } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { return MusicTableViewCell() } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) } }
mit
d4a32e7518e97fdf372d225ead82a153
30.383562
108
0.650371
5.390588
false
false
false
false
teambition/GrowingTextView
GrowingTextViewExample/LeftMessageCell.swift
1
1587
// // LeftMessageCell.swift // GrowingTextViewExample // // Created by 洪鑫 on 16/2/17. // Copyright © 2016年 Teambition. All rights reserved. // import UIKit let kLeftMessageCellID = "LeftMessageCell" private let leftPadding: CGFloat = 20 private let rightPadding: CGFloat = UIScreen.main.bounds.width / 4 class LeftMessageCell: UITableViewCell { @IBOutlet weak var contentLabel: MessageLabel! @IBOutlet weak var contentLabelTrainingSpace: NSLayoutConstraint! override func awakeFromNib() { super.awakeFromNib() contentLabel.layer.masksToBounds = true contentLabel.layer.cornerRadius = 6 } class func rowHeight(for message: String) -> CGFloat { return contentLabelFrame(for: message).height + 15 } class func trainingSpace(for message: String) -> CGFloat { return UIScreen.main.bounds.width - leftPadding - contentLabelFrame(for: message).width } fileprivate class func contentLabelFrame(for message: String) -> CGRect { guard !message.isEmpty else { return .zero } let messageString = message as NSString let size = CGSize(width: UIScreen.main.bounds.width - leftPadding - rightPadding, height: CGFloat.greatestFiniteMagnitude) let frame = messageString.boundingRect(with: size, options: .usesLineFragmentOrigin, attributes: [.font: UIFont.systemFont(ofSize: 16)], context: nil) return CGRect(x: ceil(frame.origin.x), y: ceil(frame.origin.y), width: ceil(frame.width) + kMessageLabelPadding * 2.0, height: ceil(frame.height)) } }
mit
1965162aa630b222e9097db34e5a8a14
36.619048
158
0.707595
4.42577
false
false
false
false
viWiD/Persist
Sources/Persist/Persist.swift
1
7162
// // Persist.swift // uni-hd // // Created by Nils Fischer on 29.03.16. // Copyright © 2016 Universität Heidelberg. All rights reserved. // import Foundation import CoreData import Evergreen import Freddy import Result // TODO: move background execution here using a `ContextProvider` protocol with `newBackgroundContext()` and `mainContext`? // This would relieve the user from merging the background changes into the main context BUT it would require the core data stack to be structured in a certain way: both mainContext and a backgroundContext must be direct descendents of the persistent store coordinator (or must they?) //public protocol ContextProvider { // // var mainContext: NSManagedObjectContext { get } // // func newBackgroundContext() -> NSManagedObjectContext // //} // TODO: separate from Core Data using a `PersistenceProvider` protocol that NSManagedObjectContext conforms to // TODO: make sure to execute everything in background // MARK: - EntityRepresentable public protocol EntityRepresentable { static var entityName: String { get } } // MARK: - Persistable public protocol Persistable: Identifyable, Fillable {} extension Persistable { internal static var identificationProperty: PropertyMapping? { return persistablePropertiesByName[identificationAttributeName] } } public enum PersistError: ErrorType, CustomStringConvertible { case InvalidJSONData(underlying: ErrorType), OrphanDeletionFailed(underlying: ErrorType), FillingObjectsFailed(underlying: ErrorType), SaveContextFailed(underlying: ErrorType) public var description: String { switch self { case .InvalidJSONData(underlying: let underlyingError): return "Invalid JSON data: \(underlyingError)" case .OrphanDeletionFailed(underlying: let underlyingError): return "Orphan deletion failed: \(underlyingError)" case .FillingObjectsFailed(underlying: let underlyingError): return "Filling objects failed: \(underlyingError)" case .SaveContextFailed(underlying: let underlyingError): return "Save context failed: \(underlyingError)" } } } public typealias Completion = (Result<[NSManagedObject], PersistError>) -> Void // - Persist public enum Persist { // Namespace for `changes` function family public static func changes(jsonData: NSData, to entityType: Persistable.Type, context: NSManagedObjectContext, scope: NSPredicate? = nil, completion: Completion?) { // dispatch on background dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0)) { let logger = Evergreen.getLogger("Persist.Parse") let traceLogger = Evergreen.getLogger("Persist.Trace") traceLogger.tic(andLog: "Parsing \(entityType) JSON data...", forLevel: .Debug, timerKey: "parse_json_\(entityType.entityName)") // parse json let json: JSON do { json = try JSON(data: jsonData) } catch { logger.error("Failed to parse JSON from data.", error: error) dispatch_sync(dispatch_get_main_queue()) { completion?(.Failure(.InvalidJSONData(underlying: error))) } return } traceLogger.toc(andLog: "Parsed \(entityType) JSON data.", forLevel: .Debug, timerKey: "parse_json_\(entityType.entityName)") logger.verbose(json) // pass forward self.changes(json, to: entityType.self, context: context, scope: scope, completion: completion) } } public static func changes(json: JSON, to entityType: Persistable.Type, context: NSManagedObjectContext, scope: NSPredicate? = nil, completion: Completion?) { // dispatch on context's queue context.performBlock { let contextLogger = Evergreen.getLogger("Persist.Context") let traceLogger = Evergreen.getLogger("Persist.Trace") traceLogger.debug("Persisting changes of entity \(entityType.self)...") // delete orphans do { try deleteOrphans(ofEntity: entityType.self, onlyKeeping: json, context: context, scope: scope) } catch { dispatch_sync(dispatch_get_main_queue()) { completion?(.Failure(.OrphanDeletionFailed(underlying: error))) } return } // retrieve filled objects let objects: [NSManagedObject] do { objects = try filledObjects(ofEntity: entityType.self, withRepresentation: json, context: context) } catch { dispatch_sync(dispatch_get_main_queue()) { completion?(.Failure(.FillingObjectsFailed(underlying: error))) } return } // save do { if context.hasChanges { try context.save() contextLogger.debug("Saved context with changes to \(entityType).") } else { contextLogger.debug("Nothing changed for \(entityType), no need to save context.") } } catch { contextLogger.error("Failed saving context with changes to \(entityType).", error: error) dispatch_sync(dispatch_get_main_queue()) { completion?(.Failure(.SaveContextFailed(underlying: error))) } return } completion?(.Success(objects)) } } // public static func changes(json: JSON, contextProvider: ContextProvider, scope: NSPredicate? = nil) -> ChangesPromise { // let logger = Evergreen.getLogger("Persist.Trace") // logger.debug("Persisting changes of entity \(EntityType.self)...") // // let context = contextProvider.newBackgroundContext() // // let contextMerger = ContextMerger(observing: context, toMergeInto: contextProvider.mainContext, deduplicatingEntity: EntityType.self) // // return filledObjects(ofEntity: EntityType.self, withRepresentation: json, context: context).then { objects in // Promise { fulfill, reject in // context.performBlock { // // // mainly to keep the context merger from deiniting // contextMerger.beginObserving() // // // save context // do { // try context.save() // logger.debug("Saved changes to \(EntityType.self) in context.") // fulfill(objects) // } catch { // logger.error("Failed saving context.", error: error) // reject(error) // } // // } // } // } // // } }
mit
7729afc0ef9b830ebba2e3d5732f5636
37.702703
284
0.596927
5.211063
false
false
false
false
aipeople/PokeIV
PokeIV/UIButtonExtensions.swift
1
2432
// // UIButtonExtension.swift // PokeIV // // Created by aipeople on 8/17/16. // Github: https://github.com/aipeople/PokeIV // Copyright © 2016 su. All rights reserved. // import UIKit struct BorderButtonData { var title: String var titleColor: UIColor var borderColor: UIColor init(title: String, titleColor: UIColor = UIColor(white: 0.15, alpha: 1.0), borderColor: UIColor = UIColor(white: 0, alpha: 0.15)) { self.title = title self.titleColor = titleColor self.borderColor = borderColor } } extension UIButton { static func barButtonWithImage(image: UIImage?) -> UIButton { let button = self.init(type: .System) if let image = image { button.tintColor = UIColor(white: 0.35, alpha: 1.0) button.setImage(image.imageWithRenderingMode(.AlwaysTemplate), forState: .Normal) } return button } static func borderButtonWithTitle(title: String?, titleColor: UIColor, borderColor: UIColor = UIColor(white: 0, alpha: 0.15)) -> UIButton { let button = self.init(type: .System) button.setTitle(title, forState: .Normal) button.setTitleColor(titleColor, forState: .Normal) button.setTitleColor(titleColor.colorWithAlphaComponent(0.25), forState: .Disabled) button.layer.borderWidth = 0.5 button.layer.borderColor = borderColor.CGColor button.layer.cornerRadius = 4 button.titleLabel?.font = UIFont.systemFontOfSize(18, weight: UIFontWeightMedium) return button } static func borderButtonWithImage(image: UIImage?, overlayColor: UIColor?, borderColor: UIColor = UIColor(white: 0, alpha: 0.15)) -> UIButton { let tintImage: UIImage? if let overlayColor = overlayColor { tintImage = image?.imageColoredWithColor(overlayColor) } else { tintImage = image } let button = self.init(type: .System) button.setImage(tintImage?.imageWithRenderingMode(.AlwaysOriginal), forState: .Normal) button.layer.borderWidth = 0.5 button.layer.borderColor = borderColor.CGColor button.layer.cornerRadius = 4 button.titleLabel?.font = UIFont.systemFontOfSize(18, weight: UIFontWeightMedium) return button } }
gpl-3.0
c3f496623950b450967b3f1c9ee65f3b
31.413333
147
0.627725
4.595463
false
false
false
false
rnine/AudioMate
AudioMate/MasterVolumeGraphicView.swift
2
2683
// // MasterVolumeGraphicView.swift // AudioMate // // Created by Ruben Nine on 08/05/16. // Copyright © 2016 Ruben Nine. All rights reserved. // import Cocoa protocol MasterVolumeGraphicViewDelegate { func volumeViewScrolled(volumeView: MasterVolumeGraphicView, delta: CGFloat) } class MasterVolumeGraphicView: NSView { var delegate: MasterVolumeGraphicViewDelegate? private var needsLayerSetup: Bool = true private var maskLayer: CALayer! private var innerLayer: CALayer! var shouldHighlight: Bool = false { didSet { setNeedsDisplay(bounds) } } var isEnabled: Bool = true { didSet { setNeedsDisplay(bounds) } } var value: CGFloat = 0 { didSet { setNeedsDisplay(bounds) } } override var allowsVibrancy: Bool { return true } // MARK: Lifecycle Functions override init(frame frameRect: NSRect) { super.init(frame: frameRect) wantsLayer = true } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - Overrides override func viewDidMoveToSuperview() { super.viewDidMoveToSuperview() if needsLayerSetup { setupLayers() needsLayerSetup = false } } override func scrollWheel(with theEvent: NSEvent) { super.scrollWheel(with: theEvent) delegate?.volumeViewScrolled(volumeView: self, delta: theEvent.deltaY) } override func draw(_ dirtyRect: NSRect) { updateUI() super.draw(dirtyRect) } // MARK: Private Functions private func updateUI() { guard let layer = layer else { return } layer.backgroundColor = contentColor().copy(alpha: 0.16) innerLayer.backgroundColor = contentColor() let size = CGSize(width: bounds.width * value, height: bounds.height) innerLayer.frame = CGRect(origin: .zero, size: size) } private func setupLayers() { guard let layer = layer else { return } if let volumeControlImage = NSImage(named: "Volume-control") { maskLayer = CALayer() maskLayer.frame = CGRect(origin: .zero, size: volumeControlImage.size) maskLayer.contents = volumeControlImage innerLayer = CALayer() layer.mask = maskLayer layer.addSublayer(innerLayer) } } private func contentColor() -> CGColor { let color = (shouldHighlight ? NSColor.white : NSColor.labelColor).cgColor return isEnabled ? color : color.copy(alpha: 0.33)! } }
mit
f878221df9d9e01cd4072c51faf10eda
20.11811
82
0.618195
4.713533
false
false
false
false
makezwl/zhao
Nimble/DSL.swift
75
2457
import Foundation /// Make an expectation on a given actual value. The value given is lazily evaluated. public func expect<T>(expression: @autoclosure () -> T?, file: String = __FILE__, line: UInt = __LINE__) -> Expectation<T> { return Expectation( expression: Expression( expression: expression, location: SourceLocation(file: file, line: line))) } /// Make an expectation on a given actual value. The closure is lazily invoked. public func expect<T>(file: String = __FILE__, line: UInt = __LINE__, expression: () -> T?) -> Expectation<T> { return Expectation( expression: Expression( expression: expression, location: SourceLocation(file: file, line: line))) } /// Wait asynchronously until the done closure is called. /// /// This will advance the run loop. public func waitUntil(#timeout: NSTimeInterval, action: (() -> Void) -> Void, file: String = __FILE__, line: UInt = __LINE__) -> Void { var completed = false var token: dispatch_once_t = 0 let result = pollBlock(pollInterval: 0.01, timeoutInterval: timeout) { dispatch_once(&token) { dispatch_async(dispatch_get_main_queue()) { action() { completed = true } } } return completed } if result == PollResult.Failure { let pluralize = (timeout == 1 ? "" : "s") fail("Waited more than \(timeout) second\(pluralize)", file: file, line: line) } else if result == PollResult.Timeout { fail("Stall on main thread - too much enqueued on main run loop before waitUntil executes.", file: file, line: line) } } /// Wait asynchronously until the done closure is called. /// /// This will advance the run loop. public func waitUntil(action: (() -> Void) -> Void, file: String = __FILE__, line: UInt = __LINE__) -> Void { waitUntil(timeout: 1, action, file: file, line: line) } /// Always fails the test with a message and a specified location. public func fail(message: String, #location: SourceLocation) { CurrentAssertionHandler.assert(false, message: message, location: location) } /// Always fails the test with a message. public func fail(message: String, file: String = __FILE__, line: UInt = __LINE__) { fail(message, location: SourceLocation(file: file, line: line)) } /// Always fails the test. public func fail(file: String = __FILE__, line: UInt = __LINE__) { fail("fail() always fails") }
apache-2.0
5109f9dc0d3d36d20da78a332208eee9
39.295082
135
0.639805
4.122483
false
false
false
false
superk589/DereGuide
DereGuide/Unit/Simulation/View/UnitSimulationMainBodyCell.swift
2
11765
// // UnitSimulationMainBodyCell.swift // DereGuide // // Created by zzk on 2017/5/16. // Copyright © 2017 zzk. All rights reserved. // import UIKit import SnapKit protocol UnitSimulationMainBodyCellDelegate: class { func startCalculate(_ unitSimulationMainBodyCell: UnitSimulationMainBodyCell) func startSimulate(_ unitSimulationMainBodyCell: UnitSimulationMainBodyCell) func cancelSimulating(_ unitSimulationMainBodyCell: UnitSimulationMainBodyCell) func startAfkModeSimulating(_ unitSimulationMainBodyCell: UnitSimulationMainBodyCell) func cancelAfkModeSimulating(_ unitSimulationMainBodyCell: UnitSimulationMainBodyCell) } class UnitSimulationMainBodyCell: UITableViewCell { var calculationButton: UIButton! var calculationGrid: GridLabel! var simulationButton: UIButton! var cancelButton: UIButton! var simulationGrid: GridLabel! var simulatingIndicator: UIActivityIndicatorView! var cancelButtonWidthConstraint: Constraint! var cancelButtonLeftConstraint: Constraint! let afkModeButton = WideButton() let afkModeCancelButton = WideButton() let afkModeIndicator = UIActivityIndicatorView(style: .white) let afkModeGrid = GridLabel(rows: 2, columns: 3) var afkModeCancelButtonLeftConstraint: Constraint! var afkModeCancelButtonWidthConstraint: Constraint! // var scoreDistributionButton: UIButton! // // var scoreDetailButton: UIButton! // // var supportSkillDetailButton: UIButton! weak var delegate: UnitSimulationMainBodyCellDelegate? override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) calculationButton = WideButton() calculationButton.setTitle(NSLocalizedString("一般计算", comment: "队伍详情页面"), for: .normal) calculationButton.backgroundColor = .dance calculationButton.addTarget(self, action: #selector(startCalculate), for: .touchUpInside) contentView.addSubview(calculationButton) calculationButton.snp.makeConstraints { (make) in make.left.equalTo(10) make.right.equalTo(-10) make.top.equalTo(10) } calculationGrid = GridLabel.init(rows: 2, columns: 4) contentView.addSubview(calculationGrid) calculationGrid.snp.makeConstraints { (make) in make.left.equalTo(10) make.right.equalTo(-10) make.top.equalTo(calculationButton.snp.bottom).offset(10) } simulationButton = WideButton() simulationButton.setTitle(NSLocalizedString("模拟计算", comment: "队伍详情页面"), for: .normal) simulationButton.backgroundColor = .vocal simulationButton.addTarget(self, action: #selector(startSimulate), for: .touchUpInside) contentView.addSubview(simulationButton) simulationButton.snp.makeConstraints { (make) in make.left.equalTo(10) make.top.equalTo(calculationGrid.snp.bottom).offset(10) } simulatingIndicator = UIActivityIndicatorView(style: .white) simulationButton.addSubview(simulatingIndicator) simulatingIndicator.snp.makeConstraints { (make) in make.right.equalTo(simulationButton.titleLabel!.snp.left) make.centerY.equalTo(simulationButton) } cancelButton = WideButton() cancelButton.setTitle(NSLocalizedString("取消", comment: ""), for: .normal) cancelButton.backgroundColor = .vocal cancelButton.addTarget(self, action: #selector(cancelSimulating), for: .touchUpInside) contentView.addSubview(cancelButton) cancelButton.snp.makeConstraints { (make) in make.right.equalTo(-10) make.top.equalTo(simulationButton) self.cancelButtonWidthConstraint = make.width.equalTo(0).constraint self.cancelButtonLeftConstraint = make.left.equalTo(simulationButton.snp.right).constraint make.width.equalTo(calculationGrid.snp.width).dividedBy(4).priority(900) make.left.equalTo(simulationButton.snp.right).offset(1).priority(900) } cancelButton.titleLabel?.adjustsFontSizeToFitWidth = true cancelButton.titleLabel?.baselineAdjustment = .alignCenters simulationGrid = GridLabel.init(rows: 2, columns: 4) contentView.addSubview(simulationGrid) simulationGrid.snp.makeConstraints { (make) in make.left.equalTo(10) make.right.equalTo(-10) make.top.equalTo(simulationButton.snp.bottom).offset(10) } contentView.addSubview(afkModeButton) afkModeButton.setTitle(NSLocalizedString("模拟挂机模式", comment: ""), for: .normal) afkModeButton.backgroundColor = .passion afkModeButton.snp.makeConstraints { (make) in make.left.equalTo(10) make.top.equalTo(simulationGrid.snp.bottom).offset(10) } afkModeButton.addTarget(self, action: #selector(startAfkModeSimulating), for: .touchUpInside) contentView.addSubview(afkModeGrid) afkModeGrid.snp.makeConstraints { (make) in make.left.equalTo(10) make.right.equalTo(-10) make.top.equalTo(afkModeButton.snp.bottom).offset(10) make.bottom.equalTo(-10) } afkModeButton.addSubview(afkModeIndicator) afkModeIndicator.snp.makeConstraints { (make) in make.right.equalTo(afkModeButton.titleLabel!.snp.left) make.centerY.equalTo(afkModeButton) } afkModeCancelButton.setTitle(NSLocalizedString("取消", comment: ""), for: .normal) afkModeCancelButton.backgroundColor = .passion afkModeCancelButton.addTarget(self, action: #selector(cancelAfkModeSimulating), for: .touchUpInside) contentView.addSubview(afkModeCancelButton) afkModeCancelButton.snp.makeConstraints { (make) in make.right.equalTo(-10) make.top.equalTo(afkModeButton) self.afkModeCancelButtonWidthConstraint = make.width.equalTo(0).constraint self.afkModeCancelButtonLeftConstraint = make.left.equalTo(afkModeButton.snp.right).constraint make.width.equalTo(afkModeGrid.snp.width).dividedBy(4).priority(900) make.left.equalTo(afkModeButton.snp.right).offset(1).priority(900) } afkModeCancelButton.titleLabel?.adjustsFontSizeToFitWidth = true afkModeCancelButton.titleLabel?.baselineAdjustment = .alignCenters prepareGridViewFields() selectionStyle = .none } private func prepareGridViewFields() { var calculationString = [[String]]() calculationString.append([NSLocalizedString("表现值", comment: "队伍详情页面"), NSLocalizedString("极限分数", comment: "队伍详情页面") + "1", NSLocalizedString("极限分数", comment: "队伍详情页面") + "2", NSLocalizedString("平均分数", comment: "队伍详情页面")]) calculationString.append(["", "", "", ""]) calculationGrid.setContents(calculationString) var simulationStrings = [[String]]() simulationStrings.append(["1%", "5%", "20%", "50%"]) simulationStrings.append(["", "", "", ""]) simulationGrid.setContents(simulationStrings) var afkModeStrings = [[String]]() afkModeStrings.append([NSLocalizedString("存活率%", comment: ""), NSLocalizedString("S Rank率%", comment: ""), NSLocalizedString("最高得分", comment: "")]) afkModeStrings.append(["", "", "", ""]) afkModeGrid.setContents(afkModeStrings) } func resetCalculationButton() { calculationButton.setTitle(NSLocalizedString("一般计算", comment: ""), for: .normal) calculationButton.isUserInteractionEnabled = true } func stopSimulationAnimating() { simulationButton.isUserInteractionEnabled = true UIView.animate(withDuration: 0.25) { self.cancelButtonWidthConstraint.activate() self.cancelButtonLeftConstraint.activate() self.layoutIfNeeded() } simulatingIndicator.stopAnimating() simulationButton.setTitle(NSLocalizedString("模拟计算", comment: ""), for: .normal) } func startSimulationAnimating() { simulatingIndicator.startAnimating() UIView.animate(withDuration: 0.25) { self.cancelButtonLeftConstraint.deactivate() self.cancelButtonWidthConstraint.deactivate() self.layoutIfNeeded() } simulationButton.isUserInteractionEnabled = false } func startAfkModeSimulationAnimating() { afkModeIndicator.startAnimating() UIView.animate(withDuration: 0.25) { self.afkModeCancelButtonLeftConstraint.deactivate() self.afkModeCancelButtonWidthConstraint.deactivate() self.layoutIfNeeded() } afkModeButton.isUserInteractionEnabled = false } func stopAfkModeSimulationAnimating() { afkModeButton.isUserInteractionEnabled = true UIView.animate(withDuration: 0.25) { self.afkModeCancelButtonLeftConstraint.activate() self.afkModeCancelButtonWidthConstraint.activate() self.layoutIfNeeded() } afkModeIndicator.stopAnimating() afkModeButton.setTitle(NSLocalizedString("模拟挂机模式", comment: ""), for: .normal) } func setupCalculationResult(value1: Int, value2: Int, value3: Int, value4: Int) { calculationGrid[1, 0].text = String(value1) calculationGrid[1, 1].text = String(value2) calculationGrid[1, 2].text = String(value3) calculationGrid[1, 3].text = String(value4) } func setupSimulationResult(value1: Int, value2: Int, value3: Int, value4: Int) { simulationGrid[1, 0].text = String(value1) simulationGrid[1, 1].text = String(value2) simulationGrid[1, 2].text = String(value3) simulationGrid[1, 3].text = String(value4) } func setupAfkModeResult(value1: String, value2: String, value3: String) { afkModeGrid[1, 0].text = value1 afkModeGrid[1, 1].text = value2 afkModeGrid[1, 2].text = value3 } func setupAppeal(_ appeal: Int) { calculationGrid[1, 0].text = String(appeal) } func clearCalculationGrid() { calculationGrid[1, 2].text = "" calculationGrid[1, 1].text = "" calculationGrid[1, 0].text = "" calculationGrid[1, 3].text = "" } func clearSimulationGrid() { simulationGrid[1, 0].text = "" simulationGrid[1, 1].text = "" simulationGrid[1, 2].text = "" simulationGrid[1, 3].text = "" } func clearAfkModeGrid() { afkModeGrid[1, 0].text = "" afkModeGrid[1, 1].text = "" afkModeGrid[1, 2].text = "" } @objc func startCalculate() { delegate?.startCalculate(self) } @objc func startSimulate() { delegate?.startSimulate(self) } @objc func cancelSimulating() { delegate?.cancelSimulating(self) } @objc private func startAfkModeSimulating() { delegate?.startAfkModeSimulating(self) } @objc private func cancelAfkModeSimulating() { delegate?.cancelAfkModeSimulating(self) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
mit
95120bf4bd560bd951df3332376d481b
37.865772
229
0.659299
4.51364
false
false
false
false
getaaron/no-ads
ContentBlocker/ActionRequestHandler.swift
1
855
// // ActionRequestHandler.swift // ContentBlocker // // Created by Aaron on 7/8/15. // Copyright © 2015 Aaron Brager. All rights reserved. // import UIKit import MobileCoreServices class ActionRequestHandler: NSObject, NSExtensionRequestHandling { func beginRequestWithExtensionContext(context: NSExtensionContext) { let containerURL = NSFileManager.defaultManager().containerURLForSecurityApplicationGroupIdentifier("group.noads")! let fileDestinationUrl = containerURL.URLByAppendingPathComponent("easylist.json") let attachment = NSItemProvider(contentsOfURL: fileDestinationUrl)! let item = NSExtensionItem() item.attachments = [attachment] context.completeRequestReturningItems([item]) { (success) -> Void in print("success: \(success)") } } }
mit
5a8ae1ff59a5f69bbb34ff81d9b32581
28.448276
123
0.708431
5.509677
false
false
false
false
russbishop/swift
test/SILGen/protocol_extensions.swift
1
34100
// RUN: %target-swift-frontend -disable-objc-attr-requires-foundation-module -emit-silgen %s | FileCheck %s public protocol P1 { func reqP1a() subscript(i: Int) -> Int { get set } } struct Box { var number: Int } extension P1 { // CHECK-LABEL: sil hidden @_TFE19protocol_extensionsPS_2P16extP1a{{.*}} : $@convention(method) <Self where Self : P1> (@in_guaranteed Self) -> () { // CHECK: bb0([[SELF:%[0-9]+]] : $*Self): final func extP1a() { // CHECK: [[WITNESS:%[0-9]+]] = witness_method $Self, #P1.reqP1a!1 : $@convention(witness_method) <τ_0_0 where τ_0_0 : P1> (@in_guaranteed τ_0_0) -> () // CHECK-NEXT: apply [[WITNESS]]<Self>([[SELF]]) : $@convention(witness_method) <τ_0_0 where τ_0_0 : P1> (@in_guaranteed τ_0_0) -> () reqP1a() // CHECK: return } // CHECK-LABEL: sil @_TFE19protocol_extensionsPS_2P16extP1b{{.*}} : $@convention(method) <Self where Self : P1> (@in_guaranteed Self) -> () { // CHECK: bb0([[SELF:%[0-9]+]] : $*Self): public final func extP1b() { // CHECK: [[FN:%[0-9]+]] = function_ref @_TFE19protocol_extensionsPS_2P16extP1a{{.*}} : $@convention(method) <τ_0_0 where τ_0_0 : P1> (@in_guaranteed τ_0_0) -> () // CHECK-NEXT: apply [[FN]]<Self>([[SELF]]) : $@convention(method) <τ_0_0 where τ_0_0 : P1> (@in_guaranteed τ_0_0) -> () extP1a() // CHECK: return } subscript(i: Int) -> Int { // materializeForSet can do static dispatch to peer accessors (tested later, in the emission of the concrete conformance) get { return 0 } set {} } final func callSubscript() -> Int { // But here we have to do a witness method call: // CHECK-LABEL: sil hidden @_TFE19protocol_extensionsPS_2P113callSubscript{{.*}} // CHECK: bb0(%0 : $*Self): // CHECK: witness_method $Self, #P1.subscript!getter.1 // CHECK: return return self[0] } static var staticReadOnlyProperty: Int { return 0 } static var staticReadWrite1: Int { get { return 0 } set { } } static var staticReadWrite2: Box { get { return Box(number: 0) } set { } } } // ---------------------------------------------------------------------------- // Using protocol extension members with concrete types // ---------------------------------------------------------------------------- class C : P1 { func reqP1a() { } } // (materializeForSet test from above) // CHECK-LABEL: sil [transparent] [thunk] @_TTWC19protocol_extensions1CS_2P1S_FS1_m9subscriptFSiSi // CHECK: bb0(%0 : $Builtin.RawPointer, %1 : $*Builtin.UnsafeValueBuffer, %2 : $Int, %3 : $*C): // CHECK: function_ref @_TFE19protocol_extensionsPS_2P1g9subscriptFSiSi // CHECK: return class D : C { } struct S : P1 { func reqP1a() { } } struct G<T> : P1 { func reqP1a() { } } struct MetaHolder { var d: D.Type = D.self var s: S.Type = S.self } struct GenericMetaHolder<T> { var g: G<T>.Type = G<T>.self } func inout_func(_ n: inout Int) {} // CHECK-LABEL: sil hidden @_TF19protocol_extensions5testDFTVS_10MetaHolder2ddMCS_1D1dS1__T_ : $@convention(thin) (MetaHolder, @thick D.Type, @owned D) -> () // CHECK: bb0([[M:%[0-9]+]] : $MetaHolder, [[DD:%[0-9]+]] : $@thick D.Type, [[D:%[0-9]+]] : $D): func testD(_ m: MetaHolder, dd: D.Type, d: D) { // CHECK: [[D2:%[0-9]+]] = alloc_box $D // CHECK: [[RESULT:%.*]] = project_box [[D2]] // CHECK: [[FN:%[0-9]+]] = function_ref @_TFE19protocol_extensionsPS_2P111returnsSelf{{.*}} // CHECK: [[DCOPY:%[0-9]+]] = alloc_stack $D // CHECK: store [[D]] to [[DCOPY]] : $*D // CHECK: apply [[FN]]<D>([[RESULT]], [[DCOPY]]) : $@convention(method) <τ_0_0 where τ_0_0 : P1> (@in_guaranteed τ_0_0) -> @out τ_0_0 var d2: D = d.returnsSelf() // CHECK: metatype $@thick D.Type // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1g22staticReadOnlyPropertySi let _ = D.staticReadOnlyProperty // CHECK: metatype $@thick D.Type // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1s16staticReadWrite1Si D.staticReadWrite1 = 1 // CHECK: metatype $@thick D.Type // CHECK: alloc_stack $Int // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1g16staticReadWrite1Si // CHECK: store // CHECK: load // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1s16staticReadWrite1Si // CHECK: dealloc_stack D.staticReadWrite1 += 1 // CHECK: metatype $@thick D.Type // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1s16staticReadWrite2VS_3Box D.staticReadWrite2 = Box(number: 2) // CHECK: metatype $@thick D.Type // CHECK: alloc_stack $Box // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1g16staticReadWrite2VS_3Box // CHECK: store // CHECK: load // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1s16staticReadWrite2VS_3Box // CHECK: dealloc_stack D.staticReadWrite2.number += 5 // CHECK: function_ref @_TF19protocol_extensions10inout_funcFRSiT_ // CHECK: metatype $@thick D.Type // CHECK: alloc_stack $Box // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1g16staticReadWrite2VS_3Box // CHECK: store // CHECK: load // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1s16staticReadWrite2VS_3Box // CHECK: dealloc_stack inout_func(&D.staticReadWrite2.number) // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1g22staticReadOnlyPropertySi let _ = dd.staticReadOnlyProperty // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1s16staticReadWrite1Si dd.staticReadWrite1 = 1 // CHECK: alloc_stack $Int // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1g16staticReadWrite1Si // CHECK: store // CHECK: load // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1s16staticReadWrite1Si // CHECK: dealloc_stack dd.staticReadWrite1 += 1 // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1s16staticReadWrite2VS_3Box dd.staticReadWrite2 = Box(number: 2) // CHECK: alloc_stack $Box // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1g16staticReadWrite2VS_3Box // CHECK: store // CHECK: load // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1s16staticReadWrite2VS_3Box // CHECK: dealloc_stack dd.staticReadWrite2.number += 5 // CHECK: function_ref @_TF19protocol_extensions10inout_funcFRSiT_ // CHECK: alloc_stack $Box // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1g16staticReadWrite2VS_3Box // CHECK: store // CHECK: load // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1s16staticReadWrite2VS_3Box // CHECK: dealloc_stack inout_func(&dd.staticReadWrite2.number) // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1g22staticReadOnlyPropertySi let _ = m.d.staticReadOnlyProperty // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1s16staticReadWrite1Si m.d.staticReadWrite1 = 1 // CHECK: alloc_stack $Int // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1g16staticReadWrite1Si // CHECK: store // CHECK: load // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1s16staticReadWrite1Si // CHECK: dealloc_stack m.d.staticReadWrite1 += 1 // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1s16staticReadWrite2VS_3Box m.d.staticReadWrite2 = Box(number: 2) // CHECK: alloc_stack $Box // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1g16staticReadWrite2VS_3Box // CHECK: store // CHECK: load // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1s16staticReadWrite2VS_3Box // CHECK: dealloc_stack m.d.staticReadWrite2.number += 5 // CHECK: function_ref @_TF19protocol_extensions10inout_funcFRSiT_ // CHECK: alloc_stack $Box // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1g16staticReadWrite2VS_3Box // CHECK: store // CHECK: load // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1s16staticReadWrite2VS_3Box // CHECK: dealloc_stack inout_func(&m.d.staticReadWrite2.number) // CHECK: return } // CHECK-LABEL: sil hidden @_TF19protocol_extensions5testSFTVS_10MetaHolder2ssMVS_1S_T_ func testS(_ m: MetaHolder, ss: S.Type) { // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1g22staticReadOnlyPropertySi // CHECK: metatype $@thick S.Type let _ = S.staticReadOnlyProperty // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1s16staticReadWrite1Si // CHECK: metatype $@thick S.Type S.staticReadWrite1 = 1 // CHECK: alloc_stack $Int // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1g16staticReadWrite1Si // CHECK: metatype $@thick S.Type // CHECK: store // CHECK: load // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1s16staticReadWrite1Si // CHECK: dealloc_stack S.staticReadWrite1 += 1 // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1s16staticReadWrite2VS_3Box // CHECK: metatype $@thick S.Type S.staticReadWrite2 = Box(number: 2) // CHECK: alloc_stack $Box // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1g16staticReadWrite2VS_3Box // CHECK: metatype $@thick S.Type // CHECK: store // CHECK: load // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1s16staticReadWrite2VS_3Box // CHECK: dealloc_stack S.staticReadWrite2.number += 5 // CHECK: function_ref @_TF19protocol_extensions10inout_funcFRSiT_ // CHECK: alloc_stack $Box // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1g16staticReadWrite2VS_3Box // CHECK: metatype $@thick S.Type // CHECK: store // CHECK: load // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1s16staticReadWrite2VS_3Box // CHECK: dealloc_stack inout_func(&S.staticReadWrite2.number) // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1g22staticReadOnlyPropertySi // CHECK: metatype $@thick S.Type let _ = ss.staticReadOnlyProperty // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1s16staticReadWrite1Si // CHECK: metatype $@thick S.Type ss.staticReadWrite1 = 1 // CHECK: alloc_stack $Int // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1g16staticReadWrite1Si // CHECK: metatype $@thick S.Type // CHECK: store // CHECK: load // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1s16staticReadWrite1Si // CHECK: dealloc_stack ss.staticReadWrite1 += 1 // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1s16staticReadWrite2VS_3Box // CHECK: metatype $@thick S.Type ss.staticReadWrite2 = Box(number: 2) // CHECK: alloc_stack $Box // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1g16staticReadWrite2VS_3Box // CHECK: metatype $@thick S.Type // CHECK: store // CHECK: load // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1s16staticReadWrite2VS_3Box // CHECK: dealloc_stack ss.staticReadWrite2.number += 5 // CHECK: function_ref @_TF19protocol_extensions10inout_funcFRSiT_ // CHECK: alloc_stack $Box // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1g16staticReadWrite2VS_3Box // CHECK: metatype $@thick S.Type // CHECK: store // CHECK: load // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1s16staticReadWrite2VS_3Box // CHECK: dealloc_stack inout_func(&ss.staticReadWrite2.number) // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1g22staticReadOnlyPropertySi // CHECK: metatype $@thick S.Type let _ = m.s.staticReadOnlyProperty // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1s16staticReadWrite1Si // CHECK: metatype $@thick S.Type m.s.staticReadWrite1 = 1 // CHECK: alloc_stack $Int // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1g16staticReadWrite1Si // CHECK: metatype $@thick S.Type // CHECK: store // CHECK: load // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1s16staticReadWrite1Si // CHECK: dealloc_stack m.s.staticReadWrite1 += 1 // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1s16staticReadWrite2VS_3Box // CHECK: metatype $@thick S.Type m.s.staticReadWrite2 = Box(number: 2) // CHECK: alloc_stack $Box // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1g16staticReadWrite2VS_3Box // CHECK: metatype $@thick S.Type // CHECK: store // CHECK: load // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1s16staticReadWrite2VS_3Box // CHECK: dealloc_stack m.s.staticReadWrite2.number += 5 // CHECK: function_ref @_TF19protocol_extensions10inout_funcFRSiT_ // CHECK: alloc_stack $Box // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1g16staticReadWrite2VS_3Box // CHECK: metatype $@thick S.Type // CHECK: store // CHECK: load // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1s16staticReadWrite2VS_3Box // CHECK: dealloc_stack inout_func(&m.s.staticReadWrite2.number) // CHECK: return } // CHECK-LABEL: sil hidden @_TF19protocol_extensions5testG func testG<T>(_ m: GenericMetaHolder<T>, gg: G<T>.Type) { // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1g22staticReadOnlyPropertySi // CHECK: metatype $@thick G<T>.Type let _ = G<T>.staticReadOnlyProperty // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1s16staticReadWrite1Si // CHECK: metatype $@thick G<T>.Type G<T>.staticReadWrite1 = 1 // CHECK: alloc_stack $Int // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1g16staticReadWrite1Si // CHECK: metatype $@thick G<T>.Type // CHECK: store // CHECK: load // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1s16staticReadWrite1Si // CHECK: dealloc_stack G<T>.staticReadWrite1 += 1 // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1s16staticReadWrite2VS_3Box // CHECK: metatype $@thick G<T>.Type G<T>.staticReadWrite2 = Box(number: 2) // CHECK: alloc_stack $Box // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1g16staticReadWrite2VS_3Box // CHECK: metatype $@thick G<T>.Type // CHECK: store // CHECK: load // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1s16staticReadWrite2VS_3Box // CHECK: dealloc_stack G<T>.staticReadWrite2.number += 5 // CHECK: function_ref @_TF19protocol_extensions10inout_funcFRSiT_ // CHECK: alloc_stack $Box // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1g16staticReadWrite2VS_3Box // CHECK: metatype $@thick G<T>.Type // CHECK: store // CHECK: load // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1s16staticReadWrite2VS_3Box // CHECK: dealloc_stack inout_func(&G<T>.staticReadWrite2.number) // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1g22staticReadOnlyPropertySi // CHECK: metatype $@thick G<T>.Type let _ = gg.staticReadOnlyProperty // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1s16staticReadWrite1Si // CHECK: metatype $@thick G<T>.Type gg.staticReadWrite1 = 1 // CHECK: alloc_stack $Int // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1g16staticReadWrite1Si // CHECK: metatype $@thick G<T>.Type // CHECK: store // CHECK: load // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1s16staticReadWrite1Si // CHECK: dealloc_stack gg.staticReadWrite1 += 1 // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1s16staticReadWrite2VS_3Box // CHECK: metatype $@thick G<T>.Type gg.staticReadWrite2 = Box(number: 2) // CHECK: alloc_stack $Box // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1g16staticReadWrite2VS_3Box // CHECK: metatype $@thick G<T>.Type // CHECK: store // CHECK: load // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1s16staticReadWrite2VS_3Box // CHECK: dealloc_stack gg.staticReadWrite2.number += 5 // CHECK: function_ref @_TF19protocol_extensions10inout_funcFRSiT_ // CHECK: alloc_stack $Box // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1g16staticReadWrite2VS_3Box // CHECK: metatype $@thick G<T>.Type // CHECK: store // CHECK: load // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1s16staticReadWrite2VS_3Box // CHECK: dealloc_stack inout_func(&gg.staticReadWrite2.number) // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1g22staticReadOnlyPropertySi // CHECK: metatype $@thick G<T>.Type let _ = m.g.staticReadOnlyProperty // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1s16staticReadWrite1Si // CHECK: metatype $@thick G<T>.Type m.g.staticReadWrite1 = 1 // CHECK: alloc_stack $Int // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1g16staticReadWrite1Si // CHECK: metatype $@thick G<T>.Type // CHECK: store // CHECK: load // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1s16staticReadWrite1Si // CHECK: dealloc_stack m.g.staticReadWrite1 += 1 // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1s16staticReadWrite2VS_3Box // CHECK: metatype $@thick G<T>.Type m.g.staticReadWrite2 = Box(number: 2) // CHECK: alloc_stack $Box // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1g16staticReadWrite2VS_3Box // CHECK: metatype $@thick G<T>.Type // CHECK: store // CHECK: load // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1s16staticReadWrite2VS_3Box // CHECK: dealloc_stack m.g.staticReadWrite2.number += 5 // CHECK: function_ref @_TF19protocol_extensions10inout_funcFRSiT_ // CHECK: alloc_stack $Box // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1g16staticReadWrite2VS_3Box // CHECK: metatype $@thick G<T>.Type // CHECK: store // CHECK: load // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1s16staticReadWrite2VS_3Box // CHECK: dealloc_stack inout_func(&m.g.staticReadWrite2.number) // CHECK: return } // ---------------------------------------------------------------------------- // Using protocol extension members with existentials // ---------------------------------------------------------------------------- extension P1 { final func f1() { } final subscript (i: Int64) -> Bool { get { return true } } final var prop: Bool { get { return true } } final func returnsSelf() -> Self { return self } final var prop2: Bool { get { return true } set { } } final subscript (b: Bool) -> Bool { get { return b } set { } } } // CHECK-LABEL: sil hidden @_TF19protocol_extensions17testExistentials1 // CHECK: bb0([[P:%[0-9]+]] : $*P1, [[B:%[0-9]+]] : $Bool, [[I:%[0-9]+]] : $Int64): func testExistentials1(_ p1: P1, b: Bool, i: Int64) { // CHECK: [[POPENED:%[0-9]+]] = open_existential_addr [[P]] : $*P1 to $*@opened([[UUID:".*"]]) // CHECK: [[F1:%[0-9]+]] = function_ref @_TFE19protocol_extensionsPS_2P12f1{{.*}} // CHECK: apply [[F1]]<@opened([[UUID]]) P1>([[POPENED]]) : $@convention(method) <τ_0_0 where τ_0_0 : P1> (@in_guaranteed τ_0_0) -> () p1.f1() // CHECK: [[POPENED:%[0-9]+]] = open_existential_addr [[P]] : $*P1 to $*@opened([[UUID:".*"]]) P1 // CHECK: copy_addr [[POPENED]] to [initialization] [[POPENED_COPY:%.*]] : // CHECK: [[GETTER:%[0-9]+]] = function_ref @_TFE19protocol_extensionsPS_2P1g9subscriptFVs5Int64Sb // CHECK: apply [[GETTER]]<@opened([[UUID]]) P1>([[I]], [[POPENED_COPY]]) : $@convention(method) <τ_0_0 where τ_0_0 : P1> (Int64, @in_guaranteed τ_0_0) -> Bool // CHECK: destroy_addr [[POPENED_COPY]] // CHECK: store{{.*}} : $*Bool // CHECK: dealloc_stack [[POPENED_COPY]] var b2 = p1[i] // CHECK: [[POPENED:%[0-9]+]] = open_existential_addr [[P]] : $*P1 to $*@opened([[UUID:".*"]]) P1 // CHECK: copy_addr [[POPENED]] to [initialization] [[POPENED_COPY:%.*]] : // CHECK: [[GETTER:%[0-9]+]] = function_ref @_TFE19protocol_extensionsPS_2P1g4propSb // CHECK: apply [[GETTER]]<@opened([[UUID]]) P1>([[POPENED_COPY]]) : $@convention(method) <τ_0_0 where τ_0_0 : P1> (@in_guaranteed τ_0_0) -> Bool // CHECK: store{{.*}} : $*Bool // CHECK: dealloc_stack [[POPENED_COPY]] var b3 = p1.prop } // CHECK-LABEL: sil hidden @_TF19protocol_extensions17testExistentials2 // CHECK: bb0([[P:%[0-9]+]] : $*P1): func testExistentials2(_ p1: P1) { // CHECK: [[P1A:%[0-9]+]] = alloc_box $P1 // CHECK: [[PB:%.*]] = project_box [[P1A]] // CHECK: [[POPENED:%[0-9]+]] = open_existential_addr [[P]] : $*P1 to $*@opened([[UUID:".*"]]) P1 // CHECK: [[P1AINIT:%[0-9]+]] = init_existential_addr [[PB]] : $*P1, $@opened([[UUID2:".*"]]) P1 // CHECK: [[FN:%[0-9]+]] = function_ref @_TFE19protocol_extensionsPS_2P111returnsSelf{{.*}} // CHECK: apply [[FN]]<@opened([[UUID]]) P1>([[P1AINIT]], [[POPENED]]) : $@convention(method) <τ_0_0 where τ_0_0 : P1> (@in_guaranteed τ_0_0) -> @out τ_0_0 var p1a: P1 = p1.returnsSelf() } // CHECK-LABEL: sil hidden @_TF19protocol_extensions23testExistentialsGetters // CHECK: bb0([[P:%[0-9]+]] : $*P1): func testExistentialsGetters(_ p1: P1) { // CHECK: [[POPENED:%[0-9]+]] = open_existential_addr [[P]] : $*P1 to $*@opened([[UUID:".*"]]) P1 // CHECK: copy_addr [[POPENED]] to [initialization] [[POPENED_COPY:%.*]] : // CHECK: [[FN:%[0-9]+]] = function_ref @_TFE19protocol_extensionsPS_2P1g5prop2Sb // CHECK: [[B:%[0-9]+]] = apply [[FN]]<@opened([[UUID]]) P1>([[POPENED_COPY]]) : $@convention(method) <τ_0_0 where τ_0_0 : P1> (@in_guaranteed τ_0_0) -> Bool let b: Bool = p1.prop2 // CHECK: [[POPENED:%[0-9]+]] = open_existential_addr [[P]] : $*P1 to $*@opened([[UUID:".*"]]) P1 // CHECK: copy_addr [[POPENED]] to [initialization] [[POPENED_COPY:%.*]] : // CHECK: [[GETTER:%[0-9]+]] = function_ref @_TFE19protocol_extensionsPS_2P1g9subscriptFSbSb // CHECK: apply [[GETTER]]<@opened([[UUID]]) P1>([[B]], [[POPENED_COPY]]) : $@convention(method) <τ_0_0 where τ_0_0 : P1> (Bool, @in_guaranteed τ_0_0) -> Bool let b2: Bool = p1[b] } // CHECK-LABEL: sil hidden @_TF19protocol_extensions22testExistentialSetters // CHECK: bb0([[P:%[0-9]+]] : $*P1, [[B:%[0-9]+]] : $Bool): func testExistentialSetters(_ p1: P1, b: Bool) { var p1 = p1 // CHECK: [[PBOX:%[0-9]+]] = alloc_box $P1 // CHECK: [[PBP:%[0-9]+]] = project_box [[PBOX]] // CHECK-NEXT: copy_addr [[P]] to [initialization] [[PBP]] : $*P1 // CHECK: [[POPENED:%[0-9]+]] = open_existential_addr [[PBP]] : $*P1 to $*@opened([[UUID:".*"]]) P1 // CHECK: [[GETTER:%[0-9]+]] = function_ref @_TFE19protocol_extensionsPS_2P1s5prop2Sb // CHECK: apply [[GETTER]]<@opened([[UUID]]) P1>([[B]], [[POPENED]]) : $@convention(method) <τ_0_0 where τ_0_0 : P1> (Bool, @inout τ_0_0) -> () // CHECK-NOT: deinit_existential_addr p1.prop2 = b // CHECK: [[POPENED:%[0-9]+]] = open_existential_addr [[PBP]] : $*P1 to $*@opened([[UUID:".*"]]) P1 // CHECK: [[SUBSETTER:%[0-9]+]] = function_ref @_TFE19protocol_extensionsPS_2P1s9subscriptFSbSb // CHECK: apply [[SUBSETTER]]<@opened([[UUID]]) P1>([[B]], [[B]], [[POPENED]]) : $@convention(method) <τ_0_0 where τ_0_0 : P1> (Bool, Bool, @inout τ_0_0) -> () // CHECK-NOT: deinit_existential_addr [[PB]] : $*P1 p1[b] = b // CHECK: return } struct HasAP1 { var p1: P1 var someP1: P1 { get { return p1 } set { p1 = newValue } } } // CHECK-LABEL: sil hidden @_TF19protocol_extensions29testLogicalExistentialSetters // CHECK: bb0([[HASP1:%[0-9]+]] : $*HasAP1, [[B:%[0-9]+]] : $Bool) func testLogicalExistentialSetters(_ hasAP1: HasAP1, _ b: Bool) { var hasAP1 = hasAP1 // CHECK: [[HASP1_BOX:%[0-9]+]] = alloc_box $HasAP1 // CHECK: [[PBHASP1:%[0-9]+]] = project_box [[HASP1_BOX]] // CHECK-NEXT: copy_addr [[HASP1]] to [initialization] [[PBHASP1]] : $*HasAP1 // CHECK: [[P1_COPY:%[0-9]+]] = alloc_stack $P1 // CHECK-NEXT: [[HASP1_COPY:%[0-9]+]] = alloc_stack $HasAP1 // CHECK-NEXT: copy_addr [[PBHASP1]] to [initialization] [[HASP1_COPY]] : $*HasAP1 // CHECK: [[SOMEP1_GETTER:%[0-9]+]] = function_ref @_TFV19protocol_extensions6HasAP1g6someP1PS_2P1_ : $@convention(method) (@in_guaranteed HasAP1) -> @out P1 // CHECK: [[RESULT:%[0-9]+]] = apply [[SOMEP1_GETTER]]([[P1_COPY]], %8) : $@convention(method) (@in_guaranteed HasAP1) -> @out P1 // CHECK: [[P1_OPENED:%[0-9]+]] = open_existential_addr [[P1_COPY]] : $*P1 to $*@opened([[UUID:".*"]]) P1 // CHECK: [[PROP2_SETTER:%[0-9]+]] = function_ref @_TFE19protocol_extensionsPS_2P1s5prop2Sb : $@convention(method) <τ_0_0 where τ_0_0 : P1> (Bool, @inout τ_0_0) -> () // CHECK: apply [[PROP2_SETTER]]<@opened([[UUID]]) P1>([[B]], [[P1_OPENED]]) : $@convention(method) <τ_0_0 where τ_0_0 : P1> (Bool, @inout τ_0_0) -> () // CHECK: [[SOMEP1_SETTER:%[0-9]+]] = function_ref @_TFV19protocol_extensions6HasAP1s6someP1PS_2P1_ : $@convention(method) (@in P1, @inout HasAP1) -> () // CHECK: apply [[SOMEP1_SETTER]]([[P1_COPY]], [[PBHASP1]]) : $@convention(method) (@in P1, @inout HasAP1) -> () // CHECK-NOT: deinit_existential_addr hasAP1.someP1.prop2 = b // CHECK: return } func plusOneP1() -> P1 {} // CHECK-LABEL: sil hidden @_TF19protocol_extensions38test_open_existential_semantics_opaque func test_open_existential_semantics_opaque(_ guaranteed: P1, immediate: P1) { var immediate = immediate // CHECK: [[IMMEDIATE_BOX:%.*]] = alloc_box $P1 // CHECK: [[PB:%.*]] = project_box [[IMMEDIATE_BOX]] // CHECK: [[VALUE:%.*]] = open_existential_addr %0 // CHECK: [[METHOD:%.*]] = function_ref // CHECK: apply [[METHOD]]<{{.*}}>([[VALUE]]) guaranteed.f1() // -- Need a guaranteed copy because it's immutable // CHECK: copy_addr [[PB]] to [initialization] [[IMMEDIATE:%.*]] : // CHECK: [[VALUE:%.*]] = open_existential_addr [[IMMEDIATE]] // CHECK: [[METHOD:%.*]] = function_ref // -- Can consume the value from our own copy // CHECK: apply [[METHOD]]<{{.*}}>([[VALUE]]) // CHECK: deinit_existential_addr [[IMMEDIATE]] // CHECK: dealloc_stack [[IMMEDIATE]] immediate.f1() // CHECK: [[PLUS_ONE:%.*]] = alloc_stack $P1 // CHECK: [[VALUE:%.*]] = open_existential_addr [[PLUS_ONE]] // CHECK: [[METHOD:%.*]] = function_ref // -- Can consume the value from our own copy // CHECK: apply [[METHOD]]<{{.*}}>([[VALUE]]) // CHECK: deinit_existential_addr [[PLUS_ONE]] // CHECK: dealloc_stack [[PLUS_ONE]] plusOneP1().f1() } protocol CP1: class {} extension CP1 { final func f1() { } } func plusOneCP1() -> CP1 {} // CHECK-LABEL: sil hidden @_TF19protocol_extensions37test_open_existential_semantics_class func test_open_existential_semantics_class(_ guaranteed: CP1, immediate: CP1) { var immediate = immediate // CHECK: [[IMMEDIATE_BOX:%.*]] = alloc_box $CP1 // CHECK: [[PB:%.*]] = project_box [[IMMEDIATE_BOX]] // CHECK-NOT: strong_retain %0 // CHECK: [[VALUE:%.*]] = open_existential_ref %0 // CHECK: [[METHOD:%.*]] = function_ref // CHECK: apply [[METHOD]]<{{.*}}>([[VALUE]]) // CHECK-NOT: strong_release [[VALUE]] // CHECK-NOT: strong_release %0 guaranteed.f1() // CHECK: [[IMMEDIATE:%.*]] = load [[PB]] // CHECK: strong_retain [[IMMEDIATE]] // CHECK: [[VALUE:%.*]] = open_existential_ref [[IMMEDIATE]] // CHECK: [[METHOD:%.*]] = function_ref // CHECK: apply [[METHOD]]<{{.*}}>([[VALUE]]) // CHECK: strong_release [[VALUE]] // CHECK-NOT: strong_release [[IMMEDIATE]] immediate.f1() // CHECK: [[F:%.*]] = function_ref {{.*}}plusOneCP1 // CHECK: [[PLUS_ONE:%.*]] = apply [[F]]() // CHECK: [[VALUE:%.*]] = open_existential_ref [[PLUS_ONE]] // CHECK: [[METHOD:%.*]] = function_ref // CHECK: apply [[METHOD]]<{{.*}}>([[VALUE]]) // CHECK: strong_release [[VALUE]] // CHECK-NOT: strong_release [[PLUS_ONE]] plusOneCP1().f1() } protocol InitRequirement { init(c: C) } extension InitRequirement { // CHECK-LABEL: sil hidden @_TFE19protocol_extensionsPS_15InitRequirementC{{.*}} : $@convention(method) <Self where Self : InitRequirement> (@owned D, @thick Self.Type) -> @out Self // CHECK: bb0([[OUT:%.*]] : $*Self, [[ARG:%.*]] : $D, [[SELF_TYPE:%.*]] : $@thick Self.Type): init(d: D) { // CHECK: [[DELEGATEE:%.*]] = witness_method $Self, #InitRequirement.init!allocator.1 : $@convention(witness_method) <τ_0_0 where τ_0_0 : InitRequirement> (@owned C, @thick τ_0_0.Type) -> @out τ_0_0 // CHECK: [[ARG_UP:%.*]] = upcast [[ARG]] // CHECK: apply [[DELEGATEE]]<Self>({{%.*}}, [[ARG_UP]], [[SELF_TYPE]]) self.init(c: d) } // CHECK-LABEL: sil hidden @_TFE19protocol_extensionsPS_15InitRequirementC{{.*}} // CHECK: function_ref @_TFE19protocol_extensionsPS_15InitRequirementC{{.*}} init(d2: D) { self.init(d: d2) } } protocol ClassInitRequirement: class { init(c: C) } extension ClassInitRequirement { // CHECK-LABEL: sil hidden @_TFE19protocol_extensionsPS_20ClassInitRequirementC{{.*}} : $@convention(method) <Self where Self : ClassInitRequirement> (@owned D, @thick Self.Type) -> @owned Self // CHECK: bb0([[ARG:%.*]] : $D, [[SELF_TYPE:%.*]] : $@thick Self.Type): // CHECK: [[DELEGATEE:%.*]] = witness_method $Self, #ClassInitRequirement.init!allocator.1 : $@convention(witness_method) <τ_0_0 where τ_0_0 : ClassInitRequirement> (@owned C, @thick τ_0_0.Type) -> @owned τ_0_0 // CHECK: [[ARG_UP:%.*]] = upcast [[ARG]] // CHECK: apply [[DELEGATEE]]<Self>([[ARG_UP]], [[SELF_TYPE]]) init(d: D) { self.init(c: d) } } @objc class OC {} @objc class OD: OC {} @objc protocol ObjCInitRequirement { init(c: OC, d: OC) } func foo(_ t: ObjCInitRequirement.Type, c: OC) -> ObjCInitRequirement { return t.init(c: OC(), d: OC()) } extension ObjCInitRequirement { // CHECK-LABEL: sil hidden @_TFE19protocol_extensionsPS_19ObjCInitRequirementC{{.*}} : $@convention(method) <Self where Self : ObjCInitRequirement> (@owned OD, @thick Self.Type) -> @owned Self // CHECK: bb0([[ARG:%.*]] : $OD, [[SELF_TYPE:%.*]] : $@thick Self.Type): // CHECK: [[OBJC_SELF_TYPE:%.*]] = thick_to_objc_metatype [[SELF_TYPE]] // CHECK: [[SELF:%.*]] = alloc_ref_dynamic [objc] [[OBJC_SELF_TYPE]] : $@objc_metatype Self.Type, $Self // CHECK: [[WITNESS:%.*]] = witness_method [volatile] $Self, #ObjCInitRequirement.init!initializer.1.foreign : $@convention(objc_method) <τ_0_0 where τ_0_0 : ObjCInitRequirement> (OC, OC, @owned τ_0_0) -> @owned τ_0_0 // CHECK: [[UPCAST1:%.*]] = upcast [[ARG]] // CHECK: [[UPCAST2:%.*]] = upcast [[ARG]] // CHECK: apply [[WITNESS]]<Self>([[UPCAST1]], [[UPCAST2]], [[SELF]]) init(d: OD) { self.init(c: d, d: d) } } // rdar://problem/21370992 - delegation from an initializer in a // protocol extension to an @objc initializer in a class. class ObjCInitClass { @objc init() { } } protocol ProtoDelegatesToObjC { } extension ProtoDelegatesToObjC where Self : ObjCInitClass { // CHECK-LABEL: sil hidden @_TFe19protocol_extensionsRxCS_13ObjCInitClassxS_20ProtoDelegatesToObjCrS1_C{{.*}} // CHECK: bb0([[STR:%[0-9]+]] : $String, [[SELF_META:%[0-9]+]] : $@thick Self.Type): init(string: String) { // CHECK: [[SELF_BOX:%[0-9]+]] = alloc_box $Self // CHECK: [[PB:%.*]] = project_box [[SELF_BOX]] // CHECK: [[SELF:%[0-9]+]] = mark_uninitialized [delegatingself] [[PB]] : $*Self // CHECK: [[SELF_META_OBJC:%[0-9]+]] = thick_to_objc_metatype [[SELF_META]] : $@thick Self.Type to $@objc_metatype Self.Type // CHECK: [[SELF_ALLOC:%[0-9]+]] = alloc_ref_dynamic [objc] [[SELF_META_OBJC]] : $@objc_metatype Self.Type, $Self // CHECK: [[SELF_ALLOC_C:%[0-9]+]] = upcast [[SELF_ALLOC]] : $Self to $ObjCInitClass // CHECK: [[OBJC_INIT:%[0-9]+]] = class_method [[SELF_ALLOC_C]] : $ObjCInitClass, #ObjCInitClass.init!initializer.1 : (ObjCInitClass.Type) -> () -> ObjCInitClass , $@convention(method) (@owned ObjCInitClass) -> @owned ObjCInitClass // CHECK: [[SELF_RESULT:%[0-9]+]] = apply [[OBJC_INIT]]([[SELF_ALLOC_C]]) : $@convention(method) (@owned ObjCInitClass) -> @owned ObjCInitClass // CHECK: [[SELF_RESULT_AS_SELF:%[0-9]+]] = unchecked_ref_cast [[SELF_RESULT]] : $ObjCInitClass to $Self // CHECK: assign [[SELF_RESULT_AS_SELF]] to [[SELF]] : $*Self self.init() } } // Delegating from an initializer in a protocol extension where Self // has a superclass to a required initializer of that class. class RequiredInitClass { required init() { } } protocol ProtoDelegatesToRequired { } extension ProtoDelegatesToRequired where Self : RequiredInitClass { // CHECK-LABEL: sil hidden @_TFe19protocol_extensionsRxCS_17RequiredInitClassxS_24ProtoDelegatesToRequiredrS1_C{{.*}} // CHECK: bb0([[STR:%[0-9]+]] : $String, [[SELF_META:%[0-9]+]] : $@thick Self.Type): init(string: String) { // CHECK: [[SELF_BOX:%[0-9]+]] = alloc_box $Self // CHECK: [[PB:%.*]] = project_box [[SELF_BOX]] // CHECK: [[SELF:%[0-9]+]] = mark_uninitialized [delegatingself] [[PB]] : $*Self // CHECK: [[SELF_META_AS_CLASS_META:%[0-9]+]] = upcast [[SELF_META]] : $@thick Self.Type to $@thick RequiredInitClass.Type // CHECK: [[INIT:%[0-9]+]] = class_method [[SELF_META_AS_CLASS_META]] : $@thick RequiredInitClass.Type, #RequiredInitClass.init!allocator.1 : (RequiredInitClass.Type) -> () -> RequiredInitClass , $@convention(method) (@thick RequiredInitClass.Type) -> @owned RequiredInitClass // CHECK: [[SELF_RESULT:%[0-9]+]] = apply [[INIT]]([[SELF_META_AS_CLASS_META]]) : $@convention(method) (@thick RequiredInitClass.Type) -> @owned RequiredInitClass // CHECK: [[SELF_RESULT_AS_SELF:%[0-9]+]] = unchecked_ref_cast [[SELF_RESULT]] : $RequiredInitClass to $Self // CHECK: assign [[SELF_RESULT_AS_SELF]] to [[SELF]] : $*Self self.init() } } // ---------------------------------------------------------------------------- // Default implementations via protocol extensions // ---------------------------------------------------------------------------- protocol P2 { associatedtype A func f1(_ a: A) func f2(_ a: A) var x: A { get } } extension P2 { // CHECK-LABEL: sil hidden @_TFE19protocol_extensionsPS_2P22f1{{.*}} // CHECK: witness_method $Self, #P2.f2!1 // CHECK: function_ref @_TFE19protocol_extensionsPS_2P22f3{{.*}} // CHECK: return func f1(_ a: A) { f2(a) f3(a) } // CHECK-LABEL: sil hidden @_TFE19protocol_extensionsPS_2P22f2{{.*}} // CHECK: witness_method $Self, #P2.f1!1 // CHECK: function_ref @_TFE19protocol_extensionsPS_2P22f3{{.*}} // CHECK: return func f2(_ a: A) { f1(a) f3(a) } func f3(_ a: A) {} // CHECK-LABEL: sil hidden @_TFE19protocol_extensionsPS_2P22f4{{.*}} // CHECK: witness_method $Self, #P2.f1!1 // CHECK: witness_method $Self, #P2.f2!1 // CHECK: return func f4() { f1(x) f2(x) } }
apache-2.0
58387bb9834943cee4e86abcf9e29e9b
39.963899
280
0.648248
3.31913
false
false
false
false
xiaomudegithub/viossvc
viossvc/Scenes/Share/Tour/TourShareViewController.swift
1
3921
// // TourShareViewController.swift // viossvc // // Created by yaowang on 2016/10/28. // Copyright © 2016年 ywwlcom.yundian. All rights reserved. // import Foundation class TourShareViewController: BaseListTableViewController,OEZTableViewDelegate { override func viewDidLoad() { super.viewDidLoad(); tableView.registerNib(TourShareCell.self, forCellReuseIdentifier: "TourShareCell"); // tableView.registerNib(TourLeaderShareCell.self, forCellReuseIdentifier: "TourLeaderShareCell"); } override func isSections() -> Bool { return true; } override func isCalculateCellHeight() -> Bool { return true } override func tableView(tableView: UITableView, cellIdentifierForRowAtIndexPath indexPath: NSIndexPath) -> String? { return indexPath.section == 0 ? "TourLeaderShareCell" : "TourShareCell" } override func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let view:TableViewHeaderView? = TableViewHeaderView.loadFromNib(); view?.titleLabel.text = section == 0 ? "V领队分享" : "推荐分享"; return view; } func tableView(tableView: UITableView!, rowAtIndexPath indexPath: NSIndexPath!, didSelectColumnAtIndex column: Int) { switch indexPath.section { case 0: let array = self.tableView(tableView, cellDataForRowAtIndexPath: indexPath) as! [TourShareTypeModel] let model = array[column] let viewController:TourShareListViewController = storyboardViewController() viewController.setValue(model, forKey: "typeModel") self.navigationController?.pushViewController(viewController, animated: true); default: break } } func tableView(tableView: UITableView!, rowAtIndexPath indexPath: NSIndexPath!, didAction action: Int, data: AnyObject!) { if UInt(action) == AppConst.Action.CallPhone.rawValue { let model = self.tableView(tableView, cellDataForRowAtIndexPath: indexPath) as? TourShareModel if model?.telephone != nil { didActionTel(model!.telephone) } } } override func didRequest() { var array : [[AnyObject]] = [[],] AppAPIHelper.tourShareAPI().type({ [weak self](obj) in if obj != nil { array[0].append(obj as! [TourShareTypeModel]) self?.didRequestComplete(array) } }, error: errorBlockFunc()) AppAPIHelper.tourShareAPI().list(0, count: AppConst.DefaultPageSize, type: 0, complete: {[weak self] (obj) in if obj != nil { array.append(obj as! [TourShareModel]) self?.didRequestComplete(array) } }, error: errorBlockFunc()) } override func didRequestComplete(data: AnyObject?) { super.didRequestComplete(data) } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { if indexPath.section == 1 { let model = self.tableView(tableView, cellDataForRowAtIndexPath: indexPath) as? TourShareModel let viewController:TourShareDetailViewController = storyboardViewController() viewController.share_id = model!.share_id viewController.title = model!.share_theme self.navigationController?.pushViewController(viewController, animated: true); } } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.destinationViewController.isKindOfClass(TourShareListViewController) { segue.destinationViewController.setValue(sender?.tag, forKey: "listType"); } } }
apache-2.0
be93465317ef477b9207211ef1c0bd5d
35.12963
126
0.63634
5.294437
false
false
false
false
cnbin/wikipedia-ios
Wikipedia/Images/SDWebImageManager+PromiseKit.swift
3
2095
// // SDWebImageManager+PromiseKit.swift // Wikipedia // // Created by Brian Gerstle on 6/22/15. // Copyright (c) 2015 Wikimedia Foundation. All rights reserved. // import Foundation import PromiseKit extension SDImageCacheType: ImageOriginConvertible { public func asImageOrigin() -> ImageOrigin { switch self { case SDImageCacheType.Disk: return ImageOrigin.Disk case SDImageCacheType.Memory: return ImageOrigin.Memory case SDImageCacheType.None: return ImageOrigin.Network } } } // FIXME: Can't extend the SDWebImageOperation protocol or cast the return value, so we wrap it. class SDWebImageOperationWrapper: NSObject, Cancellable { weak var operation: SDWebImageOperation? required init(operation: SDWebImageOperation) { super.init() self.operation = operation // keep wrapper around as long as operation is around objc_setAssociatedObject(operation, "SDWebImageOperationWrapper", self, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC) } func cancel() -> Void { operation?.cancel() } } extension SDWebImageManager { func promisedImageWithURL(URL: NSURL, options: SDWebImageOptions) -> (Cancellable, Promise<WMFImageDownload>) { let (promise, fulfill, reject) = Promise<WMFImageDownload>.pendingPromise() let promiseCompatibleOptions: SDWebImageOptions = [options, SDWebImageOptions.ReportCancellationAsError] let webImageOperation = self.downloadImageWithURL(URL, options: promiseCompatibleOptions, progress: nil) { img, err, cacheType, finished, imageURL in if finished && err == nil { fulfill(WMFImageDownload(url: URL, image: img, origin: asImageOrigin(cacheType).rawValue)) } else { reject(err) } } return (SDWebImageOperationWrapper(operation: webImageOperation), promise) } }
mit
79298d3a05c06d2f2e932ea7d1d1e0fa
33.916667
115
0.647733
5.198511
false
false
false
false
peferron/algo
EPI/Stacks and Queues/Implement a circular queue/swift/main.swift
1
1020
public struct Queue<T> { var array = [T]() var firstIndex = 0 public var count = 0 public var capacity: Int public init(capacity: Int) { self.array.reserveCapacity(capacity) self.capacity = capacity } public mutating func enqueue(_ element: T) { if count == capacity { increaseCapacity() } let enqueueIndex = (firstIndex + count) % capacity if enqueueIndex >= array.count { array.append(element) } else { array[enqueueIndex] = element } count += 1 } public mutating func dequeue() -> T { let first = array[firstIndex] firstIndex = (firstIndex + 1) % capacity count -= 1 return first } mutating func increaseCapacity() { let countAtEndOfArray = capacity - firstIndex let countAtStartOfArray = count - countAtEndOfArray array.append(contentsOf: array[0..<countAtStartOfArray]) capacity *= 2 } }
mit
6ae865b9333a11126ca8a89d31dbe2d0
23.878049
64
0.57549
4.744186
false
false
false
false
64characters/Telephone
TelephoneTests/StoreViewSpy.swift
1
2617
// // StoreViewSpy.swift // Telephone // // Copyright © 2008-2016 Alexey Kuznetsov // Copyright © 2016-2022 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. // final class StoreViewSpy { private(set) var didCallShowPurchaseCheckProgress = false private(set) var invokedProducts: [PresentationProduct] = [] private(set) var invokedProductsFetchError = "" private(set) var didCallShowProductsFetchProgress = false private(set) var didCallShowPurchaseProgress = false private(set) var invokedPurchaseError = "" private(set) var didCallShowPurchaseRestorationProgress = false private(set) var invokedPurchaseRestorationError = "" private(set) var didCallDisablePurchaseRestoration = false private(set) var didCallEnablePurchaseRestoration = false private(set) var didCallShowPurchased = false private(set) var didCallShowSubscriptionManagement = false } extension StoreViewSpy: StoreView {} extension StoreViewSpy: StoreViewPresenterOutput { func showPurchaseCheckProgress() { didCallShowPurchaseCheckProgress = true } func show(_ products: [PresentationProduct]) { invokedProducts = products } func showProductsFetchError(_ error: String) { invokedProductsFetchError = error } func showProductsFetchProgress() { didCallShowProductsFetchProgress = true } func showPurchaseProgress() { didCallShowPurchaseProgress = true } func showPurchaseError(_ error: String) { invokedPurchaseError = error } func showPurchaseRestorationProgress() { didCallShowPurchaseRestorationProgress = true } func showPurchaseRestorationError(_ error: String) { invokedPurchaseRestorationError = error } func disablePurchaseRestoration() { didCallDisablePurchaseRestoration = true } func enablePurchaseRestoration() { didCallEnablePurchaseRestoration = true } func showPurchased(until date: Date) { didCallShowPurchased = true } func showSubscriptionManagement() { didCallShowSubscriptionManagement = true } }
gpl-3.0
4a1f132fcd1fdbdac4689d7f54fabcf7
28.382022
72
0.723518
4.780622
false
false
false
false
tnantoka/generative-swift
GenerativeSwift/Controllers/StupidAgentViewController.swift
1
3832
// // StupidAgentViewController.swift // GenerativeSwift // // Created by Tatsuya Tobioka on 4/21/16. // Copyright © 2016 tnantoka. All rights reserved. // import UIKit import C4 class StupidAgentViewController: BaseCanvasController { var point = Point(0, 0) var x = 0.0 var y = 0.0 var timer: Foundation.Timer? var step: Double { return 1.0 } let diameter = 1.0 var startItem: UIBarButtonItem! var stopItem: UIBarButtonItem! override init() { super.init() title = "Stupid Agent" trash = true } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() startItem = UIBarButtonItem(title: "Start", style: .plain, target: self, action: #selector(start)) stopItem = UIBarButtonItem(title: "Stop", style: .plain, target: self, action: #selector(stop)) let flexible = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil) toolbarItems = [flexible, startItem, flexible, stopItem, flexible] } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) navigationController?.setToolbarHidden(false, animated: true) stop() } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) stop() } override func setup() { let _ = canvas.addPanGestureRecognizer { locations, center, translation, velocity, state in self.point = center } clear() } func draw() { let speed = map(point.x, min: 0, max: canvas.width, toMin: 2, toMax: 100) var points = [Point]() (0..<Int(speed)).forEach { _ in let direction = Direction.random() switch direction { case .north: y -= step case .northEast: x += step y -= step case .east: x += step case .southEast: x += step y += step case .south: y += step case .southWest: x -= step y += step case .west: x -= step case .northWest: x -= step y -= step } if x > canvas.width - diameter { x = 0 } if x < 0 { x = canvas.width } if y > canvas.height - diameter { y = 0 } if y < 0 { y = canvas.height } // let circle = Circle(frame: Rect(x, y, diameter, diameter)) // circle.strokeColor = nil // circle.fillColor = Color(UIColor(white: 0.0, alpha: 0.4)) // canvas.add(circle) points.append(Point(x, y)) } let polygon = CirclePolygon(points, Size(diameter, diameter)) polygon.strokeColor = nil polygon.fillColor = Color(UIColor(white: 0.0, alpha: 0.4)) canvas.add(polygon) } func start() { startItem.isEnabled = false stopItem.isEnabled = true timer = Timer.scheduledTimer(timeInterval: 0.1, target: self, selector: #selector(draw), userInfo: nil, repeats: true) } func stop() { startItem.isEnabled = true stopItem.isEnabled = false timer?.invalidate() } override func clear() { super.clear() clearPoints() } func clearPoints() { point = canvas.center x = point.x y = point.y } }
apache-2.0
938e93fc3446f0c169cedae9dd1d94e7
26.170213
126
0.515009
4.571599
false
false
false
false
i-schuetz/SwiftCharts
Examples/AppDelegate.swift
1
4656
// // AppDelegate.swift // Examples // // Created by ischuetz on 08/05/15. // Copyright (c) 2015 ivanschuetz. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate, UISplitViewControllerDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { if UIDevice.current.userInterfaceIdiom == .pad { let splitViewController = self.window!.rootViewController as! UISplitViewController let navigationController = splitViewController.viewControllers.last as! UINavigationController splitViewController.delegate = self if #available(iOS 8.0, *) { navigationController.topViewController?.navigationItem.leftBarButtonItem = splitViewController.displayModeButtonItem } } 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: - Split view func splitViewController(_ splitViewController: UISplitViewController, collapseSecondary secondaryViewController:UIViewController, onto primaryViewController:UIViewController) -> Bool { if let secondaryAsNavController = secondaryViewController as? UINavigationController { if let topAsDetailController = secondaryAsNavController.topViewController as? DetailViewController { if topAsDetailController.detailItem == nil { // Return true to indicate that we have handled the collapse by doing nothing; the secondary controller will be discarded. return true } } } return false } fileprivate func setSplitSwipeEnabled(_ enabled: Bool) { if UIDevice.current.userInterfaceIdiom == UIUserInterfaceIdiom.pad { let splitViewController = UIApplication.shared.delegate?.window!!.rootViewController as! UISplitViewController splitViewController.presentsWithGesture = enabled } } func splitViewController(_ svc: UISplitViewController, willHide aViewController: UIViewController, with barButtonItem: UIBarButtonItem, for pc: UIPopoverController) { let navigationController = svc.viewControllers[svc.viewControllers.count-1] as! UINavigationController if let topAsDetailController = navigationController.topViewController as? DetailViewController { barButtonItem.title = "Examples" topAsDetailController.navigationItem.setLeftBarButton(barButtonItem, animated: true) } } } // src: http://stackoverflow.com/a/27399688/930450 extension UISplitViewController { func toggleMasterView() { if #available(iOS 8.0, *) { let barButtonItem = self.displayModeButtonItem UIApplication.shared.sendAction(barButtonItem.action!, to: barButtonItem.target, from: nil, for: nil) } } }
apache-2.0
73bd08099d684d6860e1a7d4ed8c0be9
47.5
285
0.718857
6.14248
false
false
false
false
phatblat/realm-cocoa
RealmSwift/Util.swift
1
7181
//////////////////////////////////////////////////////////////////////////// // // Copyright 2015 Realm Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////// import Foundation import Realm #if BUILDING_REALM_SWIFT_TESTS import RealmSwift #endif // MARK: Internal Helpers // Swift 3.1 provides fixits for some of our uses of unsafeBitCast // to use unsafeDowncast instead, but the bitcast is required. internal func noWarnUnsafeBitCast<T, U>(_ x: T, to type: U.Type) -> U { return unsafeBitCast(x, to: type) } /// Given a list of `Any`-typed varargs, unwrap any optionals and /// replace them with the underlying value or NSNull. internal func unwrapOptionals(in varargs: [Any]) -> [Any] { return varargs.map { arg in if let someArg = arg as Any? { return someArg } return NSNull() } } internal func notFoundToNil(index: UInt) -> Int? { if index == UInt(NSNotFound) { return nil } return Int(index) } internal func throwRealmException(_ message: String, userInfo: [AnyHashable: Any]? = nil) -> Never { NSException(name: NSExceptionName(rawValue: RLMExceptionName), reason: message, userInfo: userInfo).raise() fatalError() // unreachable } internal func throwForNegativeIndex(_ int: Int, parameterName: String = "index") { if int < 0 { throwRealmException("Cannot pass a negative value for '\(parameterName)'.") } } internal func gsub(pattern: String, template: String, string: String, error: NSErrorPointer = nil) -> String? { let regex = try? NSRegularExpression(pattern: pattern, options: []) return regex?.stringByReplacingMatches(in: string, options: [], range: NSRange(location: 0, length: string.utf16.count), withTemplate: template) } extension ObjectBase { // Must *only* be used to call Realm Objective-C APIs that are exposed on `RLMObject` // but actually operate on `RLMObjectBase`. Do not expose cast value to user. internal func unsafeCastToRLMObject() -> RLMObject { return noWarnUnsafeBitCast(self, to: RLMObject.self) } } internal func coerceToNil(_ value: Any) -> Any? { if value is NSNull { return nil } // nil in Any is bridged to obj-c as NSNull. In the obj-c code we usually // convert NSNull back to nil, which ends up as Optional<Any>.none if case Optional<Any>.none = value { return nil } return value } // MARK: CustomObjectiveCBridgeable /// :nodoc: public func dynamicBridgeCast<T>(fromObjectiveC x: Any) -> T { return failableDynamicBridgeCast(fromObjectiveC: x)! } /// :nodoc: @usableFromInline internal func failableDynamicBridgeCast<T>(fromObjectiveC x: Any) -> T? { if let value = x as? T { return value } else if T.self == DynamicObject.self { return unsafeBitCast(x as AnyObject, to: T.self) } else if let bridgeableType = T.self as? CustomObjectiveCBridgeable.Type { return bridgeableType.bridging(objCValue: x) as? T } else if let bridgeableType = T.self as? RealmEnum.Type { return bridgeableType._rlmFromRawValue(x).flatMap { $0 as? T } } else { return x as? T } } /// :nodoc: public func dynamicBridgeCast<T>(fromSwift x: T) -> Any { if let x = x as? CustomObjectiveCBridgeable { return x.objCValue } else if let bridgeableType = T.self as? RealmEnum.Type { return bridgeableType._rlmToRawValue(x) } else { return x } } // Used for conversion from Objective-C types to Swift types internal protocol CustomObjectiveCBridgeable { static func bridging(objCValue: Any) -> Self var objCValue: Any { get } } // `NSNumber as? Float` fails if the value can't be exactly represented as a float, // unlike the other NSNumber conversions extension Float: CustomObjectiveCBridgeable { internal static func bridging(objCValue: Any) -> Float { return (objCValue as! NSNumber).floatValue } internal var objCValue: Any { return NSNumber(value: self) } } extension Int8: CustomObjectiveCBridgeable { internal static func bridging(objCValue: Any) -> Int8 { return (objCValue as! NSNumber).int8Value } internal var objCValue: Any { return NSNumber(value: self) } } extension Int16: CustomObjectiveCBridgeable { internal static func bridging(objCValue: Any) -> Int16 { return (objCValue as! NSNumber).int16Value } internal var objCValue: Any { return NSNumber(value: self) } } extension Int32: CustomObjectiveCBridgeable { internal static func bridging(objCValue: Any) -> Int32 { return (objCValue as! NSNumber).int32Value } internal var objCValue: Any { return NSNumber(value: self) } } extension Int64: CustomObjectiveCBridgeable { internal static func bridging(objCValue: Any) -> Int64 { return (objCValue as! NSNumber).int64Value } internal var objCValue: Any { return NSNumber(value: self) } } extension Optional: CustomObjectiveCBridgeable { internal static func bridging(objCValue: Any) -> Optional { if objCValue as AnyObject is NSNull { return nil } return failableDynamicBridgeCast(fromObjectiveC: objCValue) } internal var objCValue: Any { if let value = self { return dynamicBridgeCast(fromSwift: value) } else { return NSNull() } } } extension Decimal128: CustomObjectiveCBridgeable { static func bridging(objCValue: Any) -> Decimal128 { if let number = objCValue as? NSNumber { return Decimal128(number: number) } if let str = objCValue as? String { return (try? Decimal128(string: str)) ?? Decimal128("nan") } return objCValue as! Decimal128 } var objCValue: Any { return self } } extension AnyRealmValue: CustomObjectiveCBridgeable { static func bridging(objCValue: Any) -> AnyRealmValue { if let any = objCValue as? RLMValue { return ObjectiveCSupport.convert(value: any) } throwRealmException("objCValue is not bridgeable to AnyRealmValue") } var objCValue: Any { return ObjectiveCSupport.convert(value: self) ?? NSNull() } } // MARK: AssistedObjectiveCBridgeable internal protocol AssistedObjectiveCBridgeable { static func bridging(from objectiveCValue: Any, with metadata: Any?) -> Self var bridged: (objectiveCValue: Any, metadata: Any?) { get } }
apache-2.0
e2055f8573361ea75b10dc4fc5d6dd0f
31.789954
111
0.654505
4.392049
false
false
false
false
zenangst/Faker
Source/Generators/Commerce.swift
1
1503
import Foundation public class Commerce: Generator { public func color() -> String { return generate("commerce.color") } public func department(maximum: Int = 3, fixedAmount: Bool = false) -> String { var amount = fixedAmount ? maximum : 1 + Int(arc4random_uniform(UInt32(maximum))) let fetchedCategories = categories(amount) let count = fetchedCategories.count var department = "" if count > 1 { department = mergeCategories(fetchedCategories) } else if count == 1 { department = fetchedCategories[0] } return department } public func productName() -> String { return generate("commerce.product_name.adjective") + " " + generate("commerce.product_name.material") + " " + generate("commerce.product_name.product") } public func price() -> Double { let arc4randoMax:Double = 0x100000000 return floor(Double((Double(arc4random()) / arc4randoMax) * 100.0) * 100) / 100.0 } // MARK: - Helpers func categories(amount: Int) -> [String] { var categories: [String] = [] while categories.count < amount { let category = generate("commerce.department") if !contains(categories, category) { categories.append(category) } } return categories } func mergeCategories(categories: [String]) -> String { let separator = generate("separator") let commaSeparated = ", ".join(categories[0..<categories.count - 1]) return commaSeparated + separator + categories.last! } }
mit
b4bf47fc8ff25e868efca54c6ad4f44e
27.358491
155
0.660679
4.106557
false
false
false
false
serp1412/LazyTransitions
LazyTransitions.playground/Sources/Helpers.swift
1
6371
import Foundation import UIKit public extension CGRect { public static var iphone6: CGRect { return CGRect(x: 0, y: 0, width: 750 / 2, height: 1334 / 2) } public static var iphone4: CGRect { return CGRect(x: 0, y: 0, width: 320, height: 480) } public static var ipad: CGRect { return CGRect(x: 0, y: 0, width: 1536 / 2, height: 2048 / 2) } public static var ipadLandscape: CGRect { return CGRect(x: 0, y: 0, width: 2048 / 2, height: 1536 / 2) } } public let images: [UIImage] = { return (0...26).map { UIImage(named: "\($0)")! } }() public let sectionInsets = UIEdgeInsets(top: 50.0, left: 20.0, bottom: 50.0, right: 20.0) public let itemsPerRow: CGFloat = 3 public class PhotoCell: UICollectionViewCell { public static let identifier = "PhotoCell" public let imageView = UIImageView() public override func layoutSubviews() { if imageView.superview == nil { addSubview(imageView) imageView.bindFrameToSuperviewBounds() } } } public class RowCell: UICollectionViewCell, UICollectionViewDelegateFlowLayout { public static let identifier = "RowCell" public let collectionView = UICollectionView(frame: .zero, collectionViewLayout: UICollectionViewFlowLayout()) public func setup() { collectionView.register(PhotoCell.self, forCellWithReuseIdentifier: PhotoCell.identifier) if collectionView.superview == nil { addSubview(collectionView) collectionView.bindFrameToSuperviewBounds() } let layout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout layout.scrollDirection = .horizontal collectionView.dataSource = self collectionView.delegate = self collectionView.backgroundColor = .white } } extension RowCell: UICollectionViewDataSource { public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return 5 } public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: PhotoCell.identifier, for: indexPath) as! PhotoCell cell.backgroundColor = UIColor.white cell.imageView.image = images.randomElement()! return cell } public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { return CGSize(width: collectionView.frame.height, height: collectionView.frame.height) } public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets { return sectionInsets } public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat { return sectionInsets.left } } public extension UIView { public func bindFrameToSuperviewBounds() { guard let superview = self.superview else { print("Error! `superview` was nil – call `addSubview(view: UIView)` before calling `bindFrameToSuperviewBounds()` to fix this.") return } translatesAutoresizingMaskIntoConstraints = false topAnchor.constraint(equalTo: superview.topAnchor, constant: 0).isActive = true bottomAnchor.constraint(equalTo: superview.bottomAnchor, constant: 0).isActive = true leadingAnchor.constraint(equalTo: superview.leadingAnchor, constant: 0).isActive = true trailingAnchor.constraint(equalTo: superview.trailingAnchor, constant: 0).isActive = true } } public extension UIView { public func bindToSuperviewCenter() { guard let superview = self.superview else { print("Error! `superview` was nil – call `addSubview(view: UIView)` before calling `bindFrameToSuperviewBounds()` to fix this.") return } translatesAutoresizingMaskIntoConstraints = false centerXAnchor.constraint(equalTo: superview.centerXAnchor).isActive = true centerYAnchor.constraint(equalTo: superview.centerYAnchor).isActive = true } } public extension UIButton { public static var tapMe: UIButton { let button = UIButton(type: .system) button.backgroundColor = UIColor.red button.setTitle("Tap me!", for: .normal) button.setTitleColor(.white, for: .normal) button.translatesAutoresizingMaskIntoConstraints = false button.heightAnchor.constraint(equalToConstant: 200.0).isActive = true button.widthAnchor.constraint(equalToConstant: 200.0).isActive = true button.layer.cornerRadius = 200 / 2 return button } } public class BackgroundViewController <T: UIViewController>: UIViewController, UINavigationControllerDelegate { public var screenToPresent: T.Type! var action: ((UIViewController, UIViewController) -> ())! public static func instantiate(with screen: T.Type, action: @escaping (_ presented: UIViewController, _ presenting: UIViewController) -> ()) -> BackgroundViewController { let backVC = BackgroundViewController() backVC.action = action backVC.screenToPresent = screen return backVC } public override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = .white let button = UIButton.tapMe view.addSubview(button) button.bindToSuperviewCenter() button.addTarget(self, action: #selector(triggerAction), for: .touchUpInside) } @objc func triggerAction() { action(screenToPresent.init(), self) } public func navigationController(_ navigationController: UINavigationController, willShow viewController: UIViewController, animated: Bool) { } public func navigationController(_ navigationController: UINavigationController, didShow viewController: UIViewController, animated: Bool) { } }
bsd-2-clause
8e4df6782a77e272113f584f51c8a19f
37.587879
177
0.682425
5.451199
false
false
false
false
OscarSwanros/swift
test/decl/func/static_func.swift
2
6473
// RUN: %target-typecheck-verify-swift static func gf1() {} // expected-error {{static methods may only be declared on a type}}{{1-8=}} class func gf2() {} // expected-error {{class methods may only be declared on a type}}{{1-7=}} override static func gf3() {} // expected-error {{static methods may only be declared on a type}}{{10-17=}} // expected-error@-1 {{'override' can only be specified on class members}}{{1-10=}} override class func gf4() {} // expected-error {{class methods may only be declared on a type}}{{10-16=}} // expected-error@-1 {{'override' can only be specified on class members}}{{1-10=}} static override func gf5() {} // expected-error {{static methods may only be declared on a type}}{{1-8=}} // expected-error@-1 {{'override' can only be specified on class members}}{{8-17=}} class override func gf6() {} // expected-error {{class methods may only be declared on a type}}{{1-7=}} // expected-error@-1 {{'override' can only be specified on class members}}{{7-16=}} static gf7() {} // expected-error {{expected declaration}} expected-error {{closure expression is unused}} expected-error{{begin with a closure}} expected-note{{did you mean to use a 'do' statement?}} {{14-14=do }} class gf8() {} // expected-error {{expected '{' in class}} expected-error {{closure expression is unused}} expected-error{{begin with a closure}} expected-note{{did you mean to use a 'do' statement?}} {{13-13=do }} func inGlobalFunc() { static func gf1() {} // expected-error {{static methods may only be declared on a type}}{{3-10=}} class func gf2() {} // expected-error {{class methods may only be declared on a type}}{{3-9=}} } struct InMemberFunc { func member() { static func gf1() {} // expected-error {{static methods may only be declared on a type}}{{5-12=}} class func gf2() {} // expected-error {{class methods may only be declared on a type}}{{5-11=}} } } struct DuplicateStatic { static static func f1() {} // expected-error{{'static' specified twice}}{{10-17=}} static class func f2() {} // expected-error{{'class' specified twice}}{{10-16=}} class static func f3() {} // expected-error{{'static' specified twice}}{{9-16=}} expected-error{{class methods are only allowed within classes; use 'static' to declare a static method}}{{3-8=static}} class class func f4() {} // expected-error{{'class' specified twice}}{{9-15=}} expected-error{{class methods are only allowed within classes; use 'static' to declare a static method}}{{3-8=static}} override static static func f5() {} // expected-error{{'static' specified twice}}{{19-26=}} expected-error{{'override' can only be specified on class members}} {{3-12=}} static override static func f6() {} // expected-error{{'static' specified twice}}{{19-26=}} expected-error{{'override' can only be specified on class members}} {{10-19=}} static static override func f7() {} // expected-error{{'static' specified twice}}{{10-17=}} expected-error{{'override' can only be specified on class members}} {{17-26=}} static final func f8() {} // expected-error {{only classes and class members may be marked with 'final'}} } struct S { // expected-note {{extended type declared here}} static func f1() {} class func f2() {} // expected-error {{class methods are only allowed within classes; use 'static' to declare a static method}} {{3-8=static}} } extension S { static func ef1() {} class func ef2() {} // expected-error {{class methods are only allowed within classes; use 'static' to declare a static method}} {{3-8=static}} } enum E { // expected-note {{extended type declared here}} static func f1() {} class func f2() {} // expected-error {{class methods are only allowed within classes; use 'static' to declare a static method}} {{3-8=static}} static final func f3() {} // expected-error {{only classes and class members may be marked with 'final'}} } extension E { static func f4() {} class func f5() {} // expected-error {{class methods are only allowed within classes; use 'static' to declare a static method}} {{3-8=static}} } class C { static func f1() {} // expected-note 3{{overridden declaration is here}} class func f2() {} class func f3() {} class func f4() {} // expected-note {{overridden declaration is here}} class func f5() {} // expected-note {{overridden declaration is here}} static final func f6() {} // expected-error {{static declarations are already final}} {{10-16=}} final class func f7() {} // expected-note 3{{overridden declaration is here}} } extension C { static func ef1() {} class func ef2() {} // expected-note {{overridden declaration is here}} class func ef3() {} // expected-note {{overridden declaration is here}} class func ef4() {} // expected-note {{overridden declaration is here}} class func ef5() {} // expected-note {{overridden declaration is here}} } class C_Derived : C { override static func f1() {} // expected-error {{cannot override static method}} override class func f2() {} class override func f3() {} override class func ef2() {} // expected-error {{overriding declarations from extensions is not supported}} class override func ef3() {} // expected-error {{overriding declarations from extensions is not supported}} override static func f7() {} // expected-error {{static method overrides a 'final' class method}} } class C_Derived2 : C { override final class func f1() {} // expected-error {{cannot override static method}} override final class func f7() {} // expected-error {{class method overrides a 'final' class method}} } class C_Derived3 : C { override class func f1() {} // expected-error {{cannot override static method}} override class func f7() {} // expected-error {{class method overrides a 'final' class method}} } extension C_Derived { override class func f4() {} // expected-error {{overriding declarations in extensions is not supported}} class override func f5() {} // expected-error {{overriding declarations in extensions is not supported}} override class func ef4() {} // expected-error {{overriding declarations in extensions is not supported}} class override func ef5() {} // expected-error {{overriding declarations in extensions is not supported}} } protocol P { static func f1() static func f2() static func f3() {} // expected-error {{protocol methods must not have bodies}} static final func f4() // expected-error {{only classes and class members may be marked with 'final'}} }
apache-2.0
b469c89f9161cb49c14202b819e8b121
55.780702
214
0.687162
3.983385
false
false
false
false
jwfriese/FrequentFlyer
FrequentFlyer/ObjectMapperExtension/StrictBoolTransform.swift
1
984
import ObjectMapper import Foundation.NSData public struct StrictBoolTransform: TransformType { public typealias Object = Bool public typealias JSON = String public func transformFromJSON(_ value: Any?) -> Bool? { if let stringValue = value as? String { if stringValue == "true" { return true } else if stringValue == "false" { return false } return nil } guard let numberValue = value as? NSNumber else { return nil } guard type(of: numberValue) != type(of: NSNumber(integerLiteral: 1)) else { return nil } guard type(of: numberValue) == type(of: NSNumber(booleanLiteral: true)) else { return nil } return value as? Bool } public func transformToJSON(_ value: Bool?) -> String? { guard let value = value else { return nil } return value ? "true" : "false" } }
apache-2.0
d7fe14a1fb1fa87d9245dacde2f7b788
27.941176
79
0.566057
4.969697
false
false
false
false
SASAbus/SASAbus-ios
SASAbus/Util/Extensions/UIScreenExtension.swift
1
405
import Foundation extension UIScreen { var isPhone4: Bool { return self.nativeBounds.size.height == 960; } var isPhone5: Bool { return self.nativeBounds.size.height == 1136; } var isPhone6: Bool { return self.nativeBounds.size.height == 1334; } var isPhone6Plus: Bool { return self.nativeBounds.size.height == 2208; } }
gpl-3.0
fcb9d107de13882d13e58d5f766498dd
19.25
53
0.592593
4.263158
false
false
false
false
k0nserv/SwiftTracer
Pods/SwiftTracer-Core/Sources/Geometry/Plane.swift
1
951
// // Plane.swift // SwiftTracer // // Created by Hugo Tunius on 09/08/15. // Copyright © 2015 Hugo Tunius. All rights reserved. // import Foundation public class Plane { public let position: Vector public let normal: Vector public let material: Material public init(position: Vector, normal: Vector, material: Material) { self.position = position self.normal = normal self.material = material } } extension Plane : Shape { public func intersectWithRay(ray: Ray) -> Intersection? { let denominator = normal.dot(ray.direction) if abs(denominator) < 1e-5 { return nil } let t = (position - ray.origin).dot(normal) / denominator if t >= 1e-5 { let intersectionPoint = ray.origin + ray.direction * t return Intersection(t: t, point: intersectionPoint, normal: normal, shape: self) } return nil } }
mit
841881d4bec4fbc42ffb5849f657c339
22.75
92
0.614737
4.059829
false
false
false
false
sandorgyulai/InAppFramework
InAppFw/InAppFw.swift
1
12032
// The MIT License (MIT) // // Copyright (c) 2015 Sándor Gyulai // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. import UIKit import StoreKit extension Notification.Name { static let iapPurchased = Notification.Name("IAPPurchasedNotification") static let iapFailed = Notification.Name("IAPFailedNotification") } open class InAppFw: NSObject, SKProductsRequestDelegate, SKPaymentTransactionObserver{ public static let sharedInstance = InAppFw() var productIdentifiers: Set<String>? var productsRequest: SKProductsRequest? var completionHandler: ((_ success: Bool, _ products: [SKProduct]?) -> Void)? var purchasedProductIdentifiers = Set<String>() fileprivate var hasValidReceipt = false public override init() { super.init() SKPaymentQueue.default().add(self) productIdentifiers = Set<String>() } /** Add a single product ID - Parameter id: Product ID in string format */ open func addProduct(_ id: String) { productIdentifiers?.insert(id) } /** Add multiple product IDs - Parameter ids: Set of product ID strings you wish to add */ open func addProducts(_ ids: Set<String>) { productIdentifiers?.formUnion(ids) } /** Load purchased products - Parameter checkWithApple: True if you want to validate the purchase receipt with Apple servers */ open func loadPurchasedProducts(validate: Bool, completion: ((_ valid: Bool) -> Void)?) { if let productIdentifiers = productIdentifiers { for productIdentifier in productIdentifiers { let isPurchased = UserDefaults.standard.bool(forKey: productIdentifier) if isPurchased { purchasedProductIdentifiers.insert(productIdentifier) print("Purchased: \(productIdentifier)") } else { print("Not purchased: \(productIdentifier)") } } if validate { print("Checking with Apple...") if let completion = completion { validateReceipt(false, completion: completion) } else { validateReceipt(false) { (valid) -> Void in if valid { print("Receipt is Valid!") } else { print("BEWARE! Reciept is not Valid!!!") } } } } } } fileprivate func validateReceipt(_ sandbox: Bool, completion: @escaping (_ valid: Bool) -> Void) { let url = Bundle.main.appStoreReceiptURL let receipt = try? Data(contentsOf: url!) if let r = receipt { let receiptData = r.base64EncodedString(options: NSData.Base64EncodingOptions()) let requestContent = [ "receipt-data" : receiptData ] do { let requestData = try JSONSerialization.data(withJSONObject: requestContent, options: JSONSerialization.WritingOptions()) let storeURL = URL(string: "https://buy.itunes.apple.com/verifyReceipt") let sandBoxStoreURL = URL(string: "https://sandbox.itunes.apple.com/verifyReceipt") guard let finalURL = sandbox ? sandBoxStoreURL : storeURL else { return } var storeRequest = URLRequest(url: finalURL) storeRequest.httpMethod = "POST" storeRequest.httpBody = requestData let task = URLSession.shared.dataTask(with: storeRequest, completionHandler: { [weak self] (data, response, error) -> Void in if (error != nil) { print("Validation Error: \(String(describing: error))") self?.hasValidReceipt = false completion(false) } else { self?.checkStatus(with: data, completion: completion) } }) task.resume() } catch { print("validateReceipt: Caught error serializing response JSON") } } else { hasValidReceipt = false completion(false) } } fileprivate func checkStatus(with data: Data?, completion: @escaping (_ valid: Bool) -> Void) { do { if let data = data, let jsonResponse = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions()) as? [String: AnyObject] { if let status = jsonResponse["status"] as? Int { if status == 0 { print("Status: VALID") hasValidReceipt = true completion(true) } else if status == 21007 { print("Status: CHECK WITH SANDBOX") validateReceipt(true, completion: completion) } else { print("Status: INVALID") hasValidReceipt = false completion(false) } } } } catch { print("checkStatus: Caught error") } } /** Request products from Apple */ open func requestProducts(_ completionHandler: @escaping (_ success:Bool, _ products:[SKProduct]?) -> Void) { self.completionHandler = completionHandler print("Requesting Products") if let productIdentifiers = productIdentifiers { productsRequest = SKProductsRequest(productIdentifiers: productIdentifiers) productsRequest!.delegate = self productsRequest!.start() } else { print("No productIdentifiers") completionHandler(false, nil) } } /** Initiate purchase for the product - Parameter product: The product you want to purchase */ open func purchase(_ product: SKProduct) { print("Purchasing product: \(product.productIdentifier)") let payment = SKPayment(product: product) SKPaymentQueue.default().add(payment) } /** Check if the product with identifier is already purchased */ open func checkPurchase(for productIdentifier: String) -> (isPurchased: Bool, hasValidReceipt: Bool) { let purchased = purchasedProductIdentifiers.contains(productIdentifier) return (purchased, hasValidReceipt) } /** Begin to start restoration of already purchased products */ open func restoreCompletedTransactions() { SKPaymentQueue.default().restoreCompletedTransactions() } //MARK: - Transactions fileprivate func completeTransaction(_ transaction: SKPaymentTransaction) { print("Complete Transaction...") provideContentForProductIdentifier(transaction.payment.productIdentifier) SKPaymentQueue.default().finishTransaction(transaction) } fileprivate func restoreTransaction(_ transaction: SKPaymentTransaction) { print("Restore Transaction...") provideContentForProductIdentifier(transaction.original!.payment.productIdentifier) SKPaymentQueue.default().finishTransaction(transaction) } fileprivate func failedTransaction(_ transaction: SKPaymentTransaction) { print("Failed Transaction...") SKPaymentQueue.default().finishTransaction(transaction) NotificationCenter.default.post(name: .iapPurchased, object: nil, userInfo: nil) } fileprivate func provideContentForProductIdentifier(_ productIdentifier: String!) { purchasedProductIdentifiers.insert(productIdentifier) UserDefaults.standard.set(true, forKey: productIdentifier) UserDefaults.standard.synchronize() NotificationCenter.default.post(name: .iapFailed, object: productIdentifier, userInfo: nil) } // MARK: - Delegate Implementations open func paymentQueue(_ queue: SKPaymentQueue, updatedTransactions transactions: [SKPaymentTransaction]) { for transaction:AnyObject in transactions { if let trans = transaction as? SKPaymentTransaction { switch trans.transactionState { case .purchased: completeTransaction(trans) break case .failed: failedTransaction(trans) break case .restored: restoreTransaction(trans) break default: break } } } } open func productsRequest(_ request: SKProductsRequest, didReceive response: SKProductsResponse) { print("Loaded product list!") productsRequest = nil let skProducts = response.products for skProduct in skProducts { print("Found product: \(skProduct.productIdentifier) - \(skProduct.localizedTitle) - \(skProduct.price)") } if let completionHandler = completionHandler { completionHandler(true, skProducts) } completionHandler = nil } open func request(_ request: SKRequest, didFailWithError error: Error) { print("Failed to load list of products!") productsRequest = nil if let completionHandler = completionHandler { completionHandler(false, nil) } completionHandler = nil } //MARK: - Helpers /** Check if the user can make purchase */ open func canMakePurchase() -> Bool { return SKPaymentQueue.canMakePayments() } //MARK: - Class Functions /** Format the price for the given locale - Parameter price: The price you want to format - Parameter locale: The price locale you want to format with - Returns: The formatted price */ open class func formatPrice(_ price: NSNumber, locale: Locale) -> String { var formattedString = "" let numberFormatter = NumberFormatter() numberFormatter.formatterBehavior = NumberFormatter.Behavior.behavior10_4 numberFormatter.numberStyle = NumberFormatter.Style.currency numberFormatter.locale = locale formattedString = numberFormatter.string(from: price)! return formattedString } }
mit
401af4589bd7c811ca3abd68e32dc0f9
34.594675
166
0.585072
5.903337
false
false
false
false
salemoh/GoldenQuraniOS
GoldenQuranSwift/Pods/GRDB.swift/GRDB/FTS/FTS3Pattern.swift
1
7688
/// A full text pattern that can query FTS3 and FTS4 virtual tables. public struct FTS3Pattern { /// The raw pattern string. Guaranteed to be a valid FTS3/4 pattern. public let rawPattern: String /// Creates a pattern from a raw pattern string; throws DatabaseError on /// invalid syntax. /// /// The pattern syntax is documented at https://www.sqlite.org/fts3.html#full_text_index_queries /// /// try FTS3Pattern(rawPattern: "and") // OK /// try FTS3Pattern(rawPattern: "AND") // malformed MATCH expression: [AND] public init(rawPattern: String) throws { // Correctness above all: use SQLite to validate the pattern. // // Invalid patterns have SQLite return an error on the first // call to sqlite3_step() on a statement that matches against // that pattern. do { try DatabaseQueue().inDatabase { db in try db.execute("CREATE VIRTUAL TABLE documents USING fts3()") try db.execute("SELECT * FROM documents WHERE content MATCH ?", arguments: [rawPattern]) } } catch let error as DatabaseError { // Remove private SQL & arguments from the thrown error throw DatabaseError(resultCode: error.extendedResultCode, message: error.message, sql: nil, arguments: nil) } // Pattern is valid self.rawPattern = rawPattern } #if USING_CUSTOMSQLITE || USING_SQLCIPHER /// Creates a pattern that matches any token found in the input string; /// returns nil if no pattern could be built. /// /// FTS3Pattern(matchingAnyTokenIn: "") // nil /// FTS3Pattern(matchingAnyTokenIn: "foo bar") // foo OR bar /// /// - parameter string: The string to turn into an FTS3 pattern public init?(matchingAnyTokenIn string: String) { let tokens = FTS3TokenizerDescriptor.simple.tokenize(string) guard !tokens.isEmpty else { return nil } try? self.init(rawPattern: tokens.joined(separator: " OR ")) } /// Creates a pattern that matches all tokens found in the input string; /// returns nil if no pattern could be built. /// /// FTS3Pattern(matchingAllTokensIn: "") // nil /// FTS3Pattern(matchingAllTokensIn: "foo bar") // foo bar /// /// - parameter string: The string to turn into an FTS3 pattern public init?(matchingAllTokensIn string: String) { let tokens = FTS3TokenizerDescriptor.simple.tokenize(string) guard !tokens.isEmpty else { return nil } try? self.init(rawPattern: tokens.joined(separator: " ")) } /// Creates a pattern that matches a contiguous string; returns nil if no /// pattern could be built. /// /// FTS3Pattern(matchingPhrase: "") // nil /// FTS3Pattern(matchingPhrase: "foo bar") // "foo bar" /// /// - parameter string: The string to turn into an FTS3 pattern public init?(matchingPhrase string: String) { let tokens = FTS3TokenizerDescriptor.simple.tokenize(string) guard !tokens.isEmpty else { return nil } try? self.init(rawPattern: "\"" + tokens.joined(separator: " ") + "\"") } #else /// Creates a pattern that matches any token found in the input string; /// returns nil if no pattern could be built. /// /// FTS3Pattern(matchingAnyTokenIn: "") // nil /// FTS3Pattern(matchingAnyTokenIn: "foo bar") // foo OR bar /// /// - parameter string: The string to turn into an FTS3 pattern @available(iOS 8.2, OSX 10.10, *) public init?(matchingAnyTokenIn string: String) { let tokens = FTS3TokenizerDescriptor.simple.tokenize(string) guard !tokens.isEmpty else { return nil } try? self.init(rawPattern: tokens.joined(separator: " OR ")) } /// Creates a pattern that matches all tokens found in the input string; /// returns nil if no pattern could be built. /// /// FTS3Pattern(matchingAllTokensIn: "") // nil /// FTS3Pattern(matchingAllTokensIn: "foo bar") // foo bar /// /// - parameter string: The string to turn into an FTS3 pattern @available(iOS 8.2, OSX 10.10, *) public init?(matchingAllTokensIn string: String) { let tokens = FTS3TokenizerDescriptor.simple.tokenize(string) guard !tokens.isEmpty else { return nil } try? self.init(rawPattern: tokens.joined(separator: " ")) } /// Creates a pattern that matches a contiguous string; returns nil if no /// pattern could be built. /// /// FTS3Pattern(matchingPhrase: "") // nil /// FTS3Pattern(matchingPhrase: "foo bar") // "foo bar" /// /// - parameter string: The string to turn into an FTS3 pattern @available(iOS 8.2, OSX 10.10, *) public init?(matchingPhrase string: String) { let tokens = FTS3TokenizerDescriptor.simple.tokenize(string) guard !tokens.isEmpty else { return nil } try? self.init(rawPattern: "\"" + tokens.joined(separator: " ") + "\"") } #endif } extension FTS3Pattern : DatabaseValueConvertible { /// Returns a value that can be stored in the database. public var databaseValue: DatabaseValue { return rawPattern.databaseValue } /// Returns an FTS3Pattern initialized from *databaseValue*, if it contains /// a suitable value. public static func fromDatabaseValue(_ databaseValue: DatabaseValue) -> FTS3Pattern? { return String .fromDatabaseValue(databaseValue) .flatMap { try? FTS3Pattern(rawPattern: $0) } } } extension QueryInterfaceRequest { // MARK: Full Text Search /// Returns a new QueryInterfaceRequest with a matching predicate added /// to the eventual set of already applied predicates. /// /// // SELECT * FROM books WHERE books MATCH '...' /// var request = Book.all() /// request = request.matching(pattern) /// /// If the search pattern is nil, the request does not match any /// database row. public func matching(_ pattern: FTS3Pattern?) -> QueryInterfaceRequest<T> { switch query.source { case .table(let name, let alias)?: return filter(SQLExpressionBinary(.match, Column(alias ?? name), pattern ?? DatabaseValue.null)) default: // Programmer error fatalError("fts3 match requires a table") } } } extension TableMapping { // MARK: Full Text Search /// Returns a QueryInterfaceRequest with a matching predicate. /// /// // SELECT * FROM books WHERE books MATCH '...' /// var request = Book.matching(pattern) /// /// If the `selectsRowID` type property is true, then the selection includes /// the hidden "rowid" column: /// /// // SELECT *, rowid FROM books WHERE books MATCH '...' /// var request = Book.matching(pattern) /// /// If the search pattern is nil, the request does not match any /// database row. public static func matching(_ pattern: FTS3Pattern?) -> QueryInterfaceRequest<Self> { return all().matching(pattern) } } extension Column { /// A matching SQL expression with the `MATCH` SQL operator. /// /// // content MATCH '...' /// Column("content").match(pattern) /// /// If the search pattern is nil, SQLite will evaluate the expression /// to false. public func match(_ pattern: FTS3Pattern?) -> SQLExpression { return SQLExpressionBinary(.match, self, pattern ?? DatabaseValue.null) } }
mit
50fc59c45ce52a20cdafa86623420d40
39.463158
119
0.62487
4.482799
false
false
false
false
filmhomage/swift_tutorial
swift_tutorial/Util/SWProgress.swift
1
1842
// // SWProgress.swift // swift_tutorial // // Created by JonghyunKim on 5/18/16. // Copyright © 2016 kokaru.com. All rights reserved. // import Foundation import UIKit import MBProgressHUD class SWProgress : NSObject { static let sharedInstance = SWProgress() override init() { print("SWProgress init!") } func showProgress() { self.hideProgress() let hud = MBProgressHUD.showHUDAddedTo(UIApplication.topViewController()!.view, animated: true) hud.mode = MBProgressHUDMode.Indeterminate hud.color = colorOrange hud.alpha = 0.95 hud.minSize = CGSize(width: 100.0, height:100.0) } func showProgress(labelText : String?) { self.hideProgress() let hud = MBProgressHUD.showHUDAddedTo(UIApplication.topViewController()!.view, animated: true) hud.mode = MBProgressHUDMode.Indeterminate hud.color = colorOrange hud.alpha = 0.95 hud.minSize = CGSize(width: 100.0, height:100.0) hud.labelText = labelText } func showProgress(labelText: String?, mode: MBProgressHUDMode = MBProgressHUDMode.Indeterminate, alpha: CGFloat = 0.95, color: UIColor = UIColor.redColor(), backgroundColor: UIColor, minsize: CGSize = CGSize(width: 100.0, height: 100.0)) { self.hideProgress() let hud = MBProgressHUD.showHUDAddedTo(UIApplication.topViewController()!.view, animated: true) hud.mode = mode hud.color = color hud.alpha = alpha hud.minSize = minsize hud.labelText = labelText } func hideProgress () { MBProgressHUD .hideHUDForView(UIApplication.topViewController()!.view, animated: true) } }
mit
46e9540d8dfb0295560d67ce7108e571
30.220339
103
0.614883
4.732648
false
false
false
false
Mars182838/WJCycleScrollView
WJCycleScrollView/Extentions/UIDeviceExtensions.swift
3
6793
// // UIDeviceExtensions.swift // EZSwiftExtensions // // Created by Goktug Yilmaz on 15/07/15. // Copyright (c) 2015 Goktug Yilmaz. All rights reserved. // import UIKit /// EZSwiftExtensions private let DeviceList = [ /* iPod 5 */ "iPod5,1": "iPod Touch 5", /* iPod 6 */ "iPod7,1": "iPod Touch 6", /* iPhone 4 */ "iPhone3,1": "iPhone 4", "iPhone3,2": "iPhone 4", "iPhone3,3": "iPhone 4", /* iPhone 4S */ "iPhone4,1": "iPhone 4S", /* iPhone 5 */ "iPhone5,1": "iPhone 5", "iPhone5,2": "iPhone 5", /* iPhone 5C */ "iPhone5,3": "iPhone 5C", "iPhone5,4": "iPhone 5C", /* iPhone 5S */ "iPhone6,1": "iPhone 5S", "iPhone6,2": "iPhone 5S", /* iPhone 6 */ "iPhone7,2": "iPhone 6", /* iPhone 6 Plus */ "iPhone7,1": "iPhone 6 Plus", /* iPhone 6S */ "iPhone8,1": "iPhone 6S", /* iPhone 6S Plus */ "iPhone8,2": "iPhone 6S Plus", /* iPad 2 */ "iPad2,1": "iPad 2", "iPad2,2": "iPad 2", "iPad2,3": "iPad 2", "iPad2,4": "iPad 2", /* iPad 3 */ "iPad3,1": "iPad 3", "iPad3,2": "iPad 3", "iPad3,3": "iPad 3", /* iPad 4 */ "iPad3,4": "iPad 4", "iPad3,5": "iPad 4", "iPad3,6": "iPad 4", /* iPad Air */ "iPad4,1": "iPad Air", "iPad4,2": "iPad Air", "iPad4,3": "iPad Air", /* iPad Air 2 */ "iPad5,3": "iPad Air 2", "iPad5,4": "iPad Air 2", /* iPad Mini */ "iPad2,5": "iPad Mini", "iPad2,6": "iPad Mini", "iPad2,7": "iPad Mini", /* iPad Mini 2 */ "iPad4,4": "iPad Mini 2", "iPad4,5": "iPad Mini 2", "iPad4,6": "iPad Mini 2", /* iPad Mini 3 */ "iPad4,7": "iPad Mini 3", "iPad4,8": "iPad Mini 3", "iPad4,9": "iPad Mini 3", /* iPad Mini 4 */ "iPad5,1": "iPad Mini 4", "iPad5,2": "iPad Mini 4", /* iPad Pro */ "iPad6,7": "iPad Pro", "iPad6,8": "iPad Pro", /* AppleTV */ "AppleTV5,3": "AppleTV", /* Simulator */ "x86_64": "Simulator", "i386": "Simulator" ] extension UIDevice { /// EZSwiftExtensions public class func idForVendor() -> String? { return UIDevice.currentDevice().identifierForVendor?.UUIDString } /// EZSwiftExtensions - Operating system name public class func systemName() -> String { return UIDevice.currentDevice().systemName } /// EZSwiftExtensions - Operating system version public class func systemVersion() -> String { return UIDevice.currentDevice().systemVersion } /// EZSwiftExtensions - Operating system version public class func systemFloatVersion() -> Float { return (systemVersion() as NSString).floatValue } /// EZSwiftExtensions public class func deviceName() -> String { return UIDevice.currentDevice().name } /// EZSwiftExtensions public class func deviceLanguage() -> String { return NSBundle.mainBundle().preferredLocalizations[0] } /// EZSwiftExtensions public class func deviceModelReadable() -> String { return DeviceList[deviceModel()] ?? deviceModel() } /// EZSE: Returns true if the device is iPhone //TODO: Add to readme public class func isPhone() -> Bool { return UIDevice.currentDevice().userInterfaceIdiom == UIUserInterfaceIdiom.Phone } /// EZSE: Returns true if the device is iPad //TODO: Add to readme public class func isPad() -> Bool { return UIDevice.currentDevice().userInterfaceIdiom == UIUserInterfaceIdiom.Pad } /// EZSwiftExtensions public class func deviceModel() -> String { var systemInfo = utsname() uname(&systemInfo) let machine = systemInfo.machine var identifier = "" let mirror = Mirror(reflecting: machine) for child in mirror.children { let value = child.value if let value = value as? Int8 where value != 0 { identifier.append(UnicodeScalar(UInt8(value))) } } return identifier } //TODO: Fix syntax, add docs and readme for these methods: //TODO: Delete isSystemVersionOver() // MARK: - Device Version Checks public enum Versions: Float { case Five = 5.0 case Six = 6.0 case Seven = 7.0 case Eight = 8.0 case Nine = 9.0 } public class func isVersion(version: Versions) -> Bool { return systemFloatVersion() >= version.rawValue && systemFloatVersion() < (version.rawValue + 1.0) } public class func isVersionOrLater(version: Versions) -> Bool { return systemFloatVersion() >= version.rawValue } public class func isVersionOrEarlier(version: Versions) -> Bool { return systemFloatVersion() < (version.rawValue + 1.0) } public class var CURRENT_VERSION: String { return "\(systemFloatVersion())" } // MARK: iOS 5 Checks public class func IS_OS_5() -> Bool { return isVersion(.Five) } public class func IS_OS_5_OR_LATER() -> Bool { return isVersionOrLater(.Five) } public class func IS_OS_5_OR_EARLIER() -> Bool { return isVersionOrEarlier(.Five) } // MARK: iOS 6 Checks public class func IS_OS_6() -> Bool { return isVersion(.Six) } public class func IS_OS_6_OR_LATER() -> Bool { return isVersionOrLater(.Six) } public class func IS_OS_6_OR_EARLIER() -> Bool { return isVersionOrEarlier(.Six) } // MARK: iOS 7 Checks public class func IS_OS_7() -> Bool { return isVersion(.Seven) } public class func IS_OS_7_OR_LATER() -> Bool { return isVersionOrLater(.Seven) } public class func IS_OS_7_OR_EARLIER() -> Bool { return isVersionOrEarlier(.Seven) } // MARK: iOS 8 Checks public class func IS_OS_8() -> Bool { return isVersion(.Eight) } public class func IS_OS_8_OR_LATER() -> Bool { return isVersionOrLater(.Eight) } public class func IS_OS_8_OR_EARLIER() -> Bool { return isVersionOrEarlier(.Eight) } // MARK: iOS 9 Checks public class func IS_OS_9() -> Bool { return isVersion(.Nine) } public class func IS_OS_9_OR_LATER() -> Bool { return isVersionOrLater(.Nine) } public class func IS_OS_9_OR_EARLIER() -> Bool { return isVersionOrEarlier(.Nine) } /// EZSwiftExtensions public class func isSystemVersionOver(requiredVersion: String) -> Bool { switch systemVersion().compare(requiredVersion, options: NSStringCompareOptions.NumericSearch) { case .OrderedSame, .OrderedDescending: //println("iOS >= 8.0") return true case .OrderedAscending: //println("iOS < 8.0") return false } } }
mit
40fb3d504aa97210a4db10315faf63e5
30.742991
109
0.582511
3.831359
false
false
false
false
emilstahl/swift
validation-test/compiler_crashers_fixed/1299-resolvetypedecl.swift
10
451
// RUN: not %target-swift-frontend %s -parse // REQUIRES: asserts // 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<b : b, d : b where b.d == d> { } class i: d{ class func f {} func c<i>() -> (i, i -> i) -> i { k b k.i = { } { i) { k } } protocol c { } class k: c{ class func i { } }lass func c() } var x1 = 1 =1 as a=1
apache-2.0
c544641b2c1ef7b4c2a1e56a7575570a
17.04
87
0.607539
2.684524
false
true
false
false
Pursuit92/antlr4
runtime/Swift/Antlr4/org/antlr/v4/runtime/misc/DoubleKeyMap.swift
3
1943
/* Copyright (c) 2012-2016 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. */ /** Sometimes we need to map a key to a value but key is two pieces of data. * This nested hash table saves creating a single key each time we access * map; avoids mem creation. */ public struct DoubleKeyMap<Key1:Hashable, Key2:Hashable, Value> { private var data: HashMap<Key1, HashMap<Key2, Value>> = HashMap<Key1, HashMap<Key2, Value>>() @discardableResult public mutating func put(_ k1: Key1, _ k2: Key2, _ v: Value) -> Value? { var data2 = data[k1] var prev: Value? = nil if data2 == nil { data2 = HashMap<Key2, Value>() } else { prev = data2![k2] } data2![k2] = v data[k1] = data2 return prev } public func get(_ k1: Key1, _ k2: Key2) -> Value? { if let data2 = data[k1] { return data2[k2] } return nil } public func get(_ k1: Key1) -> HashMap<Key2, Value>? { return data[k1] } // /** Get all values associated with primary key */ // public func values(k1: Key1) -> LazyMapCollection<[Key2:Value], Value>? { // let data2: Dictionary<Key2, Value>? = data[k1] // if data2 == nil { // return nil // } // return data2!.values // } // // /** get all primary keys */ // public func keySet() -> LazyMapCollection<Dictionary<Key1, Dictionary<Key2, Value>>, Key1> { // return data.keys // } // // /** get all secondary keys associated with a primary key */ // public func keySet(k1: Key1) -> LazyMapCollection<[Key2:Value], Key2>? { // let data2: Dictionary<Key2, Value>? = data[k1] // if data2 == nil { // return nil // } // return data2!.keys // } }
bsd-3-clause
cac17fa04524a227fc13b1da9cc445bc
28.439394
98
0.566135
3.414763
false
false
false
false
devedbox/AXAnimationChain
AXAnimationChain/Classes/Swifty/AXCoreAnimations.swift
1
1884
// // AXDecayAnimation+Extensions.swift // AXAnimationChain // // Created by devedbox on 2017/4/1. // Copyright © 2017年 devedbox. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. import AXAnimationChainSwift extension AXDecayAnimation { convenience public init(velocity: CGFloat, deceleration: CGFloat = 0.998, value: Any) { self.init() self.velocity = velocity self.deceleration = deceleration self.fromValue = value } } extension AXSpringAnimation { convenience public init(mass: CGFloat = 1.0, stiffness: CGFloat = 100.0, damping: CGFloat = 10.0, initialVelocity: CGFloat = 0.0) { self.init() self.mass = mass self.stiffness = stiffness self.damping = damping self.initialVelocity = initialVelocity } }
mit
5a4894973c2bc7eb87c2f16e2710e908
39.021277
135
0.715045
4.374419
false
false
false
false
FutureWorkshops/Notifiable-iOS
Sample/Sample/ViewController.swift
1
7859
// // ViewController.swift // Sample // // Created by Igor Fereira on 25/01/2016. // Copyright © 2016 Future Workshops. All rights reserved. // import UIKit import FWTNotifiable import SVProgressHUD import UserNotifications class ViewController: UIViewController { let FWTDeviceListSegue = "FWTDeviceListSegue" lazy var manager:NotifiableManager! = { let manager = NotifiableManager(groupId: kAppGroupId, session: URLSession.shared, didRegister: { [weak self] (_, token) in self?.registerCompleted?(token as NSData) }, didRecieve: nil) manager.logger = kLogger manager.retryAttempts = 0 return manager }() typealias FWTRegisterCompleted = (NSData)->Void; var registerCompleted:FWTRegisterCompleted? @IBOutlet weak var onSiteSwitch: UISwitch! override func viewDidLoad() { super.viewDidLoad() self.updateScreen() } func updateScreen() { guard let information = self.manager?.currentDevice?.properties?["onsite"] as? NSNumber else { onSiteSwitch.isOn = false return } onSiteSwitch.isOn = information.boolValue } } //MARK - Register extension ViewController { @IBAction func registerAnonymous(sender: AnyObject) { self._registerForNotifications { [weak self] (token) in self?._registerAnonymousToken(token: token) } } @IBAction func registerToUser(sender: AnyObject) { let alertController = UIAlertController(title: "User", message: "Please, insert the user name", preferredStyle: .alert) alertController.addTextField { $0.placeholder = "User Name" } alertController.addAction(UIAlertAction(title: "Cancel", style: .default, handler: nil)) alertController.addAction(UIAlertAction(title: "Ok", style: .default) { [weak self] (alertAction) -> Void in guard let userName = alertController.textFields?.first?.text else { return } self?._registerWithUser(user: userName) }) self.present(alertController, animated: true, completion: nil) } private func _registerWithUser(user:String) { self._registerForNotifications { [weak self] (token) -> Void in self?._registerToken(token: token, user: user) } } private func _registerAnonymousToken(token:NSData) { let deviceName = UIDevice.current.name self.manager.register(name: deviceName, locale: nil, properties: nil) { (device, error) in if let error = error { SVProgressHUD.showError(withStatus: error.localizedDescription) } else { SVProgressHUD.showSuccess(withStatus: "Anonymous device registered") } } } private func _registerToken(token:NSData, user:String) { let deviceName = UIDevice.current.name self.manager.register(name: deviceName, userAlias: user, locale: nil, properties: nil) { (device, error) in if let error = error { SVProgressHUD.showError(withStatus: error.localizedDescription) } else { SVProgressHUD.showSuccess(withStatus: "Device registered to user \(user)") } } } private func _registerForNotifications(completion:@escaping FWTRegisterCompleted) { self.registerCompleted = completion SVProgressHUD.show() UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound]) { (authorized, error) in guard authorized else { SVProgressHUD.showError(withStatus: error?.localizedDescription ?? "Permission not granted") return } DispatchQueue.main.async { UIApplication.shared.registerForRemoteNotifications() } } } } extension ViewController { @IBAction func associateToUser(sender: AnyObject) { let alertController = UIAlertController(title: "User", message: "Please, insert the user name", preferredStyle: .alert) alertController.addTextField { $0.placeholder = "User Name" } alertController.addAction(UIAlertAction(title: "Cancel", style: .default, handler: nil)) alertController.addAction(UIAlertAction(title: "Ok", style: .default) { [weak self] (alertAction) -> Void in guard let userName = alertController.textFields?.first?.text else { return } self?._associateToUser(user: userName) }) self.present(alertController, animated: true, completion: nil) } private func _associateToUser(user:String) { SVProgressHUD.show(withStatus: nil) self.manager.associated(to: user, completion: { (device, error) -> Void in if let error = error { SVProgressHUD.showError(withStatus: error.localizedDescription) } else { SVProgressHUD.showSuccess(withStatus: "Device associated with the user \(user)") } }) } @IBAction func anonymiseDevice(sender: AnyObject) { SVProgressHUD.show(withStatus: nil) self.manager.anonymise { (device, error) -> Void in if let error = error { SVProgressHUD.showError(withStatus: error.localizedDescription) } else { SVProgressHUD.showSuccess(withStatus: "Device is now anonymous") } } } } //MARK - Update extension ViewController { @IBAction func updateDeviceName(sender: AnyObject) { let alertController = UIAlertController(title: "Device Name", message: "Please, insert the device name", preferredStyle: .alert) alertController.addTextField { $0.placeholder = "Device Name" } alertController.addAction(UIAlertAction(title: "Cancel", style: .default, handler: nil)) alertController.addAction(UIAlertAction(title: "Ok", style: .default) { [weak self] (alertAction) -> Void in guard let deviceName = alertController.textFields?.first?.text else { return } self?._updateDeviceName(name: deviceName) }) self.present(alertController, animated: true, completion: nil) } @IBAction func updateOnSite(sender: UISwitch) { let onSite = sender.isOn let deviceInformation = ["onsite":NSNumber(value: onSite)] SVProgressHUD.show(withStatus: nil) self.manager.update(properties: deviceInformation) { [weak self] (device, error) in if let error = error { SVProgressHUD.showError(withStatus: error.localizedDescription) } else { SVProgressHUD.showSuccess(withStatus: "On site updated") } self?.updateScreen() } } private func _updateDeviceName(name:String) { SVProgressHUD.show(withStatus: nil) self.manager.update(name: name) { (device, error) -> Void in if let error = error { SVProgressHUD.showError(withStatus: error.localizedDescription) } else { SVProgressHUD.showSuccess(withStatus: "Device name updated to \(name)") } } } } //MARK - Unregister extension ViewController { @IBAction func unregisterDevice(sender: AnyObject) { SVProgressHUD.show(withStatus: nil) self.manager.unregister { (device, error) -> Void in if let error = error { SVProgressHUD.showError(withStatus: error.localizedDescription) } else { SVProgressHUD.showSuccess(withStatus: "Device unregistered") } } } }
apache-2.0
a9e04808dc8c0009f2cedb700335d9d0
36.241706
136
0.620769
4.989206
false
false
false
false
ephread/Instructions
Sources/Instructions/Managers/Internal/OverlayStyleManager/BlurringOverlayStyleManager.swift
2
7036
// Copyright (c) 2017-present Frédéric Maquin <[email protected]> and contributors. // Licensed under the terms of the MIT License. import UIKit /// The idea is simple: /// /// 1. Snapshot what's behind the overlay twice (let's call those foreground and background). /// 2. Blur them (Hypothetical improvement -> pre-render the foregorund overlay) /// 3. Show them on top of one another, the foreground one will hold the mask /// displaying the cutout. /// 4. Fade out the background to make it look it the cutout is appearing. /// /// All that work because UIVisualEffectView doesn't support: /// /// 1. Opacity animation /// 2. Mask animation /// /// TODO: Look for ways to improve everything, I'm fairly confident we can optimize /// a bunch of things. class BlurringOverlayStyleManager: OverlayStyleManager { // MARK: Properties weak var overlayView: OverlayView? { didSet { sizeTransitionOverlay = UIVisualEffectView(effect: blurEffect) sizeTransitionOverlay?.translatesAutoresizingMaskIntoConstraints = false sizeTransitionOverlay?.isHidden = true overlayView?.holder.addSubview(sizeTransitionOverlay!) sizeTransitionOverlay?.fillSuperview() } } /// Will provide shapshot to use for animations involving blurs. weak var snapshotDelegate: Snapshottable? // MARK: Private Properties /// Basic blurring overlay used during size transitions private var sizeTransitionOverlay: UIView? /// Subview holding the actual bunch. private var subOverlay: UIView? /// Foreground and background overlay. private var cutoutOverlays: (background: OverlaySnapshotView, foreground: OverlaySnapshotView)? // `true` is a size change is on going, `false` otherwise. private var onGoingTransition = false // Used to mask the `foreground`, thus showing the cutout. private var mask: MaskView { let view = MaskView() view.backgroundColor = UIColor.clear guard let overlay = self.overlayView, let cutoutPath = self.overlayView?.cutoutPath else { return view } let path = UIBezierPath(rect: overlay.bounds) path.append(cutoutPath) path.usesEvenOddFillRule = true view.shapeLayer.path = path.cgPath view.shapeLayer.fillRule = CAShapeLayerFillRule.evenOdd return view } private var blurEffect: UIVisualEffect { return UIBlurEffect(style: style) } private let style: UIBlurEffect.Style private var isOverlayHidden: Bool = true // MARK: Initialization init(style: UIBlurEffect.Style) { self.style = style } // MARK: OverlayStyleManager func viewWillTransition() { onGoingTransition = true guard let overlay = overlayView else { return } overlay.holder.subviews.forEach { if $0 !== sizeTransitionOverlay { $0.removeFromSuperview() } } sizeTransitionOverlay?.isHidden = false } func viewDidTransition() { onGoingTransition = false } func showOverlay(_ show: Bool, withDuration duration: TimeInterval, completion: ((Bool) -> Void)?) { sizeTransitionOverlay?.isHidden = true let subviews = overlayView?.holder.subviews setUpOverlay() guard let overlay = overlayView, let subOverlay = subOverlay as? UIVisualEffectView else { completion?(false) return } overlay.isHidden = false overlay.alpha = 1.0 subOverlay.frame = overlay.bounds subOverlay.effect = (show || isOverlayHidden) ? nil : blurEffect subviews?.forEach { if $0 !== sizeTransitionOverlay { $0.removeFromSuperview() } } overlay.holder.addSubview(subOverlay) UIView.animate(withDuration: duration, animations: { subOverlay.effect = show ? self.blurEffect : nil overlay.ornaments.alpha = show ? 1.0 : 0.0 self.isOverlayHidden = !show }, completion: { success in if !show { subOverlay.removeFromSuperview() overlay.alpha = 0.0 } completion?(success) }) } func showCutout(_ show: Bool, withDuration duration: TimeInterval, completion: ((Bool) -> Void)?) { if onGoingTransition { return } let subviews = overlayView?.holder.subviews setUpOverlay() sizeTransitionOverlay?.isHidden = true guard let overlay = overlayView, let background = cutoutOverlays?.background, let foreground = cutoutOverlays?.foreground else { completion?(false) return } background.frame = overlay.bounds foreground.frame = overlay.bounds background.visualEffectView.effect = show ? self.blurEffect : nil foreground.visualEffectView.effect = self.blurEffect foreground.mask = self.mask subviews?.forEach { if $0 !== sizeTransitionOverlay { $0.removeFromSuperview() } } overlay.holder.addSubview(background) overlay.holder.addSubview(foreground) UIView.animate(withDuration: duration, animations: { if duration > 0 { background.visualEffectView?.effect = show ? nil : self.blurEffect } }, completion: { success in background.removeFromSuperview() completion?(success) }) } func updateStyle(with traitCollection: UITraitCollection) { overlayView?.setNeedsDisplay() } // MARK: Private methods private func setUpOverlay() { guard let cutoutOverlays = self.makeSnapshotOverlays() else { return } self.cutoutOverlays = cutoutOverlays subOverlay = UIVisualEffectView(effect: blurEffect) subOverlay?.translatesAutoresizingMaskIntoConstraints = false } private func makeSnapshotView() -> OverlaySnapshotView? { guard let overlayView = overlayView, let snapshot = snapshotDelegate?.snapshot() else { return nil } let view = OverlaySnapshotView(frame: overlayView.bounds) let backgroundEffectView = UIVisualEffectView(effect: blurEffect) backgroundEffectView.frame = overlayView.bounds backgroundEffectView.translatesAutoresizingMaskIntoConstraints = false view.translatesAutoresizingMaskIntoConstraints = false view.backgroundView = snapshot view.visualEffectView = backgroundEffectView return view } private func makeSnapshotOverlays() -> (background: OverlaySnapshotView, foreground: OverlaySnapshotView)? { guard let background = makeSnapshotView(), let foreground = makeSnapshotView() else { return nil } return (background: background, foreground: foreground) } }
mit
7ded0294136a5694a29557db93b94fd4
32.655502
104
0.644726
5.36128
false
false
false
false
wendyabrantes/WAPullToShare
WAPullToShare/WAPullToShare.swift
1
11469
// // ITPullToShare.swift // ITPullToShareExample // // Created by Wendy Abrantes on 25/10/2015. // Copyright © 2015 Wendy Abrantes. All rights reserved. // import UIKit enum WAPullToShareButtonType : Int{ case googlePlus case pinterest case twitter case facebook func iconNormal() -> UIImage{ switch self { case .googlePlus: return WAPullToShareStyleKit.imageOfGooglePlus case .pinterest: return WAPullToShareStyleKit.imageOfPinterest case .twitter: return WAPullToShareStyleKit.imageOfTwitter case .facebook: return WAPullToShareStyleKit.imageOfFacebook } } } public class WAPullToShareScrollView : UIScrollView, UIScrollViewDelegate { public var containerBackgroundColor : UIColor = UIColor(red: 0.238, green: 0.238, blue: 0.238, alpha: 1.000) public var circleSelectionColor : UIColor = UIColor(red: 0.227, green: 0.569, blue: 1.000, alpha: 1.000) public var buttonTintColor : UIColor = UIColor.whiteColor() let circleSize : CGFloat = 60.0 let iconSize : CGFloat = 48.0 let buttonViewHeight : CGFloat = 300 var containerView = UIView() var icons : [UIButton] = [] var isLayoutSubview = false var pullThresholdValue : CGFloat = -60 var circleLayer = CAShapeLayer() var iconSelectedIndex : Int = 0 //var block selectedItem var buttonSelectedCallback:((UIButton, WAPullToShareButtonType) -> Void)? override init(frame: CGRect) { super.init(frame: frame) setupLayout() } convenience init(){ self.init(frame: CGRect.zero) } public required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func addShareIcons(iconTypes: [WAPullToShareButtonType]){ icons = [] for iconType in iconTypes { let btn = UIButton() btn.tag = iconType.hashValue btn.tintColor = buttonTintColor btn.setImage(iconType.iconNormal(), forState: UIControlState.Normal) btn.tintColor = UIColor.whiteColor() //btn.setImage(UIImage(named: iconType.iconSelected()), forState: UIControlState.Selected) containerView.addSubview(btn) icons += [btn] } } public override func layoutSubviews() { super.layoutSubviews() if !isLayoutSubview { containerView.frame.size = CGSize(width: frame.width, height: buttonViewHeight) var index = 0 let btnWidth = containerView.frame.width / CGFloat(icons.count) for btn in icons { btn.frame = CGRect( x: CGFloat(index)*btnWidth, y: containerView.frame.height - (circleSize), width: btnWidth, height: iconSize) index++ } isLayoutSubview = true } } func setupLayout(){ delegate = self alwaysBounceVertical = true contentInset = UIEdgeInsetsMake(-buttonViewHeight, 0, 0, 0) circleLayer.anchorPoint = CGPointMake(0.5, 0.5) circleLayer.frame = CGRectMake(0, 0, circleSize, circleSize) circleLayer.path = circleCurrentPath().CGPath circleLayer.fillColor = circleSelectionColor.CGColor circleLayer.zPosition = -1 containerView.layer.addSublayer(circleLayer) panGestureRecognizer.maximumNumberOfTouches = 1 panGestureRecognizer.addTarget(self, action: Selector("panGestureHandler:")) containerView.backgroundColor = containerBackgroundColor containerView.layer.masksToBounds = true addSubview(containerView) } let threshold : CGFloat = 30.0 var isAnimating = false func panGestureHandler(gesture: UIPanGestureRecognizer) { let location = gesture.locationInView(self) let translation = gesture.translationInView(self) let offsetY = contentOffset.y + contentInset.top if gesture.state == UIGestureRecognizerState.Began || gesture.state == UIGestureRecognizerState.Changed { if offsetY <= pullThresholdValue { var index = 0 var newIndex : Int = -1 for btn in icons { if CGRectContainsPoint(btn.frame, CGPoint(x: location.x, y: btn.frame.origin.y)) { newIndex = index } index++ } if iconSelectedIndex == -1 && newIndex != -1{ circleLayer.position = CGPointMake( (icons[newIndex].center.x), icons[newIndex].center.y) iconSelectedIndex = newIndex } circleAppear() //change bezier path shape left /right if !isAnimating && iconSelectedIndex != -1 { //25px pan before deforming leftOffset = min((translation.x+30)/2,0) leftOffset = max(leftOffset, -threshold) rightOffset = max((translation.x-30)/2,0) rightOffset = min(rightOffset, threshold) circleLayer.path = circleCurrentPath().CGPath circleLayer.position = CGPointMake( (icons[iconSelectedIndex].center.x) + leftOffset/5 + rightOffset/5, circleLayer.position.y) } //only after if !isAnimating && (rightOffset >= threshold || leftOffset <= -threshold){ if newIndex != iconSelectedIndex { NSLog("animated trigger") isAnimating = true //animate to nex index gesture.setTranslation(CGPointMake(0,translation.y), inView: self) iconSelectedIndex = newIndex animateToIndex() } } // }else{ resetPanGestureTranslation() deselectItem() } } if gesture.state == UIGestureRecognizerState.Ended || gesture.state == UIGestureRecognizerState.Cancelled { if offsetY <= pullThresholdValue { //trigger selected selectItem() }else{ //reset deselectItem() } } } var currentPoint : CGPoint = CGPointZero var leftOffset: CGFloat = 0.0 var rightOffset: CGFloat = 0.0 var leftPoint : CGPoint! var topPoint : CGPoint! var rightPoint : CGPoint! var bottomPoint : CGPoint! /// circle animation func animateToIndex(){ isAnimating = true self.rightOffset = 0 self.leftOffset = 0 let layerAnimation = CABasicAnimation(keyPath: "position") layerAnimation.fromValue = NSValue(CGPoint:circleLayer.position) layerAnimation.toValue = NSValue(CGPoint:CGPointMake(icons[iconSelectedIndex].center.x, icons[iconSelectedIndex].center.y)) circleLayer.position = CGPointMake(icons[iconSelectedIndex].center.x, icons[iconSelectedIndex].center.y) let pathAnimation = CABasicAnimation(keyPath: "path") pathAnimation.fromValue = circleLayer.path pathAnimation.toValue = circleCurrentPath().CGPath circleLayer.path = circleCurrentPath().CGPath let groupAnimation = CAAnimationGroup() groupAnimation.duration = 0.3 groupAnimation.animations = [layerAnimation, pathAnimation] groupAnimation.delegate = self groupAnimation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseOut) circleLayer.addAnimation(groupAnimation, forKey: "selectedIndex") } public override func animationDidStart(anim: CAAnimation) { } public override func animationDidStop(anim: CAAnimation, finished flag: Bool) { self.rightOffset = 0 self.leftOffset = 0 resetPanGestureTranslation() isAnimating = false } func resetPanGestureTranslation(){ let translation = panGestureRecognizer.translationInView(self) panGestureRecognizer.setTranslation(CGPointMake(0, translation.y), inView: self) } func circleCurrentPath() -> UIBezierPath { leftPoint = CGPoint(x: leftOffset, y: circleSize/2) rightPoint = CGPoint(x: circleSize+rightOffset, y: circleSize/2) //direction left right if fabs(leftOffset) > fabs(rightOffset){ topPoint = CGPoint(x: circleSize/2 + rightOffset, y: 0) bottomPoint = CGPoint(x: circleSize/2 + rightOffset, y: circleSize) }else{ topPoint = CGPoint(x: circleSize/2 + leftOffset, y: 0) bottomPoint = CGPoint(x: circleSize/2 + leftOffset, y: circleSize) } //control point let controlPointLeft : CGFloat = topPoint.x - leftPoint.x let controlPointRight : CGFloat = rightPoint.x - topPoint.x let path = UIBezierPath() path.moveToPoint(leftPoint) //top path.addCurveToPoint( topPoint, controlPoint1: CGPoint(x: leftPoint.x, y: leftPoint.y - (controlPointLeft/2)), controlPoint2: CGPoint(x: topPoint.x - (controlPointLeft/2), y: topPoint.y)) //right path.addCurveToPoint( rightPoint, controlPoint1: CGPoint(x: topPoint.x + (controlPointRight/2), y: topPoint.y), controlPoint2: CGPoint(x: rightPoint.x, y: rightPoint.y - (controlPointRight/2))) //bottom path.addCurveToPoint( bottomPoint, controlPoint1: CGPoint(x: rightPoint.x, y: rightPoint.y + (controlPointRight/2)), controlPoint2: CGPoint(x: bottomPoint.x + (controlPointRight/2), y: bottomPoint.y)) //left path.addCurveToPoint( leftPoint, controlPoint1: CGPoint(x: bottomPoint.x - (controlPointLeft/2), y: bottomPoint.y ), controlPoint2: CGPoint(x: leftPoint.x, y: leftPoint.y + (controlPointLeft/2))) path.closePath() return path } func circleAppear(){ circleLayer.transform = CATransform3DMakeScale(1.0, 1.0, 0.0) circleLayer.opacity = 1.0 } func circleDisappear(){ circleLayer.transform = CATransform3DMakeScale(0.0, 0.0, 0.0) circleLayer.opacity = 0.0 } func selectItem(){ let transform = circleLayer.transform circleLayer.transform = CATransform3DScale(transform, 10.0, 10.0, 0.0) if iconSelectedIndex != -1 && buttonSelectedCallback != nil { buttonSelectedCallback!( icons[iconSelectedIndex], WAPullToShareButtonType(rawValue: icons[iconSelectedIndex].tag)!) } } func deselectItem(){ iconSelectedIndex = -1 circleLayer.transform = CATransform3DMakeScale(0.0, 0.0, 0.0) circleLayer.opacity = 0.0 } }
mit
f7e769d0cbb0ce585776712ce3e02d4d
33.542169
147
0.586066
5.255729
false
false
false
false
thierryH91200/Charts-log
Charts-log/Demos/DateValueFormatter.swift
1
812
// // DateValueFormatter.swift // graphPG // // Created by thierryH24A on 20/09/2016. // Copyright © 2016 thierryH24A. All rights reserved. // import Foundation import Charts open class DateValueFormatter : NSObject, IAxisValueFormatter { var dateFormatter : DateFormatter var miniTime :Double public init(miniTime: Double) { //super.init() self.miniTime = miniTime self.dateFormatter = DateFormatter() self.dateFormatter.dateFormat = "dd/MM" dateFormatter.timeZone = NSTimeZone(abbreviation: "GMT+0:00") as TimeZone! } public func stringForValue(_ value: Double, axis: AxisBase?) -> String { let date2 = Date(timeIntervalSince1970 : (value * 3600 * 24) + miniTime) return dateFormatter.string(from: date2) } }
apache-2.0
86c621a24eb216e98e649e6498589fec
26.033333
82
0.667078
4.034826
false
false
false
false
devpunk/velvet_room
Source/Model/Vita/MVitaLinkStrategyRequestItemTreatElements.swift
1
983
import Foundation final class MVitaLinkStrategyRequestItemTreatElements:MVitaLinkStrategyRequestItemTreatProtocol { //MARK: internal func success( strategy:MVitaLinkStrategyRequestItemTreat) { let data:Data = strategy.data let counterSize:Int = MemoryLayout<UInt32>.size guard let rawCountElements:UInt32 = data.valueFromBytes() else { strategy.failed() return } let countElements:Int = Int(rawCountElements) let subData:Data = data.subdata( start:counterSize) guard let itemElements:[UInt32] = subData.arrayFromBytes( elements:countElements) else { strategy.failed() return } strategy.itemElementsReceived( itemElements:itemElements) } }
mit
5256052938869d7f1cbc14243e1b6960
21.860465
95
0.538149
5.585227
false
false
false
false
jadbox/ASwiftPromise
ASwiftPromise/Promise.swift
1
7022
// ASwiftPromise // // Promise.swift // TestSwf // // Created by Jonathan Dunlap on 6/4/14. // Copyright (c) 2014 Jonathan Dunlap. All rights reserved. // //typealias FS = T->(); import Foundation operator prefix <= {} // shortcut for assignments operator prefix >= {} // shortcut for forEach operator prefix >>= {} // shortcut for map operator prefix %= {} // shortcut for filter //operator prefix +{} // shortcut for merge, not needed to be defined extension Observable { /* func print() -> () { forEach() { println( String( $0 ) ); } }*/ // Map elements from the stream func map<K>( f:(T)->K ) -> Observable<K> { var p = Observable<K>(isCold:isCold) // Hot on() { (v:T)->() in p.val = f(v) }; return p; } // Reduce the stream func fold<K>( f:(T, K)->K, var total:K ) -> Observable<K> { var p = Observable<K>(isCold:isCold) // Hot on() { total = f($0, total); p.val = total; } return p; } // Filter elements from the stream func filter( f:(T)->Bool ) -> Observable<T> { var p = Observable<T>(isCold:isCold) // Hot on() { (v:T)->() in if(f(v)) { p.val = v } }; return p; } // Merge two streams together func merge<K>( f:Observable<K> ) -> Observable<(T,K)> { var p = Observable<(T,K)>(isCold:isCold); var myCurrent:T? var fCurrent:K? on() { if myCurrent && fCurrent { p.val = ($0,fCurrent!); } else { for b in f.history { p.val = ($0,b); } } myCurrent = $0; } f.on() { if fCurrent && myCurrent { p.val = (myCurrent!, $0); } else { for b in self.history { p.val = (b, $0); } } fCurrent = $0; } return p; } func forEach(f:(T)->()) -> Observable<T> { on(f); return self; } // Produce a future with an array of values that slide from the last N values // Slides are always hot func slideBy( n:Int ) -> Observable<[T]> { var fu = Observable<[T]>(isCold:isCold); var list:[T] = []; on() { list += $0; if(list.count >= n) { let start = list.count - n; let end = list.count; list = Array(list[start..<end]); fu.val = list; } } return fu; } } class FNode<T> { // function node typealias F = (T)->(); var f:F; var once:Bool = false var next:FNode<T>?; var prev:FNode<T>?; var isHead:Bool=false; // workaround for compiler head comparison bug init(cb:F, once:Bool=false) { self.f = cb; self.once = once; } } class FLL<T> { // function link list typealias F = (T)->(); var head:FNode<T>?; func forEachCall(t:T) { var current = head; do { if let node = current { node.f(t); current = node.next; if(node.once) { removeNode(node); } } else { break; } } while(true); } func removeNode(n:FNode<T>) { if let p = n.prev { p.next = n.next; // it's fine that n has no next node (option type); } n.next = nil; n.prev = nil; // compiler bug http://stackoverflow.com/questions/24668210/swift-using-if-on-an-enum-resulting-in-error-not-convertible-to-arraycastkind if(n.isHead) { head = nil; } } func add(f:F, once:Bool=false) { var c = head; head = FNode(cb:f, once:once); head!.isHead = true; head!.next = c; if c { c!.prev = head; c!.isHead = false; } } func removeAll()->() { var current = head; do { if let node = current { node.prev = nil; // break circles current = node.next; } else { break; } } while(true); head=nil; // chop the head } init() {} } @assignment func +=<T> (inout left: FLL<T>, right: (T)->()) { left.add(right); } class Observable<T> { // : Future<T> var _onSet:FLL<T> = FLL<T>(); var history:[T] = []; var isCold = false; var val:T? = nil { didSet { if isCold || history.count == 0 { history += val!; } else { history[0] = val!; } _onSet.forEachCall(val!); } } init(isCold:Bool=false) { self.isCold = isCold; } deinit { } // Call the handler only once func once( t:(T)->() )->Observable<T> { _onSet.add(t, once:true); return self; } func removeAllListeners() { _onSet.removeAll(); } func removeHistory() { history = []; } func on( t:(T)->() )->Observable<T> { if isCold { for s in history { t(s); } //replay history } _onSet += t; return self; } func clone()->Observable<T> { return Observable<T>(isCold: isCold); } } @assignment func <=<T> (inout left: Observable<T>, right: T) { left.val = right; } @infix @assignment func >=<T> (inout left: Observable<T>, right: (T)->()) -> Observable<T> { left.forEach(right); return left; } @infix func >>=<T,K> (left: Observable<T>, right: (T)->(K)) -> Observable<K> { return left.map(right); } @infix func %=<T> (left: Observable<T>, right: (T)->(Bool)) -> Observable<T> { return left.filter(right); } @infix func +<T,K> (left: Observable<T>, right: Observable<K>) -> Observable<(T,K)> { return left.merge(right); } // Promises encapsolate two Observables for success and fail class Promise<T,F> { let success:Observable<T>; let errors:Observable<F>; func subscribe(data:(T)->(), err:(F)->()) { onData(data).onFail(err); } func onData(f:(T)->()) -> Promise<T,F> { success.on(f); return self; } func onFail(f:(F)->()) -> Promise<T,F> { errors.on(f); return self; } func send(e:T) { success.val = e; } func fail(e:F) { errors.val = e; } init(isCold:Bool=false) { success = Observable<T>(isCold:isCold); errors = Observable<F>(isCold:isCold); } } // Shorthand for success handlers on the promise @infix func >=<T,F> (left: Promise<T,F>, right: (T)->()) -> Observable<T> { left.success.forEach(right); return left.success; } @infix func >>=<T,F,K> (left: Promise<T,F>, right: (T)->(K)) -> Observable<K> { return left.success >>= right; } @infix func %=<T,F> (left: Promise<T,F>, right: (T)->(Bool)) -> Observable<T> { return left.success %= right; } @infix func <=<T,F> (left: Promise<T,F>, right: T) { left.success.val = right; }
mit
f86d774efa169b39702bdea83a740f8a
25.69962
145
0.489889
3.502244
false
false
false
false
armadsen/Oxygen
Sources/MainViewController.swift
1
1668
// // ViewController.swift // Oxygen // // Created by Andrew Madsen on 7/21/15. // Copyright (c) 2015 Open Reel Software. All rights reserved. // import Cocoa import ORSSerial import Observable import CorePlot class MainViewController: NSViewController, CPTPlotDataSource { private let monitorController = OxygenMonitorController(ORSSerialPort(path: "/dev/cu.KeySerial1")!) override func viewDidLoad() { self.monitorController.allReadings.afterChange.add(owner: self) { (_) in if let reading = self.monitorController.allReadings.value.last { self.oxygenLabel.stringValue = String(reading.oxygen) self.heartRateLabel.stringValue = String(reading.heartRate) } } let graph = CPTXYGraph(frame: self.graphView.bounds, xScaleType: .Linear, yScaleType: .Linear) self.oxygenPlot = CPTScatterPlot(frame: graph.bounds) self.oxygenPlot?.dataSource = self graph.addPlot(oxygenPlot) self.graphView.hostedGraph = graph } // MARK: - CPTPlotDataSource func numberOfRecordsForPlot(plot: CPTPlot) -> UInt { return UInt(self.monitorController.allReadings.value.count) } // func numberForPlot(plot: CPTPlot, field fieldEnum: UInt, recordIndex idx: UInt) -> AnyObject? { // switch let field = CPTScatterPlotField(rawValue: Int(fieldEnum)) { // case .X: // return idx + 1 // case .Y: // let readings = self.monitorController.allReadings.value // return readings[idx].oxygen // } // return nil // } // MARK: - Properties private var oxygenPlot: CPTScatterPlot? @IBOutlet weak var oxygenLabel: NSTextField! @IBOutlet weak var heartRateLabel: NSTextField! @IBOutlet weak var graphView: CPTGraphHostingView! }
mit
71939a0ce3ef8278dc713ba1a28d1f78
27.271186
100
0.736211
3.257813
false
false
false
false
acalvomartinez/RandomUser
RandomUser/GetUsersResult.swift
1
706
// // GetUsersResult.swift // RandomUser // // Created by Toni on 29/06/2017. // Copyright © 2017 Antonio Calvo. All rights reserved. // import Foundation struct GetUsersResult { let page: Int let results: Int let users: [User] } extension GetUsersResult: JSONDecodable { init?(dictionary: JSONDictionary) { guard let infoJSON = dictionary["info"] as? JSONDictionary, let page = infoJSON["page"] as? Int, let results = infoJSON["results"] as? Int, let usersJSONArray = dictionary["results"] as? [JSONDictionary] else { return nil } self.page = page self.results = results self.users = JSONDecoder.decode(usersJSONArray) ?? [] } }
apache-2.0
0ae441e426b3af5a9fcffcd21a2c36a6
21.741935
69
0.655319
3.810811
false
false
false
false
sleekbyte/tailor
src/test/swift/com/sleekbyte/tailor/grammar/AutomaticReferenceCounting.swift
1
2178
class Person { let name: String init(name: String) { self.name = name print("\(name) is being initialized") } deinit { print("\(name) is being deinitialized") } } class Person { let name: String init(name: String) { self.name = name } var apartment: Apartment? deinit { print("\(name) is being deinitialized") } } class Apartment { let number: Int init(number: Int) { self.number = number } var tenant: Person? deinit { print("Apartment #\(number) is being deinitialized") } } class Customer { let name: String var card: CreditCard? init(name: String) { self.name = name } deinit { print("\(name) is being deinitialized") } } class CreditCard { let number: UInt64 unowned let customer: Customer init(number: UInt64, customer: Customer) { self.number = number self.customer = customer } deinit { print("Card #\(number) is being deinitialized") } } class HTMLElement { let name: String let text: String? lazy var asHTML: () -> String = { if let text = self.text { return "<\(self.name)>\(text)</\(self.name)>" } else { return "<\(self.name) />" } } init(name: String, text: String? = nil) { self.name = name self.text = text } deinit { print("\(name) is being deinitialized") } } lazy var someClosure: (Int, String) -> String = { [unowned self, weak delegate = self.delegate!] (index: Int, stringToProcess: String) -> String in return "" } lazy var someClosure: () -> String = { [unowned self, weak delegate = self.delegate!] in return "" } class HTMLElement { let name: String let text: String? lazy var asHTML: () -> String = { [unowned self] in if let text = self.text { return "<\(self.name)>\(text)</\(self.name)>" } else { return "<\(self.name) />" } } init(name: String, text: String? = nil) { self.name = name self.text = text } deinit { print("\(name) is being deinitialized") } }
mit
885ab7d686d48beba6c9bda3e0542d76
20.352941
101
0.555556
3.945652
false
false
false
false
emaloney/CleanroomConcurrency
Sources/LockImpl.swift
1
1916
// // LockImpl.swift // Cleanroom Project // // Created by Evan Maloney on 3/8/17. // Copyright © 2017 Gilt Groupe. All rights reserved. // internal class FastWriteFacade: FastWriteLock { public var mechanism: LockMechanism { return lock.mechanism } private let lock: Lock public init(wrapping: Lock) { lock = wrapping } public func read<R>(_ fn: () -> R) -> R { return lock.read(fn) } public func write(_ fn: @escaping () -> Void) { lock.write(fn) } } internal class NoLock: Lock { public let mechanism = LockMechanism.none public init() {} public func read<R>(_ fn: () -> R) -> R { return fn() } public func write<R>(_ fn: () -> R) -> R { return fn() } } internal class MutexLock: Lock { public let mechanism = LockMechanism.mutex private let cs = CriticalSection() public init() {} public func read<R>(_ fn: () -> R) -> R { return cs.execute(fn) } public func write<R>(_ fn: () -> R) -> R { return cs.execute(fn) } } internal class ReadWriteLock: Lock { public let mechanism = LockMechanism.readWrite private let coordinator = ReadWriteCoordinator() public init() {} public func read<R>(_ fn: () -> R) -> R { return coordinator.read(fn) } public func write<R>(_ fn: () -> R) -> R { return coordinator.blockingWrite(fn) } } internal class FastWriteLockImpl: FastWriteLock { public let mechanism = LockMechanism.readWrite private let coordinator = ReadWriteCoordinator() public init() {} public func read<R>(_ fn: () -> R) -> R { return coordinator.read(fn) } public func write(_ fn: @escaping () -> Void) { coordinator.enqueueWrite(fn) } }
mit
e961f3554b4f600d4293cd90fefa76f0
16.409091
54
0.549869
3.853119
false
false
false
false
tgyhlsb/RxSwiftExt
Tests/RxSwift/WeakTarget.swift
2
2891
// // WeakTarget.swift // RxSwiftExtDemo // // Created by Ian Keen on 17/04/2016. // Copyright © 2016 RxSwift Community. All rights reserved. // import Foundation import RxSwift enum WeakTargetError: Error { case error } enum RxEvent { case next, error, completed, disposed init<T>(event: Event<T>) { switch event { case .next(_): self = .next case .error(_): self = .error case .completed: self = .completed } } } var WeakTargetReferenceCount: Int = 0 class WeakTarget<Type> { let listener: ([RxEvent: Int]) -> Void fileprivate let observable: Observable<Type> fileprivate var disposeBag = DisposeBag() fileprivate var events: [RxEvent: Int] = [.next: 0, .error: 0, .completed: 0, .disposed: 0] fileprivate func updateEvents(_ event: RxEvent) { self.events[event] = (self.events[event] ?? 0) + 1 self.listener(self.events) } init(obs: Observable<Type>, listener: @escaping ([RxEvent: Int]) -> Void) { WeakTargetReferenceCount += 1 self.listener = listener self.observable = obs } deinit { WeakTargetReferenceCount -= 1 } //MARK: - Subscribers fileprivate func subscriber_on(_ event: Event<Type>) { self.updateEvents(RxEvent(event: event)) } fileprivate func subscriber_onNext(_ element: Type) { self.updateEvents(.next) } fileprivate func subscriber_onError(_ error: Error) { self.updateEvents(.error) } fileprivate func subscriber_onComplete() { self.updateEvents(.completed) } fileprivate func subscriber_onDisposed() { self.updateEvents(.disposed) } //MARK: - Subscription Setup func useSubscribe() { self.observable.subscribe(weak: self, WeakTarget.subscriber_on).addDisposableTo(self.disposeBag) } func useSubscribeNext() { //self.observable.subscribeNext(self.subscriber_onNext).addDisposableTo(self.disposeBag) //uncomment this line to create a retain cycle self.observable.subscribeNext(weak: self, WeakTarget.subscriber_onNext).addDisposableTo(self.disposeBag) } func useSubscribeError() { self.observable.subscribeError(weak: self, WeakTarget.subscriber_onError).addDisposableTo(self.disposeBag) } func useSubscribeComplete() { self.observable.subscribeCompleted(weak: self, WeakTarget.subscriber_onComplete).addDisposableTo(self.disposeBag) } func useSubscribeMulti() { self.observable .subscribe( weak: self, onNext: WeakTarget.subscriber_onNext, onError: WeakTarget.subscriber_onError, onCompleted: WeakTarget.subscriber_onComplete, onDisposed: WeakTarget.subscriber_onDisposed ) .addDisposableTo(self.disposeBag) } func dispose() { self.disposeBag = DisposeBag() } }
mit
bdf37fb7a88feb550e19a15c1cac0812
34.679012
143
0.660554
4.332834
false
false
false
false
Vanlol/MyYDW
SwiftCocoa/Resource/Mine/Controller/MineViewController.swift
1
3031
// // MineViewController.swift // SwiftCocoa // // Created by admin on 2017/7/4. // Copyright © 2017年 admin. All rights reserved. // import UIKit import HealthKit import Photos class MineViewController: BaseViewController { lazy var mineVM = MineViewModel() var healthStore:HKHealthStore! override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) Print.dlog("mine willappear") } override func viewDidLoad() { super.viewDidLoad() initNav() blindViewModel() } /** * 初始化nav */ fileprivate func initNav() { setUpCustomNav(title: "我的", hexColorTitle: UIColor.black, hexColorBg: 0xffffff) setUpNavShadow() } fileprivate func blindViewModel() { PhotoAuthoriz().checkAuthorizationState(allow: { Print.dlog("allow") }) { Print.dlog("deine") } } // MARK: 模仿咸鱼首页滑动 @IBAction func gotoXYMainVcClick(_ sender: Any) { tabPushVCWith(storyboardName: "Mine", vcId: "XYMainViewControllerID") } } extension MineViewController { fileprivate func testHealthKit() { healthStore = HKHealthStore() let step = HKObjectType.quantityType(forIdentifier: .stepCount) let set = NSSet(objects: step as Any) as? Set<HKObjectType> healthStore.requestAuthorization(toShare: nil, read: set) { (isSuccess, error) in if isSuccess { self.readStepCount() }else{ print("获取授权失败") } } } fileprivate func readStepCount() { let sampleType = HKQuantityType.quantityType(forIdentifier: .stepCount) let start = NSSortDescriptor(key: HKSampleSortIdentifierStartDate, ascending: false) let end = NSSortDescriptor(key: HKSampleSortIdentifierEndDate, ascending: false) let now = Date() let calender = Calendar.current let dateComponent = calender.dateComponents([.year,.month,.day,.hour,.minute,.second], from: now) let hour = dateComponent.hour! let minute = dateComponent.minute! let second = dateComponent.second! let nowDay = Date(timeIntervalSinceNow: -(Double(hour*3600 + minute * 60 + second))) let nextDay = Date(timeIntervalSinceNow: -(Double(hour*3600 + minute * 60 + second) + 86400)) let predicate = HKQuery.predicateForSamples(withStart: nowDay, end: nextDay, options: .init(rawValue: 0)) let sampleQuery = HKSampleQuery(sampleType: sampleType!, predicate: predicate, limit: 0, sortDescriptors: [start,end]) { (query, results, error) in //let allStepCount = 0 for result in results! { let quantity = (result as! HKQuantitySample).quantity print(quantity) } } healthStore.execute(sampleQuery) } }
apache-2.0
398dfae844f8a4fb0ce9395e3a18265f
26.943925
155
0.610702
4.708661
false
false
false
false
jeffreybergier/SwiftSwiftChartwell
SSChartwell/SSChartwell_common/FontLoader.swift
1
3137
// // FontManager.swift // SSChartwell // // Created by Jeffrey Bergier on 11/22/15. // // Copyright © 2015 Jeffrey Bergier. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // // public extension Chart { public class FontLoader { public static let sharedInstance = FontLoader() public static let attemptedFonts = [ Chart.Style.Bars, Chart.Style.BarsVertical, Chart.Style.Lines, Chart.Style.Pies, Chart.Style.Radar, Chart.Style.Rings, Chart.Style.Rose ] public let failedFonts: [Chart.Style] public let availableFonts: [Chart.Style] private init() { var availableFonts: [Chart.Style] = [] var failedFonts: [Chart.Style] = [] for fontStyle in self.dynamicType.attemptedFonts { #if os(iOS) || os(tvOS) let optionalFont = UIFont(name: fontStyle.rawValue.fontName, size: 20) #elseif os(OSX) let optionalFont = NSFont(name: fontStyle.rawValue.fontName, size: 20) #endif if let _ = optionalFont { availableFonts.append(fontStyle) } else { if let font = NSBundle.mainBundle().URLForResource(fontStyle.rawValue.fontFileName, withExtension: "ttf") { CTFontManagerRegisterFontsForURL(font, CTFontManagerScope.Process, nil) availableFonts.append(fontStyle) } else { failedFonts.append(fontStyle) } } } self.availableFonts = availableFonts self.failedFonts = failedFonts } public func fontAvailableForStyle(aStyle: Chart.Style) -> Bool { for existingStyle in self.failedFonts { if existingStyle == aStyle { return false } } return true } } }
mit
3ec32ac077058cd8b2b79c76ddb72b6b
38.2125
127
0.599809
4.869565
false
false
false
false
TheInfiniteKind/duckduckgo-iOS
DuckDuckGoTests/VersionTests.swift
1
1867
// // VersionTests.swift // DuckDuckGo // // Created by Mia Alexiou on 31/01/2017. // Copyright © 2017 DuckDuckGo. All rights reserved. // import Foundation import XCTest class VersionTests: XCTestCase { private static let name = "DuckDuckGo" private static let version = "2.0.4" private static let build = "14" private var mockBundle: MockBundle! private var testee: Version! override func setUp() { mockBundle = MockBundle() testee = Version(bundle: mockBundle) } func testName() { mockBundle.add(name: Version.Keys.name, value: VersionTests.name) XCTAssertEqual(VersionTests.name, testee.name()) } func testVersionNumber() { mockBundle.add(name: Version.Keys.versionNumber, value: VersionTests.version) XCTAssertEqual(VersionTests.version, testee.versionNumber()) } func testBuildNumber() { mockBundle.add(name: Version.Keys.buildNumber, value: VersionTests.build) XCTAssertEqual(VersionTests.build, testee.buildNumber()) } func testLocalisedTextContainsNameVersionAndBuild() { mockBundle.add(name: Version.Keys.name, value: VersionTests.name) mockBundle.add(name: Version.Keys.versionNumber, value: VersionTests.version) mockBundle.add(name: Version.Keys.buildNumber, value: VersionTests.build) XCTAssertEqual("DuckDuckGo 2.0.4 (14)", testee.localized()) } func testLocalisedTextContainsNameAndVersionButNotBuildWhenBuildAndVersionSame() { mockBundle.add(name: Version.Keys.name, value: VersionTests.name) mockBundle.add(name: Version.Keys.versionNumber, value: VersionTests.version) mockBundle.add(name: Version.Keys.buildNumber, value: VersionTests.version) XCTAssertEqual("DuckDuckGo 2.0.4", testee.localized()) } }
apache-2.0
6df16f09b19d1511bfda2ac865937361
32.927273
86
0.691854
4.240909
false
true
false
false
SanLiangSan/DDProgressView-Swift
DDSwiftDemo/ViewController.swift
1
1480
// // ViewController.swift // DDSwiftDemo // // Created by Tracy on 14-9-23. // Copyright (c) 2014年 DIDI. All rights reserved. // import UIKit class ViewController: UIViewController { override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) var versionString = UIDevice.currentDevice().systemVersion if (versionString as NSString).floatValue >= 7.0 { self.extendedLayoutIncludesOpaqueBars = true self.edgesForExtendedLayout = UIRectEdge.None self.navigationController?.navigationBar.translucent = false } UINavigationBar.appearance().barTintColor = UIColor.blackColor() } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. self.view.backgroundColor = UIColor.whiteColor() self.title = "首页" self.navigationController?.view.backgroundColor = UIColor.blackColor() var progressView : DDProgressView = DDProgressView(frame: CGRectMake(0, 20, 320, 1), bgColor: UIColor.blackColor()) self.view.addSubview(progressView) progressView.setProgress(0.5, seconds: 2, animated: true) delay(2) { progressView.setProgress(0.8, seconds: 2, animated: true) } delay(5) { progressView.setProgress(1.0, seconds: 2, animated: true) } } }
mit
999ba827a430c499c7162bbb62fd728a
29.081633
123
0.640434
4.848684
false
false
false
false
mironal/NowPlayingFormatter
Playground.playground/Contents.swift
1
1009
//: Playground - noun: a place where people can play import NowPlayingFormatter import MediaPlayer class MockMPMediaItem: MPMediaItem { let dict: [String: Any] init(dict: [String: Any]) { self.dict = dict super.init() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func value(forProperty property: String) -> Any? { return dict[property] } } let item = MockMPMediaItem(dict: [ MPMediaItemPropertyTitle: "music title" ]) do { let formatter = NowPlayingFormatter(format: "#nowplaying %t") print(formatter.string(from: item)) // #nowplaying music title } do { let formatter = NowPlayingFormatter(format: "#nowplaying %t by %a") print(formatter.string(from: item)) // #nowplaying music title by } do { let formatter = NowPlayingFormatter(format: "#nowplaying %t${ by %a}") print(formatter.string(from: item)) // #nowplaying music title }
mit
232274df7972fdc33a4fea2005dc6b72
21.422222
74
0.656095
3.92607
false
false
false
false
TheNounProject/CollectionView
CollectionView/ClipView.swift
1
7756
// // ClipView.swift // CollectionView // // Created by Wesley Byrne on 3/30/16. // Copyright © 2016 Noun Project. All rights reserved. // import AppKit open class ClipView: NSClipView { static let DefaultDecelerationRate: CGFloat = 0.78 var shouldAnimateOriginChange = false var destinationOrigin = CGPoint.zero var scrollView: NSScrollView? { return self.enclosingScrollView ?? self.superview as? NSScrollView } var scrollEnabled: Bool = true /// The rate of deceleration for animated scrolls. Higher is slower. default is 0.78 public var decelerationRate = DefaultDecelerationRate { didSet { if decelerationRate > 1 { self.decelerationRate = 1 } else if decelerationRate < 0 { self.decelerationRate = 0 } } } var completionBlock: AnimationCompletion? init(clipView: NSClipView) { super.init(frame: clipView.frame) self.backgroundColor = clipView.backgroundColor self.drawsBackground = clipView.drawsBackground self.setup() } deinit { NotificationCenter.default.removeObserver(self) } override init(frame frameRect: NSRect) { super.init(frame: frameRect) self.setup() } required public init?(coder: NSCoder) { super.init(coder: coder) self.setup() } func setup() { self.wantsLayer = true } override open func viewWillMove(toWindow newWindow: NSWindow?) { if self.window != nil { NotificationCenter.default.removeObserver(self, name: NSWindow.didChangeScreenNotification, object: self.window) } super.viewWillMove(toWindow: newWindow) if newWindow != nil { NotificationCenter.default.addObserver(self, selector: #selector(ClipView.updateCVDisplay(_:)), name: NSWindow.didChangeScreenNotification, object: newWindow) } } // open override func constrainBoundsRect(_ proposedBounds: NSRect) -> NSRect { // var rect = proposedBounds // rect.origin.x = 50 // return rect // } var _displayLink: CVDisplayLink? var displayLink: CVDisplayLink { if let link = _displayLink { return link } let linkCallback: CVDisplayLinkOutputCallback = {( _, _, _, _, _, displayLinkContext) -> CVReturn in unsafeBitCast(displayLinkContext, to: ClipView.self).updateOrigin() return kCVReturnSuccess } var link: CVDisplayLink? CVDisplayLinkCreateWithActiveCGDisplays(&link) CVDisplayLinkSetOutputCallback(link!, linkCallback, UnsafeMutableRawPointer(Unmanaged.passUnretained(self).toOpaque())) self._displayLink = link return link! } open override func mouseDown(with event: NSEvent) { self.cancelScrollAnimation() super.mouseDown(with: event) } @objc func updateCVDisplay(_ note: Notification) { guard self._displayLink != nil else { return } if let screen = self.window?.screen { let screenDictionary = screen.deviceDescription let screenID = screenDictionary[NSDeviceDescriptionKey("NSScreenNumber")] as! NSNumber let displayID = screenID.uint32Value CVDisplayLinkSetCurrentCGDisplay(displayLink, displayID) } else { CVDisplayLinkSetCurrentCGDisplay(displayLink, CGMainDisplayID()) } } var manualScroll = false @discardableResult open func scrollRectToVisible(_ rect: CGRect, animated: Bool, completion: AnimationCompletion? = nil) -> Bool { manualScroll = false shouldAnimateOriginChange = animated if animated == false { // Calculate the point to scroll to to get make the rect visible var o = rect.origin o.y -= self.contentInsets.top self.scroll(to: o) completion?(true) return true } self.completionBlock = completion let success = super.scrollToVisible(rect) if !success { self.finishedScrolling(success) } return success } func finishedScrolling(_ success: Bool) { self.completionBlock?(success) self.completionBlock = nil } open override func scroll(to newOrigin: NSPoint) { if self.shouldAnimateOriginChange { self.shouldAnimateOriginChange = false if CVDisplayLinkIsRunning(self.displayLink) { self.destinationOrigin = newOrigin return } self.destinationOrigin = newOrigin self.beginScrolling() } else if self.scrollEnabled || manualScroll { // Otherwise, we stop any scrolling that is currently occurring (if needed) and let // super's implementation handle a normal scroll. super.scroll(to: newOrigin) self.cancelScrollAnimation() } } func cancelScrollAnimation() { self.destinationOrigin = self.bounds.origin } func updateOrigin() { var o = CGPoint.zero var integral = false var cancel = false DispatchQueue.main.sync { if self.window == nil { cancel = true } o = self.bounds.origin integral = self.window?.backingScaleFactor == 1 } if cancel { self.endScrolling() return } let lastOrigin = o let deceleration = self.decelerationRate // Calculate the next origin on a basic ease-out curve. o.x = o.x * deceleration + self.destinationOrigin.x * (1 - self.decelerationRate) o.y = o.y * deceleration + self.destinationOrigin.y * (1 - self.decelerationRate) if integral { o = o.integral } // Calling -scrollToPoint: instead of manually adjusting the bounds lets us get the expected // overlay scroller behavior for free. DispatchQueue.main.async { super.scroll(to: o) // Make this call so that we can force an update of the scroller positions. self.scrollView?.reflectScrolledClipView(self) NotificationCenter.default.post(name: NSScrollView.didLiveScrollNotification, object: self.scrollView) } if abs(o.x - lastOrigin.x) < 0.1 && abs(o.y - lastOrigin.y) < 0.1 { self.endScrolling() // Make sure we always finish out the animation with the actual coordinates DispatchQueue.main.async(execute: { super.scroll(to: self.destinationOrigin) if let cv = self.scrollView as? CollectionView { cv.delegate?.collectionViewDidEndScrolling?(cv, animated: true) } self.finishedScrolling(true) }) } } func beginScrolling() { if CVDisplayLinkIsRunning(self.displayLink) { return } DispatchQueue.main.async { (self.scrollView as? CollectionView)?.isScrolling = true } CVDisplayLinkStart(self.displayLink) } func endScrolling() { manualScroll = false if !CVDisplayLinkIsRunning(self.displayLink) { return } DispatchQueue.main.async { (self.scrollView as? CollectionView)?.isScrolling = false } CVDisplayLinkStop(self.displayLink) } }
mit
f2fe0abbc7fc903794f57326730d1925
33.466667
134
0.595358
5.225741
false
false
false
false
justindarc/firefox-ios
Client/Frontend/Browser/TabLocationView.swift
1
19659
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import UIKit import Shared import SnapKit import XCGLogger private let log = Logger.browserLogger protocol TabLocationViewDelegate { func tabLocationViewDidTapLocation(_ tabLocationView: TabLocationView) func tabLocationViewDidLongPressLocation(_ tabLocationView: TabLocationView) func tabLocationViewDidTapReaderMode(_ tabLocationView: TabLocationView) func tabLocationViewDidTapShield(_ tabLocationView: TabLocationView) func tabLocationViewDidTapPageOptions(_ tabLocationView: TabLocationView, from button: UIButton) func tabLocationViewDidLongPressPageOptions(_ tabLocationVIew: TabLocationView) func tabLocationViewDidBeginDragInteraction(_ tabLocationView: TabLocationView) /// - returns: whether the long-press was handled by the delegate; i.e. return `false` when the conditions for even starting handling long-press were not satisfied @discardableResult func tabLocationViewDidLongPressReaderMode(_ tabLocationView: TabLocationView) -> Bool func tabLocationViewLocationAccessibilityActions(_ tabLocationView: TabLocationView) -> [UIAccessibilityCustomAction]? } private struct TabLocationViewUX { static let HostFontColor = UIColor.black static let BaseURLFontColor = UIColor.Photon.Grey50 static let Spacing: CGFloat = 8 static let StatusIconSize: CGFloat = 18 static let TPIconSize: CGFloat = 24 static let ReaderModeButtonWidth: CGFloat = 34 static let ButtonSize: CGFloat = 44 static let URLBarPadding = 4 } class TabLocationView: UIView { var delegate: TabLocationViewDelegate? var longPressRecognizer: UILongPressGestureRecognizer! var tapRecognizer: UITapGestureRecognizer! var contentView: UIStackView! fileprivate let menuBadge = BadgeWithBackdrop(imageName: "menuBadge", backdropCircleSize: 32) @objc dynamic var baseURLFontColor: UIColor = TabLocationViewUX.BaseURLFontColor { didSet { updateTextWithURL() } } var url: URL? { didSet { let wasHidden = lockImageView.isHidden lockImageView.isHidden = url?.scheme != "https" if wasHidden != lockImageView.isHidden { UIAccessibility.post(notification: UIAccessibility.Notification.layoutChanged, argument: nil) } updateTextWithURL() pageOptionsButton.isHidden = (url == nil) if url == nil { trackingProtectionButton.isHidden = true } setNeedsUpdateConstraints() } } var readerModeState: ReaderModeState { get { return readerModeButton.readerModeState } set (newReaderModeState) { if newReaderModeState != self.readerModeButton.readerModeState { let wasHidden = readerModeButton.isHidden self.readerModeButton.readerModeState = newReaderModeState readerModeButton.isHidden = (newReaderModeState == ReaderModeState.unavailable) separatorLine.isHidden = readerModeButton.isHidden if wasHidden != readerModeButton.isHidden { UIAccessibility.post(notification: UIAccessibility.Notification.layoutChanged, argument: nil) if !readerModeButton.isHidden { // Delay the Reader Mode accessibility announcement briefly to prevent interruptions. DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(2)) { UIAccessibility.post(notification: UIAccessibility.Notification.announcement, argument: Strings.ReaderModeAvailableVoiceOverAnnouncement) } } } UIView.animate(withDuration: 0.1, animations: { () -> Void in self.readerModeButton.alpha = newReaderModeState == .unavailable ? 0 : 1 }) } } } lazy var placeholder: NSAttributedString = { let placeholderText = NSLocalizedString("Search or enter address", comment: "The text shown in the URL bar on about:home") return NSAttributedString(string: placeholderText, attributes: [NSAttributedString.Key.foregroundColor: UIColor.Photon.Grey50]) }() lazy var urlTextField: UITextField = { let urlTextField = DisplayTextField() // Prevent the field from compressing the toolbar buttons on the 4S in landscape. urlTextField.setContentCompressionResistancePriority(UILayoutPriority(rawValue: 250), for: .horizontal) urlTextField.attributedPlaceholder = self.placeholder urlTextField.accessibilityIdentifier = "url" urlTextField.accessibilityActionsSource = self urlTextField.font = UIConstants.DefaultChromeFont urlTextField.backgroundColor = .clear // Remove the default drop interaction from the URL text field so that our // custom drop interaction on the BVC can accept dropped URLs. if let dropInteraction = urlTextField.textDropInteraction { urlTextField.removeInteraction(dropInteraction) } return urlTextField }() fileprivate lazy var lockImageView: UIImageView = { let lockImageView = UIImageView(image: UIImage.templateImageNamed("lock_verified")) lockImageView.tintColor = UIColor.Photon.Green60 lockImageView.isAccessibilityElement = true lockImageView.contentMode = .center lockImageView.accessibilityLabel = NSLocalizedString("Secure connection", comment: "Accessibility label for the lock icon, which is only present if the connection is secure") return lockImageView }() lazy var trackingProtectionButton: UIButton = { let trackingProtectionButton = UIButton() trackingProtectionButton.setImage(UIImage.templateImageNamed("tracking-protection"), for: .normal) trackingProtectionButton.addTarget(self, action: #selector(didPressTPShieldButton(_:)), for: .touchUpInside) trackingProtectionButton.tintColor = UIColor.Photon.Grey50 trackingProtectionButton.imageView?.contentMode = .scaleAspectFill trackingProtectionButton.isHidden = true return trackingProtectionButton }() fileprivate lazy var readerModeButton: ReaderModeButton = { let readerModeButton = ReaderModeButton(frame: .zero) readerModeButton.addTarget(self, action: #selector(tapReaderModeButton), for: .touchUpInside) readerModeButton.addGestureRecognizer(UILongPressGestureRecognizer(target: self, action: #selector(longPressReaderModeButton))) readerModeButton.isAccessibilityElement = true readerModeButton.isHidden = true readerModeButton.imageView?.contentMode = .scaleAspectFit readerModeButton.contentHorizontalAlignment = .left readerModeButton.accessibilityLabel = NSLocalizedString("Reader View", comment: "Accessibility label for the Reader View button") readerModeButton.accessibilityIdentifier = "TabLocationView.readerModeButton" readerModeButton.accessibilityCustomActions = [UIAccessibilityCustomAction(name: NSLocalizedString("Add to Reading List", comment: "Accessibility label for action adding current page to reading list."), target: self, selector: #selector(readerModeCustomAction))] return readerModeButton }() lazy var pageOptionsButton: ToolbarButton = { let pageOptionsButton = ToolbarButton(frame: .zero) pageOptionsButton.setImage(UIImage.templateImageNamed("menu-More-Options"), for: .normal) pageOptionsButton.addTarget(self, action: #selector(didPressPageOptionsButton), for: .touchUpInside) pageOptionsButton.isAccessibilityElement = true pageOptionsButton.isHidden = true pageOptionsButton.imageView?.contentMode = .left pageOptionsButton.accessibilityLabel = NSLocalizedString("Page Options Menu", comment: "Accessibility label for the Page Options menu button") pageOptionsButton.accessibilityIdentifier = "TabLocationView.pageOptionsButton" let longPressGesture = UILongPressGestureRecognizer(target: self, action: #selector(didLongPressPageOptionsButton)) pageOptionsButton.addGestureRecognizer(longPressGesture) return pageOptionsButton }() lazy var separatorLine: UIView = { let line = UIView() line.layer.cornerRadius = 2 line.isHidden = true return line }() override init(frame: CGRect) { super.init(frame: frame) register(self, forTabEvents: .didGainFocus, .didToggleDesktopMode, .didChangeContentBlocking) longPressRecognizer = UILongPressGestureRecognizer(target: self, action: #selector(longPressLocation)) longPressRecognizer.delegate = self tapRecognizer = UITapGestureRecognizer(target: self, action: #selector(tapLocation)) tapRecognizer.delegate = self addGestureRecognizer(longPressRecognizer) addGestureRecognizer(tapRecognizer) let spaceView = UIView() spaceView.snp.makeConstraints { make in make.width.equalTo(TabLocationViewUX.Spacing) } // The lock and TP icons have custom spacing. // TODO: Once we cut ios10 support we can use UIstackview.setCustomSpacing let iconStack = UIStackView(arrangedSubviews: [spaceView, lockImageView, trackingProtectionButton]) iconStack.spacing = TabLocationViewUX.Spacing / 2 let subviews = [iconStack, urlTextField, readerModeButton, separatorLine, pageOptionsButton] contentView = UIStackView(arrangedSubviews: subviews) contentView.distribution = .fill contentView.alignment = .center addSubview(contentView) contentView.snp.makeConstraints { make in make.edges.equalTo(self) } lockImageView.snp.makeConstraints { make in make.width.equalTo(TabLocationViewUX.StatusIconSize) make.height.equalTo(TabLocationViewUX.ButtonSize) } trackingProtectionButton.snp.makeConstraints { make in make.width.equalTo(TabLocationViewUX.TPIconSize) make.height.equalTo(TabLocationViewUX.ButtonSize) } pageOptionsButton.snp.makeConstraints { make in make.size.equalTo(TabLocationViewUX.ButtonSize) } separatorLine.snp.makeConstraints { make in make.width.equalTo(1) make.height.equalTo(26) } readerModeButton.snp.makeConstraints { make in make.width.equalTo(TabLocationViewUX.ReaderModeButtonWidth) make.height.equalTo(TabLocationViewUX.ButtonSize) } // Setup UIDragInteraction to handle dragging the location // bar for dropping its URL into other apps. let dragInteraction = UIDragInteraction(delegate: self) dragInteraction.allowsSimultaneousRecognitionDuringLift = true self.addInteraction(dragInteraction) menuBadge.add(toParent: contentView) menuBadge.layout(onButton: pageOptionsButton) menuBadge.show(false) } required init(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } override var accessibilityElements: [Any]? { get { return [lockImageView, urlTextField, readerModeButton, pageOptionsButton].filter { !$0.isHidden } } set { super.accessibilityElements = newValue } } func overrideAccessibility(enabled: Bool) { [lockImageView, urlTextField, readerModeButton, pageOptionsButton].forEach { $0.isAccessibilityElement = enabled } } @objc func tapReaderModeButton() { delegate?.tabLocationViewDidTapReaderMode(self) } @objc func longPressReaderModeButton(_ recognizer: UILongPressGestureRecognizer) { if recognizer.state == .began { delegate?.tabLocationViewDidLongPressReaderMode(self) } } @objc func didPressPageOptionsButton(_ button: UIButton) { delegate?.tabLocationViewDidTapPageOptions(self, from: button) } @objc func didLongPressPageOptionsButton(_ recognizer: UILongPressGestureRecognizer) { delegate?.tabLocationViewDidLongPressPageOptions(self) } @objc func longPressLocation(_ recognizer: UITapGestureRecognizer) { if recognizer.state == .began { delegate?.tabLocationViewDidLongPressLocation(self) } } @objc func tapLocation(_ recognizer: UITapGestureRecognizer) { delegate?.tabLocationViewDidTapLocation(self) } @objc func didPressTPShieldButton(_ button: UIButton) { delegate?.tabLocationViewDidTapShield(self) } @objc func readerModeCustomAction() -> Bool { return delegate?.tabLocationViewDidLongPressReaderMode(self) ?? false } fileprivate func updateTextWithURL() { if let host = url?.host, AppConstants.MOZ_PUNYCODE { urlTextField.text = url?.absoluteString.replacingOccurrences(of: host, with: host.asciiHostToUTF8()) } else { urlTextField.text = url?.absoluteString } // remove https:// (the scheme) from the url when displaying if let scheme = url?.scheme, let range = url?.absoluteString.range(of: "\(scheme)://") { urlTextField.text = url?.absoluteString.replacingCharacters(in: range, with: "") } } } extension TabLocationView: UIGestureRecognizerDelegate { func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool { // When long pressing a button make sure the textfield's long press gesture is not triggered return !(otherGestureRecognizer.view is UIButton) } func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldBeRequiredToFailBy otherGestureRecognizer: UIGestureRecognizer) -> Bool { // If the longPressRecognizer is active, fail the tap recognizer to avoid conflicts. return gestureRecognizer == longPressRecognizer && otherGestureRecognizer == tapRecognizer } } @available(iOS 11.0, *) extension TabLocationView: UIDragInteractionDelegate { func dragInteraction(_ interaction: UIDragInteraction, itemsForBeginning session: UIDragSession) -> [UIDragItem] { // Ensure we actually have a URL in the location bar and that the URL is not local. guard let url = self.url, !InternalURL.isValid(url: url), let itemProvider = NSItemProvider(contentsOf: url) else { return [] } UnifiedTelemetry.recordEvent(category: .action, method: .drag, object: .locationBar) let dragItem = UIDragItem(itemProvider: itemProvider) return [dragItem] } func dragInteraction(_ interaction: UIDragInteraction, sessionWillBegin session: UIDragSession) { delegate?.tabLocationViewDidBeginDragInteraction(self) } } extension TabLocationView: AccessibilityActionsSource { func accessibilityCustomActionsForView(_ view: UIView) -> [UIAccessibilityCustomAction]? { if view === urlTextField { return delegate?.tabLocationViewLocationAccessibilityActions(self) } return nil } } extension TabLocationView: Themeable { func applyTheme() { backgroundColor = UIColor.theme.textField.background urlTextField.textColor = UIColor.theme.textField.textAndTint readerModeButton.selectedTintColor = UIColor.theme.urlbar.readerModeButtonSelected readerModeButton.unselectedTintColor = UIColor.theme.urlbar.readerModeButtonUnselected pageOptionsButton.selectedTintColor = UIColor.theme.urlbar.pageOptionsSelected pageOptionsButton.unselectedTintColor = UIColor.theme.urlbar.pageOptionsUnselected pageOptionsButton.tintColor = pageOptionsButton.unselectedTintColor separatorLine.backgroundColor = UIColor.theme.textField.separator let color = ThemeManager.instance.currentName == .dark ? UIColor(white: 0.3, alpha: 0.6): UIColor.theme.textField.background menuBadge.badge.tintBackground(color: color) } } extension TabLocationView: TabEventHandler { func tabDidChangeContentBlocking(_ tab: Tab) { updateBlockerStatus(forTab: tab) } private func updateBlockerStatus(forTab tab: Tab) { assertIsMainThread("UI changes must be on the main thread") guard let blocker = tab.contentBlocker else { return } switch blocker.status { case .Blocking: self.trackingProtectionButton.setImage(UIImage.templateImageNamed("tracking-protection"), for: .normal) self.trackingProtectionButton.isHidden = false case .Disabled, .NoBlockedURLs: self.trackingProtectionButton.isHidden = true case .Whitelisted: self.trackingProtectionButton.setImage(UIImage.templateImageNamed("tracking-protection-off"), for: .normal) self.trackingProtectionButton.isHidden = false } } func tabDidGainFocus(_ tab: Tab) { updateBlockerStatus(forTab: tab) menuBadge.show(tab.desktopSite) } func tabDidToggleDesktopMode(_ tab: Tab) { menuBadge.show(tab.desktopSite) } } class ReaderModeButton: UIButton { var selectedTintColor: UIColor? var unselectedTintColor: UIColor? override init(frame: CGRect) { super.init(frame: frame) adjustsImageWhenHighlighted = false setImage(UIImage.templateImageNamed("reader"), for: .normal) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override var isSelected: Bool { didSet { self.tintColor = (isHighlighted || isSelected) ? selectedTintColor : unselectedTintColor } } override open var isHighlighted: Bool { didSet { self.tintColor = (isHighlighted || isSelected) ? selectedTintColor : unselectedTintColor } } override var tintColor: UIColor! { didSet { self.imageView?.tintColor = self.tintColor } } var _readerModeState = ReaderModeState.unavailable var readerModeState: ReaderModeState { get { return _readerModeState } set (newReaderModeState) { _readerModeState = newReaderModeState switch _readerModeState { case .available: self.isEnabled = true self.isSelected = false case .unavailable: self.isEnabled = false self.isSelected = false case .active: self.isEnabled = true self.isSelected = true } } } } private class DisplayTextField: UITextField { weak var accessibilityActionsSource: AccessibilityActionsSource? override var accessibilityCustomActions: [UIAccessibilityCustomAction]? { get { return accessibilityActionsSource?.accessibilityCustomActionsForView(self) } set { super.accessibilityCustomActions = newValue } } fileprivate override var canBecomeFirstResponder: Bool { return false } override func textRect(forBounds bounds: CGRect) -> CGRect { return bounds.insetBy(dx: TabLocationViewUX.Spacing, dy: 0) } }
mpl-2.0
38e45b21f9b3782451aa9e3cf002be17
41.460043
270
0.697187
5.799115
false
false
false
false
CaiMiao/CGSSGuide
DereGuide/Live/Model/CGSSBeatmapNote.swift
1
1642
// // CGSSBeatmapNote.swift // DereGuide // // Created by zzk on 21/10/2017. // Copyright © 2017 zzk. All rights reserved. // import Foundation class CGSSBeatmapNote { // 判定范围类型(用于计算得分, 并非按键类型) enum RangeType: Int { case click case flick case slide static let hold = RangeType.click } var id: Int! var sec: Float! var type: Int! var startPos: Int! var finishPos: Int! var status: Int! var sync: Int! var groupId: Int! // 0 no press, 1 start, 2 end var longPressType = 0 // used in shifting bpm var offset: Float = 0 // from 1 to max combo var comboIndex: Int = 1 // context free note information, so each long press slide and filck note need to know the related note weak var previous: CGSSBeatmapNote? weak var next: CGSSBeatmapNote? weak var along: CGSSBeatmapNote? } extension CGSSBeatmapNote { func append(_ anotherNote: CGSSBeatmapNote) { self.next = anotherNote anotherNote.previous = self } func intervalTo(_ anotherNote: CGSSBeatmapNote) -> Float { return anotherNote.sec - sec } var offsetSecond: Float { return sec + offset } } extension CGSSBeatmapNote { var rangeType: RangeType { if type == 3 { if status != 2 && status != 1 { return .flick } else { return .slide } } else if type == 2 { return .hold } else { return .click } } }
mit
be2fd3912e6a91b164e5c887957d75cf
20.118421
107
0.560748
4.314516
false
false
false
false
srikanthg88/SlidingPopDemo
SlidingPopDemo/SlidingPopDemo/FirstVC.swift
1
2019
// // FirstVC.swift // sampleApp001 // // Created by Srikanth Ganji on 13/06/15. // Copyright (c) 2015 Srikanth Ganji. All rights reserved. // import UIKit class FirstVC: HMViewController { @IBOutlet weak var swtNavBar: UISwitch! @IBOutlet weak var swtCustomBack: UISwitch! @IBOutlet weak var lblTitle: UILabel! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. lblTitle.hidden = swtNavBar.on } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func viewDidAppear(animated: Bool) { self.navigationController?.interactivePopGestureRecognizer?.enabled = false self.navigationController?.interactivePopGestureRecognizer?.delegate = nil } @IBAction func navigationBarModeChanged(sender: AnyObject) { self.navigationController?.navigationBarHidden = !swtNavBar.on swtCustomBack.enabled = swtNavBar.on lblTitle.hidden = swtNavBar.on } @IBAction func navBackBtnModeChanged(sender: AnyObject) { } override func gestureRecognizerShouldBegin(gestureRecognizer: UIGestureRecognizer) -> Bool { println("In func \(__FILE__) - \(__FUNCTION__)") return false } // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. if segue.identifier == "SecondVC" { let secondVC: SecondVC = segue.destinationViewController as! SecondVC secondVC.showCustomBackButton = swtCustomBack.on } } }
mit
ee3b982eabe1ffd1317bfee0dca16752
28.26087
106
0.65577
5.163683
false
false
false
false
wiseguy16/iOS-Portfolio
NacdNews/SecondCollectionViewController.swift
1
3362
// // SecondCollectionViewController.swift // NacdNews // // Created by Gregory Weiss on 9/9/16. // Copyright © 2016 Gregory Weiss. All rights reserved. // import UIKit private let reuseIdentifier = "SecondCollectionViewCell" class SecondCollectionViewController: UICollectionViewController { var blogItems = [BlogItem]() var myFormatter = NSDateFormatter() override func viewDidLoad() { super.viewDidLoad() myFormatter.dateStyle = .ShortStyle myFormatter.timeStyle = .NoStyle loadBlogs() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: UICollectionViewDataSource override func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int { return 1 } override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return blogItems.count } override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! SecondCollectionViewCell // Configure the cell let aBlog = blogItems[indexPath.row] // var imageData: NSData cell.secondTitleLabel.text = aBlog.title cell.secondDescriptionLabel.text = aBlog.author.uppercaseString cell.secondImageView.image = UIImage(named: aBlog.blog_primary) return cell } func loadBlogs() { let filePath = NSBundle.mainBundle().pathForResource("nacdBlog3", ofType: "json") //main.path(forResource: "nacdSample3", ofType: "json") let dataFromFile2 = NSData(contentsOfFile: filePath!) // (contentsOf: URL(fileURLWithPath: filePath!)) do { let jsonData = try NSJSONSerialization.JSONObjectWithData(dataFromFile2!, options: []) //jsonObject(with: dataFromFile2!, options: []) guard let jsonDict = jsonData as? [String: AnyObject], let itemsArray = jsonDict["items"] as? [[String: AnyObject]] //let itemsArray = items1["item"] as? [[String: Any]] else { return } for aBlogDict in itemsArray { let aBlogItem = BlogItem(myDictionary: aBlogDict) blogItems.append(aBlogItem) } // var finalItems = [MediaItem]() } catch let error as NSError { print(error) } } override func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) { let aBlog = blogItems[indexPath.row] //as! BlogItem let detailVC = self.storyboard?.instantiateViewControllerWithIdentifier("BlogDetailViewController") as! BlogDetailViewController navigationController?.pushViewController(detailVC, animated: true) detailVC.aBlogItem = aBlog } }
gpl-3.0
6d2c1129cbe1537f9e41ce609d423129
28.226087
149
0.617376
5.601667
false
false
false
false
onevcat/CotEditor
CotEditor/Sources/IncompatibleCharacterScanner.swift
1
2493
// // IncompatibleCharacterScanner.swift // // CotEditor // https://coteditor.com // // Created by 1024jp on 2016-05-28. // // --------------------------------------------------------------------------- // // © 2016-2022 1024jp // // 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 // // https://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 Combine import AppKit final class IncompatibleCharacterScanner { // MARK: Public Properties var shouldScan = false @Published private(set) var incompatibleCharacters: [IncompatibleCharacter] = [] // line endings applied @Published private(set) var isScanning = false // MARK: Private Properties private weak var document: Document? private var task: Task<Void, Error>? private lazy var updateDebouncer = Debouncer(delay: .milliseconds(400)) { [weak self] in self?.scan() } // MARK: - // MARK: Lifecycle required init(document: Document) { self.document = document } deinit { self.task?.cancel() } // MARK: Public Methods /// Scan only when needed. func invalidate() { guard self.shouldScan else { return } self.updateDebouncer.schedule() } /// Scan immediately. func scan() { self.updateDebouncer.cancel() self.task?.cancel() guard let document = self.document else { return assertionFailure() } let encoding = document.fileEncoding.encoding guard !document.string.canBeConverted(to: encoding) else { self.incompatibleCharacters = [] return } let string = document.string.immutable self.isScanning = true self.task = Task { [weak self] in defer { self?.isScanning = false } self?.incompatibleCharacters = try string.scanIncompatibleCharacters(with: encoding) } } }
apache-2.0
e531c8f44770a4769fbd5b62909b0f10
24.690722
109
0.595104
4.746667
false
false
false
false
nathawes/swift
test/ClangImporter/submodules_scoped.swift
22
1045
// RUN: %empty-directory(%t) // RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -typecheck -verify %s -DCHECK_SCOPING // RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -emit-module -o %t %s -module-name submodules // RUN: echo 'import submodules; let s = "\(x), \(y)"' | %target-swift-frontend(mock-sdk: %clang-importer-sdk) -typecheck - -I %t // RUN: echo 'import submodules; let s = "\(x), \(y)"' | not %target-swift-frontend -typecheck - -I %t 2>&1 | %FileCheck -check-prefix=MISSING %s import typealias ctypes.bits.DWORD // MISSING: missing required modules: // MISSING-DAG: 'ctypes.bits' // MISSING-DAG: 'ctypes' // From bits submodule public var x : DWORD = 0 public var y : CInt = x let _: ctypes.DWORD = 0 func markUsed<T>(_ t: T) {} #if CHECK_SCOPING markUsed(MY_INT) // expected-error {{cannot find 'MY_INT' in scope}} markUsed(ctypes.MY_INT) // expected-error {{module 'ctypes' has no member named 'MY_INT'}} let _: ctypes.Color? = nil // expected-error {{no type named 'Color' in module 'ctypes'}} #endif
apache-2.0
01665bec95c147e2a1271e4dcdb4532b
42.541667
145
0.678469
3.055556
false
false
false
false
GrandCentralBoard/GrandCentralBoard
GrandCentralBoardTests/Core/SchedulerTests.swift
2
1046
// // Created by Oktawian Chojnacki on 07.03.2016. // Copyright © 2016 Oktawian Chojnacki. All rights reserved. // import XCTest import GCBCore @testable import GrandCentralBoard final class SourceMock: UpdatingSource { var interval: NSTimeInterval = 1 } let source = SourceMock() final class TargetMock: Updateable { var sources: [UpdatingSource] = [source] let expectation: XCTestExpectation func update(source: UpdatingSource) { expectation.fulfill() } init(expectation: XCTestExpectation) { self.expectation = expectation } } class SchedulerTests: XCTestCase { func testSchedulerFiresTheSelectorOnTarget() { let scheduler = Scheduler() let expectation = expectationWithDescription("Called selector") let target: Updateable = TargetMock(expectation: expectation) let job = Job(target: target, source: source) scheduler.schedule(job) waitForExpectationsWithTimeout(5) { error in XCTAssertNil(error) } } }
gpl-3.0
43a83321e03636ebc8717244e01f3d5e
20.326531
71
0.688038
4.686099
false
true
false
false
practicalswift/swift
test/stdlib/KeyPathAppending.swift
9
4060
// RUN: %target-typecheck-verify-swift // Check that all combinations of key paths produce the expected result type // and choose the expected overloads. #if BUILDING_OUTSIDE_STDLIB import Swift #endif func expect<T>(_: inout T, is: T.Type) {} func wellTypedAppends<T, U, V>(readOnlyLeft: KeyPath<T, U>, writableLeft: WritableKeyPath<T, U>, referenceLeft: ReferenceWritableKeyPath<T, U>, readOnlyRight: KeyPath<U, V>, writableRight: WritableKeyPath<U, V>, referenceRight: ReferenceWritableKeyPath<U, V>){ var a = readOnlyLeft.appending(path: readOnlyRight) expect(&a, is: KeyPath<T, V>.self) var b = readOnlyLeft.appending(path: writableRight) expect(&b, is: KeyPath<T, V>.self) var c = readOnlyLeft.appending(path: referenceRight) expect(&c, is: ReferenceWritableKeyPath<T, V>.self) var d = writableLeft.appending(path: readOnlyRight) expect(&d, is: KeyPath<T, V>.self) var e = writableLeft.appending(path: writableRight) expect(&e, is: WritableKeyPath<T, V>.self) var f = writableLeft.appending(path: referenceRight) expect(&f, is: ReferenceWritableKeyPath<T, V>.self) var g = referenceLeft.appending(path: readOnlyRight) expect(&g, is: KeyPath<T, V>.self) var h = referenceLeft.appending(path: writableRight) expect(&h, is: ReferenceWritableKeyPath<T, V>.self) var i = referenceLeft.appending(path: referenceRight) expect(&i, is: ReferenceWritableKeyPath<T, V>.self) } func mismatchedAppends<T, U, V>(readOnlyLeft: KeyPath<T, U>, writableLeft: WritableKeyPath<T, U>, referenceLeft: ReferenceWritableKeyPath<T, U>, readOnlyRight: KeyPath<U, V>, writableRight: WritableKeyPath<U, V>, referenceRight: ReferenceWritableKeyPath<U, V>){ // expected-error@+1{{}} _ = readOnlyRight.appending(path: readOnlyLeft) // expected-error@+1{{}} _ = readOnlyRight.appending(path: writableLeft) // expected-error@+1{{}} _ = readOnlyRight.appending(path: referenceLeft) // expected-error@+1{{}} _ = writableRight.appending(path: readOnlyLeft) // expected-error@+1{{}} _ = writableRight.appending(path: writableLeft) // expected-error@+1{{}} _ = writableRight.appending(path: referenceLeft) // expected-error@+1{{}} _ = referenceRight.appending(path: readOnlyLeft) // expected-error@+1{{}} _ = referenceRight.appending(path: writableLeft) // expected-error@+1{{}} _ = referenceRight.appending(path: referenceLeft) } func partialAppends<T, U, V>(partial: PartialKeyPath<T>, concrete: KeyPath<U, V>, reference: ReferenceWritableKeyPath<U, V>, any: AnyKeyPath) { var a = any.appending(path: any) expect(&a, is: Optional<AnyKeyPath>.self) var b = any.appending(path: partial) expect(&b, is: Optional<AnyKeyPath>.self) var c = any.appending(path: concrete) expect(&c, is: Optional<AnyKeyPath>.self) var d = any.appending(path: reference) expect(&d, is: Optional<AnyKeyPath>.self) var e = partial.appending(path: any) expect(&e, is: Optional<PartialKeyPath<T>>.self) var f = partial.appending(path: partial) expect(&f, is: Optional<PartialKeyPath<T>>.self) var g = partial.appending(path: concrete) expect(&g, is: Optional<KeyPath<T, V>>.self) var h = partial.appending(path: reference) expect(&h, is: Optional<ReferenceWritableKeyPath<T, V>>.self) /* TODO var i = concrete.appending(path: any) expect(&i, is: Optional<PartialKeyPath<U>>.self) var j = concrete.appending(path: partial) expect(&j, is: Optional<PartialKeyPath<U>>.self) var m = reference.appending(path: any) expect(&m, is: Optional<PartialKeyPath<U>>.self) var n = reference.appending(path: partial) expect(&n, is: Optional<PartialKeyPath<U>>.self) */ }
apache-2.0
68815a53c2634de0758e05359e5c5d76
31.741935
80
0.641626
4.105157
false
false
false
false
priyanka16/RPChatUI
RPChatUI/Classes/ChatInputView.swift
1
18454
// // ChatInputView.swift // Chismoso // // Created by Priyanka // Copyright © 2017 __MyCompanyName__. All rights reserved. // import Foundation import UIKit protocol ChatInputDelegate : class { func chatInputDidResize(chatInput: ChatInputView) func chatInput(didSendMessage message: String, oftype messageType: MessageType) //func chatInput(didAttach images: UIImage) func attachmentButtonPressed() } class ChatInputView : UIView, FlexiTextViewDelegate { // MARK: Styling struct Appearance { static var includeBlur = false static var tintColor = UIColor(red: 0.0, green: 120 / 255.0, blue: 255 / 255.0, alpha: 1.0) static var backgroundColor = UIColor.white static var textViewFont = UIFont(name: "SFUIText-Light", size: 16.0) static var textViewTextColor = UIColor.darkText static var textViewBackgroundColor = UIColor(red: 228 / 255.0, green: 233 / 255.0, blue: 236 / 255.0, alpha: 1.0) } // MARK: Public Properties var textViewInsets = UIEdgeInsets(top: 5, left: 20, bottom: 8, right: 5) weak var delegate: ChatInputDelegate? var isListening: Bool? // MARK: Private Properties let textView = FlexiTextView(frame: CGRect.zero, textContainer: nil) private let sendButton = UIButton(type: .custom) private let attachmentButton = UIButton(type: .custom) private let stopListeningButton = UIButton(type: .custom) private let blurredBackgroundView: UIToolbar = UIToolbar() private var heightConstraint: NSLayoutConstraint! private var sendButtonHeightConstraint: NSLayoutConstraint! // MARK: Initialization override init(frame: CGRect = CGRect.zero) { super.init(frame: frame) self.setup() self.stylize() NotificationCenter.default.addObserver(self, selector: #selector(transactionDidReceiveRecognition), name: Notification.Name("SKTransactionDidReceiveRecognition"), object: nil) } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: Setup func setup() { self.translatesAutoresizingMaskIntoConstraints = false isListening = false self.setupSendButton() self.setupSendButtonConstraints() self.setupAttachmentButton() self.setupAttachmentButtonConstraints() self.setupTextView() self.setupTextViewConstraints() self.setupBlurredBackgroundView() self.setupBlurredBackgroundViewConstraints() } func setupTextView() { textView.bounds = UIEdgeInsetsInsetRect(self.bounds, self.textViewInsets) textView.flexiTextViewDelegate = self textView.center = CGPoint(x: self.bounds.midX, y: self.bounds.midY) self.styleTextView() self.textView.placeholder = NSLocalizedString("Type Something...", comment: "") self.addSubview(textView) } func styleTextView() { textView.layer.rasterizationScale = UIScreen.main.scale textView.layer.shouldRasterize = true } func setupSendButton() { if let customBundle = Bundle.init(identifier: "org.cocoapods.RPChatUI")?.path(forResource: "RPBundle", ofType: "bundle") { if let imagePath: String = (customBundle.appending("/mic.tiff")) { if let micImage = UIImage(contentsOfFile:imagePath) { self.sendButton.setImage(micImage, for: .normal) } } } self.sendButton.tag = 100 self.sendButton.addTarget(self, action: #selector(sendButtonPressed(sender:)), for: .touchUpInside) self.sendButton.bounds = CGRect(x: 0, y: 0, width: 40, height: 1) self.addSubview(sendButton) } func setupAttachmentButton() { if let customBundle = Bundle.init(identifier: "org.cocoapods.RPChatUI")?.path(forResource: "RPBundle", ofType: "bundle") { if let imagePath: String = (customBundle.appending("/icAttachment.tiff")) { if let micImage = UIImage(contentsOfFile:imagePath) { self.attachmentButton.setImage(micImage, for: .normal) } } } self.attachmentButton.addTarget(self, action: #selector(attachmentButtonPressed(sender:)), for: .touchUpInside) self.attachmentButton.bounds = CGRect(x: 0, y: 0, width: 40, height: 1) self.addSubview(attachmentButton) } func setupStopListeningButton() { if let customBundle = Bundle.init(identifier: "org.cocoapods.RPChatUI")?.path(forResource: "RPBundle", ofType: "bundle") { if let imagePath: String = (customBundle.appending("/icClose.tiff")) { if let image = UIImage(contentsOfFile:imagePath) { self.stopListeningButton.setImage(image, for: .normal) } } } self.stopListeningButton.addTarget(self, action: #selector(closeButtonPressed(sender:)), for: .touchUpInside) self.stopListeningButton.bounds = CGRect(x: 0, y: 0, width: 30, height: 1) self.addSubview(stopListeningButton) } func setupListening() { self.attachmentButton.removeFromSuperview() if let customBundle = Bundle.init(identifier: "org.cocoapods.RPChatUI")?.path(forResource: "RPBundle", ofType: "bundle") { if let imagePath: String = (customBundle.appending("/sound-wave.tiff")) { if let image = UIImage(contentsOfFile:imagePath) { self.sendButton.setImage(image, for: .normal) } } } self.sendButton.tag = 1010 self.sendButton.layer.borderColor = UIColor.clear.cgColor self.setupTextViewConstraintsInListeningMode() self.setupSendButtonConstraintsInMicMode() self.setupStopListeningButton() self.setupStopListeningButtonConstraints() } func setupSendButtonConstraints() { self.sendButton.translatesAutoresizingMaskIntoConstraints = false self.sendButton.removeConstraints(self.sendButton.constraints) let rightConstraint = NSLayoutConstraint(item: self, attribute: .right, relatedBy: .equal, toItem: self.sendButton, attribute: .right, multiplier: 1.0, constant: 40) let bottomConstraint = NSLayoutConstraint(item: self, attribute: .bottom, relatedBy: .equal, toItem: self.sendButton, attribute: .bottom, multiplier: 1.0, constant: textViewInsets.bottom) let widthConstraint = NSLayoutConstraint(item: self.sendButton, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: 40) sendButtonHeightConstraint = NSLayoutConstraint(item: self.sendButton, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: 40) self.addConstraints([sendButtonHeightConstraint, widthConstraint, rightConstraint, bottomConstraint]) } func setupSendButtonConstraintsInMicMode() { self.sendButton.translatesAutoresizingMaskIntoConstraints = false self.sendButton.removeConstraints(self.sendButton.constraints) let rightConstraint = NSLayoutConstraint(item: self, attribute: .right, relatedBy: .equal, toItem: self.sendButton, attribute: .right, multiplier: 1.0, constant: textViewInsets.right) let bottomConstraint = NSLayoutConstraint(item: self, attribute: .bottom, relatedBy: .equal, toItem: self.sendButton, attribute: .bottom, multiplier: 1.0, constant: textViewInsets.bottom) let widthConstraint = NSLayoutConstraint(item: self.sendButton, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: 40) sendButtonHeightConstraint = NSLayoutConstraint(item: self.sendButton, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: 40) self.addConstraints([sendButtonHeightConstraint, widthConstraint, rightConstraint, bottomConstraint]) } func setupStopListeningButtonConstraints() { self.stopListeningButton.translatesAutoresizingMaskIntoConstraints = false self.stopListeningButton.removeConstraints(self.stopListeningButton.constraints) let leftConstraint = NSLayoutConstraint(item: self, attribute: .left, relatedBy: .equal, toItem: self.stopListeningButton, attribute: .left, multiplier: 1, constant: -10) let centerConstraint = NSLayoutConstraint(item: self.textView, attribute: .centerY, relatedBy: .equal, toItem: self.stopListeningButton, attribute: .centerY, multiplier: 1.0, constant: 0) let widthConstraint = NSLayoutConstraint(item: self.stopListeningButton, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: 25) let hieghtConstraint = NSLayoutConstraint(item: self.stopListeningButton, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: 25) self.addConstraints([hieghtConstraint, widthConstraint, leftConstraint, centerConstraint]) } func setupAttachmentButtonConstraints() { self.attachmentButton.translatesAutoresizingMaskIntoConstraints = false self.attachmentButton.removeConstraints(self.attachmentButton.constraints) let rightConstraint = NSLayoutConstraint(item: self, attribute: .right, relatedBy: .equal, toItem: self.attachmentButton, attribute: .right, multiplier: 1.0, constant: textViewInsets.right) let bottomConstraint = NSLayoutConstraint(item: self, attribute: .bottom, relatedBy: .equal, toItem: self.attachmentButton, attribute: .bottom, multiplier: 1.0, constant: textViewInsets.bottom) let widthConstraint = NSLayoutConstraint(item: self.attachmentButton, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: 40) sendButtonHeightConstraint = NSLayoutConstraint(item: self.attachmentButton, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: 40) self.addConstraints([sendButtonHeightConstraint, widthConstraint, rightConstraint, bottomConstraint]) } func setupTextViewConstraints() { self.textView.translatesAutoresizingMaskIntoConstraints = false self.textView.removeConstraints(self.textView.constraints) let topConstraint = NSLayoutConstraint(item: self, attribute: .top, relatedBy: .equal, toItem: self.textView, attribute: .top, multiplier: 1.0, constant: -textViewInsets.top) let leftConstraint = NSLayoutConstraint(item: self, attribute: .left, relatedBy: .equal, toItem: self.textView, attribute: .left, multiplier: 1, constant: -textViewInsets.left) let bottomConstraint = NSLayoutConstraint(item: self, attribute: .bottom, relatedBy: .equal, toItem: self.textView, attribute: .bottom, multiplier: 1, constant: textViewInsets.bottom) let rightConstraint = NSLayoutConstraint(item: self.textView, attribute: .right, relatedBy: .equal, toItem: self.sendButton, attribute: .left, multiplier: 1, constant: -textViewInsets.right) heightConstraint = NSLayoutConstraint(item: self, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .height, multiplier: 1.00, constant: 40) self.addConstraints([topConstraint, leftConstraint, bottomConstraint, rightConstraint, heightConstraint]) } func setupTextViewConstraintsInListeningMode() { self.textView.translatesAutoresizingMaskIntoConstraints = false let topConstraint = NSLayoutConstraint(item: self, attribute: .top, relatedBy: .equal, toItem: self.textView, attribute: .top, multiplier: 1.0, constant: -textViewInsets.top) let leftConstraint = NSLayoutConstraint(item: self, attribute: .left, relatedBy: .equal, toItem: self.textView, attribute: .left, multiplier: 1, constant: -36) let bottomConstraint = NSLayoutConstraint(item: self, attribute: .bottom, relatedBy: .equal, toItem: self.textView, attribute: .bottom, multiplier: 1, constant: textViewInsets.bottom) let rightConstraint = NSLayoutConstraint(item: self.textView, attribute: .right, relatedBy: .equal, toItem: self.sendButton, attribute: .left, multiplier: 1, constant: -textViewInsets.right) heightConstraint = NSLayoutConstraint(item: self, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .height, multiplier: 1.00, constant: 40) self.addConstraints([topConstraint, leftConstraint, bottomConstraint, rightConstraint, heightConstraint]) } func setupBlurredBackgroundView() { self.addSubview(self.blurredBackgroundView) self.sendSubview(toBack: self.blurredBackgroundView) } func setupBlurredBackgroundViewConstraints() { self.blurredBackgroundView.translatesAutoresizingMaskIntoConstraints = false let topConstraint = NSLayoutConstraint(item: self, attribute: .top, relatedBy: .equal, toItem: self.blurredBackgroundView, attribute: .top, multiplier: 1.0, constant: 0) let leftConstraint = NSLayoutConstraint(item: self, attribute: .left, relatedBy: .equal, toItem: self.blurredBackgroundView, attribute: .left, multiplier: 1.0, constant: 0) let bottomConstraint = NSLayoutConstraint(item: self, attribute: .bottom, relatedBy: .equal, toItem: self.blurredBackgroundView, attribute: .bottom, multiplier: 1.0, constant: 0) let rightConstraint = NSLayoutConstraint(item: self, attribute: .right, relatedBy: .equal, toItem: self.blurredBackgroundView, attribute: .right, multiplier: 1.0, constant: 0) self.addConstraints([topConstraint, leftConstraint, bottomConstraint, rightConstraint]) } // MARK: Styling func stylize() { self.textView.backgroundColor = Appearance.textViewBackgroundColor self.textView.font = Appearance.textViewFont self.textView.textColor = Appearance.textViewTextColor self.blurredBackgroundView.isHidden = !Appearance.includeBlur self.backgroundColor = UIColor(red: 228 / 255.0, green: 233 / 255.0, blue: 236 / 255.0, alpha: 1.0) } // MARK: StretchyTextViewDelegate func stretchyTextViewDidChangeSize(chatInput textView: FlexiTextView) { let textViewHeight = textView.bounds.height if textView.text.characters.count == 0 { self.sendButtonHeightConstraint.constant = textViewHeight } let targetConstant = textViewHeight + textViewInsets.top + textViewInsets.bottom self.heightConstraint.constant = targetConstant self.delegate?.chatInputDidResize(chatInput: self) } func stretchyTextView(textView: FlexiTextView, validityDidChange isValid: Bool) { } func stretchyTextViewDidChange(chatInput: FlexiTextView) { if (chatInput.text.characters.count > 0) { if let customBundle = Bundle.init(identifier: "org.cocoapods.RPChatUI")?.path(forResource: "RPBundle", ofType: "bundle") { if let imagePath: String = (customBundle.appending("/icSend.tiff")) { if let image = UIImage(contentsOfFile:imagePath) { self.sendButton.setImage(image, for: .normal) } } } self.sendButton.tag = 500 } else { if let customBundle = Bundle.init(identifier: "org.cocoapods.RPChatUI")?.path(forResource: "RPBundle", ofType: "bundle") { if let imagePath: String = (customBundle.appending("/mic.tiff")) { if let image = UIImage(contentsOfFile:imagePath) { self.sendButton.setImage(image, for: .normal) } } } self.sendButton.tag = 100 } } // MARK: Button Presses func sendButtonPressed(sender: UIButton) { if (sender.tag == 100) { self.setupListening() self.textView.text = "" self.textView.placeholder = NSLocalizedString("Listening...", comment: "") isListening = true } else { if self.textView.text.characters.count > 0 { if (isListening)! { self.delegate?.chatInput(didSendMessage: self.textView.text, oftype: .voice) } else { self.delegate?.chatInput(didSendMessage: self.textView.text, oftype: .text) } self.textView.text = "" self.textView.placeholder = NSLocalizedString("Type Something...", comment: "") if let customBundle = Bundle.init(identifier: "org.cocoapods.RPChatUI")?.path(forResource: "RPBundle", ofType: "bundle") { if let imagePath: String = (customBundle.appending("/mic.tiff")) { if let image = UIImage(contentsOfFile:imagePath) { self.sendButton.setImage(image, for: .normal) } } } self.sendButton.tag = 100 isListening = false } } } func attachmentButtonPressed(sender: UIButton) { self.delegate?.attachmentButtonPressed() } func closeButtonPressed(sender: UIButton) { self.stopListeningButton.removeFromSuperview() self.sendButton.removeFromSuperview() self.textView.removeFromSuperview() self.setup() } // MARK: Notification Handler func transactionDidReceiveRecognition(withNotification notification : NSNotification) { if let notfObj = notification.object as? Dictionary<String, AnyObject> { if let message = notfObj["RecognitionText"] as? String { OperationQueue.main.addOperation({ self.textView.placeholderLabel.isHidden = true self.textView.text = message self.sendButton.tag = 500 self.sendButtonPressed(sender: self.sendButton) self.closeButtonPressed(sender: self.stopListeningButton) }) } } } }
mit
9d1c2fc288c3e5052a1ce13688eb7df1
52.798834
201
0.674254
4.87015
false
false
false
false
practicalswift/swift
test/SILGen/dynamic_self.swift
2
20003
// RUN: %target-swift-emit-silgen -swift-version 4 %s -disable-objc-attr-requires-foundation-module -enable-objc-interop | %FileCheck %s // RUN: %target-swift-emit-sil -swift-version 4 -O %s -disable-objc-attr-requires-foundation-module -enable-objc-interop // RUN: %target-swift-emit-ir -swift-version 4 %s -disable-objc-attr-requires-foundation-module -enable-objc-interop // RUN: %target-swift-emit-silgen -swift-version 5 %s -disable-objc-attr-requires-foundation-module -enable-objc-interop | %FileCheck %s // RUN: %target-swift-emit-sil -swift-version 5 -O %s -disable-objc-attr-requires-foundation-module -enable-objc-interop // RUN: %target-swift-emit-ir -swift-version 5 %s -disable-objc-attr-requires-foundation-module -enable-objc-interop protocol P { func f() -> Self } protocol CP : class { func f() -> Self } class X : P, CP { required init(int i: Int) { } // CHECK-LABEL: sil hidden [ossa] @$s12dynamic_self1XC1f{{[_0-9a-zA-Z]*}}F : $@convention(method) (@guaranteed X) -> @owned func f() -> Self { return self } // CHECK-LABEL: sil hidden [ossa] @$s12dynamic_self1XC7factory{{[_0-9a-zA-Z]*}}FZ : $@convention(method) (Int, @thick X.Type) -> @owned X // CHECK: bb0([[I:%[0-9]+]] : $Int, [[SELF:%[0-9]+]] : $@thick X.Type): // CHECK: [[DYNAMIC_SELF:%[0-9]+]] = unchecked_trivial_bit_cast [[SELF]] : $@thick X.Type to $@thick @dynamic_self X.Type // CHECK: [[STATIC_SELF:%[0-9]+]] = upcast [[DYNAMIC_SELF]] : $@thick @dynamic_self X.Type to $@thick X.Type // CHECK: [[CTOR:%[0-9]+]] = class_method [[STATIC_SELF]] : $@thick X.Type, #X.init!allocator.1 : (X.Type) -> (Int) -> X, $@convention(method) (Int, @thick X.Type) -> @owned X // CHECK: apply [[CTOR]]([[I]], [[STATIC_SELF]]) : $@convention(method) (Int, @thick X.Type) -> @owned X class func factory(i: Int) -> Self { return self.init(int: i) } } class Y : X { required init(int i: Int) { super.init(int: i) } } class GX<T> { func f() -> Self { return self } } class GY<T> : GX<[T]> { } // CHECK-LABEL: sil hidden [ossa] @$s12dynamic_self23testDynamicSelfDispatch{{[_0-9a-zA-Z]*}}F : $@convention(thin) (@guaranteed Y) -> () // CHECK: bb0([[Y:%[0-9]+]] : @guaranteed $Y): // CHECK: [[Y_AS_X:%[0-9]+]] = upcast [[Y]] : $Y to $X // CHECK: [[X_F:%[0-9]+]] = class_method [[Y_AS_X]] : $X, #X.f!1 : (X) -> () -> @dynamic_self X, $@convention(method) (@guaranteed X) -> @owned X // CHECK: [[X_RESULT:%[0-9]+]] = apply [[X_F]]([[Y_AS_X]]) : $@convention(method) (@guaranteed X) -> @owned X // CHECK: [[Y_RESULT:%[0-9]+]] = unchecked_ref_cast [[X_RESULT]] : $X to $Y // CHECK: destroy_value [[Y_RESULT]] : $Y func testDynamicSelfDispatch(y: Y) { _ = y.f() } // CHECK-LABEL: sil hidden [ossa] @$s12dynamic_self30testDynamicSelfDispatchGeneric{{[_0-9a-zA-Z]*}}F : $@convention(thin) (@guaranteed GY<Int>) -> () func testDynamicSelfDispatchGeneric(gy: GY<Int>) { // CHECK: bb0([[GY:%[0-9]+]] : @guaranteed $GY<Int>): // CHECK: [[GY_AS_GX:%[0-9]+]] = upcast [[GY]] : $GY<Int> to $GX<Array<Int>> // CHECK: [[GX_F:%[0-9]+]] = class_method [[GY_AS_GX]] : $GX<Array<Int>>, #GX.f!1 : <T> (GX<T>) -> () -> @dynamic_self GX<T>, $@convention(method) <τ_0_0> (@guaranteed GX<τ_0_0>) -> @owned GX<τ_0_0> // CHECK: [[GX_RESULT:%[0-9]+]] = apply [[GX_F]]<[Int]>([[GY_AS_GX]]) : $@convention(method) <τ_0_0> (@guaranteed GX<τ_0_0>) -> @owned GX<τ_0_0> // CHECK: [[GY_RESULT:%[0-9]+]] = unchecked_ref_cast [[GX_RESULT]] : $GX<Array<Int>> to $GY<Int> // CHECK: destroy_value [[GY_RESULT]] : $GY<Int> _ = gy.f() } // CHECK-LABEL: sil hidden [ossa] @$s12dynamic_self21testArchetypeDispatch{{[_0-9a-zA-Z]*}}F : $@convention(thin) <T where T : P> (@in_guaranteed T) -> () func testArchetypeDispatch<T: P>(t: T) { // CHECK: bb0([[T:%[0-9]+]] : $*T): // CHECK: [[T_RESULT:%[0-9]+]] = alloc_stack $T // CHECK: [[ARCHETYPE_F:%[0-9]+]] = witness_method $T, #P.f!1 : {{.*}} : $@convention(witness_method: P) <τ_0_0 where τ_0_0 : P> (@in_guaranteed τ_0_0) -> @out τ_0_0 // CHECK: [[SELF_RESULT:%[0-9]+]] = apply [[ARCHETYPE_F]]<T>([[T_RESULT]], [[T]]) : $@convention(witness_method: P) <τ_0_0 where τ_0_0 : P> (@in_guaranteed τ_0_0) -> @out τ_0_0 _ = t.f() } // CHECK-LABEL: sil hidden [ossa] @$s12dynamic_self23testExistentialDispatch{{[_0-9a-zA-Z]*}}F func testExistentialDispatch(p: P) { // CHECK: bb0([[P:%[0-9]+]] : $*P): // CHECK: [[PCOPY_ADDR:%[0-9]+]] = open_existential_addr immutable_access [[P]] : $*P to $*@opened([[N:".*"]]) P // CHECK: [[P_RESULT:%[0-9]+]] = alloc_stack $P // CHECK: [[P_F_METHOD:%[0-9]+]] = witness_method $@opened([[N]]) P, #P.f!1 : {{.*}}, [[PCOPY_ADDR]]{{.*}} : $@convention(witness_method: P) <τ_0_0 where τ_0_0 : P> (@in_guaranteed τ_0_0) -> @out τ_0_0 // CHECK: [[P_RESULT_ADDR:%[0-9]+]] = init_existential_addr [[P_RESULT]] : $*P, $@opened([[N]]) P // CHECK: apply [[P_F_METHOD]]<@opened([[N]]) P>([[P_RESULT_ADDR]], [[PCOPY_ADDR]]) : $@convention(witness_method: P) <τ_0_0 where τ_0_0 : P> (@in_guaranteed τ_0_0) -> @out τ_0_0 // CHECK: destroy_addr [[P_RESULT]] : $*P // CHECK: dealloc_stack [[P_RESULT]] : $*P _ = p.f() } // CHECK-LABEL: sil hidden [ossa] @$s12dynamic_self28testExistentialDispatchClass{{[_0-9a-zA-Z]*}}F : $@convention(thin) (@guaranteed CP) -> () // CHECK: bb0([[CP:%[0-9]+]] : @guaranteed $CP): // CHECK: [[CP_ADDR:%[0-9]+]] = open_existential_ref [[CP]] : $CP to $@opened([[N:".*"]]) CP // CHECK: [[CP_F:%[0-9]+]] = witness_method $@opened([[N]]) CP, #CP.f!1 : {{.*}}, [[CP_ADDR]]{{.*}} : $@convention(witness_method: CP) <τ_0_0 where τ_0_0 : CP> (@guaranteed τ_0_0) -> @owned τ_0_0 // CHECK: [[CP_F_RESULT:%[0-9]+]] = apply [[CP_F]]<@opened([[N]]) CP>([[CP_ADDR]]) : $@convention(witness_method: CP) <τ_0_0 where τ_0_0 : CP> (@guaranteed τ_0_0) -> @owned τ_0_0 // CHECK: [[RESULT_EXISTENTIAL:%[0-9]+]] = init_existential_ref [[CP_F_RESULT]] : $@opened([[N]]) CP : $@opened([[N]]) CP, $CP // CHECK: destroy_value [[RESULT_EXISTENTIAL]] func testExistentialDispatchClass(cp: CP) { _ = cp.f() } @objc class ObjC { @objc func method() -> Self { return self } } // CHECK-LABEL: sil hidden [ossa] @$s12dynamic_self21testAnyObjectDispatch1oyyXl_tF : $@convention(thin) (@guaranteed AnyObject) -> () { func testAnyObjectDispatch(o: AnyObject) { // CHECK: dynamic_method_br [[O_OBJ:%[0-9]+]] : $@opened({{.*}}) AnyObject, #ObjC.method!1.foreign, bb1, bb2 // CHECK: bb1([[METHOD:%[0-9]+]] : $@convention(objc_method) (@opened({{.*}}) AnyObject) -> @autoreleased AnyObject): // CHECK: [[O_OBJ_COPY:%.*]] = copy_value [[O_OBJ]] // CHECK: [[VAR_9:%[0-9]+]] = partial_apply [callee_guaranteed] [[METHOD]]([[O_OBJ_COPY]]) : $@convention(objc_method) (@opened({{.*}}) AnyObject) -> @autoreleased AnyObject var _ = o.method } // CHECK: } // end sil function '$s12dynamic_self21testAnyObjectDispatch1oyyXl_tF' // <rdar://problem/16270889> Dispatch through ObjC metatypes. class ObjCInit { @objc dynamic required init() { } } // CHECK-LABEL: sil hidden [ossa] @$s12dynamic_self12testObjCInit{{[_0-9a-zA-Z]*}}F : $@convention(thin) (@thick ObjCInit.Type) -> () func testObjCInit(meta: ObjCInit.Type) { // CHECK: bb0([[THICK_META:%[0-9]+]] : $@thick ObjCInit.Type): // CHECK: [[OBJC_META:%[0-9]+]] = thick_to_objc_metatype [[THICK_META]] : $@thick ObjCInit.Type to $@objc_metatype ObjCInit.Type // CHECK: [[OBJ:%[0-9]+]] = alloc_ref_dynamic [objc] [[OBJC_META]] : $@objc_metatype ObjCInit.Type, $ObjCInit // CHECK: [[INIT:%[0-9]+]] = objc_method [[OBJ]] : $ObjCInit, #ObjCInit.init!initializer.1.foreign : (ObjCInit.Type) -> () -> ObjCInit, $@convention(objc_method) (@owned ObjCInit) -> @owned ObjCInit // CHECK: [[RESULT_OBJ:%[0-9]+]] = apply [[INIT]]([[OBJ]]) : $@convention(objc_method) (@owned ObjCInit) -> @owned ObjCInit // CHECK: [[RESULT:%[0-9]+]] = tuple () // CHECK: return [[RESULT]] : $() _ = meta.init() } class OptionalResult { func foo() -> Self? { return self } } // CHECK-LABEL: sil hidden [ossa] @$s12dynamic_self14OptionalResultC3fooACXDSgyF : $@convention(method) (@guaranteed OptionalResult) -> @owned Optional<OptionalResult> { // CHECK: bb0([[SELF:%.*]] : @guaranteed $OptionalResult): // CHECK-NEXT: debug_value [[SELF]] : $OptionalResult // CHECK-NEXT: [[SELF_COPY:%.*]] = copy_value [[SELF]] // CHECK-NEXT: [[T0:%.*]] = enum $Optional<OptionalResult>, #Optional.some!enumelt.1, [[SELF_COPY]] : $OptionalResult // CHECK-NEXT: return [[T0]] : $Optional<OptionalResult> // CHECK: } // end sil function '$s12dynamic_self14OptionalResultC3fooACXDSgyF' class OptionalResultInheritor : OptionalResult { func bar() {} } func testOptionalResult(v : OptionalResultInheritor) { v.foo()?.bar() } // CHECK-LABEL: sil hidden [ossa] @$s12dynamic_self18testOptionalResult1vyAA0dE9InheritorC_tF : $@convention(thin) (@guaranteed OptionalResultInheritor) -> () { // CHECK: bb0([[ARG:%.*]] : @guaranteed $OptionalResultInheritor): // CHECK: [[CAST_ARG:%.*]] = upcast [[ARG]] // CHECK: [[T0:%.*]] = class_method [[CAST_ARG]] : $OptionalResult, #OptionalResult.foo!1 : (OptionalResult) -> () -> @dynamic_self OptionalResult?, $@convention(method) (@guaranteed OptionalResult) -> @owned Optional<OptionalResult> // CHECK-NEXT: [[RES:%.*]] = apply [[T0]]([[CAST_ARG]]) // CHECK-NEXT: [[T4:%.*]] = unchecked_ref_cast [[RES]] : $Optional<OptionalResult> to $Optional<OptionalResultInheritor> func id<T>(_ t: T) -> T { return t } class Z { required init() {} // CHECK-LABEL: sil hidden [ossa] @$s12dynamic_self1ZC23testDynamicSelfCaptures1xACXDSi_tF : $@convention(method) (Int, @guaranteed Z) -> @owned Z { func testDynamicSelfCaptures(x: Int) -> Self { // CHECK: bb0({{.*}}, [[SELF:%.*]] : @guaranteed $Z): // Single capture of 'self' type // CHECK: [[FN:%.*]] = function_ref @$s12dynamic_self1ZC23testDynamicSelfCaptures1xACXDSi_tFyycfU_ : $@convention(thin) (@guaranteed Z) -> () // CHECK-NEXT: [[SELF_COPY:%.*]] = copy_value [[SELF]] : $Z // CHECK-NEXT: partial_apply [callee_guaranteed] [[FN]]([[SELF_COPY]]) let fn1 = { _ = self } fn1() // Capturing 'self', but it's not the last capture. Make sure it ends // up at the end of the list anyway // CHECK: [[FN:%.*]] = function_ref @$s12dynamic_self1ZC23testDynamicSelfCaptures1xACXDSi_tFyycfU0_ : $@convention(thin) (Int, @guaranteed Z) -> () // CHECK-NEXT: [[SELF_COPY:%.*]] = copy_value [[SELF]] : $Z // CHECK-NEXT: partial_apply [callee_guaranteed] [[FN]]({{.*}}, [[SELF_COPY]]) let fn2 = { _ = self _ = x } fn2() // Capturing 'self' weak, so we have to pass in a metatype explicitly // so that IRGen can recover metadata. // CHECK: [[WEAK_SELF:%.*]] = alloc_box ${ var @sil_weak Optional<Z> } // CHECK: [[FN:%.*]] = function_ref @$s12dynamic_self1ZC23testDynamicSelfCaptures1xACXDSi_tFyycfU1_ : $@convention(thin) (@guaranteed { var @sil_weak Optional<Z> }, @thick @dynamic_self Z.Type) -> () // CHECK: [[WEAK_SELF_COPY:%.*]] = copy_value [[WEAK_SELF]] : ${ var @sil_weak Optional<Z> } // CHECK-NEXT: [[DYNAMIC_SELF:%.*]] = metatype $@thick @dynamic_self Z.Type // CHECK: partial_apply [callee_guaranteed] [[FN]]([[WEAK_SELF_COPY]], [[DYNAMIC_SELF]]) : $@convention(thin) (@guaranteed { var @sil_weak Optional<Z> }, @thick @dynamic_self Z.Type) -> () let fn3 = { [weak self] in _ = self } fn3() // Capturing a value with a complex type involving self // CHECK: [[FN:%.*]] = function_ref @$s12dynamic_self1ZC23testDynamicSelfCaptures1xACXDSi_tFyycfU2_ : $@convention(thin) (@guaranteed (Z, Z), @thick @dynamic_self Z.Type) -> () let xx = (self, self) let fn4 = { _ = xx } fn4() return self } // Capturing metatype of dynamic self static func testStaticMethodDynamicSelfCaptures() -> Self { let fn0 = { _ = self; _ = { _ = self } } fn0() let x = self let fn1 = { _ = x; _ = { _ = x } } fn1() let xx = (self, self) let fn2 = { _ = xx; _ = { _ = xx } } fn2() return self.init() } static func testStaticMethodMutableDynamicSelfCaptures() -> Self { let fn0 = { _ = self; _ = { _ = self } } fn0() var x = self let fn1 = { _ = x; _ = { _ = x } } fn1() var xx = (self, self) let fn2 = { _ = xx; _ = { _ = xx } } fn2() return self.init() } // Make sure the actual self value has the same lowered type as the // substituted result of a generic function call func testDynamicSelfSubstitution(_ b: Bool) -> Self { return b ? self : id(self) } // Same for metatype of self static func testStaticMethodDynamicSelfSubstitution(_ b: Bool) -> Self { _ = (b ? self : id(self)) return self.init() } } // Unbound reference to a method returning Self. class Factory { required init() {} func newInstance() -> Self { return self } class func classNewInstance() -> Self { return self.init() } static func staticNewInstance() -> Self { return self.init() } } // CHECK-LABEL: sil hidden [ossa] @$s12dynamic_self22partialApplySelfReturn1c1tyAA7FactoryC_AFmtF : $@convention(thin) (@guaranteed Factory, @thick Factory.Type) -> () func partialApplySelfReturn(c: Factory, t: Factory.Type) { // CHECK: function_ref @$s12dynamic_self7FactoryC11newInstanceACXDyFTc : $@convention(thin) (@guaranteed Factory) -> @owned @callee_guaranteed () -> @owned Factory _ = c.newInstance // CHECK: function_ref @$s12dynamic_self7FactoryC11newInstanceACXDyFTc : $@convention(thin) (@guaranteed Factory) -> @owned @callee_guaranteed () -> @owned Factory _ = Factory.newInstance // CHECK: function_ref @$s12dynamic_self7FactoryC11newInstanceACXDyFTc : $@convention(thin) (@guaranteed Factory) -> @owned @callee_guaranteed () -> @owned Factory _ = t.newInstance _ = type(of: c).newInstance // CHECK: function_ref @$s12dynamic_self7FactoryC16classNewInstanceACXDyFZTc : $@convention(thin) (@thick Factory.Type) -> @owned @callee_guaranteed () -> @owned Factory _ = t.classNewInstance // CHECK: function_ref @$s12dynamic_self7FactoryC16classNewInstanceACXDyFZTc : $@convention(thin) (@thick Factory.Type) -> @owned @callee_guaranteed () -> @owned Factory _ = type(of: c).classNewInstance // CHECK: function_ref @$s12dynamic_self7FactoryC16classNewInstanceACXDyFZTc : $@convention(thin) (@thick Factory.Type) -> @owned @callee_guaranteed () -> @owned Factory _ = Factory.classNewInstance // CHECK: function_ref @$s12dynamic_self7FactoryC17staticNewInstanceACXDyFZTc : $@convention(thin) (@thick Factory.Type) -> @owned @callee_guaranteed () -> @owned Factory _ = t.staticNewInstance // CHECK: function_ref @$s12dynamic_self7FactoryC17staticNewInstanceACXDyFZTc : $@convention(thin) (@thick Factory.Type) -> @owned @callee_guaranteed () -> @owned Factory _ = type(of: c).staticNewInstance // CHECK: function_ref @$s12dynamic_self7FactoryC17staticNewInstanceACXDyFZTc : $@convention(thin) (@thick Factory.Type) -> @owned @callee_guaranteed () -> @owned Factory _ = Factory.staticNewInstance } class FactoryFactory { // CHECK-LABEL: sil hidden [ossa] @$s12dynamic_self07FactoryC0C11newInstanceACXDyFZ : $@convention(method) (@thick FactoryFactory.Type) -> @owned FactoryFactory static func newInstance() -> Self { // CHECK: bb0(%0 : $@thick FactoryFactory.Type): // CHECK: [[DYNAMIC_SELF:%.*]] = unchecked_trivial_bit_cast %0 : $@thick FactoryFactory.Type to $@thick @dynamic_self FactoryFactory.Type // CHECK: [[METATYPE:%.*]] = value_metatype $@thick @dynamic_self FactoryFactory.Type.Type, [[DYNAMIC_SELF]] : $@thick @dynamic_self FactoryFactory.Type // CHECK: [[ANY:%.*]] = init_existential_metatype [[METATYPE]] : $@thick @dynamic_self FactoryFactory.Type.Type, $@thick Any.Type let _: Any.Type = type(of: self) while true {} } } // Super call to a method returning Self class Base { required init() {} func returnsSelf() -> Self { return self } static func returnsSelfStatic() -> Self { return self.init() } } class Derived : Base { // CHECK-LABEL: sil hidden [ossa] @$s12dynamic_self7DerivedC9superCallyyF : $@convention(method) (@guaranteed Derived) -> () // CHECK: [[SELF:%.*]] = copy_value %0 // CHECK: [[SUPER:%.*]] = upcast [[SELF]] : $Derived to $Base // CHECK: [[METHOD:%.*]] = function_ref @$s12dynamic_self4BaseC11returnsSelfACXDyF // CHECK: apply [[METHOD]]([[SUPER]]) // CHECK: return func superCall() { _ = super.returnsSelf() } // CHECK-LABEL: sil hidden [ossa] @$s12dynamic_self7DerivedC15superCallStaticyyFZ : $@convention(method) (@thick Derived.Type) -> () // CHECK: [[SUPER:%.*]] = upcast %0 : $@thick Derived.Type to $@thick Base.Type // CHECK: [[METHOD:%.*]] = function_ref @$s12dynamic_self4BaseC17returnsSelfStaticACXDyFZ // CHECK: apply [[METHOD]]([[SUPER]]) // CHECK: return static func superCallStatic() { _ = super.returnsSelfStatic() } // CHECK-LABEL: sil hidden [ossa] @$s12dynamic_self7DerivedC32superCallFromMethodReturningSelfACXDyF : $@convention(method) (@guaranteed Derived) -> @owned Derived // CHECK: [[SELF:%.*]] = copy_value %0 // CHECK: [[SUPER:%.*]] = upcast [[SELF]] : $Derived to $Base // CHECK: [[METHOD:%.*]] = function_ref @$s12dynamic_self4BaseC11returnsSelfACXDyF // CHECK: apply [[METHOD]]([[SUPER]]) // CHECK: return func superCallFromMethodReturningSelf() -> Self { _ = super.returnsSelf() return self } // CHECK-LABEL: sil hidden [ossa] @$s12dynamic_self7DerivedC38superCallFromMethodReturningSelfStaticACXDyFZ : $@convention(method) (@thick Derived.Type) -> @owned Derived // CHECK; [[DYNAMIC_SELF:%.*]] = unchecked_trivial_bit_cast %0 : $@thick Derived.Type to $@thick @synamic_self Derived.Type // CHECK: [[SUPER:%.*]] = upcast [[DYNAMIC_SELF]] : $@thick @dynamic_self Derived.Type to $@thick Base.Type // CHECK: [[METHOD:%.*]] = function_ref @$s12dynamic_self4BaseC17returnsSelfStaticACXDyFZ // CHECK: apply [[METHOD]]([[SUPER]]) // CHECK: return static func superCallFromMethodReturningSelfStatic() -> Self { _ = super.returnsSelfStatic() return self.init() } } class Generic<T> { // Examples where we have to add a special argument to capture Self's metadata func t1() -> Self { // CHECK-LABEL: sil private [ossa] @$s12dynamic_self7GenericC2t1ACyxGXDyFAEXDSgycfU_ : $@convention(thin) <T> (@guaranteed <τ_0_0> { var @sil_weak Optional<Generic<τ_0_0>> } <T>, @thick @dynamic_self Generic<T>.Type) -> @owned Optional<Generic<T>> _ = {[weak self] in self } return self } func t2() -> Self { // CHECK-LABEL: sil private [ossa] @$s12dynamic_self7GenericC2t2ACyxGXDyFAEXD_AEXDtycfU_ : $@convention(thin) <T> (@guaranteed (Generic<T>, Generic<T>), @thick @dynamic_self Generic<T>.Type) -> (@owned Generic<T>, @owned Generic<T>) let selves = (self, self) _ = { selves } return self } func t3() -> Self { // CHECK-LABEL: sil private [ossa] @$s12dynamic_self7GenericC2t3ACyxGXDyFAEXDycfU_ : $@convention(thin) <T> (@guaranteed @sil_unowned Generic<T>, @thick @dynamic_self Generic<T>.Type) -> @owned Generic<T> _ = {[unowned self] in self } return self } } protocol SelfReplaceable { init<T>(t: T) } extension SelfReplaceable { init(with fn: (Self.Type) -> Self) { self = fn(Self.self) } init<T>(with genericFn: (Self.Type) -> T) { self.init(t: genericFn(Self.self)) } } class SelfReplaceClass : SelfReplaceable { let t: Any required init<T>(t: T) { self.t = t } convenience init(y: Int) { self.init(with: { type in type.init(t: y) }) } convenience init(z: Int) { self.init(with: { type in z }) } } // CHECK-LABEL: sil_witness_table hidden X: P module dynamic_self { // CHECK: method #P.f!1: {{.*}} : @$s12dynamic_self1XCAA1PA2aDP1f{{[_0-9a-zA-Z]*}}FTW // CHECK-LABEL: sil_witness_table hidden X: CP module dynamic_self { // CHECK: method #CP.f!1: {{.*}} : @$s12dynamic_self1XCAA2CPA2aDP1f{{[_0-9a-zA-Z]*}}FTW
apache-2.0
949bcb8596ad678335b1b69ae05a2e6a
46.437055
251
0.628962
3.286325
false
true
false
false
crash-wu/SGRoutePlan
Example/SGRoutePlan/AGSMapUtils.swift
1
11684
// // MapUtils.swift // imapMobile // // Created by 吴小星 on 16/5/24. // Copyright © 2016年 crash. All rights reserved. // import UIKit import SGRoutePlan import SGRoutePlan let USER_LOCTION_LAYER_NAME = "user_loction_layer_name" extension AGSMapView { /** 将地图缩放至中国地图范围 */ func zoomToChineseEnvelope() { self.zoomToEnvelopeOnWebMercator(xmin: 7800000.0, ymin: 44000.0, xmax: 15600000.0, ymax: 7500000.0) } /** 将地图缩放至广州地图范围 */ func zoomToGuangZhouEnvelope() { self.zoomToEnvelopeOnWebMercator(xmin: 12600000.0, ymin: 2637200.0, xmax: 12623900.0, ymax: 2656200.0) } func zoomToGuangZhouEnvelopeOnCGCS2000() { self.zoomToEnvelopeOnCGCS2000(xmin: 113.0, ymin: 22.5, xmax: 114.0, ymax: 23.9) } /** 将地图缩放至湖南省地图范围 */ func zoomToHuNanEnvelope() { self.zoomToEnvelopeOnWebMercator(xmin: 12320000.0, ymin: 3100000.0, xmax: 12808000.0, ymax: 3408000.0) } /** 缩放到中国视图范围 */ func zoomToChineseEnvelopeCGCS2000(){ zoomToEnvelopeOnCGCS2000(xmin: 80.76016586869, ymin: 8.37639403682149, xmax: 145.522396132932, ymax: 52.9004273434877) } func zoomToEnvelopeOnCGCS2000(xmin xmin: Double, ymin: Double, xmax: Double, ymax: Double) { let sr = AGSSpatialReference(WKID: 4490) self.zoomToEnvelope(xmin: xmin, ymin: ymin, xmax: xmax, ymax: ymax, spatialReference: sr) } func zoomToEnvelopeOnWebMercator(xmin xmin: Double, ymin: Double, xmax: Double, ymax: Double) { self.zoomToEnvelope(xmin: xmin, ymin: ymin, xmax: xmax, ymax: ymax, spatialReference: AGSSpatialReference.webMercatorSpatialReference()) } func zoomToEnvelope(xmin xmin: Double, ymin: Double, xmax: Double, ymax: Double, spatialReference: AGSSpatialReference) { let envelope = AGSEnvelope(xmin: xmin, ymin: ymin, xmax: xmax, ymax: ymax, spatialReference: spatialReference) self.zoomToEnvelope(envelope, animated: true) } } /** * @author crash [email protected] , 16-05-24 09:05:01 * * @brief 地图工具类 */ class AGSMapUtils: NSObject,CLLocationManagerDelegate { var currentLocationPoint :AGSPoint? = AGSPoint()//当前定位坐标 weak private var currentMapView :AGSMapView? //当前地图 private var location : CLLocationManager! //=======================================// // MARK: 单例模式 // //=======================================// static let sharedInstance = AGSMapUtils() //.=======================================// // MARK: 定位功能 // //=======================================// private override init() { location = CLLocationManager() } func locationFun (mapView:AGSMapView?) -> Void { self.currentMapView = mapView if CLLocationManager.locationServicesEnabled() { location.delegate = self location.desiredAccuracy = kCLLocationAccuracyBest location.distanceFilter = 1000.0 location.requestAlwaysAuthorization() location.startUpdatingLocation() } } func locationManager(manager: CLLocationManager, didChangeAuthorizationStatus status: CLAuthorizationStatus) { switch status { case .AuthorizedAlways: if location.respondsToSelector(#selector(CLLocationManager.requestAlwaysAuthorization)) { location.requestAlwaysAuthorization() } break default: break } } func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { showCurrentLocation(currentMapView , location: locations.last!) } func showCurrentLocation(mapView: AGSMapView? , location: CLLocation) -> Void { currentLocationPoint = AGSPoint(x: location.coordinate.longitude, y: location.coordinate.latitude, spatialReference: AGSSpatialReference(WKID: 4326)) if let isweb = mapView?.spatialReference.isAnyWebMercator(){ if isweb { //经纬度坐标转墨卡托 let mercator = currentLocationPoint!.ws84PointToWebPoint() let locationLayer = AGSMapUtils().insertSymbolWithLocation(mercator!, symbolImage: "user_position") mapView?.removeMapLayerWithName("user_position") mapView?.addMapLayer(locationLayer, withName: USER_LOCTION_LAYER_NAME) mapView?.zoomToScale(36111.98186701241, withCenterPoint: mercator, animated: true) }else{ let locationLayer = AGSMapUtils().insertSymbolWithLocation(currentLocationPoint!, symbolImage: "user_position") mapView?.removeMapLayerWithName("user_position") mapView?.addMapLayer(locationLayer, withName: USER_LOCTION_LAYER_NAME) mapView?.zoomToScale(36111.98186701241, withCenterPoint: currentLocationPoint, animated: true) } } } /** 给坐标点添加显示图形 :param: point 坐标点 :param: imageName 图形名称 :returns: */ func insertSymbolWithLocation(point : AGSPoint,symbolImage imageName :String)->AGSGraphicsLayer?{ let symbolLayer = AGSGraphicsLayer() let graphicSymbol = AGSPictureMarkerSymbol(imageNamed: imageName) var attributes : [String :AnyObject] = [:] attributes["type"] = 1 let graphic = AGSGraphic(geometry: point, symbol: graphicSymbol, attributes: attributes) symbolLayer.addGraphic(graphic) symbolLayer.refresh() return symbolLayer } /** 批量给坐标点添加显示图形 :param: points 坐标点数组 :param: imageName 图形名称 :returns: */ func insertSymbolWithPoinsArray(points : [AGSPoint],symbolImage imageName :String)->AGSGraphicsLayer?{ let symbolLayer = AGSGraphicsLayer() let graphicSymbol = AGSPictureMarkerSymbol(imageNamed: imageName) var attributes : [String :AnyObject] = [:] attributes["type"] = 1 for point in points{ let graphic = AGSGraphic(geometry: point, symbol: graphicSymbol, attributes: attributes) symbolLayer.addGraphic(graphic) } symbolLayer.refresh() return symbolLayer } /** 依据坐标点数组在地图上绘制线条 :param: mapview 地图 :param: points 坐标点数组 */ func drawLinewithPoinsOnMapView(mapview:AGSMapView,points :[AGSPoint]){ let symbolLayer = AGSGraphicsLayer() let poly = AGSMutablePolyline(spatialReference: mapview.spatialReference) poly.addPathToPolyline() for point in points{ poly.addPointToPath(point) } let outlinesSymbol = AGSSimpleLineSymbol() outlinesSymbol.color = UIColor(red: 0/255, green: 1/255, blue: 1/255, alpha: 1.0) outlinesSymbol.width = 3 outlinesSymbol.style = .InsideFrame let graphic = AGSGraphic(geometry: poly, symbol: outlinesSymbol, attributes: nil) symbolLayer.addGraphic(graphic) symbolLayer.refresh() mapview.zoomToGeometry(poly, withPadding: 0, animated: true) } //MARK: 获取当前定位坐标字符串 /** 获取当前定位坐标字符串 :returns: 定位坐标字符串(130.000,28.000) */ func getCurrentLonLat() ->String?{ if let point = currentLocationPoint { return (String(point.x) + "," + String(point.y)) }else{ return nil } } /** 加载天地图图层 :param: tdtLayerType 图层类型 :param: view 地图容器 */ func loadTdtTileLayer(tdtLayerType:WMTSLayerTypes ,view:AGSMapView) -> Void { view.removeMapLayerWithName("tiandity_layer") view.removeMapLayerWithName("tiandity_layer_annotation") do{ let tileLayer = try SouthgisTdt_TileLayer(layerType: tdtLayerType) view.addMapLayer(tileLayer, withName: "tiandity_layer") }catch let error { print("创建切片图层有误: \(error)") } var annotation : WMTSLayerTypes! switch tdtLayerType { case WMTS_VECTOR_MERCATOR://天地图矢量墨卡托投影地图服务 annotation=WMTS_VECTOR_ANNOTATION_CHINESE_MERCATOR /*!< 天地图矢量墨卡托中文标注 */ break case WMTS_IMAGE_MERCATOR://天地图影像墨卡托投影地图服务 annotation=WMTS_IMAGE_ANNOTATION_CHINESE_MERCATOR /*!< 天地图影像墨卡托投影中文标注 */ break case WMTS_TERRAIN_MERCATOR://天地图地形墨卡托投影地图服务 annotation=WMTS_TERRAIN_ANNOTATION_CHINESE_MERCATOR /*!< 天地图地形墨卡托投影中文标注 */ break case WMTS_VECTOR_2000://天地图矢量国家2000坐标系地图服务 annotation=WMTS_VECTOR_ANNOTATION_CHINESE_2000 /*!< 天地图矢量国家2000坐标系中文标注 */ break case WMTS_IMAGE_2000://天地图影像国家2000坐标系地图服务 annotation=WMTS_IMAGE_ANNOTATION_CHINESE_2000 /*!< 天地图影像国家2000坐标系中文标注 */ break case WMTS_TERRAIN_2000: annotation=WMTS_TERRAIN_ANNOTATION_CHINESE_2000 /*!< 天地图地形国家2000坐标系中文标注 */ break default: break } do{ let annotationLayer = try SouthgisTdt_TileLayer(layerType: annotation) view.addMapLayer(annotationLayer, withName: "tiandity_layer_annotation") }catch let error { print("创建注记图层有误:\(error)") } //设置地图环绕 view.enableWrapAround() } /** 给标绘图层一个默认symbol,并把其转换成JSON :returns: json */ func getCompositesymbolToJSON()->[NSObject : AnyObject]?{ let lineSymbol = AGSSimpleLineSymbol() lineSymbol.color = UIColor.yellowColor() lineSymbol.width = 4 let innerSymbol = AGSSimpleFillSymbol() innerSymbol.color = UIColor.redColor().colorWithAlphaComponent(0.40) innerSymbol.outline = nil //A composite symbol for geometries on the graphics layer let compositeSymbol = AGSCompositeSymbol() compositeSymbol.addSymbol(lineSymbol) compositeSymbol.addSymbol(innerSymbol) let json : [NSObject : AnyObject] = compositeSymbol.encodeToJSON() return json } }
mit
dc2d48055e5ad4ab18ea9e99be581d46
28.617886
157
0.57718
4.491985
false
false
false
false
blockchain/My-Wallet-V3-iOS
Modules/Network/Sources/NetworkKit/General/NetworkResponseDecoder.swift
1
9688
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import AnyCoding import Combine import DIKit import Errors import Foundation import ToolKit public protocol NetworkResponseDecoderAPI { func decodeOptional<ResponseType: Decodable>( response: ServerResponse, responseType: ResponseType.Type, for request: NetworkRequest ) -> Result<ResponseType?, NetworkError> func decodeOptional<ResponseType: Decodable, ErrorResponseType: FromNetworkErrorConvertible>( response: ServerResponse, responseType: ResponseType.Type, for request: NetworkRequest ) -> Result<ResponseType?, ErrorResponseType> func decode<ResponseType: Decodable, ErrorResponseType: FromNetworkErrorConvertible>( response: ServerResponse, for request: NetworkRequest ) -> Result<ResponseType, ErrorResponseType> func decode<ResponseType: Decodable>( response: ServerResponse, for request: NetworkRequest ) -> Result<ResponseType, NetworkError> func decode<ErrorResponseType: FromNetworkErrorConvertible>( error: NetworkError, for request: NetworkRequest ) -> ErrorResponseType func decodeFailureToString(errorResponse: ServerErrorResponse) -> String? } public final class NetworkResponseDecoder: NetworkResponseDecoderAPI { public enum DecoderType { case json(() -> JSONDecoder) case any(() -> AnyDecoderProtocol) } // MARK: - Properties public static let defaultDecoder: DecoderType = .json { let decoder = JSONDecoder() decoder.dateDecodingStrategy = .secondsSince1970 return decoder } public static let anyDecoder: DecoderType = .any { AnyDecoder() } private let makeDecoder: DecoderType // MARK: - Setup public init(_ makeDecoder: DecoderType = NetworkResponseDecoder.defaultDecoder) { self.makeDecoder = makeDecoder } // MARK: - NetworkResponseDecoderAPI public func decodeOptional<ResponseType: Decodable>( response: ServerResponse, responseType: ResponseType.Type, for request: NetworkRequest ) -> Result<ResponseType?, NetworkError> { decode( response: response, for: request, emptyPayloadHandler: { serverResponse in guard serverResponse.response?.statusCode == 204 else { return .failure( NetworkError( request: request.urlRequest, type: .payloadError(.emptyData, response: serverResponse.response) ) ) } return .success(nil) } ) } public func decodeOptional<ResponseType: Decodable, ErrorResponseType: FromNetworkErrorConvertible>( response: ServerResponse, responseType: ResponseType.Type, for request: NetworkRequest ) -> Result<ResponseType?, ErrorResponseType> { decode( response: response, for: request, emptyPayloadHandler: { serverResponse in guard serverResponse.response?.statusCode == 204 else { return .failure( NetworkError( request: request.urlRequest, type: .payloadError(.emptyData, response: serverResponse.response) ) ) } return .success(nil) } ) .mapError(ErrorResponseType.from) } public func decode<ResponseType: Decodable, ErrorResponseType: FromNetworkErrorConvertible>( response: ServerResponse, for request: NetworkRequest ) -> Result<ResponseType, ErrorResponseType> { decode(response: response, for: request) .mapError(ErrorResponseType.from) } public func decode<ResponseType: Decodable>( response: ServerResponse, for request: NetworkRequest ) -> Result<ResponseType, NetworkError> { decode( response: response, for: request, emptyPayloadHandler: { serverResponse in .failure( NetworkError( request: request.urlRequest, type: .payloadError(.emptyData, response: serverResponse.response) ) ) } ) } public func decode<ErrorResponseType: FromNetworkErrorConvertible>( error: NetworkError, for request: NetworkRequest ) -> ErrorResponseType { guard let payload = error.payload else { return ErrorResponseType.from(error) } let errorResponse: ErrorResponseType do { switch makeDecoder { case .json(let json): let decoder = json() decoder.userInfo[.networkURLRequest] = request.urlRequest decoder.userInfo[.networkHTTPResponse] = error.response errorResponse = try decoder.decode(ErrorResponseType.self, from: payload) case .any(let any): let decoder = any() decoder.userInfo[.networkURLRequest] = request.urlRequest decoder.userInfo[.networkHTTPResponse] = error.response errorResponse = try decoder.decode( ErrorResponseType.self, from: JSONSerialization.jsonObject(with: payload, options: [.fragmentsAllowed]) ) } } catch _ { return ErrorResponseType.from(error) } return errorResponse } public func decodeFailureToString(errorResponse: ServerErrorResponse) -> String? { guard let payload = errorResponse.payload else { return nil } return String(data: payload, encoding: .utf8) } // MARK: - Private methods private func decode<ResponseType: Decodable>( response: ServerResponse, for request: NetworkRequest, emptyPayloadHandler: (ServerResponse) -> Result<ResponseType, NetworkError> ) -> Result<ResponseType, NetworkError> { guard ResponseType.self != EmptyNetworkResponse.self else { let emptyResponse: ResponseType = EmptyNetworkResponse() as! ResponseType return .success(emptyResponse) } guard let payload = response.payload else { return emptyPayloadHandler(response) } guard ResponseType.self != RawServerResponse.self else { let message = String(data: payload, encoding: .utf8) ?? "" let rawResponse = RawServerResponse(data: message) as! ResponseType return .success(rawResponse) } guard ResponseType.self != String.self else { let message = String(data: payload, encoding: .utf8) ?? "" return .success(message as! ResponseType) } let result: Result<ResponseType, Error> switch makeDecoder { case .json(let json): let decoder = json() decoder.userInfo[.networkURLRequest] = request.urlRequest decoder.userInfo[.networkHTTPResponse] = response.response result = Result { try decoder.decode(ResponseType.self, from: payload) } case .any(let any): let decoder = any() decoder.userInfo[.networkURLRequest] = request.urlRequest decoder.userInfo[.networkHTTPResponse] = response.response result = Result { try decoder.decode( ResponseType.self, from: JSONSerialization.jsonObject(with: payload, options: [.fragmentsAllowed]) ) } } return result.flatMapError { decodingError -> Result<ResponseType, NetworkError> in let rawPayload = String(data: payload, encoding: .utf8) ?? "" let errorMessage = debugErrorMessage( for: decodingError, response: response.response, responseType: ResponseType.self, request: request, rawPayload: rawPayload ) Logger.shared.error(errorMessage) // TODO: Fix decoding errors then uncomment this: IOS-4501 // if BuildFlag.isInternal { // fatalError(errorMessage) // } return .failure( NetworkError( request: request.urlRequest, type: .payloadError(.badData(rawPayload: rawPayload), response: response.response) ) ) } } private func debugErrorMessage<ResponseType: Decodable>( for decodingError: Error, response: HTTPURLResponse?, responseType: ResponseType.Type, request: NetworkRequest, rawPayload: String ) -> String { """ \n---------------------- Payload decoding error. Error: '\(String(describing: ResponseType.self))': \(decodingError). URL: \(response?.url?.absoluteString ?? ""), Request: \(request), Payload: \(rawPayload) ======================\n """ } } extension CodingUserInfoKey { public static let networkURLRequest = CodingUserInfoKey(rawValue: "com.blockchain.network.url.request")! public static let networkHTTPResponse = CodingUserInfoKey(rawValue: "com.blockchain.network.http.response")! }
lgpl-3.0
6270d901cfde6d4f07dba4da194030d5
35.145522
112
0.591927
5.711675
false
false
false
false
M2Mobi/Marky-Mark
markymark/Classes/Layout Builders/UIView/Views/ListItemView.swift
1
3218
// // Created by Jim van Zummeren on 06/05/16. // Copyright © 2016 M2mobi. All rights reserved. // import Foundation import UIKit class ListItemView: UIView { var bottomSpace: CGFloat = 0 /// List Mark down item to display let listMarkDownItem: ListMarkDownItem /// Label to display the content of the top level list item var label: AttributedInteractiveLabel = AttributedInteractiveLabel() /// bullet view to display the bullet character •, 1. or a. for example( var bullet: UIView? var styling: BulletStylingRule? init( listMarkDownItem: ListMarkDownItem, styling: BulletStylingRule?, attributedText: NSAttributedString, urlOpener: URLOpener? = nil ) { self.listMarkDownItem = listMarkDownItem self.styling = styling super.init(frame: CGRect()) label.markDownAttributedString = attributedText label.numberOfLines = 0 if let urlOpener = urlOpener { label.urlOpener = urlOpener } setUpLayout() } override func layoutSubviews() { label.sizeToFit() if let styling = styling { label.frame.size.width = frame.size.width - styling.bulletViewSize.width label.frame.origin.x = styling.bulletViewSize.width bullet?.frame = CGRect(x: 0, y: 0, width: styling.bulletViewSize.width, height: styling.bulletViewSize.height) } else { label.frame.size.width = frame.size.width } super.layoutSubviews() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: Private /** Set up layout for list item with either an image or text as bullet */ private func setUpLayout() { bullet = getBulletView() if let bullet = bullet { addSubview(label) addSubview(bullet) } } private func getBulletView() -> UIView { let bulletLabel = UILabel() if let indexCharacter = listMarkDownItem.indexCharacter { bulletLabel.text = "\(indexCharacter)" } else if let styling = styling, (styling.bulletImages == nil || styling.bulletImages?.count == 0) { bulletLabel.text = "•" } else { return getImageBulletView() } if let styling = styling { if let font = styling.bulletFont { bulletLabel.font = font } if let color = styling.bulletColor { bulletLabel.textColor = color } return bulletLabel } return UIView() } private func getImageBulletView() -> UIView { guard let styling = styling, let images = styling.bulletImages, images.count > 0 else { return UIView() } let imageIndex = listMarkDownItem.level % images.count let bulletImageView = UIImageView(image: images[imageIndex]) bulletImageView.contentMode = .center return bulletImageView } override var intrinsicContentSize: CGSize { return CGSize(width: 0, height: self.label.frame.size.height + bottomSpace) } }
mit
6962f8f2b187e64017d62b5ad6b36b32
25.553719
122
0.61469
4.78125
false
false
false
false
Jnosh/swift
stdlib/public/SDK/Dispatch/Queue.swift
12
11312
//===----------------------------------------------------------------------===// // // 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 // //===----------------------------------------------------------------------===// // dispatch/queue.h import _SwiftDispatchOverlayShims public final class DispatchSpecificKey<T> { public init() {} } internal class _DispatchSpecificValue<T> { internal let value: T internal init(value: T) { self.value = value } } public extension DispatchQueue { public struct Attributes : OptionSet { public let rawValue: UInt64 public init(rawValue: UInt64) { self.rawValue = rawValue } public static let concurrent = Attributes(rawValue: 1<<1) @available(OSX 10.12, iOS 10.0, tvOS 10.0, watchOS 3.0, *) public static let initiallyInactive = Attributes(rawValue: 1<<2) fileprivate func _attr() -> __OS_dispatch_queue_attr? { var attr: __OS_dispatch_queue_attr? if self.contains(.concurrent) { attr = _swift_dispatch_queue_concurrent() } if #available(OSX 10.12, iOS 10.0, tvOS 10.0, watchOS 3.0, *) { if self.contains(.initiallyInactive) { attr = __dispatch_queue_attr_make_initially_inactive(attr) } } return attr } } public enum GlobalQueuePriority { @available(OSX, deprecated: 10.10, message: "Use qos attributes instead") @available(iOS, deprecated: 8.0, message: "Use qos attributes instead") @available(tvOS, deprecated, message: "Use qos attributes instead") @available(watchOS, deprecated, message: "Use qos attributes instead") case high @available(OSX, deprecated: 10.10, message: "Use qos attributes instead") @available(iOS, deprecated: 8.0, message: "Use qos attributes instead") @available(tvOS, deprecated, message: "Use qos attributes instead") @available(watchOS, deprecated, message: "Use qos attributes instead") case `default` @available(OSX, deprecated: 10.10, message: "Use qos attributes instead") @available(iOS, deprecated: 8.0, message: "Use qos attributes instead") @available(tvOS, deprecated, message: "Use qos attributes instead") @available(watchOS, deprecated, message: "Use qos attributes instead") case low @available(OSX, deprecated: 10.10, message: "Use qos attributes instead") @available(iOS, deprecated: 8.0, message: "Use qos attributes instead") @available(tvOS, deprecated, message: "Use qos attributes instead") @available(watchOS, deprecated, message: "Use qos attributes instead") case background internal var _translatedValue: Int { switch self { case .high: return 2 // DISPATCH_QUEUE_PRIORITY_HIGH case .default: return 0 // DISPATCH_QUEUE_PRIORITY_DEFAULT case .low: return -2 // DISPATCH_QUEUE_PRIORITY_LOW case .background: return Int(Int16.min) // DISPATCH_QUEUE_PRIORITY_BACKGROUND } } } public enum AutoreleaseFrequency { case inherit @available(OSX 10.12, iOS 10.0, tvOS 10.0, watchOS 3.0, *) case workItem @available(OSX 10.12, iOS 10.0, tvOS 10.0, watchOS 3.0, *) case never internal func _attr(attr: __OS_dispatch_queue_attr?) -> __OS_dispatch_queue_attr? { if #available(OSX 10.12, iOS 10.0, tvOS 10.0, watchOS 3.0, *) { switch self { case .inherit: // DISPATCH_AUTORELEASE_FREQUENCY_INHERIT return __dispatch_queue_attr_make_with_autorelease_frequency(attr, __dispatch_autorelease_frequency_t(0)) case .workItem: // DISPATCH_AUTORELEASE_FREQUENCY_WORK_ITEM return __dispatch_queue_attr_make_with_autorelease_frequency(attr, __dispatch_autorelease_frequency_t(1)) case .never: // DISPATCH_AUTORELEASE_FREQUENCY_NEVER return __dispatch_queue_attr_make_with_autorelease_frequency(attr, __dispatch_autorelease_frequency_t(2)) } } else { return attr } } } public class func concurrentPerform(iterations: Int, execute work: (Int) -> Void) { _swift_dispatch_apply_current(UInt32(iterations), work) } public class var main: DispatchQueue { return _swift_dispatch_get_main_queue() } @available(OSX, deprecated: 10.10) @available(iOS, deprecated: 8.0) @available(tvOS, deprecated) @available(watchOS, deprecated) public class func global(priority: GlobalQueuePriority) -> DispatchQueue { return __dispatch_get_global_queue(priority._translatedValue, 0) } @available(OSX 10.10, iOS 8.0, *) public class func global(qos: DispatchQoS.QoSClass = .default) -> DispatchQueue { return __dispatch_get_global_queue(Int(qos.rawValue.rawValue), 0) } public class func getSpecific<T>(key: DispatchSpecificKey<T>) -> T? { let k = Unmanaged.passUnretained(key).toOpaque() if let p = __dispatch_get_specific(k) { let v = Unmanaged<_DispatchSpecificValue<T>> .fromOpaque(p) .takeUnretainedValue() return v.value } return nil } public convenience init( label: String, qos: DispatchQoS = .unspecified, attributes: Attributes = [], autoreleaseFrequency: AutoreleaseFrequency = .inherit, target: DispatchQueue? = nil) { var attr = attributes._attr() if autoreleaseFrequency != .inherit { attr = autoreleaseFrequency._attr(attr: attr) } if #available(OSX 10.10, iOS 8.0, *), qos != .unspecified { attr = __dispatch_queue_attr_make_with_qos_class(attr, qos.qosClass.rawValue, Int32(qos.relativePriority)) } if #available(OSX 10.12, iOS 10.0, tvOS 10.0, watchOS 3.0, *) { self.init(__label: label, attr: attr, queue: target) } else { self.init(__label: label, attr: attr) if let tq = target { self.setTarget(queue: tq) } } } public var label: String { return String(validatingUTF8: __dispatch_queue_get_label(self))! } @available(OSX 10.10, iOS 8.0, *) public func sync(execute workItem: DispatchWorkItem) { // _swift_dispatch_sync preserves the @convention(block) for // work item blocks. _swift_dispatch_sync(self, workItem._block) } @available(OSX 10.10, iOS 8.0, *) public func async(execute workItem: DispatchWorkItem) { // _swift_dispatch_async preserves the @convention(block) // for work item blocks. _swift_dispatch_async(self, workItem._block) } @available(OSX 10.10, iOS 8.0, *) public func async(group: DispatchGroup, execute workItem: DispatchWorkItem) { // _swift_dispatch_group_async preserves the @convention(block) // for work item blocks. _swift_dispatch_group_async(group, self, workItem._block) } public func async( group: DispatchGroup? = nil, qos: DispatchQoS = .unspecified, flags: DispatchWorkItemFlags = [], execute work: @escaping @convention(block) () -> Void) { if group == nil && qos == .unspecified { // Fast-path route for the most common API usage if flags.isEmpty { _swift_dispatch_async(self, work) return } else if flags == .barrier { _swift_dispatch_barrier_async(self, work) return } } var block: @convention(block) () -> Void = work if #available(OSX 10.10, iOS 8.0, *), (qos != .unspecified || !flags.isEmpty) { let workItem = DispatchWorkItem(qos: qos, flags: flags, block: work) block = workItem._block } if let g = group { _swift_dispatch_group_async(g, self, block) } else { _swift_dispatch_async(self, block) } } private func _syncBarrier(block: () -> Void) { __dispatch_barrier_sync(self, block) } private func _syncHelper<T>( fn: (() -> Void) -> Void, execute work: () throws -> T, rescue: ((Error) throws -> (T))) rethrows -> T { var result: T? var error: Error? fn { do { result = try work() } catch let e { error = e } } if let e = error { return try rescue(e) } else { return result! } } @available(OSX 10.10, iOS 8.0, *) private func _syncHelper<T>( fn: (DispatchWorkItem) -> Void, flags: DispatchWorkItemFlags, execute work: () throws -> T, rescue: ((Error) throws -> (T))) rethrows -> T { var result: T? var error: Error? let workItem = DispatchWorkItem(flags: flags, noescapeBlock: { do { result = try work() } catch let e { error = e } }) fn(workItem) if let e = error { return try rescue(e) } else { return result! } } public func sync<T>(execute work: () throws -> T) rethrows -> T { return try self._syncHelper(fn: sync, execute: work, rescue: { throw $0 }) } public func sync<T>(flags: DispatchWorkItemFlags, execute work: () throws -> T) rethrows -> T { if flags == .barrier { return try self._syncHelper(fn: _syncBarrier, execute: work, rescue: { throw $0 }) } else if #available(OSX 10.10, iOS 8.0, *), !flags.isEmpty { return try self._syncHelper(fn: sync, flags: flags, execute: work, rescue: { throw $0 }) } else { return try self._syncHelper(fn: sync, execute: work, rescue: { throw $0 }) } } public func asyncAfter( deadline: DispatchTime, qos: DispatchQoS = .unspecified, flags: DispatchWorkItemFlags = [], execute work: @escaping @convention(block) () -> Void) { if #available(OSX 10.10, iOS 8.0, *), qos != .unspecified || !flags.isEmpty { let item = DispatchWorkItem(qos: qos, flags: flags, block: work) _swift_dispatch_after(deadline.rawValue, self, item._block) } else { _swift_dispatch_after(deadline.rawValue, self, work) } } public func asyncAfter( wallDeadline: DispatchWallTime, qos: DispatchQoS = .unspecified, flags: DispatchWorkItemFlags = [], execute work: @escaping @convention(block) () -> Void) { if #available(OSX 10.10, iOS 8.0, *), qos != .unspecified || !flags.isEmpty { let item = DispatchWorkItem(qos: qos, flags: flags, block: work) _swift_dispatch_after(wallDeadline.rawValue, self, item._block) } else { _swift_dispatch_after(wallDeadline.rawValue, self, work) } } @available(OSX 10.10, iOS 8.0, *) public func asyncAfter(deadline: DispatchTime, execute: DispatchWorkItem) { _swift_dispatch_after(deadline.rawValue, self, execute._block) } @available(OSX 10.10, iOS 8.0, *) public func asyncAfter(wallDeadline: DispatchWallTime, execute: DispatchWorkItem) { _swift_dispatch_after(wallDeadline.rawValue, self, execute._block) } @available(OSX 10.10, iOS 8.0, *) public var qos: DispatchQoS { var relPri: Int32 = 0 let cls = DispatchQoS.QoSClass(rawValue: __dispatch_queue_get_qos_class(self, &relPri))! return DispatchQoS(qosClass: cls, relativePriority: Int(relPri)) } public func getSpecific<T>(key: DispatchSpecificKey<T>) -> T? { let k = Unmanaged.passUnretained(key).toOpaque() if let p = __dispatch_queue_get_specific(self, k) { let v = Unmanaged<_DispatchSpecificValue<T>> .fromOpaque(p) .takeUnretainedValue() return v.value } return nil } public func setSpecific<T>(key: DispatchSpecificKey<T>, value: T?) { let k = Unmanaged.passUnretained(key).toOpaque() let v = value.flatMap { _DispatchSpecificValue(value: $0) } let p = v.flatMap { Unmanaged.passRetained($0).toOpaque() } __dispatch_queue_set_specific(self, k, p, _destructDispatchSpecificValue) } } private func _destructDispatchSpecificValue(ptr: UnsafeMutableRawPointer?) { if let p = ptr { Unmanaged<AnyObject>.fromOpaque(p).release() } }
apache-2.0
d87237534e8240481453b4a4f147a500
30.864789
110
0.677864
3.357673
false
false
false
false
aryzle/iLift
iChode/ViewController4.swift
2
2184
// // ViewController4.swift // iChode // // Created by Thomas Yang on 5/4/15. // Copyright (c) 2015 Aryzle. All rights reserved. // import UIKit var setN = 3 var repN = 6 class ViewController4: UIViewController { //title of the selected Workout @IBOutlet weak var workoutTitle: UILabel! //Stepper for Sets @IBOutlet weak var setButtonValue: UIStepper! @IBOutlet weak var setLabel: UILabel! @IBAction func setButton(sender: AnyObject) { self.setLabel.text = Int(self.setButtonValue.value).description } //Stepper for Reps @IBOutlet weak var repLabel: UILabel! @IBOutlet weak var repButtonValue: UIStepper! @IBAction func repButton(sender: AnyObject) { self.repLabel.text = Int(self.repButtonValue.value).description } //Slider for Weight @IBOutlet weak var weightLabel: UILabel! @IBOutlet weak var weightSliderValue: UISlider! @IBAction func weightSliderChange(sender: AnyObject) { weightLabel.text = String(stringInterpolationSegment: Int(weightSliderValue.value * 300)) + " lbs" } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. workoutTitle.text = workoutArray[activeMuscle][activeWorkout] setButtonValue.value = Double(setN) setButtonValue.wraps = false setButtonValue.autorepeat = false setButtonValue.maximumValue = 9 repButtonValue.value = Double(repN) repButtonValue.wraps = false repButtonValue.autorepeat = false repButtonValue.maximumValue = 15 } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
mit
c6f8846fa43d8b03025ae04195ecb873
28.917808
106
0.676282
4.588235
false
false
false
false
StYaphet/firefox-ios
Client/Frontend/Browser/BrowserTrayAnimators.swift
6
16064
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import UIKit import Shared class TrayToBrowserAnimator: NSObject, UIViewControllerAnimatedTransitioning { func animateTransition(using transitionContext: UIViewControllerContextTransitioning) { if let bvc = transitionContext.viewController(forKey: .to) as? BrowserViewController, let tabTray = transitionContext.viewController(forKey: .from) as? TabTrayControllerV1 { transitionFromTray(tabTray, toBrowser: bvc, usingContext: transitionContext) } } func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval { return 0.4 } } private extension TrayToBrowserAnimator { func transitionFromTray(_ tabTray: TabTrayControllerV1, toBrowser bvc: BrowserViewController, usingContext transitionContext: UIViewControllerContextTransitioning) { let container = transitionContext.containerView guard let selectedTab = bvc.tabManager.selectedTab else { return } let tabManager = bvc.tabManager let displayedTabs = selectedTab.isPrivate ? tabManager.privateTabs : tabManager.normalTabs guard let expandFromIndex = displayedTabs.firstIndex(of: selectedTab) else { return } //Disable toolbar until animation completes tabTray.toolbar.isUserInteractionEnabled = false bvc.view.frame = transitionContext.finalFrame(for: bvc) // Hide browser components bvc.toggleSnackBarVisibility(show: false) toggleWebViewVisibility(false, usingTabManager: bvc.tabManager) bvc.firefoxHomeViewController?.view.isHidden = true bvc.webViewContainerBackdrop.isHidden = true bvc.statusBarOverlay.isHidden = false if let url = selectedTab.url, !url.isReaderModeURL { bvc.hideReaderModeBar(animated: false) } // Take a snapshot of the collection view that we can scale/fade out. We don't need to wait for screen updates since it's already rendered on the screen let tabCollectionViewSnapshot = tabTray.collectionView.snapshotView(afterScreenUpdates: false)! tabTray.collectionView.alpha = 0 tabCollectionViewSnapshot.frame = tabTray.collectionView.frame container.insertSubview(tabCollectionViewSnapshot, at: 0) // Create a fake cell to use for the upscaling animation let startingFrame = calculateCollapsedCellFrameUsingCollectionView(tabTray.collectionView, atIndex: expandFromIndex) let cell = createTransitionCellFromTab(bvc.tabManager.selectedTab, withFrame: startingFrame) cell.backgroundHolder.layer.cornerRadius = 0 container.insertSubview(bvc.view, aboveSubview: tabCollectionViewSnapshot) container.insertSubview(cell, aboveSubview: bvc.view) // Flush any pending layout/animation code in preperation of the animation call container.layoutIfNeeded() let finalFrame = calculateExpandedCellFrameFromBVC(bvc) bvc.footer.alpha = shouldDisplayFooterForBVC(bvc) ? 1 : 0 bvc.urlBar.isTransitioning = true // Re-calculate the starting transforms for header/footer views in case we switch orientation resetTransformsForViews([bvc.header, bvc.readerModeBar, bvc.footer]) transformHeaderFooterForBVC(bvc, toFrame: startingFrame, container: container) let frameResizeClosure = { // Scale up the cell and reset the transforms for the header/footers cell.frame = finalFrame container.layoutIfNeeded() cell.title.transform = CGAffineTransform(translationX: 0, y: -cell.title.frame.height) bvc.tabTrayDidDismiss(tabTray) tabTray.toolbar.transform = CGAffineTransform(translationX: 0, y: UIConstants.BottomToolbarHeight) tabCollectionViewSnapshot.transform = CGAffineTransform(scaleX: 0.9, y: 0.9) } if UIAccessibility.isReduceMotionEnabled { frameResizeClosure() } UIView.animate(withDuration: self.transitionDuration(using: transitionContext), delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 0, options: [], animations: { if !UIAccessibility.isReduceMotionEnabled { frameResizeClosure() } UIApplication.shared.windows.first?.backgroundColor = UIColor.theme.browser.background tabTray.navigationController?.setNeedsStatusBarAppearanceUpdate() tabCollectionViewSnapshot.alpha = 0 tabTray.statusBarBG.alpha = 0 tabTray.searchBarHolder.alpha = 0 }, completion: { finished in // Remove any of the views we used for the animation cell.removeFromSuperview() tabCollectionViewSnapshot.removeFromSuperview() bvc.footer.alpha = 1 bvc.toggleSnackBarVisibility(show: true) toggleWebViewVisibility(true, usingTabManager: bvc.tabManager) bvc.webViewContainerBackdrop.isHidden = false bvc.firefoxHomeViewController?.view.isHidden = false bvc.urlBar.isTransitioning = false tabTray.toolbar.isUserInteractionEnabled = true transitionContext.completeTransition(true) }) } } class BrowserToTrayAnimator: NSObject, UIViewControllerAnimatedTransitioning { func animateTransition(using transitionContext: UIViewControllerContextTransitioning) { if let bvc = transitionContext.viewController(forKey: .from) as? BrowserViewController, let tabTray = transitionContext.viewController(forKey: .to) as? TabTrayControllerV1 { transitionFromBrowser(bvc, toTabTray: tabTray, usingContext: transitionContext) } } func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval { return 0.4 } } private extension BrowserToTrayAnimator { func transitionFromBrowser(_ bvc: BrowserViewController, toTabTray tabTray: TabTrayControllerV1, usingContext transitionContext: UIViewControllerContextTransitioning) { let container = transitionContext.containerView guard let selectedTab = bvc.tabManager.selectedTab else { return } let tabManager = bvc.tabManager let displayedTabs = selectedTab.isPrivate ? tabManager.privateTabs : tabManager.normalTabs guard let scrollToIndex = displayedTabs.firstIndex(of: selectedTab) else { return } //Disable toolbar until animation completes tabTray.toolbar.isUserInteractionEnabled = false tabTray.view.frame = transitionContext.finalFrame(for: tabTray) // Insert tab tray below the browser and force a layout so the collection view can get it's frame right container.insertSubview(tabTray.view, belowSubview: bvc.view) // Force subview layout on the collection view so we can calculate the correct end frame for the animation tabTray.view.layoutIfNeeded() tabTray.focusTab() // Build a tab cell that we will use to animate the scaling of the browser to the tab let expandedFrame = calculateExpandedCellFrameFromBVC(bvc) let cell = createTransitionCellFromTab(bvc.tabManager.selectedTab, withFrame: expandedFrame) cell.backgroundHolder.layer.cornerRadius = TabTrayControllerUX.CornerRadius // Take a snapshot of the collection view to perform the scaling/alpha effect let tabCollectionViewSnapshot = tabTray.collectionView.snapshotView(afterScreenUpdates: true)! tabCollectionViewSnapshot.frame = tabTray.collectionView.frame tabCollectionViewSnapshot.transform = CGAffineTransform(scaleX: 0.9, y: 0.9) tabCollectionViewSnapshot.alpha = 0 tabTray.view.insertSubview(tabCollectionViewSnapshot, belowSubview: tabTray.toolbar) if let toast = bvc.clipboardBarDisplayHandler?.clipboardToast { toast.removeFromSuperview() } container.addSubview(cell) cell.layoutIfNeeded() cell.title.transform = CGAffineTransform(translationX: 0, y: -cell.title.frame.size.height) // Hide views we don't want to show during the animation in the BVC bvc.firefoxHomeViewController?.view.isHidden = true bvc.statusBarOverlay.isHidden = true bvc.toggleSnackBarVisibility(show: false) toggleWebViewVisibility(false, usingTabManager: bvc.tabManager) bvc.urlBar.isTransitioning = true // On iPhone, fading these in produces a darkening at the top of the screen, and then // it brightens back to full white as they fade in. Setting these to not fade in produces a better effect. if UIDevice.current.userInterfaceIdiom == .phone { tabTray.statusBarBG.alpha = 1 tabTray.searchBarHolder.alpha = 1 } // Since we are hiding the collection view and the snapshot API takes the snapshot after the next screen update, // the screenshot ends up being blank unless we set the collection view hidden after the screen update happens. // To work around this, we dispatch the setting of collection view to hidden after the screen update is completed. DispatchQueue.main.async { tabTray.collectionView.isHidden = true let finalFrame = calculateCollapsedCellFrameUsingCollectionView(tabTray.collectionView, atIndex: scrollToIndex) tabTray.toolbar.transform = CGAffineTransform(translationX: 0, y: UIConstants.BottomToolbarHeight) let frameResizeClosure = { cell.frame = finalFrame cell.layoutIfNeeded() transformHeaderFooterForBVC(bvc, toFrame: finalFrame, container: container) resetTransformsForViews([tabCollectionViewSnapshot]) } if UIAccessibility.isReduceMotionEnabled { frameResizeClosure() } UIView.animate(withDuration: self.transitionDuration(using: transitionContext), delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 0, options: [], animations: { cell.title.transform = .identity UIApplication.shared.windows.first?.backgroundColor = UIColor.theme.tabTray.background tabTray.navigationController?.setNeedsStatusBarAppearanceUpdate() bvc.urlBar.updateAlphaForSubviews(0) bvc.footer.alpha = 0 tabCollectionViewSnapshot.alpha = 1 tabTray.statusBarBG.alpha = 1 tabTray.searchBarHolder.alpha = 1 tabTray.toolbar.transform = .identity if !UIAccessibility.isReduceMotionEnabled { frameResizeClosure() } }, completion: { finished in // Remove any of the views we used for the animation cell.removeFromSuperview() tabCollectionViewSnapshot.removeFromSuperview() tabTray.collectionView.isHidden = false bvc.toggleSnackBarVisibility(show: true) toggleWebViewVisibility(true, usingTabManager: bvc.tabManager) bvc.firefoxHomeViewController?.view.isHidden = false resetTransformsForViews([bvc.header, bvc.readerModeBar, bvc.footer]) bvc.urlBar.isTransitioning = false tabTray.toolbar.isUserInteractionEnabled = true transitionContext.completeTransition(true) }) } } } private func transformHeaderFooterForBVC(_ bvc: BrowserViewController, toFrame finalFrame: CGRect, container: UIView) { let footerForTransform = footerTransform(bvc.footer.frame, toFrame: finalFrame, container: container) let headerForTransform = headerTransform(bvc.header.frame, toFrame: finalFrame, container: container) bvc.footer.transform = footerForTransform bvc.header.transform = headerForTransform bvc.readerModeBar?.transform = headerForTransform } private func footerTransform( _ frame: CGRect, toFrame finalFrame: CGRect, container: UIView) -> CGAffineTransform { let frame = container.convert(frame, to: container) let endY = finalFrame.maxY - (frame.size.height / 2) let endX = finalFrame.midX let translation = CGPoint(x: endX - frame.midX, y: endY - frame.midY) let scaleX = finalFrame.width / frame.width var transform: CGAffineTransform = .identity transform = transform.translatedBy(x: translation.x, y: translation.y) transform = transform.scaledBy(x: scaleX, y: scaleX) return transform } private func headerTransform(_ frame: CGRect, toFrame finalFrame: CGRect, container: UIView) -> CGAffineTransform { let frame = container.convert(frame, to: container) let endY = finalFrame.minY + (frame.size.height / 2) let endX = finalFrame.midX let translation = CGPoint(x: endX - frame.midX, y: endY - frame.midY) let scaleX = finalFrame.width / frame.width var transform: CGAffineTransform = .identity transform = transform.translatedBy(x: translation.x, y: translation.y) transform = transform.scaledBy(x: scaleX, y: scaleX) return transform } //MARK: Private Helper Methods private func calculateCollapsedCellFrameUsingCollectionView(_ collectionView: UICollectionView, atIndex index: Int) -> CGRect { guard index < collectionView.numberOfItems(inSection: 0) else { return .zero } if let attr = collectionView.collectionViewLayout.layoutAttributesForItem(at: IndexPath(item: index, section: 0)) { return collectionView.convert(attr.frame, to: collectionView.superview) } else { return .zero } } private func calculateExpandedCellFrameFromBVC(_ bvc: BrowserViewController) -> CGRect { var frame = bvc.webViewContainer.frame // If we're navigating to a home panel and we were expecting to show the toolbar, add more height to end frame since // there is no toolbar for home panels if !bvc.shouldShowFooterForTraitCollection(bvc.traitCollection) { return frame } if let url = bvc.tabManager.selectedTab?.url, bvc.toolbar == nil, let internalPage = InternalURL(url), internalPage.isAboutURL { frame.size.height += UIConstants.BottomToolbarHeight } return frame } private func shouldDisplayFooterForBVC(_ bvc: BrowserViewController) -> Bool { guard let url = bvc.tabManager.selectedTab?.url else { return false } let isAboutPage = InternalURL(url)?.isAboutURL ?? false return bvc.shouldShowFooterForTraitCollection(bvc.traitCollection) && !isAboutPage } private func toggleWebViewVisibility(_ show: Bool, usingTabManager tabManager: TabManager) { for i in 0..<tabManager.count { if let tab = tabManager[i] { tab.webView?.isHidden = !show } } } private func resetTransformsForViews(_ views: [UIView?]) { for view in views { // Reset back to origin view?.transform = .identity } } private func createTransitionCellFromTab(_ tab: Tab?, withFrame frame: CGRect) -> TabCell { let cell = TabCell(frame: frame) cell.screenshotView.image = tab?.screenshot cell.titleText.text = tab?.displayTitle if let favIcon = tab?.displayFavicon { cell.favicon.sd_setImage(with: URL(string: favIcon.url)!) } else { let defaultFavicon = UIImage(named: "defaultFavicon") if tab?.isPrivate ?? false { cell.favicon.image = defaultFavicon cell.favicon.tintColor = (tab?.isPrivate ?? false) ? UIColor.Photon.White100 : UIColor.Photon.Grey60 } else { cell.favicon.image = defaultFavicon } } return cell }
mpl-2.0
74e696d0971189ca4219eabac30c68cf
45.16092
172
0.695219
5.591368
false
false
false
false
linkedin/LayoutKit
LayoutKitSampleApp/Benchmarks/FeedItemUIStackView.swift
1
5590
// Copyright 2016 LinkedIn Corp. // 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. import UIKit /// A LinkedIn feed item that is implemented with UIStackView. @available(iOS 9.0, *) class FeedItemUIStackView: DebugStackView, DataBinder { let actionLabel: UILabel = UILabel() let optionsLabel: UILabel = { let l = UILabel() l.text = "..." l.setContentHuggingPriority(UILayoutPriority.required, for: .horizontal) l.setContentCompressionResistancePriority(UILayoutPriority.required, for: .horizontal) return l }() lazy var topBar: UIStackView = { let v = DebugStackView(arrangedSubviews: [self.actionLabel, self.optionsLabel]) v.axis = .horizontal v.distribution = .fill v.alignment = .leading v.viewId = "topBar" v.backgroundColor = UIColor.blue return v }() let posterImageView: UIImageView = { let i = UIImageView() i.image = UIImage(named: "50x50.png") i.backgroundColor = UIColor.orange i.contentMode = .center i.setContentHuggingPriority(UILayoutPriority.required, for: .horizontal) i.setContentCompressionResistancePriority(UILayoutPriority.required, for: .horizontal) return i }() let posterNameLabel: UILabel = UILabel() let posterHeadlineLabel: UILabel = { let l = UILabel() l.numberOfLines = 3 return l }() let posterTimeLabel: UILabel = UILabel() lazy var posterLabels: DebugStackView = { let v = DebugStackView(arrangedSubviews: [self.posterNameLabel, self.posterHeadlineLabel, self.posterTimeLabel]) v.axis = .vertical v.spacing = 1 v.layoutMargins = UIEdgeInsets(top: 1, left: 2, bottom: 3, right: 4) v.isLayoutMarginsRelativeArrangement = true v.viewId = "posterLabels" return v }() lazy var posterCard: DebugStackView = { let v = DebugStackView(arrangedSubviews: [self.posterImageView, self.posterLabels]) v.axis = .horizontal v.alignment = .center v.viewId = "posterCard" return v }() let posterCommentLabel: UILabel = UILabel() let contentImageView: UIImageView = { let i = UIImageView() i.image = UIImage(named: "350x200.png") i.contentMode = .scaleAspectFit i.backgroundColor = UIColor.orange return i }() let contentTitleLabel: UILabel = UILabel() let contentDomainLabel: UILabel = UILabel() let likeLabel: UILabel = { let l = UILabel() l.backgroundColor = UIColor(red: 0, green: 0.9, blue: 0, alpha: 1) l.text = "Like" return l }() let commentLabel: UILabel = { let l = UILabel() l.text = "Comment" l.backgroundColor = UIColor(red: 0, green: 1.0, blue: 0, alpha: 1) l.textAlignment = .center return l }() let shareLabel: UILabel = { let l = UILabel() l.text = "Share" l.backgroundColor = UIColor(red: 0, green: 0.8, blue: 0, alpha: 1) l.textAlignment = .right return l }() lazy var actions: DebugStackView = { let v = DebugStackView(arrangedSubviews: [self.likeLabel, self.commentLabel, self.shareLabel]) v.axis = .horizontal v.distribution = .equalSpacing v.viewId = "actions" return v }() let actorImageView: UIImageView = { let i = UIImageView() i.image = UIImage(named: "50x50.png") i.setContentHuggingPriority(UILayoutPriority.required, for: .horizontal) i.setContentCompressionResistancePriority(UILayoutPriority.required, for: .horizontal) return i }() let actorCommentLabel: UILabel = UILabel() lazy var comment: DebugStackView = { let v = DebugStackView(arrangedSubviews: [self.actorImageView, self.actorCommentLabel]) v.axis = .horizontal v.viewId = "comment" return v }() convenience init() { self.init(arrangedSubviews: []) axis = .vertical viewId = "ComplexStackView" let subviews = [ topBar, posterCard, posterCommentLabel, contentImageView, contentTitleLabel, contentDomainLabel, actions, comment ] for view in subviews { view.translatesAutoresizingMaskIntoConstraints = false addArrangedSubview(view) } } func setData(_ data: FeedItemData) { actionLabel.text = data.actionText posterNameLabel.text = data.posterName posterHeadlineLabel.text = data.posterHeadline posterTimeLabel.text = data.posterTimestamp posterCommentLabel.text = data.posterComment contentTitleLabel.text = data.contentTitle contentDomainLabel.text = data.contentDomain actorCommentLabel.text = data.actorComment } override func sizeThatFits(_ size: CGSize) -> CGSize { return systemLayoutSizeFitting(CGSize(width: size.width, height: 0)) } } @available(iOS 9.0, *) class DebugStackView: UIStackView { var viewId: String = "" }
apache-2.0
34ffd8a3619debc0654504e05253d72e
31.312139
131
0.633989
4.570728
false
false
false
false
naocanfen/CDNY
cdny/cdny/Tools/UserDefaultsTools.swift
1
958
// // UserDefaultsTools.swift // ChengDuNongYe // // Created by MAC_HANMO on 2017/7/19. // Copyright © 2017年 MAC_HANMO. All rights reserved. // import UIKit // 本地文件 class UserDefaultsTools{ // 保存,或修改 class func saveInfo(_ name:String,_ key:String) { if (0 <= name.characters.count) { let userDefault = UserDefaults.standard userDefault.set(name, forKey: key) userDefault.synchronize() // let alert = UIAlertView(title: "温馨提示", message: "保存成功", delegate: nil, cancelButtonTitle: "知道了") // alert.show() } } // 读取 class func readInfo(_ key:String) -> String { let userDefault = UserDefaults.standard let name = userDefault.object(forKey: key) as? String if (name != nil) { return name! } return "-1" } }
mit
09cb029681e4e6d9717da82e44afb5a8
21.725
110
0.546755
3.952174
false
false
false
false
redcenturion/GGJ2016
Lightkeeper/AboutScene.swift
1
6237
// // About.swift // Lightkeeper // // Created by Peter Huynh on 1/31/16. // Copyright © 2016 GGJ2016. All rights reserved. // import Foundation import SpriteKit class AboutScene: SKScene { private var playButton: SKNode? private var aboutButton: SKNode? override func didMoveToView(view: SKView) { print("We are now in main menu scene") // Background self.backgroundColor = UIColor.blackColor() // Add the UI elements of the scene setupPlayButton() setupAboutButton() setupBackgroundEffect() setupBackgroundEffect1() //swipe gestures let swipeRight:UISwipeGestureRecognizer = UISwipeGestureRecognizer(target: self, action: Selector("swipedRight:")) swipeRight.direction = .Right view.addGestureRecognizer(swipeRight) } func touchesBegin(touches: NSSet, withEvent event: UIEvent) { self.menuHelper(touches) } private func menuHelper(touches:NSSet) { for touch in touches { let nodeAtTouch = self.nodeAtPoint(touch.locationInNode(self)) if nodeAtTouch.name == "Play" { print("Play button pressed") } else if nodeAtTouch.name == "About" { print("About button pressed") } } } // MARK: UI Elements private func setupBackgroundEffect() { let path = NSBundle.mainBundle().pathForResource("greenMagic", ofType: "sks") let greenMagicParticle = NSKeyedUnarchiver.unarchiveObjectWithFile(path!) as! SKEmitterNode greenMagicParticle.position = CGPointMake(self.size.width/2, self.size.height/2) greenMagicParticle.name = "greenMagicParticle" greenMagicParticle.targetNode = self.scene self.addChild(greenMagicParticle) } private func setupBackgroundEffect1() { let path = NSBundle.mainBundle().pathForResource("Fire", ofType: "sks") let FireParticle = NSKeyedUnarchiver.unarchiveObjectWithFile(path!) as! SKEmitterNode FireParticle.position = CGPointMake(self.size.width/2, self.size.height/1.8) FireParticle.name = "FireParticle" FireParticle.targetNode = self.scene self.addChild(FireParticle) } private func setupPlayButton() { print("Setting up the play button") // Create title label let titleLabel: SKLabelNode = SKLabelNode() titleLabel.text = "The lands are overwhelmed in darkness but" titleLabel.fontColor = SKColor.whiteColor() titleLabel.name = "Play" titleLabel.position = CGPointMake(0,160) let titleLabel1: SKLabelNode = SKLabelNode() titleLabel1.text = "performing a Dawn of Day ritual will awaken the great sun." titleLabel1.fontColor = SKColor.whiteColor() titleLabel1.name = "Play1" titleLabel1.position = CGPointMake(0,120) let titleLabel2: SKLabelNode = SKLabelNode() titleLabel2.text = "As the Lightkeeper you must complete the ritual by" titleLabel2.fontColor = SKColor.whiteColor() titleLabel2.name = "Play2" titleLabel2.position = CGPointMake(0,80) let titleLabel3: SKLabelNode = SKLabelNode() titleLabel3.text = "collecting orbs of light in the order that they appear." titleLabel3.fontColor = SKColor.whiteColor() titleLabel3.name = "Play3" titleLabel3.position = CGPointMake(0,40) let titleLabel4: SKLabelNode = SKLabelNode() titleLabel4.text = "If you successfully collect the orbs you will be rewarded" titleLabel4.fontColor = SKColor.whiteColor() titleLabel4.name = "Play4" titleLabel4.position = CGPointMake(0,0) let titleLabel5: SKLabelNode = SKLabelNode() titleLabel5.text = "with the warmth and light of the sun. Good luck!" titleLabel5.fontColor = SKColor.whiteColor() titleLabel5.name = "Play5" titleLabel5.position = CGPointMake(0,-40) titleLabel.zPosition = 5 titleLabel1.zPosition = 5 playButton = SKSpriteNode(color: SKColor.greenColor(), size: CGSize(width: 0, height: 0)) // Put it in the center of the scene if let playButton = playButton { playButton.position = CGPoint(x:CGRectGetMidX(self.frame), y:CGRectGetMidY(self.frame)); playButton.zPosition = 4 playButton.addChild(titleLabel) playButton.addChild(titleLabel1) playButton.addChild(titleLabel2) playButton.addChild(titleLabel3) playButton.addChild(titleLabel4) playButton.addChild(titleLabel5) self.addChild(playButton) } else { print("something went wrong!") } } private func setupAboutButton() { print("Setting up the play button") // Create title label let titleLabel: SKLabelNode = SKLabelNode() titleLabel.text = "Swipe right to return to main menu" titleLabel.fontColor = SKColor.whiteColor() titleLabel.zPosition = 5 aboutButton = SKSpriteNode(color: SKColor.greenColor(), size: CGSize(width: 0, height: 0)) // Put it in the center of the scene if let aboutButton = aboutButton, playButton = playButton { aboutButton.position = CGPoint(x: playButton.position.x, y: playButton.position.y - 140); aboutButton.zPosition = 4 aboutButton.addChild(titleLabel) self.addChild(aboutButton) } else { print("something went wrong!") } } // Swipe right to enter gameplay scene func swipedRight(sender:UISwipeGestureRecognizer) { let gameSceneTemp = MainMenuScene(size: self.size) gameSceneTemp.scaleMode = scaleMode let reveal = SKTransition.fadeWithDuration(1) self.view?.presentScene(gameSceneTemp, transition: reveal) print("swiped right") } }
mit
e77fc488dab1904a4513445b7fb8ff0c
34.634286
122
0.623958
5.016895
false
false
false
false
policante/PageControl
PageControl/Classes/PageControl.swift
1
10976
// // PageControl.swift // PageControl // // Created by Rodrigo Martins on 09/06/2017. // Copyright (c) 2017 Rodrigo Martins. All rights reserved. // import UIKit public protocol PageControlDelegate{ func pageControl(_ pageController: PageControlViewController, atSelected viewController: UIViewController) func pageControl(_ pageController: PageControlViewController, atUnselected viewController: UIViewController) } @objc public protocol PageControlDataSource{ @objc optional func pageControl(_ pageController: PageControlViewController, sizeAtRow row: Int) -> CGSize @objc optional func pageControl(_ pageController: PageControlViewController, willShow viewController: UIViewController) @objc optional func pageControl(_ pageController: PageControlViewController, didShow viewController: UIViewController) func numberOfCells(in pageController: PageControlViewController) -> Int func pageControl(_ pageController: PageControlViewController, cellAtRow row: Int) -> UIViewController } public class PageControlViewController: UIViewController, UICollectionViewDelegate { open var delegate: PageControlDelegate? = nil open var dataSource: PageControlDataSource? = nil open var animationSpeed: TimeInterval = 1 fileprivate var oldPosition: Int = 0 fileprivate var currentPos : Int = 0 { willSet{ self.oldPosition = currentPos } } fileprivate var currentPage: [StepPage: UIViewController?] = [:] internal enum StepPage { case prev case current case next } internal enum PageFlow { case left case rigth case nothing } open var infiniteMode: Bool = false { didSet{ updateData() } } open var count: Int { if let dataSource = self.dataSource { return dataSource.numberOfCells(in: self) } return 0 } open var currentPosition: Int { get{ return currentPos } set{ if newValue >= 0 , newValue < self.count { let oldPosition = currentPos currentPos = newValue if currentPos > oldPosition { self.setupViews(flow: .rigth) }else if currentPos < oldPosition { self.setupViews(flow: .left) }else{ self.setupViews(flow: .nothing) } } } } override public func viewDidLoad() { super.viewDidLoad() let swipeRight = UISwipeGestureRecognizer(target: self, action: #selector(PageControlViewController.slideToRightGestureRecognizer(_:))) swipeRight.direction = .right self.view.addGestureRecognizer(swipeRight) let swipeLeft = UISwipeGestureRecognizer(target: self, action: #selector(PageControlViewController.slideToLeftGestureRecognizer(_:))) swipeLeft.direction = .left self.view.addGestureRecognizer(swipeLeft) self.updateData() } open func updateData(){ self.currentPage.removeAll() for vc in self.children { remove(viewController: vc, multiplier: 0, animation: false) } guard self.count > 0 else { return } if self.currentPos >= self.count { self.currentPos = self.count - 1 } if self.currentPos <= 0 { self.currentPos = 0 } self.setupViews(flow: .nothing) } open func nextPage(){ let oldPosition = currentPos if (currentPos + 1) < self.count { currentPos += 1 }else{ if infiniteMode { currentPos = 0 } } if oldPosition != currentPos { self.setupViews(flow: .rigth) } } open func previousPage(){ let oldPosition = currentPos if (currentPos - 1) >= 0 { currentPos -= 1 }else{ if infiniteMode { currentPos = count } } if oldPosition != currentPos { self.setupViews(flow: .left) } } fileprivate func setupViews(flow: PageFlow){ guard let dataSource = self.dataSource else { return } print("\(self.currentPos)") switch flow{ case .left: flowToLeft() break case .rigth: flowToRight() break default: break } if self.currentPage[.current]??.parent == nil { let vc = dataSource.pageControl(self, cellAtRow: self.currentPos) vc.view.frame.size = dataSource.pageControl?(self, sizeAtRow: self.currentPos) ?? self.view.bounds.size self.currentPage[.current] = vc } if self.currentPage[.prev] == nil { self.buildPrevController() } if self.currentPage[.next] == nil { self.buildNextController() } for (step, page) in self.currentPage{ if let viewController = page { var multiplier: CGFloat switch step { case .prev: multiplier = -1 break case .current: multiplier = 0 break case .next: multiplier = 1 break } addViewController(viewController: viewController, multiplier: multiplier) } } } private func addViewController(viewController vc: UIViewController, multiplier: CGFloat, animation: Bool = true){ var newAttached = false var skipAnimation = false if vc.parent == nil { newAttached = true self.addChild(vc) self.view.addSubview(vc.view) vc.didMove(toParent: self) } let pageSize = vc.view.frame.size let spaceH = (self.view.frame.size.width - pageSize.width) / 2 let spaceV = (self.view.frame.size.height - pageSize.height) / 2 let toX = spaceH + (pageSize.width + 7) * multiplier if newAttached { var fromX: CGFloat if self.currentPos > self.oldPosition { if multiplier > 0 { fromX = spaceH + (pageSize.width + 7) * 2 }else{ fromX = spaceH + (pageSize.width + 7) * -2 } }else if self.currentPos < self.oldPosition{ if multiplier > 0 { fromX = spaceH + (pageSize.width + 7) * 2 }else{ fromX = spaceH + (pageSize.width + 7) * -2 } }else { skipAnimation = true fromX = toX } vc.view.frame = CGRect(x: fromX, y: spaceV, width: pageSize.width , height: pageSize.height) } if !skipAnimation, animation { UIView.animate(withDuration: animationSpeed, animations: { vc.view.frame = CGRect(x: toX, y: spaceV, width: pageSize.width , height: pageSize.height) }, completion: nil) }else{ vc.view.frame = CGRect(x: toX, y: spaceV, width: pageSize.width , height: pageSize.height) } } private func remove(viewController vc: UIViewController, multiplier: CGFloat, animation: Bool = true){ if animation { let pageSize = vc.view.frame.size let spaceH = (self.view.frame.size.width - pageSize.width) / 2 let spaceV = (self.view.frame.size.height - pageSize.height) / 2 let originX = spaceH + (pageSize.width + 7) * multiplier UIView.animate(withDuration: animationSpeed, animations: { vc.view.frame = CGRect(x: originX, y: spaceV, width: pageSize.width , height: pageSize.height) }) { _ in vc.willMove(toParent: nil) vc.view.removeFromSuperview() vc.removeFromParent() } }else{ vc.willMove(toParent: nil) vc.view.removeFromSuperview() vc.removeFromParent() } } fileprivate func buildPrevController(){ guard let dataSource = self.dataSource else { return } if self.currentPos == 0 { if infiniteMode { let row = self.count - 1 let vc = dataSource.pageControl(self, cellAtRow: row) let size = dataSource.pageControl?(self, sizeAtRow: row) ?? self.view.bounds.size let spaceV = (self.view.frame.size.height - size.height) / 2 vc.view.frame = CGRect(x: -self.view.bounds.width, y: spaceV, width: size.width, height: size.height) self.currentPage[.prev] = vc }else{ self.currentPage[.prev] = nil } }else{ let row = self.currentPos - 1 let vc = dataSource.pageControl(self, cellAtRow: row) let size = dataSource.pageControl?(self, sizeAtRow: row) ?? self.view.bounds.size let spaceV = (self.view.frame.size.height - size.height) / 2 vc.view.frame = CGRect(x: -self.view.bounds.width, y: spaceV, width: size.width, height: size.height) self.currentPage[.prev] = vc } } fileprivate func buildNextController(){ guard let dataSource = self.dataSource else { return } if self.currentPos == self.count - 1 { if infiniteMode { let vc = dataSource.pageControl(self, cellAtRow: 0) let size = dataSource.pageControl?(self, sizeAtRow: 0) ?? self.view.bounds.size let spaceV = (self.view.frame.size.height - size.height) / 2 vc.view.frame = CGRect(x: self.view.bounds.width, y: spaceV, width: size.width, height: size.height) self.currentPage[.next] = vc }else{ self.currentPage[.next] = nil } }else{ let row = self.currentPos + 1 let vc = dataSource.pageControl(self, cellAtRow: row) let size = dataSource.pageControl?(self, sizeAtRow: row) ?? self.view.bounds.size let spaceV = (self.view.frame.size.height - size.height) / 2 vc.view.frame = CGRect(x: self.view.bounds.width, y: spaceV, width: size.width, height: size.height) self.currentPage[.next] = vc } } fileprivate func flowToLeft(){ if (self.oldPosition - self.currentPos) == 1 { if let page = currentPage[.next], let viewController = page { remove(viewController: viewController, multiplier: 2, animation: true) } currentPage[.next] = currentPage[.current] currentPage[.current] = currentPage[.prev] currentPage[.prev] = nil }else{ if let page = currentPage[.next], let viewController = page { remove(viewController: viewController, multiplier: 2, animation: true) } if let page = currentPage[.current], let viewController = page { remove(viewController: viewController, multiplier: 2, animation: true) } if let page = currentPage[.prev], let viewController = page { remove(viewController: viewController, multiplier: -2, animation: true) } currentPage[.next] = nil currentPage[.current] = nil currentPage[.prev] = nil } } fileprivate func flowToRight(){ if (self.currentPos - self.oldPosition) == 1 { if let page = currentPage[.prev], let viewController = page { remove(viewController: viewController, multiplier: -2, animation: true) } currentPage[.prev] = currentPage[.current] currentPage[.current] = currentPage[.next] currentPage[.next] = nil }else{ if let page = currentPage[.prev], let viewController = page { remove(viewController: viewController, multiplier: -2, animation: true) } if let page = currentPage[.current], let viewController = page { remove(viewController: viewController, multiplier: -2, animation: true) } if let page = currentPage[.next], let viewController = page { remove(viewController: viewController, multiplier: 2, animation: true) } currentPage[.prev] = nil currentPage[.current] = nil currentPage[.next] = nil } } @objc fileprivate func slideToRightGestureRecognizer(_ gesture: UISwipeGestureRecognizer){ previousPage() } @objc fileprivate func slideToLeftGestureRecognizer(_ gesture: UISwipeGestureRecognizer){ nextPage() } }
mit
55f832d9802c8d60123f802518656256
27.215938
143
0.671829
3.767937
false
false
false
false
PureSwift/Bluetooth
Sources/BluetoothHCI/AdvertisingInterval.swift
1
2835
// // AdvertisingInterval.swift // Bluetooth // // Created by Alsey Coleman Miller on 6/1/18. // Copyright © 2018 PureSwift. All rights reserved. // /** Advertising Interval For all undirected advertising events, the time between the start of two consec- utive advertising events (`T_advEvent`) is computed as follows for each adver- tising event: ``` T_advEvent = advInterval + advDelay ``` The `advInterval` shall be an integer multiple of 0.625 ms in the range of `20` ms to `10.24` s. If the advertising event type is either a scannable undirected event type or a non-connectable undirected event type, the advInterval shall not be less than 100 ms. If the advertising event type is a connectable undirected event type, the advInterval can be 20 ms or greater. The `advDelay` is a pseudo-random value with a range of 0 ms to 10 ms generated by the Link Layer for each advertising event. As illustrated, the advertising events are perturbed in time using the `advDelay`. ![Image](https://github.com/PureSwift/Bluetooth/raw/master/Assets/AdvertisingInterval.png) */ @frozen public struct AdvertisingInterval: Equatable, Hashable { public let rawValue: UInt16 public init?(rawValue: UInt16) { guard rawValue <= AdvertisingInterval.max.rawValue, rawValue >= AdvertisingInterval.min.rawValue else { return nil } self.rawValue = rawValue } private init(_ unsafe: UInt16) { self.rawValue = unsafe } } // MARK: - Conversion public extension AdvertisingInterval { /// Initialize with the specified time in miliseconds. init?(miliseconds: Int) { let rawValue = Double(miliseconds) / 0.625 guard rawValue <= Double(AdvertisingInterval.max.rawValue), rawValue >= Double(AdvertisingInterval.min.rawValue) else { return nil } self.rawValue = UInt16(rawValue) } /// Value converted to miliseconds. var miliseconds: Int { return Int(Double(rawValue) * 0.625) } } // MARK: - Definitions public extension AdvertisingInterval { /// Minimum value. static var min: AdvertisingInterval { return AdvertisingInterval(0x0020) } /// Maximum value. static var max: AdvertisingInterval { return AdvertisingInterval(0x4000) } /// Default value. static var `default`: AdvertisingInterval { return AdvertisingInterval(0x0800) } } // MARK: - Comparable extension AdvertisingInterval: Comparable { public static func < (lhs: AdvertisingInterval, rhs: AdvertisingInterval) -> Bool { return lhs.rawValue < rhs.rawValue } } // MARK: - CustomStringConvertible extension AdvertisingInterval: CustomStringConvertible { public var description: String { return "\(miliseconds)ms" } }
mit
848c72a361fe27821b8f852724872bf1
30.142857
373
0.693719
4.346626
false
false
false
false
stripe/stripe-ios
Example/Basic Integration/Basic Integration/EmojiCheckoutCell.swift
1
2099
// // EmojiCheckoutCell.swift // Basic Integration // // Created by Yuki Tokuhiro on 5/29/19. // Copyright © 2019 Stripe. All rights reserved. // import UIKit class EmojiCheckoutCell: UITableViewCell { let emojiLabel: UILabel let detailLabel: UILabel let priceLabel: UILabel override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { priceLabel = UILabel() priceLabel.font = UIFont.systemFont(ofSize: 18, weight: .regular) detailLabel = UILabel() detailLabel.font = UIFont.systemFont(ofSize: 14) detailLabel.textColor = .stripeDarkBlue emojiLabel = UILabel() emojiLabel.font = UIFont.systemFont(ofSize: 52) super.init(style: style, reuseIdentifier: reuseIdentifier) installConstraints() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func installConstraints() { for view in [emojiLabel, priceLabel, detailLabel] { view.translatesAutoresizingMaskIntoConstraints = false contentView.addSubview(view) } NSLayoutConstraint.activate([ emojiLabel.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 12), emojiLabel.centerYAnchor.constraint(equalTo: contentView.centerYAnchor), detailLabel.leadingAnchor.constraint(equalTo: emojiLabel.trailingAnchor, constant: 12), detailLabel.centerYAnchor.constraint(equalTo: contentView.centerYAnchor), priceLabel.trailingAnchor.constraint( equalTo: contentView.trailingAnchor, constant: -16), priceLabel.centerYAnchor.constraint(equalTo: contentView.centerYAnchor), ]) } public func configure(with product: Product, numberFormatter: NumberFormatter) { priceLabel.text = numberFormatter.string(from: NSNumber(value: Float(product.price) / 100))! emojiLabel.text = product.emoji detailLabel.text = product.emoji.unicodeScalars.first?.properties.name?.localizedCapitalized } }
mit
0f4ee37f26f3a96b03bd96dd55566478
35.807018
100
0.692088
5.23192
false
false
false
false
ello/ello-ios
Sources/Networking/ElloS3.swift
1
3256
//// /// ElloS3.swift // // creds = AmazonCredentials(...) (from ElloAPI.amazonCredentials) // data = NSData() // // uploader = ElloS3( // credentials: credentials, // filename: "foo.txt", // data: data, // contentType: "text/plain" // ) // .start() // .done { response in } // .catch { error in } import PromiseKit class ElloS3 { let filename: String let data: Data let contentType: String let credentials: AmazonCredentials let (promise, seal) = Promise<Data>.pending() init(credentials: AmazonCredentials, filename: String, data: Data, contentType: String) { self.filename = filename self.data = data self.contentType = contentType self.credentials = credentials } // this is just the uploading code, the initialization and handler code is // mostly the same func start() -> Promise<Data> { let key = "\(credentials.prefix)/\(filename)" let url = URL(string: credentials.endpoint)! let builder = MultipartRequestBuilder(url: url, capacity: data.count) builder.addParam("key", value: key) builder.addParam("AWSAccessKeyId", value: credentials.accessKey) if credentials.prefix.hasPrefix("logs/") { builder.addParam("acl", value: "private") } else { builder.addParam("acl", value: "public-read") } builder.addParam("success_action_status", value: "201") builder.addParam("policy", value: credentials.policy) builder.addParam("signature", value: credentials.signature) builder.addParam("Content-Type", value: self.contentType) // builder.addParam("Content-MD5", value: md5(data)) builder.addFile("file", filename: filename, data: data, contentType: contentType) let request = builder.buildRequest() let session = URLSession.shared let task = session.dataTask( with: request, completionHandler: { (data: Data?, response: URLResponse?, error: Error?) in let httpResponse = response as? HTTPURLResponse if let error = error { self.seal.reject(error) } else if let statusCode = httpResponse?.statusCode, statusCode >= 200 && statusCode < 300 { if let data = data { self.seal.fulfill(data) } else { self.seal.reject( NSError( domain: ElloErrorDomain, code: 0, userInfo: [NSLocalizedFailureReasonErrorKey: "failure"] ) ) } } else { self.seal.reject( NSError( domain: ElloErrorDomain, code: 0, userInfo: [NSLocalizedFailureReasonErrorKey: "failure"] ) ) } } ) task.resume() return promise } }
mit
0361c62be41c08ab2999ebf5ad42bd77
32.56701
93
0.516585
5.024691
false
false
false
false