repo_name
stringlengths
7
91
path
stringlengths
8
658
copies
stringclasses
125 values
size
stringlengths
3
6
content
stringlengths
118
674k
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6.09
99.2
line_max
int64
17
995
alpha_frac
float64
0.3
0.9
ratio
float64
2
9.18
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
NqiOS/DYTV-swift
DYTV/DYTV/Classes/Home/View/NQRecommendGameView.swift
1
1957
// // NQRecommendGameView.swift // DYTV // // Created by djk on 17/3/14. // Copyright © 2017年 NQ. All rights reserved. // import UIKit private let kGameCellID = "kGameCellID" private let kEdgeInsetMargin : CGFloat = 10 class NQRecommendGameView: UIView { // MARK: 控件属性 @IBOutlet weak var collectionView: UICollectionView! // MARK: 定义数据的属性 var groups : [NQBaseModel]? { didSet { // 刷新表格 collectionView.reloadData() } } // MARK: 系统回调 override func awakeFromNib() { super.awakeFromNib() // 让控件不随着父控件的拉伸而拉伸 autoresizingMask = UIViewAutoresizing() // 注册Cell collectionView.register(UINib(nibName: "NQCollectionGameCell", bundle: nil), forCellWithReuseIdentifier: kGameCellID) // 给collectionView添加内边距 collectionView.contentInset = UIEdgeInsets(top: 0, left: kEdgeInsetMargin, bottom: 0, right: kEdgeInsetMargin) } } // MARK:- 提供快速创建的类方法 extension NQRecommendGameView { class func recommendGameView() -> NQRecommendGameView { return Bundle.main.loadNibNamed("NQRecommendGameView", owner: nil, options: nil)?.first as! NQRecommendGameView } } // MARK:- 遵守UICollectionView的数据源协议 extension NQRecommendGameView : UICollectionViewDataSource { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return groups?.count ?? 0 } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: kGameCellID, for: indexPath) as! NQCollectionGameCell cell.gameModel = groups![(indexPath as NSIndexPath).item] return cell } }
mit
7bde9d7efe40d124f1809d75a9768628
29.566667
128
0.675573
5.066298
false
false
false
false
emilstahl/swift
test/SILGen/instrprof_operators.swift
14
1930
// RUN: %target-swift-frontend -parse-as-library -emit-silgen -profile-generate %s | FileCheck %s // CHECK: sil hidden @[[F_OPERATORS:.*operators.*]] : // CHECK: %[[NAME:.*]] = string_literal utf8 "[[F_OPERATORS]]" // CHECK: %[[HASH:.*]] = integer_literal $Builtin.Int64, // CHECK: %[[NCOUNTS:.*]] = integer_literal $Builtin.Int32, 4 // CHECK: %[[INDEX:.*]] = integer_literal $Builtin.Int32, 0 // CHECK: builtin "int_instrprof_increment"(%[[NAME]] : {{.*}}, %[[HASH]] : {{.*}}, %[[NCOUNTS]] : {{.*}}, %[[INDEX]] : {{.*}}) func operators(a : Bool, b : Bool) { let c = a && b let d = a || b // CHECK: %[[NAME:.*]] = string_literal utf8 "[[F_OPERATORS]]" // CHECK: %[[HASH:.*]] = integer_literal $Builtin.Int64, // CHECK: %[[NCOUNTS:.*]] = integer_literal $Builtin.Int32, 4 // CHECK: %[[INDEX:.*]] = integer_literal $Builtin.Int32, 3 // CHECK: builtin "int_instrprof_increment"(%[[NAME]] : {{.*}}, %[[HASH]] : {{.*}}, %[[NCOUNTS]] : {{.*}}, %[[INDEX]] : {{.*}}) let e = c ? a : b // CHECK-NOT: builtin "int_instrprof_increment" } // CHECK: implicit closure // CHECK: %[[NAME:.*]] = string_literal utf8 "[[F_OPERATORS]]" // CHECK: %[[HASH:.*]] = integer_literal $Builtin.Int64, // CHECK: %[[NCOUNTS:.*]] = integer_literal $Builtin.Int32, 4 // CHECK: %[[INDEX:.*]] = integer_literal $Builtin.Int32, 1 // CHECK: builtin "int_instrprof_increment"(%[[NAME]] : {{.*}}, %[[HASH]] : {{.*}}, %[[NCOUNTS]] : {{.*}}, %[[INDEX]] : {{.*}}) // CHECK-NOT: builtin "int_instrprof_increment" // CHECK: implicit closure // CHECK: %[[NAME:.*]] = string_literal utf8 "[[F_OPERATORS]]" // CHECK: %[[HASH:.*]] = integer_literal $Builtin.Int64, // CHECK: %[[NCOUNTS:.*]] = integer_literal $Builtin.Int32, 4 // CHECK: %[[INDEX:.*]] = integer_literal $Builtin.Int32, 2 // CHECK: builtin "int_instrprof_increment"(%[[NAME]] : {{.*}}, %[[HASH]] : {{.*}}, %[[NCOUNTS]] : {{.*}}, %[[INDEX]] : {{.*}}) // CHECK-NOT: builtin "int_instrprof_increment"
apache-2.0
8c2413d55487eb626f9fe57f0d973e0c
51.162162
127
0.567358
3.282313
false
false
false
false
czechboy0/Redbird
Sources/Redis/RedisID.swift
1
2334
import Foundation import Vapor /// A type-safe representation of a String representing individual identifiers of separate Redis connections and configurations. /// /// It is recommended to define static extensions for your definitions to make it easier at call sites to reference them. /// /// For example: /// ```swift /// extension RedisID { static let oceanic = RedisID("oceanic") } /// app.redis(.oceanic) // Application.Redis instance /// ``` public struct RedisID: Hashable, Codable, RawRepresentable, ExpressibleByStringLiteral, ExpressibleByStringInterpolation, CustomStringConvertible, Comparable { public let rawValue: String public init(stringLiteral: String) { self.rawValue = stringLiteral } public init(rawValue: String) { self.rawValue = rawValue } public init(_ string: String) { self.rawValue = string } public var description: String { rawValue } public static func < (lhs: RedisID, rhs: RedisID) -> Bool { lhs.rawValue < rhs.rawValue } public static let `default`: RedisID = "default" } extension Application { /// The default Redis connection. /// /// If different Redis configurations are in use, use the `redis(_:)` method to match by `RedisID` instead. public var redis: Redis { redis(.default) } /// Returns the Redis connection for the given ID. /// - Parameter id: The Redis ID that identifies the specific connection to be used. /// - Returns: A Redis connection that is identified by the given `id`. public func redis(_ id: RedisID) -> Redis { .init(application: self, redisID: id) } } extension Request { /// The default Redis connection. /// /// If different Redis configurations are in use, use the `redis(_:)` method to match by `RedisID` instead. public var redis: Redis { redis(.default) } /// Returns the Redis connection for the given ID. /// - Parameter id: The Redis ID that identifies the specific connection to be used. /// - Returns: A Redis connection that is identified by the given `id`. public func redis(_ id: RedisID) -> Redis { .init(request: self, id: id) } }
mit
35fe53a3c7df3125b5e075f38d203939
31.873239
128
0.634533
4.763265
false
false
false
false
SwifterSwift/SwifterSwift
Sources/SwifterSwift/UIKit/UITextFieldExtensions.swift
1
6641
// UITextFieldExtensions.swift - Copyright 2020 SwifterSwift #if canImport(UIKit) && !os(watchOS) import UIKit // MARK: - Enums public extension UITextField { /// SwifterSwift: UITextField text type. /// /// - emailAddress: UITextField is used to enter email addresses. /// - password: UITextField is used to enter passwords. /// - generic: UITextField is used to enter generic text. enum TextType { /// SwifterSwift: UITextField is used to enter email addresses. case emailAddress /// SwifterSwift: UITextField is used to enter passwords. case password /// SwifterSwift: UITextField is used to enter generic text. case generic } } // MARK: - Properties public extension UITextField { /// SwifterSwift: Set textField for common text types. var textType: TextType { get { if keyboardType == .emailAddress { return .emailAddress } else if isSecureTextEntry { return .password } return .generic } set { switch newValue { case .emailAddress: keyboardType = .emailAddress autocorrectionType = .no autocapitalizationType = .none isSecureTextEntry = false placeholder = "Email Address" case .password: keyboardType = .asciiCapable autocorrectionType = .no autocapitalizationType = .none isSecureTextEntry = true placeholder = "Password" case .generic: isSecureTextEntry = false } } } /// SwifterSwift: Check if text field is empty. var isEmpty: Bool { return text?.isEmpty == true } /// SwifterSwift: Return text with no spaces or new lines in beginning and end. var trimmedText: String? { return text?.trimmingCharacters(in: .whitespacesAndNewlines) } /// SwifterSwift: Check if textFields text is a valid email format. /// /// textField.text = "[email protected]" /// textField.hasValidEmail -> true /// /// textField.text = "swifterswift" /// textField.hasValidEmail -> false /// var hasValidEmail: Bool { // http://stackoverflow.com/questions/25471114/how-to-validate-an-e-mail-address-in-swift return text!.range(of: "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}", options: String.CompareOptions.regularExpression, range: nil, locale: nil) != nil } /// SwifterSwift: Left view tint color. @IBInspectable var leftViewTintColor: UIColor? { get { guard let iconView = leftView as? UIImageView else { return nil } return iconView.tintColor } set { guard let iconView = leftView as? UIImageView else { return } iconView.image = iconView.image?.withRenderingMode(.alwaysTemplate) iconView.tintColor = newValue } } /// SwifterSwift: Right view tint color. @IBInspectable var rightViewTintColor: UIColor? { get { guard let iconView = rightView as? UIImageView else { return nil } return iconView.tintColor } set { guard let iconView = rightView as? UIImageView else { return } iconView.image = iconView.image?.withRenderingMode(.alwaysTemplate) iconView.tintColor = newValue } } } // MARK: - Methods public extension UITextField { /// SwifterSwift: Clear text. func clear() { text = "" attributedText = NSAttributedString(string: "") } /// SwifterSwift: Set placeholder text color. /// /// - Parameter color: placeholder text color. func setPlaceHolderTextColor(_ color: UIColor) { guard let holder = placeholder, !holder.isEmpty else { return } attributedPlaceholder = NSAttributedString(string: holder, attributes: [.foregroundColor: color]) } /// SwifterSwift: Add padding to the left of the textfield rect. /// /// - Parameter padding: amount of padding to apply to the left of the textfield rect. func addPaddingLeft(_ padding: CGFloat) { leftView = UIView(frame: CGRect(x: 0, y: 0, width: padding, height: frame.height)) leftViewMode = .always } /// SwifterSwift: Add padding to the right of the textfield rect. /// /// - Parameter padding: amount of padding to apply to the right of the textfield rect. func addPaddingRight(_ padding: CGFloat) { rightView = UIView(frame: CGRect(x: 0, y: 0, width: padding, height: frame.height)) rightViewMode = .always } /// SwifterSwift: Add padding to the left of the textfield rect. /// /// - Parameters: /// - image: left image. /// - padding: amount of padding between icon and the left of textfield. func addPaddingLeftIcon(_ image: UIImage, padding: CGFloat) { let iconView = UIView(frame: CGRect(x: 0, y: 0, width: image.size.width + padding, height: image.size.height)) let imageView = UIImageView(image: image) imageView.frame = iconView.bounds imageView.contentMode = .center iconView.addSubview(imageView) leftView = iconView leftViewMode = .always } /// SwifterSwift: Add padding to the right of the textfield rect. /// /// - Parameters: /// - image: right image. /// - padding: amount of padding between icon and the right of textfield. func addPaddingRightIcon(_ image: UIImage, padding: CGFloat) { let iconView = UIView(frame: CGRect(x: 0, y: 0, width: image.size.width + padding, height: image.size.height)) let imageView = UIImageView(image: image) imageView.frame = iconView.bounds imageView.contentMode = .center iconView.addSubview(imageView) rightView = iconView rightViewMode = .always } /// Add tool bars to the textfield input accessory view. /// - Parameters: /// - items: The items to present in the toolbar. /// - height: The height of the toolbar. #if os(iOS) @discardableResult func addToolbar(items: [UIBarButtonItem]?, height: CGFloat = 44) -> UIToolbar { let toolBar = UIToolbar(frame: CGRect(x: 0.0, y: 0.0, width: UIScreen.main.bounds.size.width, height: height)) toolBar.setItems(items, animated: false) inputAccessoryView = toolBar return toolBar } #endif } #endif
mit
4ebd17be198c0b1956a0d0f9139167d6
33.769634
118
0.609095
4.8795
false
false
false
false
baiyidjp/SwiftWB
SwiftWeibo/SwiftWeibo/Classes/ViewModel(视图模型)/JPStatusViewModel(单条微博的视图模型).swift
1
7937
// // JPStatusViewModel.swift // SwiftWeibo // // Created by tztddong on 2016/11/29. // Copyright © 2016年 dongjiangpeng. All rights reserved. // import Foundation /// 单条微博的视图模型 class JPStatusViewModel: CustomStringConvertible { /// 微博模型 var status: JPStatusesModel /// 会员图标 var memberImage: UIImage? /// 昵称颜色 var nameColor: UIColor? /// 认证图标 -1:没有认证 0:认证用户 2.3.5:企业认证 220:达人 var verifiedImage: UIImage? /// 转发 评论 赞 var retweetStr: String? var commentStr: String? var unlikeStr: String? /// 来源字符串 var sourceStr: String? /// 配图大小 var pictureViewSize = CGSize() /// 如果是被转发的微博 原创微博一定没有图 var picURLs: [JPStatusPicModel]? { //如果没有被转发微博 返回原创微博的图片 return status.retweeted_status?.pic_urls ?? status.pic_urls } /// 被转发微博的文本 // var retweetText: String? /// 正文的属性(带表情)文本 var originalAttributeText: NSAttributedString? /// 转发微博的属性文本 var retweetAttributeText: NSAttributedString? var cellRowHeight: CGFloat = 0 /// 构造函数 /// - Parameter model: 微博模型 init(model: JPStatusesModel) { self.status = model /// 会员等级 0-6 common_icon_membership_level1 if (model.user?.mbrank)! > 0 && (model.user?.mbrank)! < 7 { let imageName = "common_icon_membership_level\(model.user?.mbrank ?? 1)" self.memberImage = UIImage(named: imageName) nameColor = UIColor.orange }else { nameColor = UIColor.black } switch model.user?.verified_type ?? -1 { case 0: verifiedImage = UIImage(named: "avatar_vip") case 2 , 3 , 5: verifiedImage = UIImage(named: "avatar_enterprise_vip") case 0: verifiedImage = UIImage(named: "avatar_grassroot") default: break } //设置底部bar retweetStr = countString(count: status.reposts_count, defaultStr: "转发") commentStr = countString(count: status.comments_count, defaultStr: "评论") unlikeStr = countString(count: status.attitudes_count, defaultStr: "赞") //计算图片view的size (有转发的时候使用转发) pictureViewSize = pictureSize(picCount: picURLs?.count) //被转发微博的文字 let retweetText = "@" + (status.retweeted_status?.user?.screen_name ?? "") + ":" + (status.retweeted_status?.text ?? "") // 文字大小 let originalFont = UIFont.systemFont(ofSize: 15) let retweetFont = UIFont.systemFont(ofSize: 14) //正文微博属性文本 originalAttributeText = JPEmoticonManager.shared.emoticonString(string: status.text ?? "", font: originalFont) //转发微博的属性文本 retweetAttributeText = JPEmoticonManager.shared.emoticonString(string: retweetText, font: retweetFont) //使用正则表达式抽取来源字符串 if ((status.source?.jp_hrefSource()?.text) != nil) { sourceStr = "来自 " + (status.source?.jp_hrefSource()?.text)! }else { sourceStr = "" } //MARK: 更新高度 updateCellHeight() } var description: String { return status.description } /// 将数字转换为描述结果 /// /// - Parameters: /// - count: 数字 /// - default: 默认字符串 /// - Returns: 结果 fileprivate func countString(count: Int,defaultStr: String) -> String { /* count == 0 默认字符串 count < 10000 实际数值 count >= 10000 xxx万 */ if count == 0 { return defaultStr } if count < 10000 { return count.description } return String(format: "%.02f万", Double(count)/10000) } /// 根据图片的数量 计算配图view的size /// /// - Parameter picCount: 配图数量 /// - Returns: view的size fileprivate func pictureSize(picCount: Int?) -> CGSize { if picCount == 0 || picCount == nil { return CGSize(width: 0, height: 0) } //计算行数 let row = (picCount! - 1) / 3 + 1 //计算高度 let pictureViewHeight = JPStatusPicOutterMargin + CGFloat(row) * JPStatusPictureWidth + CGFloat(row-1)*JPStatusPicIntterMargin return CGSize(width: JPStatusPictureViewWidth, height: pictureViewHeight) } /// 根据已缓存的单张图片更新配图view的尺寸 /// /// - Parameter image: 缓存的单张图片 func updatePicViewSizeWithImage(image: UIImage) { var size = CGSize(width: image.size.width*2, height: image.size.height*2) /// 对于图片的过宽和过窄的处理 let maxWidth: CGFloat = ScreenWidth - 2*JPStatusPicOutterMargin let minWidth: CGFloat = 40 let maxHeight: CGFloat = maxWidth*9/16 if size.width > maxWidth { size.width = maxWidth size.height = size.width*image.size.height/image.size.width } if size.width < minWidth { size.width = minWidth size.height = size.width*image.size.height/image.size.width/4 } if size.height > maxHeight { size.height = maxHeight } size.height += JPStatusPicOutterMargin pictureViewSize = size //MARK: 重新计算行高 updateCellHeight() } fileprivate func updateCellHeight() { /* 原创微博: 顶部视图(12)+间距(12)+头像的高度(34)+间距(12)+正文高度(计算)+配图高度(计算)+间距(12)+底部视图(36) 转发微博: 顶部视图(12)+间距(12)+头像的高度(34)+间距(12)+正文高度(计算)+间距(12)+间距(12)+转发文本高度(计算)+配图高度(计算)+间距(12)+底部视图(36) */ //间距/头像/底部视图 let margin: CGFloat = 12 let iconHeight: CGFloat = 34 let bottomHeight: CGFloat = 36 //期望文本size/正文字号/转发字号 let textSize = CGSize(width: ScreenWidth-2*margin, height: CGFloat(MAXFLOAT)) //cell 高度 var cellHeight: CGFloat = 0 //文本顶部的高度 cellHeight = 2*margin + iconHeight + margin //正文文本的高度 if let text = originalAttributeText { /// attribute 设置行高不再需要Font cellHeight += text.boundingRect(with: textSize, options: .usesLineFragmentOrigin, context: nil).height+1 } //判断是否是转发微博 if status.retweeted_status != nil { cellHeight += 2*margin //转发文本一定使用retweettext 这个是拼接了@昵称:的 if let rettext = retweetAttributeText { cellHeight += rettext.boundingRect(with: textSize, options: .usesLineFragmentOrigin, context: nil).height+1 } } //配图 cellHeight += pictureViewSize.height //底部 cellHeight += margin + bottomHeight //使用属性记录 cellRowHeight = cellHeight } }
mit
ef6ef364e78a03de259a7e8cb203d380
28.965812
134
0.541215
4.296569
false
false
false
false
poolmyride/DataStoreKit
Example/Tests/PendingNetworkTask.swift
1
1368
// // PendingNetworkTask.swift // // // Created by Rohit Talwar on 29/01/16. // Copyright © 2016 Rajat Talwar. All rights reserved. // import Foundation import DataStoreKit class PendingNetworkTask:ObjectCoder { var body:[String:Any]? var method:String? var url:String? var created:TimeInterval? required init(dictionary withDictionary: [String:Any]) { self.body = withDictionary["body"] as? [String:Any] self.method = withDictionary["method"] as? String self.url = withDictionary["url"] as? String self.created = withDictionary["created"] as? Double // self.created_str = self.created != nil ? "\(self.created!)" : nil } func toDictionary() -> [String:Any] { var dic = [String:Any]() // dic["method"] = self.method ?? "" // dic["url"] = self.url ?? "" // dic["created"] = self.created ?? NSDate().timeIntervalSince1970 self.body != nil ? dic["body"] = self.body! : () self.method != nil ? dic["method"] = self.method! : () self.url != nil ? dic["url"] = self.url! : () self.created != nil ? dic["created"] = self.created! : () // dic["created_str"] = self.created_str ?? "" return dic } static func identifierKey() -> String { return "created" } }
mit
394f13a2aa250320d166ae73d5ce07c4
28.085106
75
0.565472
3.839888
false
false
false
false
kousun12/RxSwift
RxCocoa/Common/Observables/NSObject+Rx+CoreGraphics.swift
5
5895
// // NSObject+Rx+CoreGraphics.swift // RxCocoa // // Created by Krunoslav Zaher on 7/30/15. // Copyright (c) 2015 Krunoslav Zaher. All rights reserved. // import Foundation #if !RX_NO_MODULE import RxSwift #endif import CoreGraphics #if arch(x86_64) || arch(arm64) let CGRectType = "{CGRect={CGPoint=dd}{CGSize=dd}}" let CGSizeType = "{CGSize=dd}" let CGPointType = "{CGPoint=dd}" #elseif arch(i386) || arch(arm) let CGRectType = "{CGRect={CGPoint=ff}{CGSize=ff}}" let CGSizeType = "{CGSize=ff}" let CGPointType = "{CGPoint=ff}" #endif // rx_observe + CoreGraphics extension NSObject { /** Specialization of generic `rx_observe` method. For more information take a look at `rx_observe` method. */ @warn_unused_result(message="http://git.io/rxs.uo") public func rx_observe(keyPath: String, options: NSKeyValueObservingOptions = [.New, .Initial], retainSelf: Bool = true) -> Observable<CGRect?> { return rx_observe(keyPath, options: options, retainSelf: retainSelf) .map { (value: NSValue?) in if let value = value { if strcmp(value.objCType, CGRectType) != 0 { return nil } var typedValue = CGRect(x: 0, y: 0, width: 0, height: 0) value.getValue(&typedValue) return typedValue } else { return nil } } } /** Specialization of generic `rx_observe` method. For more information take a look at `rx_observe` method. */ @warn_unused_result(message="http://git.io/rxs.uo") public func rx_observe(keyPath: String, options: NSKeyValueObservingOptions = [.New, .Initial], retainSelf: Bool = true) -> Observable<CGSize?> { return rx_observe(keyPath, options: options, retainSelf: retainSelf) .map { (value: NSValue?) in if let value = value { if strcmp(value.objCType, CGSizeType) != 0 { return nil } var typedValue = CGSize(width: 0, height: 0) value.getValue(&typedValue) return typedValue } else { return nil } } } /** Specialization of generic `rx_observe` method. For more information take a look at `rx_observe` method. */ @warn_unused_result(message="http://git.io/rxs.uo") public func rx_observe(keyPath: String, options: NSKeyValueObservingOptions = [.New, .Initial], retainSelf: Bool = true) -> Observable<CGPoint?> { return rx_observe(keyPath, options: options, retainSelf: retainSelf) .map { (value: NSValue?) in if let value = value { if strcmp(value.objCType, CGPointType) != 0 { return nil } var typedValue = CGPoint(x: 0, y: 0) value.getValue(&typedValue) return typedValue } else { return nil } } } } #if !DISABLE_SWIZZLING // rx_observeWeakly + CoreGraphics extension NSObject { /** Specialization of generic `rx_observeWeakly` method. For more information take a look at `rx_observeWeakly` method. */ @warn_unused_result(message="http://git.io/rxs.uo") public func rx_observeWeakly(keyPath: String, options: NSKeyValueObservingOptions = [.New, .Initial]) -> Observable<CGRect?> { return rx_observeWeakly(keyPath, options: options) .map { (value: NSValue?) in if let value = value { if strcmp(value.objCType, CGRectType) != 0 { return nil } var typedValue = CGRect(x: 0, y: 0, width: 0, height: 0) value.getValue(&typedValue) return typedValue } else { return nil } } } /** Specialization of generic `rx_observeWeakly` method. For more information take a look at `rx_observeWeakly` method. */ @warn_unused_result(message="http://git.io/rxs.uo") public func rx_observeWeakly(keyPath: String, options: NSKeyValueObservingOptions = [.New, .Initial]) -> Observable<CGSize?> { return rx_observeWeakly(keyPath, options: options) .map { (value: NSValue?) in if let value = value { if strcmp(value.objCType, CGSizeType) != 0 { return nil } var typedValue = CGSize(width: 0, height: 0) value.getValue(&typedValue) return typedValue } else { return nil } } } /** Specialization of generic `rx_observeWeakly` method. For more information take a look at `rx_observeWeakly` method. */ @warn_unused_result(message="http://git.io/rxs.uo") public func rx_observeWeakly(keyPath: String, options: NSKeyValueObservingOptions = [.New, .Initial]) -> Observable<CGPoint?> { return rx_observeWeakly(keyPath, options: options) .map { (value: NSValue?) in if let value = value { if strcmp(value.objCType, CGPointType) != 0 { return nil } var typedValue = CGPoint(x: 0, y: 0) value.getValue(&typedValue) return typedValue } else { return nil } } } } #endif
mit
890439af18bcb671fbe62683b8944c23
33.273256
150
0.523155
4.627159
false
false
false
false
iCrany/iOSExample
iOSExample/Module/LockExample/VC/LockExampleViewController.swift
1
2423
// // LockExampleViewController.swift // iOSExample // // Created by iCrany on 2017/10/20. // Copyright © 2017 iCrany. All rights reserved. // import Foundation class LockExampleViewController: UIViewController { fileprivate var lockType: LockExampleConstant.LockType init(lockType: LockExampleConstant.LockType) { self.lockType = lockType super.init(nibName: nil, bundle: nil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = UIColor.white self.setupExample() } deinit { NSLog("LockExampleViewController deinit") } private func setupExample() { switch self.lockType { case .undefined: let alertViewController: UIAlertController = UIAlertController.init(title: "Undefined lock type", message: nil, preferredStyle: .alert) alertViewController.addAction(UIAlertAction.init(title: "Confirm", style: .cancel)) self.present(alertViewController, animated: true) case .nsLock: _ = NSLockExample.init() case .synchronized: _ = SynchronizedLockExample.init() case .pthreadMutexT: _ = PthreadMutexTExample.init() case .semaphore: _ = SemaphoreLockExample.init() case .nsLockDeadLock: let lock: NSRecursiveLockExample = NSRecursiveLockExample.init() lock.showDeadLockMethod() case .nsRecursiveLock: let lock: NSRecursiveLockExample = NSRecursiveLockExample.init() lock.showHowToUseRecursiveLockToAvoidDeadLockMethod() case .gcdLock: _ = GCDLockExample.init() case .pthreadMutexTDeadLock: let lock: PthreadRecursiveMutexLockExample = PthreadRecursiveMutexLockExample.init() lock.showDeadLockMethod() case .pthreadMutexTRecursiveLock: let lock: PthreadRecursiveMutexLockExample = PthreadRecursiveMutexLockExample.init() lock.showHowToUseRecursiveLockToAvoidDeadLockMethod() case .osspinLock: _ = OSSpinLockExample.init() case .nscondition: _ = NSConditionExample.init() case .os_unfair_lock: _ = OSUnfairLockLockExample.init() } } }
mit
7808a879790c0c5a1d43b972e58cd1b4
27.494118
147
0.646573
4.77712
false
false
false
false
jakub-tucek/fit-checker-2.0
fit-checker/networking/operations/ReadCourseListOperation.swift
1
2003
// // ReadCourseListOperation.swift // fit-checker // // Created by Josef Dolezal on 13/01/2017. // Copyright © 2017 Josef Dolezal. All rights reserved. // import Foundation import Alamofire /// Read user course list request operation. class ReadCourseListOperation: BaseOperation, ResponseType { /// Parameters presented in request query string private static let query: Parameters = ["dashboard_current_lang": "cs"] /// Parameters presented in request body private static let body: Parameters = [ "call": "dashboard_widget_update", "widget_real_id": "w_actual_courses_fit", "widget_max": 0, "lazy": 1 ] /// Database context manager private let contextManager: ContextManager init(sessionManager: SessionManager, contextManager: ContextManager) { self.contextManager = contextManager super.init(sessionManager: sessionManager) } override func start() { _ = sessionManager.request(EduxRouter.courseList( query: ReadCourseListOperation.query, body: ReadCourseListOperation.body) ) .validate() .validate(EduxValidators.authorizedJSON) .responseJSON(completionHandler: handle) } /// Course list request success callback /// /// - Parameter result: Response JSON func success(result: Any) { guard let json = result as? [String: Any?] else { return } let parser = CourseListParser() let parsedCourses = parser.parse(json: json) let courses = parsedCourses.courses.map({ course -> Course in return Course(id: course.name, name: course.name, classificationAvailable: course.classification) }) do { let realm = try contextManager.createContext() try realm.write() { realm.add(courses, update: true) } } catch { self.error = error } } }
mit
8b1538f760dceb503c1e4b60c04a34a2
28.441176
75
0.621878
4.721698
false
false
false
false
migueloruiz/la-gas-app-swift
lasgasmx/UserDefaultsManager.swift
1
2489
// // UserDefaultsManager.swift // lasgasmx // // Created by Desarrollo on 4/6/17. // Copyright © 2017 migueloruiz. All rights reserved. // import Foundation enum UserDefaultsKeys: String { case Index = "com.lagasmx.satateLocationsINDEX.key" case FirstLaunch = "com.lagasmx.FirstLaunch.key" } class UserDefaultsManager { private let userDefaults: UserDefaults init() { self.userDefaults = UserDefaults.standard } init?(suitName: String) { guard let ud = UserDefaults.init(suiteName: suitName) else { fatalError("\(suitName) error") } self.userDefaults = ud self.userDefaults.synchronize() } func isFistLaunch() -> Bool? { return userDefaults.object(forKey: UserDefaultsKeys.FirstLaunch.rawValue) as? Bool } func retrieveIndexs() -> UserDefaultPricesID { guard let indexEncode = userDefaults.object(forKey: UserDefaultsKeys.Index.rawValue) as? String else { return UserDefaultPricesID() } return UserDefaultPricesID(decode: indexEncode) } func retrieveLocations() -> [GasPriceLocation] { let index = retrieveIndexs() guard index.count() > 0 else { return [] } return index.getArray().map({id in let encode = userDefaults.object(forKey: id) as? String return GasPriceLocation(decode: encode!)! }) } func saveNewGasPrices(location: GasPriceLocation, id: String) { var index = retrieveIndexs() index.add(id: id) let encideIndex = index.encode() userDefaults.set(encideIndex, forKey: UserDefaultsKeys.Index.rawValue) let encode = location.encode() userDefaults.set(encode, forKey: id) userDefaults.synchronize() } func delateGasPrices(id: String) { var index = retrieveIndexs() guard index.hasId(id: id) else { return } index.delete(id: id) let encideIndex = index.encode() userDefaults.set(encideIndex, forKey: UserDefaultsKeys.Index.rawValue) userDefaults.removeObject(forKey: id) userDefaults.synchronize() } func editGasPrices(location: GasPriceLocation, id: String) { let index = retrieveIndexs() guard index.hasId(id: id) else { return } let encode = location.encode() userDefaults.set(encode, forKey: id) userDefaults.synchronize() } }
mit
23a70f6465a9f10e4bbeba2ca03ec99f
28.975904
110
0.633039
4.411348
false
false
false
false
zoeyzhong520/InformationTechnology
InformationTechnology/InformationTechnology/Classes/GuideViewController.swift
1
3519
// // GuideViewController.swift // InformationTechnology // // Created by qianfeng on 16/11/14. // Copyright © 2016年 zzj. All rights reserved. // import UIKit class GuideViewController: UIViewController { //创建分页控件 var pageCtrl:UIPageControl? override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = UIColor.whiteColor() //创建界面 configView() } //创建界面 func configView() { //添加滚动视图 let scrollView = UIScrollView(frame: self.view.bounds) scrollView.delegate = self scrollView.pagingEnabled = true view.addSubview(scrollView) //循环添加图片 let imgArray = ["IMG_0169_New.jpg","IMG_0172_New.jpg","IMG_0170.jpg"] for i in 0..<imgArray.count { //背景图片 let frame:CGRect = CGRectMake(kScreenWidth*CGFloat(i), 0, kScreenWidth, kScreenHeight) let imageView = UIImageView(frame: frame) imageView.image = UIImage(named: "guideView_bg@2x") scrollView.addSubview(imageView) //图片 let tmpImgView = UIImageView(frame: imageView.bounds) tmpImgView.image = UIImage(named: imgArray[i]) imageView.addSubview(tmpImgView) if i == imgArray.count-1 { imageView.userInteractionEnabled = true //按钮 let btn = UIButton(frame: CGRect(x: 110, y: kScreenHeight-120, width: kScreenWidth-2*110, height: 40)) btn.setTitle("进入应用", forState: .Normal) btn.setTitleColor(UIColor.blackColor(), forState: .Normal) btn.layer.masksToBounds = true btn.layer.cornerRadius = 20 btn.backgroundColor = UIColor.whiteColor() btn.addTarget(self, action: #selector(clickBtn), forControlEvents: .TouchUpInside) imageView.addSubview(btn) } //分页控件 pageCtrl = UIPageControl(frame: CGRect(x: 50, y: kScreenHeight-60, width: kScreenWidth-2*50, height: 30)) pageCtrl?.numberOfPages = imgArray.count pageCtrl?.currentPageIndicatorTintColor = UIColor.whiteColor() pageCtrl?.pageIndicatorTintColor = UIColor.lightGrayColor() view.addSubview(pageCtrl!) } scrollView.contentSize = CGSizeMake(kScreenWidth*CGFloat(imgArray.count), 0) } func clickBtn() { self.view.window?.rootViewController = CreateTabBarController() } 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. } */ } //MARK: UIScrollView代理方法 extension GuideViewController:UIScrollViewDelegate { func scrollViewDidEndDecelerating(scrollView: UIScrollView) { let index = scrollView.contentOffset.x/scrollView.bounds.size.width pageCtrl?.currentPage = Int(index) } }
mit
50b43de711fa5aab8a93d5d2ed0a693a
28.016949
118
0.611565
5.072593
false
false
false
false
oisdk/SwiftSequence
Sources/Slicing.swift
1
3857
// IntervalTypes public protocol OpenIntervalType { associatedtype Value func contains(v: Value) -> Bool } public protocol OpenEndedIntervalType: OpenIntervalType { associatedtype Value: Comparable var val: Value { get } } public protocol OpenStartedIntervalTypeTo: OpenIntervalType { associatedtype Value: Comparable var val: Value { get } } public protocol OpenStartedIntervalTypeThrough: OpenIntervalType { associatedtype Value: Comparable var val: Value { get } } // Interval Structs public struct OpenEndedInterval<C: Comparable>: OpenEndedIntervalType { public let val: C } public struct OpenStartedIntervalTo<C: Comparable>: OpenStartedIntervalTypeTo { public let val: C } public struct OpenStartedIntervalThrough<C: Comparable>: OpenStartedIntervalTypeThrough { public let val: C } // Range structs public struct OpenEndedRange<I: ForwardIndexType where I: Comparable>: OpenEndedIntervalType { public var val: I } public struct OpenStartedRangeTo<I: BidirectionalIndexType where I: Comparable>: OpenStartedIntervalTypeTo { public var val: I } public struct OpenStartedRangeThrough<I: BidirectionalIndexType where I: Comparable>: OpenStartedIntervalTypeThrough { public var val: I } // Generators public struct EndlessIncrement<I: ForwardIndexType>: GeneratorType { private var i: I public mutating func next() -> I? { defer { i = i.successor() } return i } } // SequenceType extension OpenEndedRange: SequenceType { public func generate() -> EndlessIncrement<I> { return EndlessIncrement(i: val) } } // Operators postfix operator ... {} prefix operator ... {} prefix operator ..< {} public postfix func ...<C: Comparable>(c: C) -> OpenEndedInterval<C> { return OpenEndedInterval(val: c) } public postfix func ...<I: ForwardIndexType>(c: I) -> OpenEndedRange<I> { return OpenEndedRange(val: c) } public prefix func ..<<C: Comparable>(c: C) -> OpenStartedIntervalTo<C> { return OpenStartedIntervalTo(val: c) } public prefix func ..<<C: BidirectionalIndexType>(c: C) -> OpenStartedRangeTo<C> { return OpenStartedRangeTo(val: c) } public prefix func ... <C: Comparable>(c: C) -> OpenStartedIntervalThrough<C> { return OpenStartedIntervalThrough(val: c) } public prefix func ... <C: BidirectionalIndexType>(c: C) -> OpenStartedRangeThrough<C> { return OpenStartedRangeThrough(val: c) } // Contains extension OpenEndedIntervalType { public func contains(v: Value) -> Bool { return val <= v } } extension OpenStartedIntervalTypeTo { public func contains(v: Value) -> Bool { return val > v } } extension OpenStartedIntervalTypeThrough { public func contains(v: Value) -> Bool { return val >= v } } // Pattern Matching public func ~=<I: OpenIntervalType>(lhs: I, rhs: I.Value) -> Bool { return lhs.contains(rhs) } // Indexing public extension CollectionType where Index: Comparable { subscript(r: OpenEndedRange<Index>) -> SubSequence { return suffixFrom(r.val) } } public extension CollectionType where Index: Comparable, Index: BidirectionalIndexType { subscript(r: OpenStartedRangeTo<Index>) -> SubSequence { return prefixUpTo(r.val) } subscript(r: OpenStartedRangeThrough<Index>) -> SubSequence { return prefixThrough(r.val) } } public extension MutableCollectionType where Index: Comparable { subscript(r: OpenEndedRange<Index>) -> SubSequence { get { return suffixFrom(r.val) } set { self[r.val..<endIndex] = newValue } } } public extension MutableCollectionType where Index: Comparable, Index: BidirectionalIndexType { subscript(r: OpenStartedRangeTo<Index>) -> SubSequence { get { return prefixUpTo(r.val) } set { self[startIndex..<r.val] = newValue } } subscript(r: OpenStartedRangeThrough<Index>) -> SubSequence { get { return prefixThrough(r.val) } set { self[startIndex...r.val] = newValue } } }
mit
0954f9ecdbc9b529de2ac50002e1ae2e
26.956522
118
0.733472
3.884189
false
false
false
false
tschob/HSAudioPlayer
HSAudioPlayer/Core/Private/HSAudioPlayerQueue.swift
1
3307
// // HSAudioPlayerQueue.swift // HSAudioPlayer // // Created by Hans Seiffert on 02.08.16. // Copyright © 2016 Hans Seiffert. All rights reserved. // import UIKit class HSAudioPlayerQueue: NSObject { // MARK: - Private variables private var currentItem : HSAudioPlayerItem? private var queue = [HSAudioPlayerItem]() private var currentItemQueueIndex = 0 private var history = [HSAudioPlayerItem]() // MARK: Set func replace(playerItems: [HSAudioPlayerItem]?, startPosition: Int) { if let _playerItems = playerItems { // Add the current playing item to the history if let _currentItem = self.currentItem { self.history.append(_currentItem) } // Replace the items in the queue with the new ones self.queue = _playerItems self.currentItemQueueIndex = startPosition self.currentItem?.cleanupAfterPlaying() self.currentItem = _playerItems[startPosition] } else { self.queue.removeAll() self.currentItem?.cleanupAfterPlaying() self.currentItem = nil self.currentItemQueueIndex = 0 } } func prepend(playerItems: [HSAudioPlayerItem]) { // Insert the player items at the beginning of the queue self.queue.insertContentsOf(playerItems, at: 0) // Adjust the current player item index to the new size self.currentItemQueueIndex += playerItems.count } func append(playerItems: [HSAudioPlayerItem]) { self.queue.appendContentsOf(playerItems) } // MARK: Forward func canForward() -> Bool { return (self.queue.count > 0 && self.followingPlayerItem() != nil) } func forward() -> Bool { if (self.canForward() == true), let _currentItem = self.currentItem, _followingPlayerItem = self.followingPlayerItem() { // Add current player item to the history _currentItem.cleanupAfterPlaying() // Replace current player item with the new one self.currentItem = _followingPlayerItem // Adjust the current item index self.currentItemQueueIndex += 1 // Add the former item to the history self.history.append(_currentItem) return true } return false } private func followingPlayerItem() -> HSAudioPlayerItem? { let followingIndex = self.currentItemQueueIndex + 1 if (followingIndex < self.queue.count) { return self.queue[followingIndex] } return nil } // MARK: Rewind func canRewind() -> Bool { return (self.previousItem() != nil) } func rewind() -> Bool { if (self.canRewind() == true), let _currentItem = self.currentItem { _currentItem.cleanupAfterPlaying() // Replace the current player item with the former one self.currentItem = self.previousItem() // Adjust the current item index self.currentItemQueueIndex -= 1 return true } return false } private func previousItem() -> HSAudioPlayerItem? { let previousIndex = self.currentItemQueueIndex - 1 if (previousIndex >= 0) { return self.queue[previousIndex] } return nil } // MARK: Get func currentPlayingItem() -> HSAudioPlayerItem? { return self.currentItem } func previousPlayingItem() -> HSAudioPlayerItem? { return self.previousItem() } func count() -> Int { return self.queue.count } // History private func appendCurrentPlayingItemToQueue() { if let _currentItem = self.currentItem { self.history.append(_currentItem) } } }
mit
cf9efe3efaa2705b50ce5551b8068eaf
23.857143
70
0.705989
3.839721
false
false
false
false
benlangmuir/swift
stdlib/public/Concurrency/Deque.swift
6
12523
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2020-2021 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// import Swift @available(SwiftStdlib 5.1, *) struct _Deque<Element> { internal struct _UnsafeHandle { let _header: UnsafeMutablePointer<_Storage._Header> let _elements: UnsafeMutablePointer<Element>? init( header: UnsafeMutablePointer<_Storage._Header>, elements: UnsafeMutablePointer<Element>?, isMutable: Bool ) { self._header = header self._elements = elements } var header: _Storage._Header { _header.pointee } var capacity: Int { _header.pointee.capacity } var count: Int { get { _header.pointee.count } nonmutating set { _header.pointee.count = newValue } } internal func slot(after slot: Int) -> Int { _internalInvariant(slot < capacity) let position = slot + 1 if position >= capacity { return 0 } return position } internal func slot(_ slot: Int, offsetBy delta: Int) -> Int { _internalInvariant(slot <= capacity) let position = slot + delta if delta >= 0 { if position >= capacity { return position - capacity } } else { if position < 0 { return position + capacity } } return position } internal var endSlot: Int { slot(startSlot, offsetBy: count) } internal func uncheckedAppend(_ element: Element) { _internalInvariant(count < capacity) ptr(at: endSlot).initialize(to: element) count += 1 } internal func uncheckedRemoveFirst() -> Element { _internalInvariant(count > 0) let result = ptr(at: startSlot).move() startSlot = slot(after: startSlot) count -= 1 return result } internal func uncheckedRemoveFirstIfPresent() -> Element? { if count > 0 { let result = ptr(at: startSlot).move() startSlot = slot(after: startSlot) count -= 1 return result } else { return nil } } struct _UnsafeWrappedBuffer { internal let first: UnsafeBufferPointer<Element> internal let second: UnsafeBufferPointer<Element>? internal init( _ first: UnsafeBufferPointer<Element>, _ second: UnsafeBufferPointer<Element>? = nil ) { self.first = first self.second = second _internalInvariant(first.count > 0 || second == nil) } internal init( start: UnsafePointer<Element>, count: Int ) { self.init(UnsafeBufferPointer(start: start, count: count)) } internal init( first start1: UnsafePointer<Element>, count count1: Int, second start2: UnsafePointer<Element>, count count2: Int ) { self.init(UnsafeBufferPointer(start: start1, count: count1), UnsafeBufferPointer(start: start2, count: count2)) } internal var count: Int { first.count + (second?.count ?? 0) } } internal struct _UnsafeMutableWrappedBuffer { internal let first: UnsafeMutableBufferPointer<Element> internal let second: UnsafeMutableBufferPointer<Element>? internal init( _ first: UnsafeMutableBufferPointer<Element>, _ second: UnsafeMutableBufferPointer<Element>? = nil ) { self.first = first self.second = second?.count == 0 ? nil : second _internalInvariant(first.count > 0 || second == nil) } internal init( start: UnsafeMutablePointer<Element>, count: Int ) { self.init(UnsafeMutableBufferPointer(start: start, count: count)) } internal init( first start1: UnsafeMutablePointer<Element>, count count1: Int, second start2: UnsafeMutablePointer<Element>, count count2: Int ) { self.init(UnsafeMutableBufferPointer(start: start1, count: count1), UnsafeMutableBufferPointer(start: start2, count: count2)) } internal init(mutating buffer: _UnsafeWrappedBuffer) { self.init(.init(mutating: buffer.first), buffer.second.map { .init(mutating: $0) }) } } internal func segments() -> _UnsafeWrappedBuffer { let wrap = capacity - startSlot if count <= wrap { return .init(start: ptr(at: startSlot), count: count) } return .init(first: ptr(at: startSlot), count: wrap, second: ptr(at: .zero), count: count - wrap) } internal func mutableSegments() -> _UnsafeMutableWrappedBuffer { return .init(mutating: segments()) } var startSlot: Int { get { _header.pointee.startSlot } nonmutating set { _header.pointee.startSlot = newValue } } func ptr(at slot: Int) -> UnsafeMutablePointer<Element> { _internalInvariant(slot >= 0 && slot <= capacity) return _elements! + slot } @discardableResult func initialize( at start: Int, from source: UnsafeBufferPointer<Element> ) -> Int { _internalInvariant(start + source.count <= capacity) guard source.count > 0 else { return start } ptr(at: start).initialize(from: source.baseAddress!, count: source.count) return start + source.count } @discardableResult func moveInitialize( at start: Int, from source: UnsafeMutableBufferPointer<Element> ) -> Int { _internalInvariant(start + source.count <= capacity) guard source.count > 0 else { return start } ptr(at: start).moveInitialize(from: source.baseAddress!, count: source.count) return start + source.count } internal func copyElements() -> _Storage { let object = _Storage._DequeBuffer.create( minimumCapacity: capacity, makingHeaderWith: { _ in header }) let result = _Storage(_buffer: ManagedBufferPointer(unsafeBufferObject: object)) guard self.count > 0 else { return result } result.update { target in let source = self.segments() target.initialize(at: startSlot, from: source.first) if let second = source.second { target.initialize(at: 0, from: second) } } return result } internal func moveElements(minimumCapacity: Int) -> _Storage { let count = self.count _internalInvariant(minimumCapacity >= count) let object = _Storage._DequeBuffer.create( minimumCapacity: minimumCapacity, makingHeaderWith: { #if os(OpenBSD) let capacity = minimumCapacity #else let capacity = $0.capacity #endif return _Storage._Header( capacity: capacity, count: count, startSlot: .zero) }) let result = _Storage(_buffer: ManagedBufferPointer(unsafeBufferObject: object)) guard count > 0 else { return result } result.update { target in let source = self.mutableSegments() let next = target.moveInitialize(at: .zero, from: source.first) if let second = source.second { target.moveInitialize(at: next, from: second) } } self.count = 0 return result } } enum _Storage { internal struct _Header { var capacity: Int var count: Int var startSlot: Int init(capacity: Int, count: Int, startSlot: Int) { self.capacity = capacity self.count = count self.startSlot = startSlot } } internal typealias _Buffer = ManagedBufferPointer<_Header, Element> case empty case buffer(_Buffer) internal class _DequeBuffer: ManagedBuffer<_Header, Element> { deinit { self.withUnsafeMutablePointers { header, elements in let capacity = header.pointee.capacity let count = header.pointee.count let startSlot = header.pointee.startSlot if startSlot + count <= capacity { (elements + startSlot).deinitialize(count: count) } else { let firstRegion = capacity - startSlot (elements + startSlot).deinitialize(count: firstRegion) elements.deinitialize(count: count - firstRegion) } } } } internal init(_buffer: _Buffer) { self = .buffer(_buffer) } internal init() { self = .empty } internal init(_ object: _DequeBuffer) { self.init(_buffer: _Buffer(unsafeBufferObject: object)) } internal var capacity: Int { switch self { case .empty: return 0 case .buffer(let buffer): return buffer.withUnsafeMutablePointerToHeader { $0.pointee.capacity } } } internal mutating func ensure( minimumCapacity: Int ) { if _slowPath(capacity < minimumCapacity) { _ensure(minimumCapacity: minimumCapacity) } } internal static var growthFactor: Double { 1.5 } internal func _growCapacity( to minimumCapacity: Int ) -> Int { return Swift.max(Int((Self.growthFactor * Double(capacity)).rounded(.up)), minimumCapacity) } internal mutating func _ensure( minimumCapacity: Int ) { if capacity >= minimumCapacity { self = self.read { $0.copyElements() } } else { let minimumCapacity = _growCapacity(to: minimumCapacity) self = self.update { source in source.moveElements(minimumCapacity: minimumCapacity) } } } internal var count: Int { switch self { case .empty: return 0 case .buffer(let buffer): return buffer.withUnsafeMutablePointerToHeader { $0.pointee.count } } } internal func read<R>(_ body: (_UnsafeHandle) throws -> R) rethrows -> R { switch self { case .empty: var header = _Header(capacity: 0, count: 0, startSlot: 0) return try withUnsafeMutablePointer(to: &header) { headerPtr in return try body(_UnsafeHandle(header: headerPtr, elements: nil, isMutable: false)) } case .buffer(let buffer): return try buffer.withUnsafeMutablePointers { header, elements in let handle = _UnsafeHandle(header: header, elements: elements, isMutable: false) return try body(handle) } } } internal func update<R>(_ body: (_UnsafeHandle) throws -> R) rethrows -> R { switch self { case .empty: var header = _Header(capacity: 0, count: 0, startSlot: 0) return try withUnsafeMutablePointer(to: &header) { headerPtr in return try body(_UnsafeHandle(header: headerPtr, elements: nil, isMutable: false)) } case .buffer(let buffer): return try buffer.withUnsafeMutablePointers { header, elements in let handle = _UnsafeHandle(header: header, elements: elements, isMutable: true) return try body(handle) } } } } internal var _storage: _Storage init() { _storage = _Storage() } var count: Int { _storage.count } mutating func append(_ newElement: Element) { _storage.ensure(minimumCapacity: _storage.count + 1) _storage.update { $0.uncheckedAppend(newElement) } } @discardableResult mutating func removeFirst() -> Element { return _storage.update { $0.uncheckedRemoveFirst() } } @discardableResult mutating func removeFirstIfPresent() -> Element? { return _storage.update { $0.uncheckedRemoveFirstIfPresent() } } } @_alwaysEmitIntoClient @_transparent internal func _internalInvariant( _ condition: @autoclosure () -> Bool, _ message: @autoclosure () -> String = String(), file: StaticString = #fileID, line: UInt = #line ) { #if INTERNAL_CHECKS_ENABLED assert(condition(), message(), file: file, line: line) #endif }
apache-2.0
299171c91f7579e741f5056c262eab4d
28.465882
92
0.593867
4.711437
false
false
false
false
yemeksepeti/YSForms
YSForms/Vendors/Style/Style.swift
1
8041
// // Style.swift // yemeksepeti // // Created by Cem Olcay on 20/03/15. // Copyright (c) 2015 yemeksepeti. All rights reserved. // import UIKit extension UIColor { class func NavBarColor () -> UIColor { return BarTintRGBColor(183, g: 28, b: 28) } class func BackgroundColor () -> UIColor { return RGBColor(237, g: 237, b: 237) } class func GreenColor () -> UIColor { return RGBColor(75, g: 174, b: 80) } class func ClearBasketColor () -> UIColor { return RGBColor(183, g: 28, b: 28) } class func YellowBasketColor () -> UIColor { return RGBColor(255, g: 184, b: 0) } class func JokerColor () -> UIColor { return UIColor.RGBColor(236, g: 40, b: 122) } class func CardHeaderColor () -> UIColor { return Gray(242) } class func CardCellColor () -> UIColor { return UIColor.whiteColor() //Gray(249) } class func CardBorderColor () -> UIColor { return Gray(200) } class func CheckoutBottomViewGreenColor () -> UIColor { return RGBColor (139, g: 195, b: 74) } class func CheckoutBottomViewRedColor () -> UIColor { return RGBColor (128, g: 17, b: 17) } class func RippleColor () -> UIColor { return Gray(51, alpha: 0.1) } class func ShadowColor () -> UIColor { return UIColor.blackColor() } class func TagLabelColor () -> UIColor { return UIColor.RGBAColor(71, g: 71, b: 71, a: 0.9) } class func TitleColor () -> UIColor { return Gray(51) } class func TextColor () -> UIColor { return Gray(144) } class func RedTitleColor () -> UIColor { return RGBColor(161, g: 24, b: 24) } class func PriceColor () -> UIColor { return RGBColor(255, g: 114, b: 8) } class func CouponColor () -> UIColor { return RGBColor(246, g: 85, b: 29) } class func DeleteColor () -> UIColor { return RGBColor (183, g: 28, b: 28) } class func LoginGreenColor () -> UIColor { return RGBColor(31, g: 145, b: 26) } class func FacebookColor () -> UIColor { return RGBColor(59, g: 89, b: 152) } class func TwitterColor () -> UIColor { return UIColor.RGBColor(85, g: 172, b: 238) } class func LineItemCountColor () -> UIColor { return UIColor.Gray(210) } class func RepeatOrderColor () -> UIColor { return UIColor.RGBColor(255, g: 114, b: 8) } class func CommentOrderColor () -> UIColor { return UIColor.RGBColor(255, g: 149, b: 0) } class func IncomingMessageBubbleColor () -> UIColor { return UIColor.Gray(220) } class func OutgoingMessageBubbleColor () -> UIColor { return UIColor.RGBColor(255, g: 149, b: 0) } class func joker30to20Color () -> UIColor { return UIColor.RGBColor (247, g: 135, b: 0) } class func joker40to25Color () -> UIColor { return UIColor.RGBColor (236, g: 40, b: 122) } class func joker70to45Color () -> UIColor { return UIColor.RGBColor (0, g: 146, b: 67) } class func joker120to75Color () -> UIColor { return UIColor.RGBColor (34, g: 119, b: 179) } } extension UIColor { class func colorForScore (score: Float) -> UIColor { if score >= 9.5 { return scoreColor10() } else if score < 9.5 && score >= 9.0 { return scoreColor95() } else if score < 9.0 && score >= 8.5 { return scoreColor90() } else if score < 8.5 && score >= 8.0 { return scoreColor85() } else if score < 8.0 && score >= 7.5 { return scoreColor80() } else if score < 7.5 && score >= 7.0 { return scoreColor75() } else if score < 7.0 && score >= 6.5 { return scoreColor70() } else if score < 6.5 && score >= 6.0 { return scoreColor65() } else if score < 6.0 && score >= 5.5 { return scoreColor60() } else if score < 5.5 && score >= 5.0 { return scoreColor55() } else if score < 5.0 && score > 4.5 { return scoreColor50() } else { return scoreColor45() } } class func scoreColor10 () -> UIColor { return UIColor.RGBColor(69, g: 197, b: 56) } class func scoreColor95 () -> UIColor { return UIColor.RGBColor(109, g: 197, b: 48) } class func scoreColor90 () -> UIColor { return UIColor.RGBColor(165, g: 197, b: 48) } class func scoreColor85 () -> UIColor { return UIColor.RGBColor(187, g: 199, b: 46) } class func scoreColor80 () -> UIColor { return UIColor.RGBColor(214, g: 208, b: 54) } class func scoreColor75 () -> UIColor { return UIColor.RGBColor(233, g: 201, b: 15) } class func scoreColor70 () -> UIColor { return UIColor.RGBColor(255, g: 186, b: 4) } class func scoreColor65 () -> UIColor { return UIColor.RGBColor(255, g: 160, b: 4) } class func scoreColor60 () -> UIColor { return UIColor.RGBColor(244, g: 111, b: 2) } class func scoreColor55 () -> UIColor { return UIColor.RGBColor(236, g: 97, b: 2) } class func scoreColor50 () -> UIColor { return UIColor.RGBColor(230, g: 81, b: 0) } class func scoreColor45 () -> UIColor { return UIColor.RGBColor(229, g: 65, b: 0) } } extension UIFont { class func TitleFont () -> UIFont { return AvenirNextDemiBold(15) } class func FooterTitleFont () -> UIFont { return AvenirNextDemiBold(14) } class func TextFont () -> UIFont { return AvenirNextRegular(13) } class func FooterTextFont () -> UIFont { return AvenirNextRegular(12) } class func MenuItemFont (size: CGFloat) -> UIFont { return AvenirNextMedium(size) } class func TagLabelFont () -> UIFont { return UIFont.AvenirNextMedium(13) } class func MediumFont () -> UIFont { return AvenirNextMedium(15) } class func RegularFont () -> UIFont { return AvenirNextRegular(15) } class func BoldFont () -> UIFont { return AvenirNextBold(15) } class func PriceFont () -> UIFont { return AvenirNextDemiBold(14) } class func StrikePriceFont () -> UIFont { return AvenirNextDemiBold(12) } class func JokerFont (size: CGFloat) -> UIFont { if let paytone = UIFont(name: "Paytone One", size: size) { return paytone } else { return UIFont.systemFontOfSize (size) } } } extension NSAttributedString { class func redtextAtt (text: String, bold: Bool) -> NSAttributedString { let font = bold ? UIFont.TitleFont() : UIFont.TextFont() return NSAttributedString (text: text, color: UIColor.RedTitleColor(), font: font, style: .plain) } class func redtitleAtt (text: String) -> NSAttributedString { let font = UIFont.AvenirNextMedium(13) return NSAttributedString (text: text, color: UIColor.RedTitleColor(), font: font, style: .plain) } class func textAtt (text: String, bold: Bool) -> NSAttributedString { let font = bold ? UIFont.TitleFont() : UIFont.TextFont() return NSAttributedString (text: text, color: UIColor.TitleColor(), font: font, style: .plain) } class func titleAtt (text: String) -> NSAttributedString { let font = UIFont.AvenirNextMedium(13) return NSAttributedString (text: text, color: UIColor.TextColor(), font: font, style: .plain) } }
mit
ead5e2f5ecfcde81a5f5774cfb746dfc
24.855305
105
0.553538
4.106742
false
false
false
false
Urinx/SomeCodes
Swift/The Swift Programming Language/2.Basic_Operators.playground/section-1.swift
1
661
// P.108 // Assignment Operator let (x, y) = (1, 2) // assignment operator does not return a value // if x = y { ... } is wrong // Arithmetic Operator "hello, "+"world" var a = 0 var b = ++a var c = a++ a += 2 var d = a > 3 ? 22:2 // Nil Coalescing Operator // a ?? b (is equal to) a != nil ? a! : b let defaultColorName = "red" var userDefinedColorName: String? // var colorNameToUse = userDefinedColorName ?? defaultColorName // P.126 // Range Operators for i in 1...5 { println("\(i) times 5 is \(i*5)") } let names = ["Anna", "Alex", "Brian", "Jack"] let count = names.count for i in 0..<count { println("Person \(i+1) is called \(names[i])") }
gpl-2.0
579593d86170636231017f66fa9e6be4
19.6875
64
0.606657
3.074419
false
false
false
false
househappy/MapPointMapper
MapPointMapper/ViewController.swift
2
8262
// // ViewController.swift // MapPointMapper // // Created by Daniel on 11/18/14. // Copyright (c) 2014 dmiedema. All rights reserved. // import Cocoa import MapKit class ViewController: NSViewController, MKMapViewDelegate, NSTextFieldDelegate { // MARK: - Properties // MARK: Buttons @IBOutlet weak var loadFileButton: NSButton! @IBOutlet weak var removeLastLineButton: NSButton! @IBOutlet weak var removeAllLinesButton: NSButton! @IBOutlet weak var addLineFromTextButton: NSButton! @IBOutlet weak var switchLatLngButton: NSButton! @IBOutlet weak var centerUSButton: NSButton! @IBOutlet weak var centerAllLinesButton: NSButton! @IBOutlet weak var colorWell: NSColorWell! // MARK: Views @IBOutlet weak var mapview: MKMapView! @IBOutlet weak var textfield: NSTextField! @IBOutlet weak var latlngLabel: NSTextField! @IBOutlet weak var searchfield: NSTextField! var parseLongitudeFirst = false // MARK: - Methods // MARK: View life cycle override func viewDidLoad() { super.viewDidLoad() mapview.delegate = self textfield.delegate = self } // MARK: Actions @IBAction func loadFileButtonPressed(sender: NSButton!) { let openPanel = NSOpenPanel() openPanel.canChooseDirectories = false openPanel.beginSheetModalForWindow(NSApplication.sharedApplication().keyWindow!, completionHandler: { (result) -> Void in self.readFileAtURL(openPanel.URL) }) } @IBAction func addLineFromTextPressed(sender: NSObject) { if textfield.stringValue.isEmpty { return } if renderInput(textfield.stringValue as NSString) { textfield.stringValue = "" } else { // TODO: dont wipe out string field and stop event from propagating! textfield.stringValue = "" } } @IBAction func removeLastLinePressed(sender: NSButton) { if let overlay: AnyObject = mapview.overlays.last { mapview.removeOverlay(overlay as! MKOverlay) } } @IBAction func removeAllLinesPressed(sender: NSButton) { mapview.removeOverlays(mapview.overlays) } @IBAction func switchLatLngPressed(sender: NSButton) { parseLongitudeFirst = !parseLongitudeFirst if self.parseLongitudeFirst { self.latlngLabel.stringValue = "Lng/Lat" } else { self.latlngLabel.stringValue = "Lat/Lng" } } @IBAction func centerUSPressed(sender: NSButton) { let centerUS = CLLocationCoordinate2D( latitude: 37.09024, longitude: -95.712891 ) let northeastUS = CLLocationCoordinate2D( latitude: 49.38, longitude: -66.94 ) let southwestUS = CLLocationCoordinate2D( latitude: 25.82, longitude: -124.39 ) let latDelta = northeastUS.latitude - southwestUS.latitude let lngDelta = northeastUS.longitude - southwestUS.longitude let span = MKCoordinateSpanMake(latDelta, lngDelta) let usRegion = MKCoordinateRegion(center: centerUS, span: span) mapview.setRegion(usRegion, animated: true) } @IBAction func centerAllLinesPressed(sender: NSButton) { let polylines = mapview.overlays as [MKOverlay] let boundingMapRect = boundingMapRectForPolylines(polylines) mapview.setVisibleMapRect(boundingMapRect, edgePadding: NSEdgeInsets(top: 10, left: 10, bottom: 10, right: 10), animated: true) } // MARK: MKMapDelegate func mapView(mapView: MKMapView, rendererForOverlay overlay: MKOverlay) -> MKOverlayRenderer { let renderer = MKPolylineRenderer(overlay: overlay) renderer.alpha = 1.0 renderer.lineWidth = 4.0 renderer.strokeColor = colorWell.color return renderer } @IBAction func searchForLocation(sender: NSObject) { if searchfield.stringValue.isEmpty { return } renderLocationSearch(searchfield.stringValue) searchfield.stringValue = "" } private func renderLocationSearch(input: String) { let geocoder = CLGeocoder() geocoder.geocodeAddressString(input) { (placemarks, errors) in guard let placemark = placemarks?.first, let center = placemark.location?.coordinate else { print(errors ?? "") return } let region = MKCoordinateRegion(center: center, span: MKCoordinateSpan(latitudeDelta: 0.8, longitudeDelta: 0.8)) self.mapview.setRegion(region, animated: true) } } // MARK: - Private /** Create an `MKOverlay` for a given array of `CLLocationCoordinate2D` instances - parameter mapPoints: array of `CLLocationCoordinate2D` instances to convert - returns: an MKOverlay created from array of `CLLocationCoordinate2D` instances */ private func createPolylineForCoordinates(mapPoints: [CLLocationCoordinate2D]) -> MKOverlay { let coordinates = UnsafeMutablePointer<CLLocationCoordinate2D>.alloc(mapPoints.count) var count: Int = 0 for coordinate in mapPoints { coordinates[count] = coordinate count += 1 } let polyline = MKPolyline(coordinates: coordinates, count: count) free(coordinates) return polyline } /** Get the bounding `MKMapRect` that contains all given `MKOverlay` objects - warning: If no `MKOverlay` objects are included the resulting `MKMapRect` will be nonsensical and will results in a warning. - parameter polylines: array of `MKOverlay` objects. - returns: an `MKMapRect` that contains all the given `MKOverlay` objects */ private func boundingMapRectForPolylines(polylines: [MKOverlay]) -> MKMapRect { var minX = Double.infinity var minY = Double.infinity var maxX = Double(0) var maxY = Double(0) for line in polylines { minX = (line.boundingMapRect.origin.x < minX) ? line.boundingMapRect.origin.x : minX minY = (line.boundingMapRect.origin.y < minY) ? line.boundingMapRect.origin.y : minY let width = line.boundingMapRect.origin.x + line.boundingMapRect.size.width maxX = (width > maxX) ? width : maxX let height = line.boundingMapRect.origin.y + line.boundingMapRect.size.height maxY = (height > maxY) ? height : maxY } let mapWidth = maxX - minX let mapHeight = maxY - minY return MKMapRect(origin: MKMapPoint(x: minX, y: minY), size: MKMapSize(width: mapWidth, height: mapHeight)) } /** Read a given file at a url - parameter passedURL: `NSURL` to attempt to read */ private func readFileAtURL(passedURL: NSURL?) { guard let url = passedURL else { return } do { let contents = try NSString(contentsOfURL: url, encoding: NSUTF8StringEncoding) as String renderInput(contents) } catch { NSAlert(error: error as NSError).runModal() } } // end readFileAtURL private func randomizeColorWell() { colorWell.color = NSColor.randomColor() } private func renderInput(input: NSString) -> Bool { if parseInput(input) { randomizeColorWell() return true } else { return false } } /** Parse the given input. - parameter input: `NSString` to parse and draw on the map. If no string is given this is essentially a noop - warning: If invalid WKT input string, will result in `NSAlert()` and false return - returns: `Bool` on render success */ private func parseInput(input: NSString) -> Bool { var coordinates = [[CLLocationCoordinate2D]()] do { coordinates = try Parser.parseString(input, longitudeFirst: parseLongitudeFirst).filter({!$0.isEmpty}) } catch ParseError.InvalidWktString { let error_msg = NSError(domain:String(), code:-1, userInfo: [NSLocalizedDescriptionKey: "Invalid WKT input string, unable to parse"]) NSAlert(error: error_msg).runModal() return false } catch { NSAlert(error: error as NSError).runModal() return false } var polylines = [MKOverlay]() for coordinateSet in coordinates { let polyline = createPolylineForCoordinates(coordinateSet) mapview.addOverlay(polyline, level: .AboveRoads) polylines.append(polyline) } if !polylines.isEmpty { let boundingMapRect = boundingMapRectForPolylines(polylines) mapview.setVisibleMapRect(boundingMapRect, edgePadding: NSEdgeInsets(top: 10, left: 10, bottom: 10, right: 10), animated: true) } return true } }
mit
56a25c68e6e4099db153a22911234998
30.899614
133
0.697168
4.465946
false
false
false
false
Urinx/SomeCodes
Swift/swiftDemo/animation/animation/demoViewController.swift
1
2044
// // demoViewController.swift // animation // // Created by Eular on 15/7/5. // Copyright (c) 2015年 Eular. All rights reserved. // import UIKit class demoViewController: UIViewController { var boxWidth:CGFloat = 50 var d:Int = 4 var padding:CGFloat = 20 var backgrounds: Array<UIView>! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. self.backgrounds = Array<UIView>() setupGameMap() } func setupGameMap() { let x:CGFloat = 30 let y:CGFloat = 150 for i in 0..<d { let dx:CGFloat = (boxWidth+padding)*CGFloat(i) for j in 0..<d { let dy:CGFloat = (boxWidth+padding)*CGFloat(j) let box = UIView(frame: CGRectMake(x+dx, y+dy, boxWidth, boxWidth)) box.backgroundColor = UIColor.grayColor() self.view.addSubview(box) backgrounds.append(box) } } } override func viewDidAppear(animated: Bool) { playAnimation() } func playAnimation() { UIView.animateWithDuration(1, delay: 0, options: [.Repeat, .Autoreverse], animations: { for box in self.backgrounds { box.transform = CGAffineTransformScale(box.transform, 0.5, 0.5) box.transform = CGAffineTransformMakeRotation(CGFloat(M_PI)) } }, completion: nil) } 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. } */ }
gpl-2.0
e254c12a4c5f89edc068e2e305c0adbe
27.361111
106
0.594515
4.630385
false
false
false
false
zeroc-ice/ice-demos
swift/IceDiscovery/helloUI/Client.swift
1
6553
// // Copyright (c) ZeroC, Inc. All rights reserved. // import Combine import Ice import PromiseKit class Client: ObservableObject { // MARK: - Public Properties // For Error bindings @Published var error: Error? @Published var showingError = false // For Status bindings @Published var isSpinning = false @Published var statusMessage = "" // For Button view bindings @Published var helloEnabled: Bool = true @Published var shutdownEnabled = true @Published var flushEnabled = false @Published var proxySettings: ProxySettings = .init() { didSet { do { try updateProxy() } catch { exception(error) } } } // MARK: - Private Properties private var helloPrx: HelloPrx! private var communicator: Ice.Communicator // MARK: - Initialize the client with a communicator init() { communicator = Client.loadCommunicator() do { try updateProxy() } catch { exception(error) } } // MARK: - Public functions to send the say hello message, flush the batch requests, and shutdown the hello server func sayHello() { do { let delay = Int32(proxySettings.delay) if proxySettings.isBatched { // Batch requests get enqueued locally thus this call is non blocking try helloPrx.sayHello(delay) queuedRequest("hello") } else { // Non Batched requests get sent asynchronously var response = false firstly { helloPrx.sayHelloAsync(delay, sentOn: DispatchQueue.main) { _ in if !response { self.requestSent() } } }.done { response = true self.ready() }.catch { error in response = true self.exception(error) } } } catch { exception(error) } } func flushBatch() { firstly { helloPrx.ice_flushBatchRequestsAsync() }.done { self.flushBatchSend() }.catch { error in self.exception(error) } } func shutdown() { do { if proxySettings.isBatched { try helloPrx.shutdown() queuedRequest("shutdown") } else { sendingRequest() var response = false firstly { helloPrx.shutdownAsync { _ in if !response { self.requestSent() } } }.done { response = true self.ready() }.catch { error in response = true self.exception(error) self.ready() } } } catch { exception(error) ready() } } // MARK: - Control the state of the client private func exception(_ err: Error) { error = err showingError = true } private func flushBatchSend() { flushEnabled = false statusMessage = "Flushed batch requests" } private class func loadCommunicator() -> Ice.Communicator { var initData = Ice.InitializationData() let properties = Ice.createProperties() properties.setProperty(key: "Ice.Plugin.IceDiscovery", value: "0") properties.setProperty(key: "Ice.Plugin.IceSSL", value: "1") properties.setProperty(key: "IceSSL.CheckCertName", value: "0") properties.setProperty(key: "IceSSL.DefaultDir", value: "certs") properties.setProperty(key: "IceSSL.CAs", value: "cacert.der") properties.setProperty(key: "IceSSL.CertFile", value: "client.p12") properties.setProperty(key: "IceSSL.Password", value: "password") properties.setProperty(key: "HelloProxy", value: "hello") initData.properties = properties do { return try Ice.initialize(initData) } catch { print(error) fatalError() } } private func queuedRequest(_ name: String) { flushEnabled = true statusMessage = "Queued \(name) request" } private func ready() { helloEnabled = true shutdownEnabled = true statusMessage = "Ready" isSpinning = false } private func requestSent() { if let connection = helloPrx.ice_getCachedConnection() { do { // Loop through the connection informations until we find an IPConnectionInfo class. for info in sequence(first: try connection.getInfo(), next: { $0.underlying }) { if let ipinfo = info as? IPConnectionInfo { proxySettings.connection = ipinfo.remoteAddress break } } } catch { // Ignore. } } if proxySettings.deliveryMode == .twoway || proxySettings.deliveryMode == .twowaySecure { statusMessage = "Waiting for response" } else { ready() } } private func sendingRequest() { helloEnabled = false shutdownEnabled = false statusMessage = "Sending request" isSpinning = true } private func updateProxy() throws { helloPrx = uncheckedCast(prx: try communicator.propertyToProxy("HelloProxy")!, type: HelloPrx.self) switch proxySettings.deliveryMode { case .twoway: helloPrx = helloPrx.ice_twoway() case .twowaySecure: helloPrx = helloPrx.ice_twoway().ice_secure(true) case .oneway: helloPrx = helloPrx.ice_oneway() case .onewayBatch: helloPrx = helloPrx.ice_batchOneway() case .onewaySecure: helloPrx = helloPrx.ice_oneway().ice_secure(true) case .onewaySecureBatch: helloPrx = helloPrx.ice_batchOneway().ice_secure(true) case .datagram: helloPrx = helloPrx.ice_datagram() case .datagramBatch: helloPrx = helloPrx.ice_batchDatagram() } if proxySettings.timeout != 0 { helloPrx = helloPrx.ice_invocationTimeout(Int32(proxySettings.timeout)) } } }
gpl-2.0
84b67ced44739d4e56a1938f27b00b06
29.910377
118
0.535785
4.930775
false
false
false
false
Aaron-zheng/yugioh
yugioh/CardTableViewCell.swift
1
3934
// // CardTableViewCell.swift // yugioh // // Created by Aaron on 25/9/2016. // Copyright © 2016 sightcorner. All rights reserved. // import Foundation import UIKit import Kingfisher class CardTableViewCell: UITableViewCell { @IBOutlet weak var cellContentView: UIView! @IBOutlet weak var cellContentInnerView: UIView! @IBOutlet weak var card: UIImageView! @IBOutlet weak var title: UILabel! @IBOutlet weak var type: UILabel! @IBOutlet weak var effect: UIVerticalAlignLabel! @IBOutlet weak var star: DOFavoriteButton! @IBOutlet weak var attack: UILabel! @IBOutlet weak var property: UILabel! @IBOutlet weak var usage: UILabel! @IBOutlet weak var effectConstraint: NSLayoutConstraint! @IBOutlet weak var password: UILabel! private var tableView: UITableView! private var cardService = CardService() var afterDeselect: (() -> Void)? func prepare(cardEntity: CardEntity, tableView: UITableView, indexPath: IndexPath) { self.tableView = tableView let img = UIImage(named: "ic_star_white")?.withRenderingMode(.alwaysTemplate) star.imageColorOn = yellowColor star.imageColorOff = greyColor star.image = img if cardEntity.isSelected { star.selectWithNoCATransaction() } else { star.deselect() } star.cardEntity = cardEntity cellContentView.backgroundColor = greyColor cellContentInnerView.backgroundColor = UIColor.white // 标题 self.title.text = cardEntity.titleName // 效果 self.effect.text = cardEntity.effect // 类型 self.type.text = cardEntity.type // 限制:从常量池中判断使用范围:禁止,限制,准限制,无限制 self.usage.text = cardEntity.usage // 编号 self.password.text = "No: " + cardEntity.password self.property.text = "" if cardEntity.property != nil && cardEntity.property != "" { self.property.text = self.property.text! + cardEntity.property } if cardEntity.race != nil && cardEntity.race != "" { self.property.text = self.property.text! + " / " + cardEntity.race } if cardEntity.star != nil && cardEntity.star != "" { self.property.text = self.property.text! + " / " + cardEntity.star } if cardEntity.attack != nil && !cardEntity.attack.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty { self.attack.text = cardEntity.attack } else { self.attack.text = "" } if cardEntity.defense != nil && !cardEntity.defense.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty { self.attack.text = self.attack.text! + " / " + cardEntity.defense } } @IBAction func clickButton(_ sender: Any) { let starButton = sender as! DOFavoriteButton let cardEntity = starButton.cardEntity //setLog(event: AnalyticsEventAddToCart, description: cardEntity.id) if starButton.isSelected { cardEntity.isSelected = false cardService.delete(id: cardEntity.id) starButton.deselect() if let f = afterDeselect { f() } } else { cardEntity.isSelected = true cardService.save(id: cardEntity.id) starButton.select() } } } fileprivate var key: UInt8 = 0 fileprivate extension UIButton { var cardEntity: CardEntity { get { return objc_getAssociatedObject(self, &key) as! CardEntity } set(value) { objc_setAssociatedObject(self, &key, value, .OBJC_ASSOCIATION_RETAIN) } } }
agpl-3.0
8f35a90022de67e0b4842d9f22b403fc
29.401575
117
0.595442
4.596429
false
false
false
false
sr-tune/RBGenericFilterController
C4GenericFilter/Classes/Filter/viewController/GenericMultiChoiceTableViewController.swift
1
4141
// // GenericMultiChoiceTableViewController.swift // Pods // // Created by rboyer on 14/08/2017. // // import UIKit protocol GenericLongListtableViewFilterDelegate { func didValidateSelection(viewModel : (cells : [FilterSelectionableItem], selectedIndex : [Bool]), parentType : FilterSpecializedCellType) func didCancelSelection(viewModel : (cells : [FilterSelectionableItem], selectedIndex : [Bool]), parentType : FilterSpecializedCellType) } class GenericMultiChoiceTableViewController: UITableViewController { var items = [FilterSelectionableItem]() var type = FilterSelectionType.multi var parentType : FilterSpecializedCellType? var delegate : GenericLongListtableViewFilterDelegate? var viewModel : (cells : [FilterSelectionableItem], selectedIndex : [Bool])? override func viewDidLoad() { super.viewDidLoad() customiseTableView() addBackButton() addRightButtons() initViewModel() } func initViewModel() { if viewModel == nil { viewModel = (items, items.map { _ in return false } ) } } func addRightButtons() { let okButton = UIBarButtonItem.init(title: "Ok", style: .plain, target: self, action: #selector(saveAction)) let reinitButton = UIBarButtonItem.init(title: "RAZ", style: .plain, target: self, action: #selector(reinitViewModel)) navigationItem.rightBarButtonItems = [okButton,reinitButton] } func saveAction() { guard let parentTSafe = parentType else { return } self.delegate?.didValidateSelection(viewModel: viewModel!, parentType: parentTSafe) self.navigationController?.popViewController(animated: true) } func reinitViewModel() { viewModel?.selectedIndex = items.map { _ in return false } tableView.reloadData() } func customiseTableView() { tableView.register(UITableViewCell.self, forCellReuseIdentifier: "reuse") tableView.allowsMultipleSelection = (type == .multi) tableView.showsVerticalScrollIndicator = false } func backAction() { guard let parentTSafe = parentType else { return } self.delegate?.didCancelSelection(viewModel: viewModel!, parentType: parentTSafe) navigationController?.popViewController(animated: true) } func addBackButton() { let backButton = UIBarButtonItem.init(title: "< Filtres", style: .plain, target: self, action: #selector(backAction)) navigationItem.leftBarButtonItem = backButton } // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return items.count ?? 0 } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { var cell = tableView.dequeueReusableCell(withIdentifier: "reuse", for: indexPath) cell = cell ?? UITableViewCell.init(style: .subtitle, reuseIdentifier: "reuse") cell.textLabel?.text = viewModel?.cells[indexPath.row].textForLabel cell.imageView?.image = viewModel?.cells[indexPath.row].image if (viewModel?.selectedIndex[indexPath.row])! { cell.accessoryType = .checkmark } else { cell.accessoryType = .none } return cell } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let cell = tableView.cellForRow(at: indexPath) switch type { case .multi: if cell?.accessoryType == .checkmark { cell?.accessoryType = .none viewModel?.selectedIndex[indexPath.row] = false } else { cell?.accessoryType = .checkmark viewModel?.selectedIndex[indexPath.row] = true } case .radio: reinitViewModel() if cell?.accessoryType == .checkmark { cell?.accessoryType = .none } else { viewModel?.selectedIndex[indexPath.row] = true cell?.accessoryType = .checkmark } default : cell?.accessoryType = .none } } }
mit
a96c75f9090019a62264d40ee0564602
26.065359
140
0.679546
4.809524
false
false
false
false
anirudh24seven/wikipedia-ios
Wikipedia/Code/WMFWelcomeIntroductionViewController.swift
1
1719
class WMFWelcomeIntroductionViewController: UIViewController { @IBOutlet private var titleLabel:UILabel! @IBOutlet private var subTitleLabel:UILabel! @IBOutlet private var tellMeMoreButton:UIButton! @IBOutlet private var nextButton:UIButton! override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = UIColor.clearColor() titleLabel.adjustsFontSizeToFitWidth = true titleLabel.text = localizedStringForKeyFallingBackOnEnglish("welcome-explore-new-ways-title").uppercaseStringWithLocale(NSLocale.currentLocale()) subTitleLabel.text = localizedStringForKeyFallingBackOnEnglish("welcome-explore-new-ways-sub-title") tellMeMoreButton.setTitle(localizedStringForKeyFallingBackOnEnglish("welcome-explore-tell-me-more"), forState: .Normal) nextButton.setTitle(localizedStringForKeyFallingBackOnEnglish("welcome-explore-continue-button").uppercaseStringWithLocale(NSLocale.currentLocale()), forState: .Normal) } @IBAction private func showHowThisWorksAlert(withSender sender: AnyObject) { let alert = UIAlertController( title:localizedStringForKeyFallingBackOnEnglish("welcome-notifications-tell-me-more-title"), message:"\(localizedStringForKeyFallingBackOnEnglish("welcome-notifications-tell-me-more-storage"))\n\n\(localizedStringForKeyFallingBackOnEnglish("welcome-notifications-tell-me-more-creation"))", preferredStyle:.Alert) alert.addAction(UIAlertAction(title:localizedStringForKeyFallingBackOnEnglish("welcome-explore-tell-me-more-done-button"), style:.Cancel, handler:nil)) presentViewController(alert, animated:true, completion:nil) } }
mit
1b37b88e2134592bb6fc6e42a1b0ff09
62.666667
208
0.76847
5.422713
false
false
false
false
chris-wood/reveiller
reveiller/Pods/SwiftCharts/SwiftCharts/Layers/ChartCandleStickLayer.swift
6
3013
// // ChartCandleStickLayer.swift // SwiftCharts // // Created by ischuetz on 28/04/15. // Copyright (c) 2015 ivanschuetz. All rights reserved. // import UIKit public class ChartCandleStickLayer<T: ChartPointCandleStick>: ChartPointsLayer<T> { private var screenItems: [CandleStickScreenItem] = [] private let itemWidth: CGFloat private let strokeWidth: CGFloat public init(xAxis: ChartAxisLayer, yAxis: ChartAxisLayer, innerFrame: CGRect, chartPoints: [T], itemWidth: CGFloat = 10, strokeWidth: CGFloat = 1) { self.itemWidth = itemWidth self.strokeWidth = strokeWidth super.init(xAxis: xAxis, yAxis: yAxis, innerFrame: innerFrame, chartPoints: chartPoints) self.screenItems = self.chartPointsModels.map {model in let chartPoint = model.chartPoint let x = model.screenLoc.x let highScreenY = self.modelLocToScreenLoc(x: Double(x), y: Double(chartPoint.high)).y let lowScreenY = self.modelLocToScreenLoc(x: Double(x), y: Double(chartPoint.low)).y let openScreenY = self.modelLocToScreenLoc(x: Double(x), y: Double(chartPoint.open)).y let closeScreenY = self.modelLocToScreenLoc(x: Double(x), y: Double(chartPoint.close)).y let (rectTop, rectBottom, fillColor) = closeScreenY < openScreenY ? (closeScreenY, openScreenY, UIColor.whiteColor()) : (openScreenY, closeScreenY, UIColor.blackColor()) return CandleStickScreenItem(x: x, lineTop: highScreenY, lineBottom: lowScreenY, rectTop: rectTop, rectBottom: rectBottom, width: self.itemWidth, fillColor: fillColor) } } override public func chartViewDrawing(context context: CGContextRef, chart: Chart) { for screenItem in self.screenItems { CGContextSetLineWidth(context, self.strokeWidth) CGContextSetStrokeColorWithColor(context, UIColor.blackColor().CGColor) CGContextMoveToPoint(context, screenItem.x, screenItem.lineTop) CGContextAddLineToPoint(context, screenItem.x, screenItem.lineBottom) CGContextStrokePath(context) CGContextSetRGBFillColor(context, 1.0, 1.0, 1.0, 0.0) CGContextSetFillColorWithColor(context, screenItem.fillColor.CGColor) CGContextFillRect(context, screenItem.rect) CGContextStrokeRect(context, screenItem.rect) } } } private struct CandleStickScreenItem { let x: CGFloat let lineTop: CGFloat let lineBottom: CGFloat let fillColor: UIColor let rect: CGRect init(x: CGFloat, lineTop: CGFloat, lineBottom: CGFloat, rectTop: CGFloat, rectBottom: CGFloat, width: CGFloat, fillColor: UIColor) { self.x = x self.lineTop = lineTop self.lineBottom = lineBottom self.rect = CGRectMake(x - (width / 2), rectTop, width, rectBottom - rectTop) self.fillColor = fillColor } }
mit
e3101bbcf90e37d8a57715b4d6da8b8d
39.716216
181
0.667773
4.55136
false
false
false
false
Acht030/HelloWorld
Practice2/TestGame 1/SKButtonNode.swift
1
4845
import Foundation import SpriteKit class FTButtonNode: SKSpriteNode { enum FTButtonActionType: Int { case TouchUpInside = 1, TouchDown, TouchUp } var isEnabled: Bool = true { didSet { if (disabledTexture != nil) { texture = isEnabled ? defaultTexture : disabledTexture } } } var isSelected: Bool = false { didSet { texture = isSelected ? selectedTexture : defaultTexture } } var defaultTexture: SKTexture var selectedTexture: SKTexture var label: SKLabelNode required init(coder: NSCoder) { fatalError("NSCoding not supported") } init(normalTexture defaultTexture: SKTexture!, selectedTexture:SKTexture!, disabledTexture: SKTexture?) { self.defaultTexture = defaultTexture self.selectedTexture = selectedTexture self.disabledTexture = disabledTexture self.label = SKLabelNode(fontNamed: "Helvetica"); super.init(texture: defaultTexture, color: UIColor.whiteColor(), size: defaultTexture.size()) userInteractionEnabled = true //Creating and adding a blank label, centered on the button self.label.verticalAlignmentMode = SKLabelVerticalAlignmentMode.Center; self.label.horizontalAlignmentMode = SKLabelHorizontalAlignmentMode.Center; addChild(self.label) // Adding this node as an empty layer. Without it the touch functions are not being called // The reason for this is unknown when this was implemented...? let bugFixLayerNode = SKSpriteNode(texture: nil, color: UIColor.clearColor(), size: defaultTexture.size()) bugFixLayerNode.position = self.position addChild(bugFixLayerNode) } /** * Taking a target object and adding an action that is triggered by a button event. */ func setButtonAction(target: AnyObject, triggerEvent event:FTButtonActionType, action:Selector) { switch (event) { case .TouchUpInside: targetTouchUpInside = target actionTouchUpInside = action case .TouchDown: targetTouchDown = target actionTouchDown = action case .TouchUp: targetTouchUp = target actionTouchUp = action } } /* New function for setting text. Calling function multiple times does not create a ton of new labels, just updates existing label. You can set the title, font type and font size with this function */ func setButtonLabel(title: NSString, font: String, fontSize: CGFloat) { self.label.text = title as String self.label.fontSize = fontSize self.label.fontName = font } var disabledTexture: SKTexture? var actionTouchUpInside: Selector? var actionTouchUp: Selector? var actionTouchDown: Selector? weak var targetTouchUpInside: AnyObject? weak var targetTouchUp: AnyObject? weak var targetTouchDown: AnyObject? override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { if (!isEnabled) { return } isSelected = true if (targetTouchDown != nil && targetTouchDown!.respondsToSelector(actionTouchDown!)) { UIApplication.sharedApplication().sendAction(actionTouchDown!, to: targetTouchDown, from: self, forEvent: nil) } } override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) { if (!isEnabled) { return } let touch: AnyObject! = touches.first let touchLocation = touch.locationInNode(parent!) if (CGRectContainsPoint(frame, touchLocation)) { isSelected = true } else { isSelected = false } } override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) { if (!isEnabled) { return } isSelected = false if (targetTouchUpInside != nil && targetTouchUpInside!.respondsToSelector(actionTouchUpInside!)) { let touch: AnyObject! = touches.first let touchLocation = touch.locationInNode(parent!) if (CGRectContainsPoint(frame, touchLocation) ) { UIApplication.sharedApplication().sendAction(actionTouchUpInside!, to: targetTouchUpInside, from: self, forEvent: nil) } } if (targetTouchUp != nil && targetTouchUp!.respondsToSelector(actionTouchUp!)) { UIApplication.sharedApplication().sendAction(actionTouchUp!, to: targetTouchUp, from: self, forEvent: nil) } } }
mit
00559d0b7192d9efe8ec7bae33c9a973
32.888112
134
0.621878
5.486976
false
false
false
false
ccrama/Slide-iOS
Slide for Reddit/CachedTitle.swift
1
37362
// // CachedTitle.swift // Slide for Reddit // // Created by Carlos Crane on 7/21/17. // Copyright © 2017 Haptic Apps. All rights reserved. // import Foundation import YYText struct Title { var mainTitle: NSAttributedString? var infoLine: NSAttributedString? var extraLine: NSAttributedString? var color: UIColor } class CachedTitle { static var titles: [String: Title] = [:] static var removed: [String] = [] static var approved: [String] = [] static var spacer = NSMutableAttributedString.init(string: " ") static let baseFontSize: CGFloat = 18 static func addTitle(s: RSubmission) { titles[s.getId()] = titleForSubmission(submission: s, full: false, white: false, gallery: false) } static var titleFont = FontGenerator.fontOfSize(size: baseFontSize, submission: true) static var titleFontSmall = FontGenerator.fontOfSize(size: 14, submission: true) static func getTitle(submission: RSubmission, full: Bool, _ refresh: Bool, _ white: Bool = false, gallery: Bool) -> Title { let title = titles[submission.getId()] if title == nil || refresh || full || white || gallery { if white { return titleForSubmission(submission: submission, full: full, white: white, gallery: gallery) } if !full { titles[submission.getId()] = titleForSubmission(submission: submission, full: full, white: white, gallery: gallery) return titles[submission.getId()]! } else { return titleForSubmission(submission: submission, full: full, white: white, gallery: gallery) } } else { return title! } } static func getTitleForMedia(submission: RSubmission) -> Title { return titleForMedia(submission: submission) } static func titleForSubmission(submission: RSubmission, full: Bool, white: Bool, gallery: Bool) -> Title { var colorF = ColorUtil.theme.fontColor if white { colorF = .white } let brightF = colorF colorF = colorF.add(overlay: ColorUtil.theme.foregroundColor.withAlphaComponent(0.20)) if gallery { let attributedTitle = NSMutableAttributedString(string: submission.title.unescapeHTML, attributes: [NSAttributedString.Key.font: titleFontSmall, NSAttributedString.Key.foregroundColor: brightF]) return Title(mainTitle: attributedTitle, color: colorF) } let attributedTitle = NSMutableAttributedString(string: submission.title.unescapeHTML, attributes: [NSAttributedString.Key.font: titleFont, NSAttributedString.Key.foregroundColor: brightF]) if !submission.flair.isEmpty { let flairTitle = NSMutableAttributedString.init(string: "\u{00A0}\(submission.flair)\u{00A0}", attributes: [NSAttributedString.Key.font: FontGenerator.boldFontOfSize(size: 12, submission: true), NSAttributedString.Key(rawValue: YYTextBackgroundBorderAttributeName): YYTextBorder(fill: ColorUtil.theme.backgroundColor, cornerRadius: 3), NSAttributedString.Key.foregroundColor: brightF]) attributedTitle.append(spacer) attributedTitle.append(flairTitle) } if submission.nsfw { let nsfw = NSMutableAttributedString.init(string: "\u{00A0}NSFW\u{00A0}", attributes: [NSAttributedString.Key.font: FontGenerator.boldFontOfSize(size: 12, submission: true), NSAttributedString.Key(rawValue: YYTextBackgroundBorderAttributeName): YYTextBorder(fill: GMColor.red500Color(), cornerRadius: 3), NSAttributedString.Key.foregroundColor: UIColor.white]) attributedTitle.append(spacer) attributedTitle.append(nsfw) } if submission.spoiler { let spoiler = NSMutableAttributedString.init(string: "\u{00A0}SPOILER\u{00A0}", attributes: [NSAttributedString.Key.font: FontGenerator.boldFontOfSize(size: 12, submission: true), NSAttributedString.Key(rawValue: YYTextBackgroundBorderAttributeName): YYTextBorder(fill: GMColor.grey50Color(), cornerRadius: 3), NSAttributedString.Key.foregroundColor: UIColor.black]) attributedTitle.append(spacer) attributedTitle.append(spoiler) } if submission.oc { let oc = NSMutableAttributedString.init(string: "\u{00A0}OC\u{00A0}", attributes: [NSAttributedString.Key.font: FontGenerator.boldFontOfSize(size: 12, submission: true), NSAttributedString.Key(rawValue: YYTextBackgroundBorderAttributeName): YYTextBorder(fill: GMColor.blue50Color(), cornerRadius: 3), NSAttributedString.Key.foregroundColor: UIColor.black]) attributedTitle.append(spacer) attributedTitle.append(oc) } /*if submission.cakeday { attributedTitle.append(spacer) let gild = NSMutableAttributedString(string: "🍰", attributes: [NSAttributedString.Key.font: FontGenerator.boldFontOfSize(size: 12, submission: true)]) attributedTitle.append(gild) }*/ if submission.stickied { let pinned = NSMutableAttributedString.init(string: "\u{00A0}PINNED\u{00A0}", attributes: [NSAttributedString.Key.font: FontGenerator.boldFontOfSize(size: 12, submission: true), NSAttributedString.Key(rawValue: YYTextBackgroundBorderAttributeName): YYTextBorder(fill: GMColor.green500Color(), cornerRadius: 3), NSAttributedString.Key.foregroundColor: UIColor.white]) attributedTitle.append(spacer) attributedTitle.append(pinned) } if submission.locked { let locked = NSMutableAttributedString.init(string: "\u{00A0}LOCKED\u{00A0}", attributes: [NSAttributedString.Key.font: FontGenerator.boldFontOfSize(size: 12, submission: true), NSAttributedString.Key(rawValue: YYTextBackgroundBorderAttributeName): YYTextBorder(fill: GMColor.green500Color(), cornerRadius: 3), NSAttributedString.Key.foregroundColor: UIColor.white]) attributedTitle.append(spacer) attributedTitle.append(locked) } if submission.archived { let archived = NSMutableAttributedString.init(string: "\u{00A0}ARCHIVED\u{00A0}", attributes: [NSAttributedString.Key.font: FontGenerator.boldFontOfSize(size: 12, submission: true), NSAttributedString.Key(rawValue: YYTextBackgroundBorderAttributeName): YYTextBorder(fill: ColorUtil.theme.backgroundColor, cornerRadius: 3), NSAttributedString.Key.foregroundColor: brightF]) attributedTitle.append(archived) } let endString = NSMutableAttributedString(string: " • \(DateFormatter().timeSince(from: submission.created, numericDates: true))\((submission.isEdited ? ("(edit \(DateFormatter().timeSince(from: submission.edited, numericDates: true)))") : "")) • ", attributes: [NSAttributedString.Key.font: FontGenerator.fontOfSize(size: 12, submission: true), NSAttributedString.Key.foregroundColor: colorF]) let authorString = NSMutableAttributedString(string: "\u{00A0}\(AccountController.formatUsername(input: submission.author + (submission.cakeday ? " 🎂" : ""), small: false))\u{00A0}", attributes: [NSAttributedString.Key.font: FontGenerator.fontOfSize(size: 12, submission: true), NSAttributedString.Key.foregroundColor: colorF]) authorString.yy_setTextHighlight(NSRange(location: 0, length: authorString.length), color: nil, backgroundColor: nil, userInfo: ["url": URL(string: "/u/\(submission.author)")!, "profile": submission.author]) let userColor = ColorUtil.getColorForUser(name: submission.author) if submission.distinguished == "admin" { authorString.addAttributes([NSAttributedString.Key(rawValue: YYTextBackgroundBorderAttributeName): YYTextBorder(fill: UIColor.init(hexString: "#E57373"), cornerRadius: 3), NSAttributedString.Key.foregroundColor: UIColor.white], range: NSRange.init(location: 0, length: authorString.length)) } else if submission.distinguished == "special" { authorString.addAttributes([NSAttributedString.Key(rawValue: YYTextBackgroundBorderAttributeName): YYTextBorder(fill: UIColor.init(hexString: "#F44336"), cornerRadius: 3), NSAttributedString.Key.foregroundColor: UIColor.white], range: NSRange.init(location: 0, length: authorString.length)) } else if submission.distinguished == "moderator" { authorString.addAttributes([NSAttributedString.Key(rawValue: YYTextBackgroundBorderAttributeName): YYTextBorder(fill: UIColor.init(hexString: "#81C784"), cornerRadius: 3), NSAttributedString.Key.foregroundColor: UIColor.white], range: NSRange.init(location: 0, length: authorString.length)) } else if AccountController.currentName == submission.author { authorString.addAttributes([NSAttributedString.Key(rawValue: YYTextBackgroundBorderAttributeName): YYTextBorder(fill: UIColor.init(hexString: "#FFB74D"), cornerRadius: 3), NSAttributedString.Key.foregroundColor: UIColor.white], range: NSRange.init(location: 0, length: authorString.length)) } else if userColor != ColorUtil.baseColor { authorString.addAttributes([NSAttributedString.Key(rawValue: YYTextBackgroundBorderAttributeName): YYTextBorder(fill: userColor, cornerRadius: 3), NSAttributedString.Key.foregroundColor: UIColor.white], range: NSRange.init(location: 0, length: authorString.length)) } endString.append(authorString) if SettingValues.domainInInfo && !full { endString.append(NSAttributedString.init(string: " • \(submission.domain)", attributes: [NSAttributedString.Key.font: FontGenerator.fontOfSize(size: 12, submission: true), NSAttributedString.Key.foregroundColor: colorF])) } let tag = ColorUtil.getTagForUser(name: submission.author) if tag != nil { let tagString = NSMutableAttributedString.init(string: "\u{00A0}\(tag!)\u{00A0}", attributes: [NSAttributedString.Key.font: FontGenerator.boldFontOfSize(size: 12, submission: true), NSAttributedString.Key(rawValue: YYTextBackgroundBorderAttributeName): YYTextBorder(fill: UIColor(rgb: 0x2196f3), cornerRadius: 3), NSAttributedString.Key.foregroundColor: UIColor.white]) endString.append(spacer) endString.append(tagString) } let infoLine = NSMutableAttributedString() var finalTitle: NSMutableAttributedString if SettingValues.newIndicator && !History.getSeen(s: submission) { finalTitle = NSMutableAttributedString(string: "• ", attributes: [NSAttributedString.Key.font: FontGenerator.boldFontOfSize(size: 12, submission: true), NSAttributedString.Key.foregroundColor: ColorUtil.accentColorForSub(sub: submission.subreddit)]) } else { finalTitle = NSMutableAttributedString() } let extraLine = NSMutableAttributedString() finalTitle.append(attributedTitle) infoLine.append(endString) if !full { if SettingValues.scoreInTitle { var sColor = ColorUtil.theme.fontColor.add(overlay: ColorUtil.theme.foregroundColor.withAlphaComponent(0.15)) switch ActionStates.getVoteDirection(s: submission) { case .down: sColor = ColorUtil.downvoteColor case .up: sColor = ColorUtil.upvoteColor case .none: break } var scoreInt = submission.score switch ActionStates.getVoteDirection(s: submission) { case .up: if submission.likes != .up { if submission.likes == .down { scoreInt += 1 } scoreInt += 1 } case .down: if submission.likes != .down { if submission.likes == .up { scoreInt -= 1 } scoreInt -= 1 } case .none: if submission.likes == .up && submission.author == AccountController.currentName { scoreInt -= 1 } } let upvoteImage = NSMutableAttributedString.yy_attachmentString(withEmojiImage: UIImage(sfString: SFSymbol.arrowUp, overrideString: "upvote")!.getCopy(withColor: ColorUtil.theme.fontColor), fontSize: titleFont.pointSize * 0.45)! let subScore = NSMutableAttributedString(string: (scoreInt >= 10000 && SettingValues.abbreviateScores) ? String(format: "%0.1fk", (Double(scoreInt) / Double(1000))) : "\(scoreInt)", attributes: [NSAttributedString.Key.font: FontGenerator.boldFontOfSize(size: 12, submission: false), NSAttributedString.Key.foregroundColor: sColor]) extraLine.append(upvoteImage) extraLine.append(subScore) } if SettingValues.commentsInTitle { if SettingValues.scoreInTitle { extraLine.append(spacer) } let commentImage = NSMutableAttributedString.yy_attachmentString(withEmojiImage: UIImage(sfString: SFSymbol.bubbleRightFill, overrideString: "comments")!.getCopy(withColor: ColorUtil.theme.fontColor), fontSize: titleFont.pointSize * 0.5)! let scoreString = NSMutableAttributedString(string: "\(submission.commentCount)", attributes: [NSAttributedString.Key.font: FontGenerator.boldFontOfSize(size: 12, submission: false), NSAttributedString.Key.foregroundColor: colorF]) extraLine.append(commentImage) extraLine.append(scoreString) } } if removed.contains(submission.id) || (!submission.removedBy.isEmpty() && !approved.contains(submission.id)) { let attrs = [NSAttributedString.Key.font: FontGenerator.boldFontOfSize(size: 12, submission: true), NSAttributedString.Key.foregroundColor: GMColor.red500Color()] as [NSAttributedString.Key: Any] extraLine.append(spacer) if submission.removedBy == "true" { extraLine.append(NSMutableAttributedString.init(string: "Removed by Reddit\(!submission.removalReason.isEmpty() ? ":\(submission.removalReason)" : "")", attributes: attrs)) } else { extraLine.append(NSMutableAttributedString.init(string: "Removed\(!submission.removedBy.isEmpty() ? "by \(submission.removedBy)" : "")\(!submission.removalReason.isEmpty() ? " for \(submission.removalReason)" : "")\(!submission.removalNote.isEmpty() ? " \(submission.removalNote)" : "")", attributes: attrs)) } } else if approved.contains(submission.id) || (!submission.approvedBy.isEmpty() && !removed.contains(submission.id)) { let attrs = [NSAttributedString.Key.font: FontGenerator.boldFontOfSize(size: 12, submission: true), NSAttributedString.Key.foregroundColor: GMColor.green500Color()] as [NSAttributedString.Key: Any] extraLine.append(spacer) extraLine.append(NSMutableAttributedString.init(string: "Approved\(!submission.approvedBy.isEmpty() ? " by \(submission.approvedBy)":"")", attributes: attrs)) } if SettingValues.typeInTitle { let info = NSMutableAttributedString.init(string: "\u{00A0}\u{00A0}\(submission.type.rawValue)\u{00A0}", attributes: [NSAttributedString.Key.font: FontGenerator.boldFontOfSize(size: 12, submission: true), NSAttributedString.Key(rawValue: YYTextBackgroundBorderAttributeName): YYTextBorder(fill: ColorUtil.theme.fontColor, cornerRadius: 3), NSAttributedString.Key.foregroundColor: ColorUtil.theme.foregroundColor]) finalTitle.append(spacer) finalTitle.append(info) } if submission.isCrosspost && !full { if extraLine.string.length > 0 { extraLine.append(NSAttributedString.init(string: "\n")) } let crosspost = NSMutableAttributedString.yy_attachmentString(withEmojiImage: UIImage(named: "crosspost")!.getCopy(withColor: ColorUtil.theme.fontColor), fontSize: titleFont.pointSize * 0.75)! let finalText = NSMutableAttributedString.init(string: " Crossposted from ", attributes: [NSAttributedString.Key.foregroundColor: colorF, NSAttributedString.Key.font: FontGenerator.boldFontOfSize(size: 12, submission: true)]) let attrs = [NSAttributedString.Key.font: FontGenerator.fontOfSize(size: 12, submission: true), NSAttributedString.Key.foregroundColor: colorF] as [NSAttributedString.Key: Any] let boldString = NSMutableAttributedString(string: "r/\(submission.crosspostSubreddit)", attributes: attrs) let color = ColorUtil.getColorForSub(sub: submission.crosspostSubreddit) if color != ColorUtil.baseColor { boldString.addAttribute(NSAttributedString.Key.foregroundColor, value: color, range: NSRange.init(location: 0, length: boldString.length)) } crosspost.append(finalText) crosspost.append(boldString) extraLine.append(crosspost) } if submission.pollOptions.count > 0 { if extraLine.string.length > 0 { extraLine.append(NSAttributedString.init(string: "\n")) } let poll = NSMutableAttributedString.yy_attachmentString(withEmojiImage: UIImage(named: "poll")!.getCopy(withColor: ColorUtil.theme.fontColor), fontSize: titleFont.pointSize * 0.75)! let finalText = NSMutableAttributedString.init(string: " Poll", attributes: [NSAttributedString.Key.foregroundColor: colorF, NSAttributedString.Key.font: FontGenerator.boldFontOfSize(size: 12, submission: true)]) poll.append(finalText) for option in submission.pollOptions { let split = option.split(";") poll.append(NSAttributedString.init(string: "\n")) let option = split[0] let count = Int(split[1]) ?? -1 if count != -1 { poll.append(NSAttributedString(string: "\(count)", attributes: [NSAttributedString.Key.foregroundColor: ColorUtil.accentColorForSub(sub: submission.subreddit), NSAttributedString.Key.font: FontGenerator.boldFontOfSize(size: 12, submission: true)])) let value = (100.0 * CGFloat(count) / CGFloat(submission.pollTotal)) let percent = String(format: " (%.1f%%)", value) poll.append(NSAttributedString(string: percent, attributes: [NSAttributedString.Key.foregroundColor: ColorUtil.accentColorForSub(sub: submission.subreddit), NSAttributedString.Key.font: FontGenerator.fontOfSize(size: 10, submission: true)])) } poll.append(NSAttributedString(string: " \(option) ", attributes: [NSAttributedString.Key.foregroundColor: colorF, NSAttributedString.Key.font: FontGenerator.fontOfSize(size: 12, submission: true)])) } poll.append(NSAttributedString.init(string: "\n")) poll.append(NSAttributedString(string: "\(submission.pollTotal) total votes", attributes: [NSAttributedString.Key.foregroundColor: ColorUtil.accentColorForSub(sub: submission.subreddit), NSAttributedString.Key.font: FontGenerator.boldFontOfSize(size: 12, submission: true)])) poll.append(NSAttributedString.init(string: "\n")) extraLine.append(poll) } if SettingValues.showFirstParagraph && submission.isSelf && !submission.spoiler && !submission.nsfw && !full && !submission.body.trimmed().isEmpty { let length = submission.htmlBody.indexOf("\n") ?? submission.htmlBody.length let text = submission.htmlBody.substring(0, length: length).trimmed() if !text.isEmpty() { extraLine.append(NSAttributedString.init(string: "\n")) //Extra space for body extraLine.append(TextDisplayStackView.createAttributedChunk(baseHTML: text, fontSize: 14, submission: false, accentColor: ColorUtil.accentColorForSub(sub: submission.subreddit), fontColor: ColorUtil.theme.fontColor, linksCallback: nil, indexCallback: nil)) } } return Title(mainTitle: finalTitle, infoLine: infoLine, extraLine: extraLine, color: colorF) } static func titleForMedia(submission: RSubmission) -> Title { let colorF = UIColor.white let attributedTitle = NSMutableAttributedString(string: submission.title.unescapeHTML, attributes: [NSAttributedString.Key.font: titleFontSmall, NSAttributedString.Key.foregroundColor: colorF]) if submission.nsfw { let nsfw = NSMutableAttributedString.init(string: "\u{00A0}NSFW\u{00A0}", attributes: [NSAttributedString.Key.font: titleFontSmall, NSAttributedString.Key(rawValue: YYTextBackgroundBorderAttributeName): YYTextBorder(fill: GMColor.red500Color(), cornerRadius: 3), NSAttributedString.Key.foregroundColor: UIColor.white]) attributedTitle.append(spacer) attributedTitle.append(nsfw) } if submission.oc { let oc = NSMutableAttributedString.init(string: "\u{00A0}OC\u{00A0}", attributes: [NSAttributedString.Key.font: titleFontSmall, NSAttributedString.Key(rawValue: YYTextBackgroundBorderAttributeName): YYTextBorder(fill: GMColor.blue50Color(), cornerRadius: 3), NSAttributedString.Key.foregroundColor: UIColor.black]) attributedTitle.append(spacer) attributedTitle.append(oc) } let endString = NSMutableAttributedString(string: "r/\(submission.subreddit) • \(DateFormatter().timeSince(from: submission.created, numericDates: true))\((submission.isEdited ? ("(edit \(DateFormatter().timeSince(from: submission.edited, numericDates: true)))") : "")) • ", attributes: [NSAttributedString.Key.font: FontGenerator.fontOfSize(size: 12, submission: true), NSAttributedString.Key.foregroundColor: colorF]) let authorString = NSMutableAttributedString(string: "\u{00A0}\(AccountController.formatUsername(input: submission.author + (submission.cakeday ? " 🎂" : ""), small: false))\u{00A0}", attributes: [NSAttributedString.Key.font: FontGenerator.fontOfSize(size: 12, submission: true), NSAttributedString.Key.foregroundColor: colorF]) authorString.yy_setTextHighlight(NSRange(location: 0, length: authorString.length), color: nil, backgroundColor: nil, userInfo: ["url": URL(string: "/u/\(submission.author)")!, "profile": submission.author]) let userColor = ColorUtil.getColorForUser(name: submission.author) if submission.distinguished == "admin" { authorString.addAttributes([NSAttributedString.Key(rawValue: YYTextBackgroundBorderAttributeName): YYTextBorder(fill: UIColor.init(hexString: "#E57373"), cornerRadius: 3), NSAttributedString.Key.foregroundColor: UIColor.white], range: NSRange.init(location: 0, length: authorString.length)) } else if submission.distinguished == "special" { authorString.addAttributes([NSAttributedString.Key(rawValue: YYTextBackgroundBorderAttributeName): YYTextBorder(fill: UIColor.init(hexString: "#F44336"), cornerRadius: 3), NSAttributedString.Key.foregroundColor: UIColor.white], range: NSRange.init(location: 0, length: authorString.length)) } else if submission.distinguished == "moderator" { authorString.addAttributes([NSAttributedString.Key(rawValue: YYTextBackgroundBorderAttributeName): YYTextBorder(fill: UIColor.init(hexString: "#81C784"), cornerRadius: 3), NSAttributedString.Key.foregroundColor: UIColor.white], range: NSRange.init(location: 0, length: authorString.length)) } else if AccountController.currentName == submission.author { authorString.addAttributes([NSAttributedString.Key(rawValue: YYTextBackgroundBorderAttributeName): YYTextBorder(fill: UIColor.init(hexString: "#FFB74D"), cornerRadius: 3), NSAttributedString.Key.foregroundColor: UIColor.white], range: NSRange.init(location: 0, length: authorString.length)) } else if userColor != ColorUtil.baseColor { authorString.addAttributes([NSAttributedString.Key(rawValue: YYTextBackgroundBorderAttributeName): YYTextBorder(fill: userColor, cornerRadius: 3), NSAttributedString.Key.foregroundColor: UIColor.white], range: NSRange.init(location: 0, length: authorString.length)) } endString.append(authorString) let tag = ColorUtil.getTagForUser(name: submission.author) if tag != nil { let tagString = NSMutableAttributedString.init(string: "\u{00A0}\(tag!)\u{00A0}", attributes: [NSAttributedString.Key.font: FontGenerator.boldFontOfSize(size: 12, submission: true), NSAttributedString.Key(rawValue: YYTextBackgroundBorderAttributeName): YYTextBorder(fill: UIColor(rgb: 0x2196f3), cornerRadius: 3), NSAttributedString.Key.foregroundColor: UIColor.white]) endString.append(spacer) endString.append(tagString) } let extraLine = NSMutableAttributedString() return Title(mainTitle: attributedTitle, infoLine: endString, extraLine: extraLine, color: UIColor.white) } static func getImageSize(fontSize: CGFloat) -> CGRect { var rect = CGRect.zero rect.origin.x = 0.75 if fontSize < 16 { rect.size.width = 1.25 * fontSize rect.size.height = 1.25 * fontSize } else if 16 <= fontSize && fontSize <= 24 { rect.size.width = 0.5 * fontSize + 12 rect.size.height = 0.5 * fontSize + 12 } else { rect.size.width = fontSize rect.size.height = fontSize } if fontSize < 16 { rect.origin.y = -0.2525 * fontSize } else if 16 <= fontSize && fontSize <= 24 { rect.origin.y = 0.1225 * fontSize - 6 } else { rect.origin.y = -0.1275 * fontSize } return rect } static func getTitleAttributedString(_ link: RSubmission, force: Bool, gallery: Bool, full: Bool, white: Bool = false, loadImages: Bool = true) -> NSAttributedString { let titleStrings = CachedTitle.getTitle(submission: link, full: full, force, white, gallery: gallery) let attrs = [NSAttributedString.Key.font: FontGenerator.boldFontOfSize(size: 12, submission: true), NSAttributedString.Key.foregroundColor: titleStrings.color] as [NSAttributedString.Key: Any] let color = ColorUtil.getColorForSub(sub: link.subreddit) var iconString = NSMutableAttributedString() if (link.subreddit_icon != "" || Subscriptions.icon(for: link.subreddit) != nil) && SettingValues.subredditIcons && !full { if Subscriptions.icon(for: link.subreddit) == nil { Subscriptions.subIcons[link.subreddit.lowercased()] = link.subreddit_icon.unescapeHTML } if let urlAsURL = URL(string: Subscriptions.icon(for: link.subreddit.lowercased())!.unescapeHTML) { if loadImages { let flairView = UIImageView(frame: CGRect(x: 0, y: 3, width: 20 + SettingValues.postFontOffset, height: 20 + SettingValues.postFontOffset)) flairView.layer.cornerRadius = CGFloat(20 + SettingValues.postFontOffset) / 2 flairView.layer.borderColor = color.cgColor flairView.backgroundColor = color flairView.layer.borderWidth = 0.5 flairView.clipsToBounds = true flairView.sd_setImage(with: urlAsURL, placeholderImage: nil, context: [.imageThumbnailPixelSize: CGSize(width: flairView.frame.size.width * UIScreen.main.scale, height: flairView.frame.size.height * UIScreen.main.scale)]) let flairImage = NSMutableAttributedString.yy_attachmentString(withContent: flairView, contentMode: UIView.ContentMode.center, attachmentSize: CGSize(width: 20 + SettingValues.postFontOffset, height: 20 + SettingValues.postFontOffset), alignTo: CachedTitle.titleFont, alignment: YYTextVerticalAlignment.center) iconString.append(flairImage) } else { let flairView = UIView(frame: CGRect(x: 0, y: 3, width: 20 + SettingValues.postFontOffset, height: 20 + SettingValues.postFontOffset)) let flairImage = NSMutableAttributedString.yy_attachmentString(withContent: flairView, contentMode: UIView.ContentMode.center, attachmentSize: CGSize(width: 20 + SettingValues.postFontOffset, height: 20 + SettingValues.postFontOffset), alignTo: CachedTitle.titleFont, alignment: YYTextVerticalAlignment.center) iconString.append(flairImage) } } let tapString = NSMutableAttributedString(string: " r/\(link.subreddit)", attributes: attrs) tapString.yy_setTextHighlight(NSRange(location: 0, length: tapString.length), color: nil, backgroundColor: nil, userInfo: ["url": URL(string: "/r/\(link.subreddit)")!]) iconString.append(tapString) } else { if color != ColorUtil.baseColor { let adjustedSize = 12 + CGFloat(SettingValues.postFontOffset) let preString = NSMutableAttributedString(string: "⬤ ", attributes: [NSAttributedString.Key.font: UIFont.systemFont(ofSize: adjustedSize), NSAttributedString.Key.foregroundColor: color]) iconString = preString let tapString = NSMutableAttributedString(string: "r/\(link.subreddit)", attributes: attrs) tapString.yy_setTextHighlight(NSRange(location: 0, length: tapString.length), color: nil, backgroundColor: nil, userInfo: ["url": URL(string: "/r/\(link.subreddit)")!]) iconString.append(tapString) } else { let tapString = NSMutableAttributedString(string: "r/\(link.subreddit)", attributes: attrs) tapString.yy_setTextHighlight(NSRange(location: 0, length: tapString.length), color: nil, backgroundColor: nil, userInfo: ["url": URL(string: "/r/\(link.subreddit)")!]) iconString = tapString } } let awardString = NSMutableAttributedString() let awardPStyle = NSMutableParagraphStyle() awardPStyle.minimumLineHeight = 20 if link.gilded { let boldFont = FontGenerator.boldFontOfSize(size: 12, submission: true) if SettingValues.hideAwards { var awardCount = link.platinum + link.silver + link.gold for award in link.awards { awardCount += Int(award.split(":")[1]) ?? 0 } let gild = NSMutableAttributedString.yy_attachmentString(withEmojiImage: UIImage(named: "gold")!, fontSize: CachedTitle.titleFont.pointSize * 0.75)! awardString.append(gild) if awardCount > 1 { let gilded = NSMutableAttributedString.init(string: "\u{00A0}x\(awardCount) ", attributes: [NSAttributedString.Key.paragraphStyle: awardPStyle, NSAttributedString.Key.font: boldFont, NSAttributedString.Key.foregroundColor: titleStrings.color]) awardString.append(gilded) } } else { for award in link.awards { let url = award.split("*")[0] let count = Int(award.split(":")[1]) ?? 0 if let urlAsURL = URL(string: url) { if loadImages { let flairView = UIImageView(frame: CGRect(x: 0, y: 0, width: 20, height: 20)) flairView.sd_setImage(with: urlAsURL, placeholderImage: nil, context: [.imageThumbnailPixelSize: CGSize(width: flairView.frame.size.width * UIScreen.main.scale, height: flairView.frame.size.height * UIScreen.main.scale)]) let flairImage = NSMutableAttributedString.yy_attachmentString(withContent: flairView, contentMode: UIView.ContentMode.center, attachmentSize: CachedTitle.getImageSize(fontSize: CachedTitle.titleFont.pointSize * 0.75).size, alignTo: CachedTitle.titleFont, alignment: YYTextVerticalAlignment.center) awardString.append(flairImage) } else { let flairView = UIView(frame: CGRect(x: 0, y: 0, width: 20, height: 20)) let flairImage = NSMutableAttributedString.yy_attachmentString(withContent: flairView, contentMode: UIView.ContentMode.center, attachmentSize: CachedTitle.getImageSize(fontSize: CachedTitle.titleFont.pointSize * 0.75).size, alignTo: CachedTitle.titleFont, alignment: YYTextVerticalAlignment.center) awardString.append(flairImage) } } if count > 1 { let gilded = NSMutableAttributedString.init(string: "\u{00A0}x\(link.gold) ", attributes: [NSAttributedString.Key.paragraphStyle: awardPStyle, NSAttributedString.Key.font: FontGenerator.boldFontOfSize(size: 12, submission: true), NSAttributedString.Key.foregroundColor: titleStrings.color]) awardString.append(gilded) } awardString.append(CachedTitle.spacer) } if link.platinum > 0 { let gild = NSMutableAttributedString.yy_attachmentString(withEmojiImage: UIImage(named: "platinum")!, fontSize: CachedTitle.titleFont.pointSize * 0.75)! awardString.append(gild) if link.platinum > 1 { let platinumed = NSMutableAttributedString.init(string: "\u{00A0}x\(link.platinum) ", attributes: [NSAttributedString.Key.paragraphStyle: awardPStyle, NSAttributedString.Key.font: boldFont, NSAttributedString.Key.foregroundColor: titleStrings.color]) awardString.append(platinumed) } awardString.append(CachedTitle.spacer) } if link.gold > 0 { let gild = NSMutableAttributedString.yy_attachmentString(withEmojiImage: UIImage(named: "gold")!, fontSize: CachedTitle.titleFont.pointSize * 0.75)! awardString.append(gild) if link.gold > 1 { let gilded = NSMutableAttributedString.init(string: "\u{00A0}x\(link.gold) ", attributes: [NSAttributedString.Key.font: boldFont, NSAttributedString.Key.foregroundColor: titleStrings.color]) awardString.append(gilded) } awardString.append(CachedTitle.spacer) } if link.silver > 0 { let gild = NSMutableAttributedString.yy_attachmentString(withEmojiImage: UIImage(named: "silver")!, fontSize: CachedTitle.titleFont.pointSize * 0.75)! awardString.append(gild) if link.silver > 1 { let silvered = NSMutableAttributedString.init(string: "\u{00A0}x\(link.silver) ", attributes: [NSAttributedString.Key.font: boldFont, NSAttributedString.Key.foregroundColor: titleStrings.color]) awardString.append(silvered) } awardString.append(CachedTitle.spacer) } } } let finalTitle = NSMutableAttributedString() if SettingValues.infoBelowTitle { if let mainTitle = titleStrings.mainTitle { finalTitle.append(mainTitle) } finalTitle.append(NSAttributedString.init(string: "\n")) finalTitle.append(iconString) if let infoLine = titleStrings.infoLine { finalTitle.append(infoLine) } if awardString.length > 0 { finalTitle.append(NSAttributedString.init(string: "\n")) finalTitle.append(awardString) } if let extraLine = titleStrings.extraLine, extraLine.length > 0 { finalTitle.append(NSAttributedString.init(string: "\n")) finalTitle.append(extraLine) } } else { finalTitle.append(iconString) if let infoLine = titleStrings.infoLine { finalTitle.append(infoLine) } finalTitle.append(NSAttributedString.init(string: "\n")) if let mainTitle = titleStrings.mainTitle { finalTitle.append(mainTitle) } if awardString.length > 0 { finalTitle.append(NSAttributedString.init(string: "\n")) finalTitle.append(awardString) } if let extraLine = titleStrings.extraLine, extraLine.length > 0 { finalTitle.append(NSAttributedString.init(string: "\n")) finalTitle.append(extraLine) } } return finalTitle } }
apache-2.0
32dc5c933201733e3e2d33cfd73cef9a
67.010929
431
0.662542
4.9
false
false
false
false
blockchain/My-Wallet-V3-iOS
Modules/Platform/Sources/PlatformUIKit/TransactionDescriptorViewModel.swift
1
6691
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import MoneyKit import PlatformKit import RxCocoa import RxRelay import RxSwift struct BadgeImageAttributes { let imageResource: ImageResource let brandColor: UIColor let isFiat: Bool static let empty = BadgeImageAttributes( imageResource: .local(name: "", bundle: .platformUIKit), brandColor: .white, isFiat: false ) init(_ currencyType: CurrencyType) { imageResource = currencyType.logoResource brandColor = currencyType.brandUIColor isFiat = currencyType.isFiatCurrency } init(imageResource: ImageResource, brandColor: UIColor, isFiat: Bool) { self.imageResource = imageResource self.brandColor = brandColor self.isFiat = isFiat } } public struct TransactionDescriptorViewModel { public var transactionTypeBadgeImageViewModel: Driver<BadgeImageViewModel> { guard adjustActionIconColor else { return Driver.just( provideBadgeImageViewModel( accentColor: .primaryButton, backgroundColor: .lightBlueBackground ) ) } return fromAccountRelay .compactMap(\.account) .map(\.currencyType) .map(BadgeImageAttributes.init) // This should not happen. .asDriver(onErrorJustReturn: .empty) .map { attributes -> BadgeImageViewModel in provideBadgeImageViewModel( accentColor: attributes.brandColor, backgroundColor: attributes.brandColor.withAlphaComponent(0.15) ) } } public var fromAccountBadgeImageViewModel: Driver<BadgeImageViewModel> { fromAccountRelay .compactMap(\.account) .map(\.currencyType) .map(BadgeImageAttributes.init) // This should not happen. .asDriver(onErrorJustReturn: .empty) .map { attributes -> BadgeImageViewModel in var model: BadgeImageViewModel switch attributes.isFiat { case true: model = BadgeImageViewModel.primary( image: attributes.imageResource, contentColor: .white, backgroundColor: attributes.brandColor, cornerRadius: attributes.isFiat ? .roundedHigh : .round, accessibilityIdSuffix: "" ) case false: model = BadgeImageViewModel.default( image: attributes.imageResource, cornerRadius: attributes.isFiat ? .roundedHigh : .round, accessibilityIdSuffix: "" ) } model.marginOffsetRelay.accept(0) return model } } public var toAccountBadgeImageViewModel: Driver<BadgeImageViewModel> { toAccountRelay .compactMap(\.account) .map(\.currencyType) .map(BadgeImageAttributes.init) // This should not happen. .asDriver(onErrorJustReturn: .empty) .map { attributes -> BadgeImageViewModel in let model = BadgeImageViewModel.default( image: attributes.imageResource, cornerRadius: attributes.isFiat ? .roundedHigh : .round, accessibilityIdSuffix: "" ) model.marginOffsetRelay.accept(0) return model } } public var toAccountBadgeIsHidden: Driver<Bool> { toAccountRelay .map(\.isEmpty) .asDriver(onErrorDriveWith: .empty()) } private let assetAction: AssetAction private let adjustActionIconColor: Bool public init(assetAction: AssetAction, adjustActionIconColor: Bool = false) { self.assetAction = assetAction self.adjustActionIconColor = adjustActionIconColor } public enum TransactionAccountValue { case value(SingleAccount) case empty var account: SingleAccount? { switch self { case .value(let account): return account case .empty: return nil } } var isEmpty: Bool { switch self { case .value: return false case .empty: return true } } } /// The `SingleAccount` that the transaction is originating from public let fromAccountRelay = BehaviorRelay<TransactionAccountValue>(value: .empty) /// The `SingleAccount` that is the destination for the transaction public let toAccountRelay = BehaviorRelay<TransactionAccountValue>(value: .empty) public init( sourceAccount: SingleAccount? = nil, destinationAccount: SingleAccount? = nil, assetAction: AssetAction, adjustActionIconColor: Bool = false ) { self.assetAction = assetAction self.adjustActionIconColor = adjustActionIconColor if let sourceAccount = sourceAccount { fromAccountRelay.accept(.value(sourceAccount)) } if let destinationAccount = destinationAccount { toAccountRelay.accept(.value(destinationAccount)) } } private func provideBadgeImageViewModel(accentColor: UIColor, backgroundColor: UIColor) -> BadgeImageViewModel { let viewModel = BadgeImageViewModel.template( image: .local(name: assetAction.assetImageName, bundle: .platformUIKit), templateColor: accentColor, backgroundColor: backgroundColor, cornerRadius: .round, accessibilityIdSuffix: "" ) viewModel.marginOffsetRelay.accept(0) return viewModel } } extension AssetAction { fileprivate var assetImageName: String { switch self { case .deposit, .interestTransfer: return "deposit-icon" case .receive: return "receive-icon" case .viewActivity: return "clock-icon" case .buy: return "plus-icon" case .sell: return "minus-icon" case .send, .linkToDebitCard: return "send-icon" case .sign: fatalError("Impossible.") case .swap: return "swap-icon" case .withdraw, .interestWithdraw: return "withdraw-icon" } } }
lgpl-3.0
7f49d68fc125ecc6fc33b65613a8ead3
31.955665
116
0.578924
5.636057
false
false
false
false
sadawi/ModelKit
ModelKitTests/ArchiveTests.swift
1
4320
// // ArchiveTests.swift // APIKit // // Created by Sam Williams on 2/13/16. // Copyright © 2016 Sam Williams. All rights reserved. // import XCTest import ModelKit fileprivate class Pet: Model { let id = Field<String>() let name = Field<String>() let owner = ModelField<Person>(key: "ownerID", foreignKey: true) } fileprivate class Person: Model { let id = Field<String>() let name = Field<String>() override var identifierField: FieldType { return self.id } } class ArchiveTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testArchiveRelated() { let archive = ArchiveModelStore.sharedInstance let context = archive.valueTransformerContext let alice = Person.with(identifier: "1234", in: context) XCTAssertEqual(alice.id.value, "1234") let alice2 = Person.with(identifier: "1234", in: context) XCTAssert(alice2 === alice) alice.name.value = "Alice" XCTAssertEqual(alice2.name.value, "Alice") let pet = Pet() pet.name.value = "Fluffy" pet.owner.value = alice let didLoad = expectation(description: "load") let didSave = expectation(description: "save") archive.saveList(Pet.self, models: [pet], includeRelated: true).then { () -> () in didSave.fulfill() archive.list(Pet.self).then { pets -> () in XCTAssertEqual(pets.count, 1) let pet = pets.first! XCTAssertEqual(pet.name.value, "Fluffy") XCTAssertEqual(pet.owner.value?.name.value, alice.name.value) XCTAssertEqual(pet.owner.value, alice) didLoad.fulfill() }.catch { error in XCTFail(String(describing: error)) } }.catch { error in XCTFail(String(describing: error)) } self.waitForExpectations(timeout: 1, handler:nil) } func testArchive() { let archive = ArchiveModelStore.sharedInstance let person1 = Person() person1.name.value = "Alice" let didLoad = expectation(description: "load") let didSave = expectation(description: "save") let didDelete = expectation(description: "delete") archive.saveList(Person.self, models: [person1]).then { () -> () in didSave.fulfill() archive.list(Person.self).then { people -> () in XCTAssertEqual(people.count, 1) let person = people.first! XCTAssertEqual(person.name.value, "Alice") didLoad.fulfill() _ = archive.deleteAll(Person.self).then { archive.list(Person.self).then { people -> () in XCTAssertEqual(people.count, 0) didDelete.fulfill() } } }.catch { error in XCTFail(String(describing: error)) } }.catch { error in XCTFail(String(describing: error)) } self.waitForExpectations(timeout: 1, handler:nil) } func testArchiveDeleteAll() { let archive = ArchiveModelStore.sharedInstance let person1 = Person() person1.name.value = "Alice" let didDelete = expectation(description: "delete") _ = archive.saveList(Person.self, models: [person1]).then { () -> () in _ = archive.deleteAll(Person.self).then { _ = archive.list(Person.self).then { people -> () in XCTAssertEqual(people.count, 0) didDelete.fulfill() } } } self.waitForExpectations(timeout: 1, handler:nil) } }
mit
923e99e4d845209847c1ac7e194f02a9
30.525547
111
0.536467
4.836506
false
true
false
false
uasys/swift
validation-test/stdlib/Dictionary.swift
3
131041
// RUN: %empty-directory(%t) // // RUN: %gyb %s -o %t/main.swift // RUN: if [ %target-runtime == "objc" ]; then \ // RUN: %target-clang -fobjc-arc %S/Inputs/SlurpFastEnumeration/SlurpFastEnumeration.m -c -o %t/SlurpFastEnumeration.o; \ // RUN: %line-directive %t/main.swift -- %target-build-swift %S/Inputs/DictionaryKeyValueTypes.swift %S/Inputs/DictionaryKeyValueTypesObjC.swift %t/main.swift -I %S/Inputs/SlurpFastEnumeration/ -Xlinker %t/SlurpFastEnumeration.o -o %t/Dictionary -Xfrontend -disable-access-control; \ // RUN: else \ // RUN: %line-directive %t/main.swift -- %target-build-swift %S/Inputs/DictionaryKeyValueTypes.swift %t/main.swift -o %t/Dictionary -Xfrontend -disable-access-control; \ // RUN: fi // // RUN: %line-directive %t/main.swift -- %target-run %t/Dictionary // REQUIRES: executable_test #if os(OSX) || os(iOS) || os(tvOS) || os(watchOS) import Darwin #else import Glibc #endif import StdlibUnittest import StdlibCollectionUnittest #if _runtime(_ObjC) import Foundation import StdlibUnittestFoundationExtras #endif extension Dictionary { func _rawIdentifier() -> Int { return unsafeBitCast(self, to: Int.self) } } // Check that the generic parameters are called 'Key' and 'Value'. protocol TestProtocol1 {} extension Dictionary where Key : TestProtocol1, Value : TestProtocol1 { var _keyValueAreTestProtocol1: Bool { fatalError("not implemented") } } extension DictionaryIndex where Key : TestProtocol1, Value : TestProtocol1 { var _keyValueAreTestProtocol1: Bool { fatalError("not implemented") } } extension DictionaryIterator where Key : TestProtocol1, Value : TestProtocol1 { var _keyValueAreTestProtocol1: Bool { fatalError("not implemented") } } var DictionaryTestSuite = TestSuite("Dictionary") DictionaryTestSuite.test("AssociatedTypes") { typealias Collection = Dictionary<MinimalHashableValue, OpaqueValue<Int>> expectCollectionAssociatedTypes( collectionType: Collection.self, iteratorType: DictionaryIterator<MinimalHashableValue, OpaqueValue<Int>>.self, subSequenceType: Slice<Collection>.self, indexType: DictionaryIndex<MinimalHashableValue, OpaqueValue<Int>>.self, indexDistanceType: Int.self, indicesType: DefaultIndices<Collection>.self) } DictionaryTestSuite.test("sizeof") { var dict = [1: "meow", 2: "meow"] #if arch(i386) || arch(arm) expectEqual(4, MemoryLayout.size(ofValue: dict)) #else expectEqual(8, MemoryLayout.size(ofValue: dict)) #endif } DictionaryTestSuite.test("valueDestruction") { var d1 = Dictionary<Int, TestValueTy>() for i in 100...110 { d1[i] = TestValueTy(i) } var d2 = Dictionary<TestKeyTy, TestValueTy>() for i in 100...110 { d2[TestKeyTy(i)] = TestValueTy(i) } } DictionaryTestSuite.test("COW.Smoke") { var d1 = Dictionary<TestKeyTy, TestValueTy>(minimumCapacity: 10) var identity1 = d1._rawIdentifier() d1[TestKeyTy(10)] = TestValueTy(1010) d1[TestKeyTy(20)] = TestValueTy(1020) d1[TestKeyTy(30)] = TestValueTy(1030) var d2 = d1 _fixLifetime(d2) assert(identity1 == d2._rawIdentifier()) d2[TestKeyTy(40)] = TestValueTy(2040) assert(identity1 != d2._rawIdentifier()) d1[TestKeyTy(50)] = TestValueTy(1050) assert(identity1 == d1._rawIdentifier()) // Keep variables alive. _fixLifetime(d1) _fixLifetime(d2) } func getCOWFastDictionary() -> Dictionary<Int, Int> { var d = Dictionary<Int, Int>(minimumCapacity: 10) d[10] = 1010 d[20] = 1020 d[30] = 1030 return d } func getCOWSlowDictionary() -> Dictionary<TestKeyTy, TestValueTy> { var d = Dictionary<TestKeyTy, TestValueTy>(minimumCapacity: 10) d[TestKeyTy(10)] = TestValueTy(1010) d[TestKeyTy(20)] = TestValueTy(1020) d[TestKeyTy(30)] = TestValueTy(1030) return d } func getCOWSlowEquatableDictionary() -> Dictionary<TestKeyTy, TestEquatableValueTy> { var d = Dictionary<TestKeyTy, TestEquatableValueTy>(minimumCapacity: 10) d[TestKeyTy(10)] = TestEquatableValueTy(1010) d[TestKeyTy(20)] = TestEquatableValueTy(1020) d[TestKeyTy(30)] = TestEquatableValueTy(1030) return d } DictionaryTestSuite.test("COW.Fast.IndexesDontAffectUniquenessCheck") { var d = getCOWFastDictionary() var identity1 = d._rawIdentifier() var startIndex = d.startIndex var endIndex = d.endIndex assert(startIndex != endIndex) assert(startIndex < endIndex) assert(startIndex <= endIndex) assert(!(startIndex >= endIndex)) assert(!(startIndex > endIndex)) assert(identity1 == d._rawIdentifier()) d[40] = 2040 assert(identity1 == d._rawIdentifier()) // Keep indexes alive during the calls above. _fixLifetime(startIndex) _fixLifetime(endIndex) } DictionaryTestSuite.test("COW.Slow.IndexesDontAffectUniquenessCheck") { var d = getCOWSlowDictionary() var identity1 = d._rawIdentifier() var startIndex = d.startIndex var endIndex = d.endIndex assert(startIndex != endIndex) assert(startIndex < endIndex) assert(startIndex <= endIndex) assert(!(startIndex >= endIndex)) assert(!(startIndex > endIndex)) assert(identity1 == d._rawIdentifier()) d[TestKeyTy(40)] = TestValueTy(2040) assert(identity1 == d._rawIdentifier()) // Keep indexes alive during the calls above. _fixLifetime(startIndex) _fixLifetime(endIndex) } DictionaryTestSuite.test("COW.Fast.SubscriptWithIndexDoesNotReallocate") { var d = getCOWFastDictionary() var identity1 = d._rawIdentifier() var startIndex = d.startIndex let empty = startIndex == d.endIndex assert((d.startIndex < d.endIndex) == !empty) assert(d.startIndex <= d.endIndex) assert((d.startIndex >= d.endIndex) == empty) assert(!(d.startIndex > d.endIndex)) assert(identity1 == d._rawIdentifier()) assert(d[startIndex].1 != 0) assert(identity1 == d._rawIdentifier()) } DictionaryTestSuite.test("COW.Slow.SubscriptWithIndexDoesNotReallocate") { var d = getCOWSlowDictionary() var identity1 = d._rawIdentifier() var startIndex = d.startIndex let empty = startIndex == d.endIndex assert((d.startIndex < d.endIndex) == !empty) assert(d.startIndex <= d.endIndex) assert((d.startIndex >= d.endIndex) == empty) assert(!(d.startIndex > d.endIndex)) assert(identity1 == d._rawIdentifier()) assert(d[startIndex].1.value != 0) assert(identity1 == d._rawIdentifier()) } DictionaryTestSuite.test("COW.Fast.SubscriptWithKeyDoesNotReallocate") .xfail(.custom({ _isStdlibDebugConfiguration() }, reason: "rdar://33358110")) .code { var d = getCOWFastDictionary() var identity1 = d._rawIdentifier() assert(d[10]! == 1010) assert(identity1 == d._rawIdentifier()) // Insert a new key-value pair. d[40] = 2040 assert(identity1 == d._rawIdentifier()) assert(d.count == 4) assert(d[10]! == 1010) assert(d[20]! == 1020) assert(d[30]! == 1030) assert(d[40]! == 2040) // Overwrite a value in existing binding. d[10] = 2010 assert(identity1 == d._rawIdentifier()) assert(d.count == 4) assert(d[10]! == 2010) assert(d[20]! == 1020) assert(d[30]! == 1030) assert(d[40]! == 2040) // Delete an existing key. d[10] = nil assert(identity1 == d._rawIdentifier()) assert(d.count == 3) assert(d[20]! == 1020) assert(d[30]! == 1030) assert(d[40]! == 2040) // Try to delete a key that does not exist. d[42] = nil assert(identity1 == d._rawIdentifier()) assert(d.count == 3) assert(d[20]! == 1020) assert(d[30]! == 1030) assert(d[40]! == 2040) do { var d2: [MinimalHashableValue : OpaqueValue<Int>] = [:] MinimalHashableValue.timesEqualEqualWasCalled = 0 MinimalHashableValue.timesHashValueWasCalled = 0 expectNil(d2[MinimalHashableValue(42)]) // If the dictionary is empty, we shouldn't be computing the hash value of // the provided key. expectEqual(0, MinimalHashableValue.timesEqualEqualWasCalled) expectEqual(0, MinimalHashableValue.timesHashValueWasCalled) } } DictionaryTestSuite.test("COW.Slow.SubscriptWithKeyDoesNotReallocate") .xfail(.custom({ _isStdlibDebugConfiguration() }, reason: "rdar://33358110")) .code { var d = getCOWSlowDictionary() var identity1 = d._rawIdentifier() assert(d[TestKeyTy(10)]!.value == 1010) assert(identity1 == d._rawIdentifier()) // Insert a new key-value pair. d[TestKeyTy(40)] = TestValueTy(2040) assert(identity1 == d._rawIdentifier()) assert(d.count == 4) assert(d[TestKeyTy(10)]!.value == 1010) assert(d[TestKeyTy(20)]!.value == 1020) assert(d[TestKeyTy(30)]!.value == 1030) assert(d[TestKeyTy(40)]!.value == 2040) // Overwrite a value in existing binding. d[TestKeyTy(10)] = TestValueTy(2010) assert(identity1 == d._rawIdentifier()) assert(d.count == 4) assert(d[TestKeyTy(10)]!.value == 2010) assert(d[TestKeyTy(20)]!.value == 1020) assert(d[TestKeyTy(30)]!.value == 1030) assert(d[TestKeyTy(40)]!.value == 2040) // Delete an existing key. d[TestKeyTy(10)] = nil assert(identity1 == d._rawIdentifier()) assert(d.count == 3) assert(d[TestKeyTy(20)]!.value == 1020) assert(d[TestKeyTy(30)]!.value == 1030) assert(d[TestKeyTy(40)]!.value == 2040) // Try to delete a key that does not exist. d[TestKeyTy(42)] = nil assert(identity1 == d._rawIdentifier()) assert(d.count == 3) assert(d[TestKeyTy(20)]!.value == 1020) assert(d[TestKeyTy(30)]!.value == 1030) assert(d[TestKeyTy(40)]!.value == 2040) do { var d2: [MinimalHashableClass : OpaqueValue<Int>] = [:] MinimalHashableClass.timesEqualEqualWasCalled = 0 MinimalHashableClass.timesHashValueWasCalled = 0 expectNil(d2[MinimalHashableClass(42)]) // If the dictionary is empty, we shouldn't be computing the hash value of // the provided key. expectEqual(0, MinimalHashableClass.timesEqualEqualWasCalled) expectEqual(0, MinimalHashableClass.timesHashValueWasCalled) } } DictionaryTestSuite.test("COW.Fast.UpdateValueForKeyDoesNotReallocate") { do { var d1 = getCOWFastDictionary() var identity1 = d1._rawIdentifier() // Insert a new key-value pair. assert(d1.updateValue(2040, forKey: 40) == .none) assert(identity1 == d1._rawIdentifier()) assert(d1[40]! == 2040) // Overwrite a value in existing binding. assert(d1.updateValue(2010, forKey: 10)! == 1010) assert(identity1 == d1._rawIdentifier()) assert(d1[10]! == 2010) } do { var d1 = getCOWFastDictionary() var identity1 = d1._rawIdentifier() var d2 = d1 assert(identity1 == d1._rawIdentifier()) assert(identity1 == d2._rawIdentifier()) // Insert a new key-value pair. d2.updateValue(2040, forKey: 40) assert(identity1 == d1._rawIdentifier()) assert(identity1 != d2._rawIdentifier()) assert(d1.count == 3) assert(d1[10]! == 1010) assert(d1[20]! == 1020) assert(d1[30]! == 1030) assert(d1[40] == .none) assert(d2.count == 4) assert(d2[10]! == 1010) assert(d2[20]! == 1020) assert(d2[30]! == 1030) assert(d2[40]! == 2040) // Keep variables alive. _fixLifetime(d1) _fixLifetime(d2) } do { var d1 = getCOWFastDictionary() var identity1 = d1._rawIdentifier() var d2 = d1 assert(identity1 == d1._rawIdentifier()) assert(identity1 == d2._rawIdentifier()) // Overwrite a value in existing binding. d2.updateValue(2010, forKey: 10) assert(identity1 == d1._rawIdentifier()) assert(identity1 != d2._rawIdentifier()) assert(d1.count == 3) assert(d1[10]! == 1010) assert(d1[20]! == 1020) assert(d1[30]! == 1030) assert(d2.count == 3) assert(d2[10]! == 2010) assert(d2[20]! == 1020) assert(d2[30]! == 1030) // Keep variables alive. _fixLifetime(d1) _fixLifetime(d2) } } DictionaryTestSuite.test("COW.Slow.AddDoesNotReallocate") { do { var d1 = getCOWSlowDictionary() var identity1 = d1._rawIdentifier() // Insert a new key-value pair. assert(d1.updateValue(TestValueTy(2040), forKey: TestKeyTy(40)) == nil) assert(identity1 == d1._rawIdentifier()) assert(d1.count == 4) assert(d1[TestKeyTy(40)]!.value == 2040) // Overwrite a value in existing binding. assert(d1.updateValue(TestValueTy(2010), forKey: TestKeyTy(10))!.value == 1010) assert(identity1 == d1._rawIdentifier()) assert(d1.count == 4) assert(d1[TestKeyTy(10)]!.value == 2010) } do { var d1 = getCOWSlowDictionary() var identity1 = d1._rawIdentifier() var d2 = d1 assert(identity1 == d1._rawIdentifier()) assert(identity1 == d2._rawIdentifier()) // Insert a new key-value pair. d2.updateValue(TestValueTy(2040), forKey: TestKeyTy(40)) assert(identity1 == d1._rawIdentifier()) assert(identity1 != d2._rawIdentifier()) assert(d1.count == 3) assert(d1[TestKeyTy(10)]!.value == 1010) assert(d1[TestKeyTy(20)]!.value == 1020) assert(d1[TestKeyTy(30)]!.value == 1030) assert(d1[TestKeyTy(40)] == nil) assert(d2.count == 4) assert(d2[TestKeyTy(10)]!.value == 1010) assert(d2[TestKeyTy(20)]!.value == 1020) assert(d2[TestKeyTy(30)]!.value == 1030) assert(d2[TestKeyTy(40)]!.value == 2040) // Keep variables alive. _fixLifetime(d1) _fixLifetime(d2) } do { var d1 = getCOWSlowDictionary() var identity1 = d1._rawIdentifier() var d2 = d1 assert(identity1 == d1._rawIdentifier()) assert(identity1 == d2._rawIdentifier()) // Overwrite a value in existing binding. d2.updateValue(TestValueTy(2010), forKey: TestKeyTy(10)) assert(identity1 == d1._rawIdentifier()) assert(identity1 != d2._rawIdentifier()) assert(d1.count == 3) assert(d1[TestKeyTy(10)]!.value == 1010) assert(d1[TestKeyTy(20)]!.value == 1020) assert(d1[TestKeyTy(30)]!.value == 1030) assert(d2.count == 3) assert(d2[TestKeyTy(10)]!.value == 2010) assert(d2[TestKeyTy(20)]!.value == 1020) assert(d2[TestKeyTy(30)]!.value == 1030) // Keep variables alive. _fixLifetime(d1) _fixLifetime(d2) } } DictionaryTestSuite.test("COW.Fast.MergeSequenceDoesNotReallocate") .xfail(.custom({ _isStdlibDebugConfiguration() }, reason: "rdar://33358110")) .code { do { var d1 = getCOWFastDictionary() var identity1 = d1._rawIdentifier() // Merge some new values. d1.merge([(40, 2040), (50, 2050)]) { _, y in y } assert(identity1 == d1._rawIdentifier()) assert(d1.count == 5) assert(d1[50]! == 2050) // Merge and overwrite some existing values. d1.merge([(10, 2010), (60, 2060)]) { _, y in y } assert(identity1 == d1._rawIdentifier()) assert(d1.count == 6) assert(d1[10]! == 2010) assert(d1[60]! == 2060) // Merge, keeping existing values. d1.merge([(30, 2030), (70, 2070)]) { x, _ in x } assert(identity1 == d1._rawIdentifier()) assert(d1.count == 7) assert(d1[30]! == 1030) assert(d1[70]! == 2070) let d2 = d1.merging([(40, 3040), (80, 3080)]) { _, y in y } assert(identity1 == d1._rawIdentifier()) assert(identity1 != d2._rawIdentifier()) assert(d2.count == 8) assert(d2[40]! == 3040) assert(d2[80]! == 3080) } do { var d1 = getCOWFastDictionary() var identity1 = d1._rawIdentifier() var d2 = d1 assert(identity1 == d1._rawIdentifier()) assert(identity1 == d2._rawIdentifier()) // Merge some new values. d2.merge([(40, 2040), (50, 2050)]) { _, y in y } assert(identity1 == d1._rawIdentifier()) assert(identity1 != d2._rawIdentifier()) assert(d1.count == 3) assert(d1[10]! == 1010) assert(d1[20]! == 1020) assert(d1[30]! == 1030) assert(d1[40] == nil) assert(d2.count == 5) assert(d2[10]! == 1010) assert(d2[20]! == 1020) assert(d2[30]! == 1030) assert(d2[40]! == 2040) assert(d2[50]! == 2050) // Keep variables alive. _fixLifetime(d1) _fixLifetime(d2) } do { var d1 = getCOWFastDictionary() var identity1 = d1._rawIdentifier() var d2 = d1 assert(identity1 == d1._rawIdentifier()) assert(identity1 == d2._rawIdentifier()) // Merge and overwrite some existing values. d2.merge([(10, 2010)]) { _, y in y } assert(identity1 == d1._rawIdentifier()) assert(identity1 != d2._rawIdentifier()) assert(d1.count == 3) assert(d1[10]! == 1010) assert(d1[20]! == 1020) assert(d1[30]! == 1030) assert(d2.count == 3) assert(d2[10]! == 2010) assert(d2[20]! == 1020) assert(d2[30]! == 1030) // Keep variables alive. _fixLifetime(d1) _fixLifetime(d2) } do { var d1 = getCOWFastDictionary() var identity1 = d1._rawIdentifier() var d2 = d1 assert(identity1 == d1._rawIdentifier()) assert(identity1 == d2._rawIdentifier()) // Merge, keeping existing values. d2.merge([(10, 2010)]) { x, _ in x } assert(identity1 == d1._rawIdentifier()) assert(identity1 != d2._rawIdentifier()) assert(d1.count == 3) assert(d1[10]! == 1010) assert(d1[20]! == 1020) assert(d1[30]! == 1030) assert(d2.count == 3) assert(d2[10]! == 1010) assert(d2[20]! == 1020) assert(d2[30]! == 1030) // Keep variables alive. _fixLifetime(d1) _fixLifetime(d2) } } DictionaryTestSuite.test("COW.Fast.MergeDictionaryDoesNotReallocate") .xfail(.custom({ _isStdlibDebugConfiguration() }, reason: "rdar://33358110")) .code { do { var d1 = getCOWFastDictionary() var identity1 = d1._rawIdentifier() // Merge some new values. d1.merge([40: 2040, 50: 2050]) { _, y in y } assert(identity1 == d1._rawIdentifier()) assert(d1.count == 5) assert(d1[50]! == 2050) // Merge and overwrite some existing values. d1.merge([10: 2010, 60: 2060]) { _, y in y } assert(identity1 == d1._rawIdentifier()) assert(d1.count == 6) assert(d1[10]! == 2010) assert(d1[60]! == 2060) // Merge, keeping existing values. d1.merge([30: 2030, 70: 2070]) { x, _ in x } assert(identity1 == d1._rawIdentifier()) assert(d1.count == 7) assert(d1[30]! == 1030) assert(d1[70]! == 2070) let d2 = d1.merging([40: 3040, 80: 3080]) { _, y in y } assert(identity1 == d1._rawIdentifier()) assert(identity1 != d2._rawIdentifier()) assert(d2.count == 8) assert(d2[40]! == 3040) assert(d2[80]! == 3080) } do { var d1 = getCOWFastDictionary() var identity1 = d1._rawIdentifier() var d2 = d1 assert(identity1 == d1._rawIdentifier()) assert(identity1 == d2._rawIdentifier()) // Merge some new values. d2.merge([40: 2040, 50: 2050]) { _, y in y } assert(identity1 == d1._rawIdentifier()) assert(identity1 != d2._rawIdentifier()) assert(d1.count == 3) assert(d1[10]! == 1010) assert(d1[20]! == 1020) assert(d1[30]! == 1030) assert(d1[40] == nil) assert(d2.count == 5) assert(d2[10]! == 1010) assert(d2[20]! == 1020) assert(d2[30]! == 1030) assert(d2[40]! == 2040) assert(d2[50]! == 2050) // Keep variables alive. _fixLifetime(d1) _fixLifetime(d2) } do { var d1 = getCOWFastDictionary() var identity1 = d1._rawIdentifier() var d2 = d1 assert(identity1 == d1._rawIdentifier()) assert(identity1 == d2._rawIdentifier()) // Merge and overwrite some existing values. d2.merge([10: 2010]) { _, y in y } assert(identity1 == d1._rawIdentifier()) assert(identity1 != d2._rawIdentifier()) assert(d1.count == 3) assert(d1[10]! == 1010) assert(d1[20]! == 1020) assert(d1[30]! == 1030) assert(d2.count == 3) assert(d2[10]! == 2010) assert(d2[20]! == 1020) assert(d2[30]! == 1030) // Keep variables alive. _fixLifetime(d1) _fixLifetime(d2) } do { var d1 = getCOWFastDictionary() var identity1 = d1._rawIdentifier() var d2 = d1 assert(identity1 == d1._rawIdentifier()) assert(identity1 == d2._rawIdentifier()) // Merge, keeping existing values. d2.merge([10: 2010]) { x, _ in x } assert(identity1 == d1._rawIdentifier()) assert(identity1 != d2._rawIdentifier()) assert(d1.count == 3) assert(d1[10]! == 1010) assert(d1[20]! == 1020) assert(d1[30]! == 1030) assert(d2.count == 3) assert(d2[10]! == 1010) assert(d2[20]! == 1020) assert(d2[30]! == 1030) // Keep variables alive. _fixLifetime(d1) _fixLifetime(d2) } } DictionaryTestSuite.test("COW.Fast.DefaultedSubscriptDoesNotReallocate") { do { var d1 = getCOWFastDictionary() var identity1 = d1._rawIdentifier() // No mutation on access. assert(d1[10, default: 0] + 1 == 1011) assert(d1[40, default: 0] + 1 == 1) assert(identity1 == d1._rawIdentifier()) assert(d1[10]! == 1010) // Increment existing in place. d1[10, default: 0] += 1 assert(identity1 == d1._rawIdentifier()) assert(d1[10]! == 1011) // Add incremented default value. d1[40, default: 0] += 1 assert(identity1 == d1._rawIdentifier()) assert(d1[40]! == 1) } do { var d1 = getCOWFastDictionary() var identity1 = d1._rawIdentifier() var d2 = d1 assert(identity1 == d1._rawIdentifier()) assert(identity1 == d2._rawIdentifier()) // No mutation on access. assert(d2[10, default: 0] + 1 == 1011) assert(d2[40, default: 0] + 1 == 1) assert(identity1 == d1._rawIdentifier()) assert(identity1 == d2._rawIdentifier()) // Increment existing in place. d2[10, default: 0] += 1 assert(identity1 == d1._rawIdentifier()) assert(identity1 != d2._rawIdentifier()) assert(d1[10]! == 1010) assert(d2[10]! == 1011) // Keep variables alive. _fixLifetime(d1) _fixLifetime(d2) } do { var d1 = getCOWFastDictionary() var identity1 = d1._rawIdentifier() var d2 = d1 assert(identity1 == d1._rawIdentifier()) assert(identity1 == d2._rawIdentifier()) // Add incremented default value. d2[40, default: 0] += 1 assert(identity1 == d1._rawIdentifier()) assert(identity1 != d2._rawIdentifier()) assert(d1[40] == nil) assert(d2[40]! == 1) // Keep variables alive. _fixLifetime(d1) _fixLifetime(d2) } } DictionaryTestSuite.test("COW.Fast.IndexForKeyDoesNotReallocate") { var d = getCOWFastDictionary() var identity1 = d._rawIdentifier() // Find an existing key. do { var foundIndex1 = d.index(forKey: 10)! assert(identity1 == d._rawIdentifier()) var foundIndex2 = d.index(forKey: 10)! assert(foundIndex1 == foundIndex2) assert(d[foundIndex1].0 == 10) assert(d[foundIndex1].1 == 1010) assert(identity1 == d._rawIdentifier()) } // Try to find a key that is not present. do { var foundIndex1 = d.index(forKey: 1111) assert(foundIndex1 == nil) assert(identity1 == d._rawIdentifier()) } do { var d2: [MinimalHashableValue : OpaqueValue<Int>] = [:] MinimalHashableValue.timesEqualEqualWasCalled = 0 MinimalHashableValue.timesHashValueWasCalled = 0 expectNil(d2.index(forKey: MinimalHashableValue(42))) // If the dictionary is empty, we shouldn't be computing the hash value of // the provided key. expectEqual(0, MinimalHashableValue.timesEqualEqualWasCalled) expectEqual(0, MinimalHashableValue.timesHashValueWasCalled) } } DictionaryTestSuite.test("COW.Slow.IndexForKeyDoesNotReallocate") { var d = getCOWSlowDictionary() var identity1 = d._rawIdentifier() // Find an existing key. do { var foundIndex1 = d.index(forKey: TestKeyTy(10))! assert(identity1 == d._rawIdentifier()) var foundIndex2 = d.index(forKey: TestKeyTy(10))! assert(foundIndex1 == foundIndex2) assert(d[foundIndex1].0 == TestKeyTy(10)) assert(d[foundIndex1].1.value == 1010) assert(identity1 == d._rawIdentifier()) } // Try to find a key that is not present. do { var foundIndex1 = d.index(forKey: TestKeyTy(1111)) assert(foundIndex1 == nil) assert(identity1 == d._rawIdentifier()) } do { var d2: [MinimalHashableClass : OpaqueValue<Int>] = [:] MinimalHashableClass.timesEqualEqualWasCalled = 0 MinimalHashableClass.timesHashValueWasCalled = 0 expectNil(d2.index(forKey: MinimalHashableClass(42))) // If the dictionary is empty, we shouldn't be computing the hash value of // the provided key. expectEqual(0, MinimalHashableClass.timesEqualEqualWasCalled) expectEqual(0, MinimalHashableClass.timesHashValueWasCalled) } } DictionaryTestSuite.test("COW.Fast.RemoveAtDoesNotReallocate") .xfail(.custom({ _isStdlibDebugConfiguration() }, reason: "rdar://33358110")) .code { do { var d = getCOWFastDictionary() var identity1 = d._rawIdentifier() let foundIndex1 = d.index(forKey: 10)! assert(identity1 == d._rawIdentifier()) assert(d[foundIndex1].0 == 10) assert(d[foundIndex1].1 == 1010) let removed = d.remove(at: foundIndex1) assert(removed.0 == 10) assert(removed.1 == 1010) assert(identity1 == d._rawIdentifier()) assert(d.index(forKey: 10) == nil) } do { var d1 = getCOWFastDictionary() var identity1 = d1._rawIdentifier() var d2 = d1 assert(identity1 == d1._rawIdentifier()) assert(identity1 == d2._rawIdentifier()) var foundIndex1 = d2.index(forKey: 10)! assert(d2[foundIndex1].0 == 10) assert(d2[foundIndex1].1 == 1010) assert(identity1 == d1._rawIdentifier()) assert(identity1 == d2._rawIdentifier()) let removed = d2.remove(at: foundIndex1) assert(removed.0 == 10) assert(removed.1 == 1010) assert(identity1 == d1._rawIdentifier()) assert(identity1 != d2._rawIdentifier()) assert(d2.index(forKey: 10) == nil) } } DictionaryTestSuite.test("COW.Slow.RemoveAtDoesNotReallocate") .xfail(.custom({ _isStdlibDebugConfiguration() }, reason: "rdar://33358110")) .code { do { var d = getCOWSlowDictionary() var identity1 = d._rawIdentifier() var foundIndex1 = d.index(forKey: TestKeyTy(10))! assert(identity1 == d._rawIdentifier()) assert(d[foundIndex1].0 == TestKeyTy(10)) assert(d[foundIndex1].1.value == 1010) let removed = d.remove(at: foundIndex1) assert(removed.0 == TestKeyTy(10)) assert(removed.1.value == 1010) assert(identity1 == d._rawIdentifier()) assert(d.index(forKey: TestKeyTy(10)) == nil) } do { var d1 = getCOWSlowDictionary() var identity1 = d1._rawIdentifier() var d2 = d1 assert(identity1 == d1._rawIdentifier()) assert(identity1 == d2._rawIdentifier()) var foundIndex1 = d2.index(forKey: TestKeyTy(10))! assert(d2[foundIndex1].0 == TestKeyTy(10)) assert(d2[foundIndex1].1.value == 1010) let removed = d2.remove(at: foundIndex1) assert(removed.0 == TestKeyTy(10)) assert(removed.1.value == 1010) assert(identity1 == d1._rawIdentifier()) assert(identity1 != d2._rawIdentifier()) assert(d2.index(forKey: TestKeyTy(10)) == nil) } } DictionaryTestSuite.test("COW.Fast.RemoveValueForKeyDoesNotReallocate") .xfail(.custom({ _isStdlibDebugConfiguration() }, reason: "rdar://33358110")) .code { do { var d1 = getCOWFastDictionary() var identity1 = d1._rawIdentifier() var deleted = d1.removeValue(forKey: 0) assert(deleted == nil) assert(identity1 == d1._rawIdentifier()) deleted = d1.removeValue(forKey: 10) assert(deleted! == 1010) assert(identity1 == d1._rawIdentifier()) // Keep variables alive. _fixLifetime(d1) } do { var d1 = getCOWFastDictionary() var identity1 = d1._rawIdentifier() var d2 = d1 var deleted = d2.removeValue(forKey: 0) assert(deleted == nil) assert(identity1 == d1._rawIdentifier()) assert(identity1 == d2._rawIdentifier()) deleted = d2.removeValue(forKey: 10) assert(deleted! == 1010) assert(identity1 == d1._rawIdentifier()) assert(identity1 != d2._rawIdentifier()) // Keep variables alive. _fixLifetime(d1) _fixLifetime(d2) } } DictionaryTestSuite.test("COW.Slow.RemoveValueForKeyDoesNotReallocate") .xfail(.custom({ _isStdlibDebugConfiguration() }, reason: "rdar://33358110")) .code { do { var d1 = getCOWSlowDictionary() var identity1 = d1._rawIdentifier() var deleted = d1.removeValue(forKey: TestKeyTy(0)) assert(deleted == nil) assert(identity1 == d1._rawIdentifier()) deleted = d1.removeValue(forKey: TestKeyTy(10)) assert(deleted!.value == 1010) assert(identity1 == d1._rawIdentifier()) // Keep variables alive. _fixLifetime(d1) } do { var d1 = getCOWSlowDictionary() var identity1 = d1._rawIdentifier() var d2 = d1 var deleted = d2.removeValue(forKey: TestKeyTy(0)) assert(deleted == nil) assert(identity1 == d1._rawIdentifier()) assert(identity1 == d2._rawIdentifier()) deleted = d2.removeValue(forKey: TestKeyTy(10)) assert(deleted!.value == 1010) assert(identity1 == d1._rawIdentifier()) assert(identity1 != d2._rawIdentifier()) // Keep variables alive. _fixLifetime(d1) _fixLifetime(d2) } } DictionaryTestSuite.test("COW.Fast.RemoveAllDoesNotReallocate") { do { var d = getCOWFastDictionary() let originalCapacity = d._variantBuffer.asNative.capacity assert(d.count == 3) assert(d[10]! == 1010) d.removeAll() // We cannot assert that identity changed, since the new buffer of smaller // size can be allocated at the same address as the old one. var identity1 = d._rawIdentifier() assert(d._variantBuffer.asNative.capacity < originalCapacity) assert(d.count == 0) assert(d[10] == nil) d.removeAll() assert(identity1 == d._rawIdentifier()) assert(d.count == 0) assert(d[10] == nil) } do { var d = getCOWFastDictionary() var identity1 = d._rawIdentifier() let originalCapacity = d._variantBuffer.asNative.capacity assert(d.count == 3) assert(d[10]! == 1010) d.removeAll(keepingCapacity: true) assert(identity1 == d._rawIdentifier()) assert(d._variantBuffer.asNative.capacity == originalCapacity) assert(d.count == 0) assert(d[10] == nil) d.removeAll(keepingCapacity: true) assert(identity1 == d._rawIdentifier()) assert(d._variantBuffer.asNative.capacity == originalCapacity) assert(d.count == 0) assert(d[10] == nil) } do { var d1 = getCOWFastDictionary() var identity1 = d1._rawIdentifier() assert(d1.count == 3) assert(d1[10]! == 1010) var d2 = d1 d2.removeAll() var identity2 = d2._rawIdentifier() assert(identity1 == d1._rawIdentifier()) assert(identity2 != identity1) assert(d1.count == 3) assert(d1[10]! == 1010) assert(d2.count == 0) assert(d2[10] == nil) // Keep variables alive. _fixLifetime(d1) _fixLifetime(d2) } do { var d1 = getCOWFastDictionary() var identity1 = d1._rawIdentifier() let originalCapacity = d1._variantBuffer.asNative.capacity assert(d1.count == 3) assert(d1[10] == 1010) var d2 = d1 d2.removeAll(keepingCapacity: true) var identity2 = d2._rawIdentifier() assert(identity1 == d1._rawIdentifier()) assert(identity2 != identity1) assert(d1.count == 3) assert(d1[10]! == 1010) assert(d2._variantBuffer.asNative.capacity == originalCapacity) assert(d2.count == 0) assert(d2[10] == nil) // Keep variables alive. _fixLifetime(d1) _fixLifetime(d2) } } DictionaryTestSuite.test("COW.Slow.RemoveAllDoesNotReallocate") { do { var d = getCOWSlowDictionary() let originalCapacity = d._variantBuffer.asNative.capacity assert(d.count == 3) assert(d[TestKeyTy(10)]!.value == 1010) d.removeAll() // We cannot assert that identity changed, since the new buffer of smaller // size can be allocated at the same address as the old one. var identity1 = d._rawIdentifier() assert(d._variantBuffer.asNative.capacity < originalCapacity) assert(d.count == 0) assert(d[TestKeyTy(10)] == nil) d.removeAll() assert(identity1 == d._rawIdentifier()) assert(d.count == 0) assert(d[TestKeyTy(10)] == nil) } do { var d = getCOWSlowDictionary() var identity1 = d._rawIdentifier() let originalCapacity = d._variantBuffer.asNative.capacity assert(d.count == 3) assert(d[TestKeyTy(10)]!.value == 1010) d.removeAll(keepingCapacity: true) assert(identity1 == d._rawIdentifier()) assert(d._variantBuffer.asNative.capacity == originalCapacity) assert(d.count == 0) assert(d[TestKeyTy(10)] == nil) d.removeAll(keepingCapacity: true) assert(identity1 == d._rawIdentifier()) assert(d._variantBuffer.asNative.capacity == originalCapacity) assert(d.count == 0) assert(d[TestKeyTy(10)] == nil) } do { var d1 = getCOWSlowDictionary() var identity1 = d1._rawIdentifier() assert(d1.count == 3) assert(d1[TestKeyTy(10)]!.value == 1010) var d2 = d1 d2.removeAll() var identity2 = d2._rawIdentifier() assert(identity1 == d1._rawIdentifier()) assert(identity2 != identity1) assert(d1.count == 3) assert(d1[TestKeyTy(10)]!.value == 1010) assert(d2.count == 0) assert(d2[TestKeyTy(10)] == nil) // Keep variables alive. _fixLifetime(d1) _fixLifetime(d2) } do { var d1 = getCOWSlowDictionary() var identity1 = d1._rawIdentifier() let originalCapacity = d1._variantBuffer.asNative.capacity assert(d1.count == 3) assert(d1[TestKeyTy(10)]!.value == 1010) var d2 = d1 d2.removeAll(keepingCapacity: true) var identity2 = d2._rawIdentifier() assert(identity1 == d1._rawIdentifier()) assert(identity2 != identity1) assert(d1.count == 3) assert(d1[TestKeyTy(10)]!.value == 1010) assert(d2._variantBuffer.asNative.capacity == originalCapacity) assert(d2.count == 0) assert(d2[TestKeyTy(10)] == nil) // Keep variables alive. _fixLifetime(d1) _fixLifetime(d2) } } DictionaryTestSuite.test("COW.Fast.CountDoesNotReallocate") { var d = getCOWFastDictionary() var identity1 = d._rawIdentifier() assert(d.count == 3) assert(identity1 == d._rawIdentifier()) } DictionaryTestSuite.test("COW.Slow.CountDoesNotReallocate") { var d = getCOWSlowDictionary() var identity1 = d._rawIdentifier() assert(d.count == 3) assert(identity1 == d._rawIdentifier()) } DictionaryTestSuite.test("COW.Fast.GenerateDoesNotReallocate") { var d = getCOWFastDictionary() var identity1 = d._rawIdentifier() var iter = d.makeIterator() var pairs = Array<(Int, Int)>() while let (key, value) = iter.next() { pairs += [(key, value)] } assert(equalsUnordered(pairs, [ (10, 1010), (20, 1020), (30, 1030) ])) assert(identity1 == d._rawIdentifier()) } DictionaryTestSuite.test("COW.Slow.GenerateDoesNotReallocate") { var d = getCOWSlowDictionary() var identity1 = d._rawIdentifier() var iter = d.makeIterator() var pairs = Array<(Int, Int)>() while let (key, value) = iter.next() { pairs += [(key.value, value.value)] } assert(equalsUnordered(pairs, [ (10, 1010), (20, 1020), (30, 1030) ])) assert(identity1 == d._rawIdentifier()) } DictionaryTestSuite.test("COW.Fast.EqualityTestDoesNotReallocate") { var d1 = getCOWFastDictionary() var identity1 = d1._rawIdentifier() var d2 = getCOWFastDictionary() var identity2 = d2._rawIdentifier() assert(d1 == d2) assert(identity1 == d1._rawIdentifier()) assert(identity2 == d2._rawIdentifier()) d2[40] = 2040 assert(d1 != d2) assert(identity1 == d1._rawIdentifier()) assert(identity2 == d2._rawIdentifier()) } DictionaryTestSuite.test("COW.Slow.EqualityTestDoesNotReallocate") { var d1 = getCOWSlowEquatableDictionary() var identity1 = d1._rawIdentifier() var d2 = getCOWSlowEquatableDictionary() var identity2 = d2._rawIdentifier() assert(d1 == d2) assert(identity1 == d1._rawIdentifier()) assert(identity2 == d2._rawIdentifier()) d2[TestKeyTy(40)] = TestEquatableValueTy(2040) assert(d1 != d2) assert(identity1 == d1._rawIdentifier()) assert(identity2 == d2._rawIdentifier()) } //===--- // Keys and Values collection tests. //===--- DictionaryTestSuite.test("COW.Fast.ValuesAccessDoesNotReallocate") { var d1 = getCOWFastDictionary() var identity1 = d1._rawIdentifier() assert([1010, 1020, 1030] == d1.values.sorted()) assert(identity1 == d1._rawIdentifier()) var d2 = d1 assert(identity1 == d2._rawIdentifier()) let i = d2.index(forKey: 10)! assert(d1.values[i] == 1010) assert(d1[i] == (10, 1010)) #if swift(>=4.0) d2.values[i] += 1 assert(d2.values[i] == 1011) assert(d2[10]! == 1011) assert(identity1 != d2._rawIdentifier()) #endif assert(d1[10]! == 1010) assert(identity1 == d1._rawIdentifier()) checkCollection( Array(d1.values), d1.values, stackTrace: SourceLocStack()) { $0 == $1 } } DictionaryTestSuite.test("COW.Fast.KeysAccessDoesNotReallocate") { var d1 = getCOWFastDictionary() var identity1 = d1._rawIdentifier() assert([10, 20, 30] == d1.keys.sorted()) let i = d1.index(forKey: 10)! assert(d1.keys[i] == 10) assert(d1[i] == (10, 1010)) assert(identity1 == d1._rawIdentifier()) checkCollection( Array(d1.keys), d1.keys, stackTrace: SourceLocStack()) { $0 == $1 } do { var d2: [MinimalHashableValue : Int] = [ MinimalHashableValue(10): 1010, MinimalHashableValue(20): 1020, MinimalHashableValue(30): 1030, MinimalHashableValue(40): 1040, MinimalHashableValue(50): 1050, MinimalHashableValue(60): 1060, MinimalHashableValue(70): 1070, MinimalHashableValue(80): 1080, MinimalHashableValue(90): 1090, ] // Find the last key in the dictionary var lastKey: MinimalHashableValue = d2.first!.key for i in d2.indices { lastKey = d2[i].key } // index(where:) - linear search MinimalHashableValue.timesEqualEqualWasCalled = 0 let j = d2.index(where: { (k, _) in k == lastKey })! expectGE(MinimalHashableValue.timesEqualEqualWasCalled, 8) // index(forKey:) - O(1) bucket + linear search MinimalHashableValue.timesEqualEqualWasCalled = 0 let k = d2.index(forKey: lastKey)! expectLE(MinimalHashableValue.timesEqualEqualWasCalled, 4) // keys.index(of:) - O(1) bucket + linear search MinimalHashableValue.timesEqualEqualWasCalled = 0 let l = d2.keys.index(of: lastKey)! #if swift(>=4.0) expectLE(MinimalHashableValue.timesEqualEqualWasCalled, 4) #endif expectEqual(j, k) expectEqual(k, l) } } //===--- // Native dictionary tests. //===--- func helperDeleteThree(_ k1: TestKeyTy, _ k2: TestKeyTy, _ k3: TestKeyTy) { var d1 = Dictionary<TestKeyTy, TestValueTy>(minimumCapacity: 10) d1[k1] = TestValueTy(1010) d1[k2] = TestValueTy(1020) d1[k3] = TestValueTy(1030) assert(d1[k1]!.value == 1010) assert(d1[k2]!.value == 1020) assert(d1[k3]!.value == 1030) d1[k1] = nil assert(d1[k2]!.value == 1020) assert(d1[k3]!.value == 1030) d1[k2] = nil assert(d1[k3]!.value == 1030) d1[k3] = nil assert(d1.count == 0) } DictionaryTestSuite.test("deleteChainCollision") { var k1 = TestKeyTy(value: 10, hashValue: 0) var k2 = TestKeyTy(value: 20, hashValue: 0) var k3 = TestKeyTy(value: 30, hashValue: 0) helperDeleteThree(k1, k2, k3) } DictionaryTestSuite.test("deleteChainNoCollision") { var k1 = TestKeyTy(value: 10, hashValue: 0) var k2 = TestKeyTy(value: 20, hashValue: 1) var k3 = TestKeyTy(value: 30, hashValue: 2) helperDeleteThree(k1, k2, k3) } DictionaryTestSuite.test("deleteChainCollision2") { var k1_0 = TestKeyTy(value: 10, hashValue: 0) var k2_0 = TestKeyTy(value: 20, hashValue: 0) var k3_2 = TestKeyTy(value: 30, hashValue: 2) var k4_0 = TestKeyTy(value: 40, hashValue: 0) var k5_2 = TestKeyTy(value: 50, hashValue: 2) var k6_0 = TestKeyTy(value: 60, hashValue: 0) var d = Dictionary<TestKeyTy, TestValueTy>(minimumCapacity: 10) d[k1_0] = TestValueTy(1010) // in bucket 0 d[k2_0] = TestValueTy(1020) // in bucket 1 d[k3_2] = TestValueTy(1030) // in bucket 2 d[k4_0] = TestValueTy(1040) // in bucket 3 d[k5_2] = TestValueTy(1050) // in bucket 4 d[k6_0] = TestValueTy(1060) // in bucket 5 d[k3_2] = nil assert(d[k1_0]!.value == 1010) assert(d[k2_0]!.value == 1020) assert(d[k3_2] == nil) assert(d[k4_0]!.value == 1040) assert(d[k5_2]!.value == 1050) assert(d[k6_0]!.value == 1060) } func uniformRandom(_ max: Int) -> Int { #if os(Linux) // SR-685: Can't use arc4random on Linux return Int(random() % (max + 1)) #else return Int(arc4random_uniform(UInt32(max))) #endif } func pickRandom<T>(_ a: [T]) -> T { return a[uniformRandom(a.count)] } func product<C1 : Collection, C2 : Collection>( _ c1: C1, _ c2: C2 ) -> [(C1.Iterator.Element, C2.Iterator.Element)] { var result: [(C1.Iterator.Element, C2.Iterator.Element)] = [] for e1 in c1 { for e2 in c2 { result.append((e1, e2)) } } return result } DictionaryTestSuite.test("deleteChainCollisionRandomized") .forEach(in: product(1...8, 0...5)) { (collisionChains, chainOverlap) in func check(_ d: Dictionary<TestKeyTy, TestValueTy>) { var keys = Array(d.keys) for i in 0..<keys.count { for j in 0..<i { assert(keys[i] != keys[j]) } } for k in keys { assert(d[k] != nil) } } let chainLength = 7 var knownKeys: [TestKeyTy] = [] func getKey(_ value: Int) -> TestKeyTy { for k in knownKeys { if k.value == value { return k } } let hashValue = uniformRandom(chainLength - chainOverlap) * collisionChains let k = TestKeyTy(value: value, hashValue: hashValue) knownKeys += [k] return k } var d = Dictionary<TestKeyTy, TestValueTy>(minimumCapacity: 30) for i in 1..<300 { let key = getKey(uniformRandom(collisionChains * chainLength)) if uniformRandom(chainLength * 2) == 0 { d[key] = nil } else { d[key] = TestValueTy(key.value * 10) } check(d) } } DictionaryTestSuite.test("init(dictionaryLiteral:)") { do { var empty = Dictionary<Int, Int>() assert(empty.count == 0) assert(empty[1111] == nil) } do { var d = Dictionary(dictionaryLiteral: (10, 1010)) assert(d.count == 1) assert(d[10]! == 1010) assert(d[1111] == nil) } do { var d = Dictionary(dictionaryLiteral: (10, 1010), (20, 1020)) assert(d.count == 2) assert(d[10]! == 1010) assert(d[20]! == 1020) assert(d[1111] == nil) } do { var d = Dictionary(dictionaryLiteral: (10, 1010), (20, 1020), (30, 1030)) assert(d.count == 3) assert(d[10]! == 1010) assert(d[20]! == 1020) assert(d[30]! == 1030) assert(d[1111] == nil) } do { var d = Dictionary(dictionaryLiteral: (10, 1010), (20, 1020), (30, 1030), (40, 1040)) assert(d.count == 4) assert(d[10]! == 1010) assert(d[20]! == 1020) assert(d[30]! == 1030) assert(d[40]! == 1040) assert(d[1111] == nil) } do { var d: Dictionary<Int, Int> = [ 10: 1010, 20: 1020, 30: 1030 ] assert(d.count == 3) assert(d[10]! == 1010) assert(d[20]! == 1020) assert(d[30]! == 1030) } } DictionaryTestSuite.test("init(uniqueKeysWithValues:)") { do { var d = Dictionary(uniqueKeysWithValues: [(10, 1010), (20, 1020), (30, 1030)]) expectEqual(d.count, 3) expectEqual(d[10]!, 1010) expectEqual(d[20]!, 1020) expectEqual(d[30]!, 1030) expectNil(d[1111]) } do { var d = Dictionary<Int, Int>(uniqueKeysWithValues: EmptyCollection<(Int, Int)>()) expectEqual(d.count, 0) expectNil(d[1111]) } do { expectCrashLater() var d = Dictionary(uniqueKeysWithValues: [(10, 1010), (20, 1020), (10, 2010)]) } } DictionaryTestSuite.test("init(_:uniquingKeysWith:)") { do { var d = Dictionary( [(10, 1010), (20, 1020), (30, 1030), (10, 2010)], uniquingKeysWith: min) expectEqual(d.count, 3) expectEqual(d[10]!, 1010) expectEqual(d[20]!, 1020) expectEqual(d[30]!, 1030) expectNil(d[1111]) } do { var d = Dictionary( [(10, 1010), (20, 1020), (30, 1030), (10, 2010)] as [(Int, Int)], uniquingKeysWith: +) expectEqual(d.count, 3) expectEqual(d[10]!, 3020) expectEqual(d[20]!, 1020) expectEqual(d[30]!, 1030) expectNil(d[1111]) } do { var d = Dictionary([(10, 1010), (20, 1020), (30, 1030), (10, 2010)]) { (a, b) in Int("\(a)\(b)")! } expectEqual(d.count, 3) expectEqual(d[10]!, 10102010) expectEqual(d[20]!, 1020) expectEqual(d[30]!, 1030) expectNil(d[1111]) } do { var d = Dictionary([(10, 1010), (10, 2010), (10, 3010), (10, 4010)]) { $1 } expectEqual(d.count, 1) expectEqual(d[10]!, 4010) expectNil(d[1111]) } do { var d = Dictionary(EmptyCollection<(Int, Int)>(), uniquingKeysWith: min) expectEqual(d.count, 0) expectNil(d[1111]) } struct TE: Error {} do { // No duplicate keys, so no error thrown. var d1 = try Dictionary([(10, 1), (20, 2), (30, 3)]) { _ in throw TE() } expectEqual(d1.count, 3) // Duplicate keys, should throw error. var d2 = try Dictionary([(10, 1), (10, 2)]) { _ in throw TE() } assertionFailure() } catch { assert(error is TE) } } DictionaryTestSuite.test("init(grouping:by:)") { let r = 0..<10 let d1 = Dictionary(grouping: r, by: { $0 % 3 }) expectEqual(3, d1.count) expectEqual([0, 3, 6, 9], d1[0]!) expectEqual([1, 4, 7], d1[1]!) expectEqual([2, 5, 8], d1[2]!) let d2 = Dictionary(grouping: r, by: { $0 }) expectEqual(10, d2.count) let d3 = Dictionary(grouping: 0..<0, by: { $0 }) expectEqual(0, d3.count) } DictionaryTestSuite.test("mapValues(_:)") { let d1 = [10: 1010, 20: 1020, 30: 1030] let d2 = d1.mapValues(String.init) expectEqual(d1.count, d2.count) expectEqual(d1.keys.first, d2.keys.first) for (key, value) in d1 { expectEqual(String(d1[key]!), d2[key]!) } do { var d3: [MinimalHashableValue : Int] = Dictionary( uniqueKeysWithValues: d1.lazy.map { (MinimalHashableValue($0), $1) }) expectEqual(d3.count, 3) MinimalHashableValue.timesEqualEqualWasCalled = 0 MinimalHashableValue.timesHashValueWasCalled = 0 // Calling mapValues shouldn't ever recalculate any hashes. let d4 = d3.mapValues(String.init) expectEqual(d4.count, d3.count) expectEqual(0, MinimalHashableValue.timesEqualEqualWasCalled) expectEqual(0, MinimalHashableValue.timesHashValueWasCalled) } } DictionaryTestSuite.test("capacity/reserveCapacity(_:)") { var d1 = [10: 1010, 20: 1020, 30: 1030] expectEqual(3, d1.capacity) d1[40] = 1040 expectEqual(6, d1.capacity) // Reserving new capacity jumps up to next limit. d1.reserveCapacity(7) expectEqual(12, d1.capacity) // Can reserve right up to a limit. d1.reserveCapacity(24) expectEqual(24, d1.capacity) // Fill up to the limit, no reallocation. d1.merge(stride(from: 50, through: 240, by: 10).lazy.map { ($0, 1000 + $0) }, uniquingKeysWith: { _ in fatalError() }) expectEqual(24, d1.count) expectEqual(24, d1.capacity) d1[250] = 1250 expectEqual(48, d1.capacity) } #if _runtime(_ObjC) //===--- // NSDictionary -> Dictionary bridging tests. //===--- func getAsNSDictionary(_ d: Dictionary<Int, Int>) -> NSDictionary { let keys = Array(d.keys.map { TestObjCKeyTy($0) }) let values = Array(d.values.map { TestObjCValueTy($0) }) // Return an `NSMutableDictionary` to make sure that it has a unique // pointer identity. return NSMutableDictionary(objects: values, forKeys: keys) } func getAsEquatableNSDictionary(_ d: Dictionary<Int, Int>) -> NSDictionary { let keys = Array(d.keys.map { TestObjCKeyTy($0) }) let values = Array(d.values.map { TestObjCEquatableValueTy($0) }) // Return an `NSMutableDictionary` to make sure that it has a unique // pointer identity. return NSMutableDictionary(objects: values, forKeys: keys) } func getAsNSMutableDictionary(_ d: Dictionary<Int, Int>) -> NSMutableDictionary { let keys = Array(d.keys.map { TestObjCKeyTy($0) }) let values = Array(d.values.map { TestObjCValueTy($0) }) return NSMutableDictionary(objects: values, forKeys: keys) } func getBridgedVerbatimDictionary() -> Dictionary<NSObject, AnyObject> { let nsd = getAsNSDictionary([10: 1010, 20: 1020, 30: 1030]) return convertNSDictionaryToDictionary(nsd) } func getBridgedVerbatimDictionary(_ d: Dictionary<Int, Int>) -> Dictionary<NSObject, AnyObject> { let nsd = getAsNSDictionary(d) return convertNSDictionaryToDictionary(nsd) } func getBridgedVerbatimDictionaryAndNSMutableDictionary() -> (Dictionary<NSObject, AnyObject>, NSMutableDictionary) { let nsd = getAsNSMutableDictionary([10: 1010, 20: 1020, 30: 1030]) return (convertNSDictionaryToDictionary(nsd), nsd) } func getBridgedNonverbatimDictionary() -> Dictionary<TestBridgedKeyTy, TestBridgedValueTy> { let nsd = getAsNSDictionary([10: 1010, 20: 1020, 30: 1030 ]) return Swift._forceBridgeFromObjectiveC(nsd, Dictionary.self) } func getBridgedNonverbatimDictionary(_ d: Dictionary<Int, Int>) -> Dictionary<TestBridgedKeyTy, TestBridgedValueTy> { let nsd = getAsNSDictionary(d) return Swift._forceBridgeFromObjectiveC(nsd, Dictionary.self) } func getBridgedNonverbatimDictionaryAndNSMutableDictionary() -> (Dictionary<TestBridgedKeyTy, TestBridgedValueTy>, NSMutableDictionary) { let nsd = getAsNSMutableDictionary([10: 1010, 20: 1020, 30: 1030]) return (Swift._forceBridgeFromObjectiveC(nsd, Dictionary.self), nsd) } func getBridgedVerbatimEquatableDictionary(_ d: Dictionary<Int, Int>) -> Dictionary<NSObject, TestObjCEquatableValueTy> { let nsd = getAsEquatableNSDictionary(d) return convertNSDictionaryToDictionary(nsd) } func getBridgedNonverbatimEquatableDictionary(_ d: Dictionary<Int, Int>) -> Dictionary<TestBridgedKeyTy, TestBridgedEquatableValueTy> { let nsd = getAsEquatableNSDictionary(d) return Swift._forceBridgeFromObjectiveC(nsd, Dictionary.self) } func getHugeBridgedVerbatimDictionaryHelper() -> NSDictionary { let keys = (1...32).map { TestObjCKeyTy($0) } let values = (1...32).map { TestObjCValueTy(1000 + $0) } return NSMutableDictionary(objects: values, forKeys: keys) } func getHugeBridgedVerbatimDictionary() -> Dictionary<NSObject, AnyObject> { let nsd = getHugeBridgedVerbatimDictionaryHelper() return convertNSDictionaryToDictionary(nsd) } func getHugeBridgedNonverbatimDictionary() -> Dictionary<TestBridgedKeyTy, TestBridgedValueTy> { let nsd = getHugeBridgedVerbatimDictionaryHelper() return Swift._forceBridgeFromObjectiveC(nsd, Dictionary.self) } /// A mock dictionary that stores its keys and values in parallel arrays, which /// allows it to return inner pointers to the keys array in fast enumeration. @objc class ParallelArrayDictionary : NSDictionary { struct Keys { var key0: AnyObject = TestObjCKeyTy(10) var key1: AnyObject = TestObjCKeyTy(20) var key2: AnyObject = TestObjCKeyTy(30) var key3: AnyObject = TestObjCKeyTy(40) } var keys = [ Keys() ] var value: AnyObject = TestObjCValueTy(1111) override init() { super.init() } override init( objects: UnsafePointer<AnyObject>?, forKeys keys: UnsafePointer<NSCopying>?, count: Int) { super.init(objects: objects, forKeys: keys, count: count) } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) not implemented by ParallelArrayDictionary") } @objc(copyWithZone:) override func copy(with zone: NSZone?) -> Any { // Ensure that copying this dictionary does not produce a CoreFoundation // object. return self } override func countByEnumerating( with state: UnsafeMutablePointer<NSFastEnumerationState>, objects: AutoreleasingUnsafeMutablePointer<AnyObject?>, count: Int ) -> Int { var theState = state.pointee if theState.state == 0 { theState.state = 1 theState.itemsPtr = AutoreleasingUnsafeMutablePointer(keys._baseAddressIfContiguous) theState.mutationsPtr = _fastEnumerationStorageMutationsPtr state.pointee = theState return 4 } return 0 } override func object(forKey aKey: Any) -> Any? { return value } override var count: Int { return 4 } } func getParallelArrayBridgedVerbatimDictionary() -> Dictionary<NSObject, AnyObject> { let nsd: NSDictionary = ParallelArrayDictionary() return convertNSDictionaryToDictionary(nsd) } func getParallelArrayBridgedNonverbatimDictionary() -> Dictionary<TestBridgedKeyTy, TestBridgedValueTy> { let nsd: NSDictionary = ParallelArrayDictionary() return Swift._forceBridgeFromObjectiveC(nsd, Dictionary.self) } @objc class CustomImmutableNSDictionary : NSDictionary { init(_privateInit: ()) { super.init() } override init() { expectUnreachable() super.init() } override init( objects: UnsafePointer<AnyObject>?, forKeys keys: UnsafePointer<NSCopying>?, count: Int) { expectUnreachable() super.init(objects: objects, forKeys: keys, count: count) } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) not implemented by CustomImmutableNSDictionary") } @objc(copyWithZone:) override func copy(with zone: NSZone?) -> Any { CustomImmutableNSDictionary.timesCopyWithZoneWasCalled += 1 return self } override func object(forKey aKey: Any) -> Any? { CustomImmutableNSDictionary.timesObjectForKeyWasCalled += 1 return getAsNSDictionary([10: 1010, 20: 1020, 30: 1030]).object(forKey: aKey) } override func keyEnumerator() -> NSEnumerator { CustomImmutableNSDictionary.timesKeyEnumeratorWasCalled += 1 return getAsNSDictionary([10: 1010, 20: 1020, 30: 1030]).keyEnumerator() } override var count: Int { CustomImmutableNSDictionary.timesCountWasCalled += 1 return 3 } static var timesCopyWithZoneWasCalled = 0 static var timesObjectForKeyWasCalled = 0 static var timesKeyEnumeratorWasCalled = 0 static var timesCountWasCalled = 0 } DictionaryTestSuite.test("BridgedFromObjC.Verbatim.DictionaryIsCopied") { var (d, nsd) = getBridgedVerbatimDictionaryAndNSMutableDictionary() var identity1 = d._rawIdentifier() assert(isCocoaDictionary(d)) // Find an existing key. do { var kv = d[d.index(forKey: TestObjCKeyTy(10))!] assert(kv.0 == TestObjCKeyTy(10)) assert((kv.1 as! TestObjCValueTy).value == 1010) } // Delete the key from the NSMutableDictionary. assert(nsd[TestObjCKeyTy(10)] != nil) nsd.removeObject(forKey: TestObjCKeyTy(10)) assert(nsd[TestObjCKeyTy(10)] == nil) // Find an existing key, again. do { var kv = d[d.index(forKey: TestObjCKeyTy(10))!] assert(kv.0 == TestObjCKeyTy(10)) assert((kv.1 as! TestObjCValueTy).value == 1010) } } DictionaryTestSuite.test("BridgedFromObjC.Nonverbatim.DictionaryIsCopied") { var (d, nsd) = getBridgedNonverbatimDictionaryAndNSMutableDictionary() var identity1 = d._rawIdentifier() assert(isNativeDictionary(d)) // Find an existing key. do { var kv = d[d.index(forKey: TestBridgedKeyTy(10))!] assert(kv.0 == TestBridgedKeyTy(10)) assert(kv.1.value == 1010) } // Delete the key from the NSMutableDictionary. assert(nsd[TestBridgedKeyTy(10) as NSCopying] != nil) nsd.removeObject(forKey: TestBridgedKeyTy(10) as NSCopying) assert(nsd[TestBridgedKeyTy(10) as NSCopying] == nil) // Find an existing key, again. do { var kv = d[d.index(forKey: TestBridgedKeyTy(10))!] assert(kv.0 == TestBridgedKeyTy(10)) assert(kv.1.value == 1010) } } DictionaryTestSuite.test("BridgedFromObjC.Verbatim.NSDictionaryIsRetained") { var nsd: NSDictionary = autoreleasepool { NSDictionary(dictionary: getAsNSDictionary([10: 1010, 20: 1020, 30: 1030])) } var d: [NSObject : AnyObject] = convertNSDictionaryToDictionary(nsd) var bridgedBack: NSDictionary = convertDictionaryToNSDictionary(d) expectEqual( unsafeBitCast(nsd, to: Int.self), unsafeBitCast(bridgedBack, to: Int.self)) _fixLifetime(nsd) _fixLifetime(d) _fixLifetime(bridgedBack) } DictionaryTestSuite.test("BridgedFromObjC.Nonverbatim.NSDictionaryIsCopied") { var nsd: NSDictionary = autoreleasepool { NSDictionary(dictionary: getAsNSDictionary([10: 1010, 20: 1020, 30: 1030])) } var d: [TestBridgedKeyTy : TestBridgedValueTy] = convertNSDictionaryToDictionary(nsd) var bridgedBack: NSDictionary = convertDictionaryToNSDictionary(d) expectNotEqual( unsafeBitCast(nsd, to: Int.self), unsafeBitCast(bridgedBack, to: Int.self)) _fixLifetime(nsd) _fixLifetime(d) _fixLifetime(bridgedBack) } DictionaryTestSuite.test("BridgedFromObjC.Verbatim.ImmutableDictionaryIsRetained") { var nsd: NSDictionary = CustomImmutableNSDictionary(_privateInit: ()) CustomImmutableNSDictionary.timesCopyWithZoneWasCalled = 0 CustomImmutableNSDictionary.timesObjectForKeyWasCalled = 0 CustomImmutableNSDictionary.timesKeyEnumeratorWasCalled = 0 CustomImmutableNSDictionary.timesCountWasCalled = 0 var d: [NSObject : AnyObject] = convertNSDictionaryToDictionary(nsd) expectEqual(1, CustomImmutableNSDictionary.timesCopyWithZoneWasCalled) expectEqual(0, CustomImmutableNSDictionary.timesObjectForKeyWasCalled) expectEqual(0, CustomImmutableNSDictionary.timesKeyEnumeratorWasCalled) expectEqual(0, CustomImmutableNSDictionary.timesCountWasCalled) var bridgedBack: NSDictionary = convertDictionaryToNSDictionary(d) expectEqual( unsafeBitCast(nsd, to: Int.self), unsafeBitCast(bridgedBack, to: Int.self)) _fixLifetime(nsd) _fixLifetime(d) _fixLifetime(bridgedBack) } DictionaryTestSuite.test("BridgedFromObjC.Nonverbatim.ImmutableDictionaryIsCopied") { var nsd: NSDictionary = CustomImmutableNSDictionary(_privateInit: ()) CustomImmutableNSDictionary.timesCopyWithZoneWasCalled = 0 CustomImmutableNSDictionary.timesObjectForKeyWasCalled = 0 CustomImmutableNSDictionary.timesKeyEnumeratorWasCalled = 0 CustomImmutableNSDictionary.timesCountWasCalled = 0 TestBridgedValueTy.bridgeOperations = 0 var d: [TestBridgedKeyTy : TestBridgedValueTy] = convertNSDictionaryToDictionary(nsd) expectEqual(0, CustomImmutableNSDictionary.timesCopyWithZoneWasCalled) expectEqual(3, CustomImmutableNSDictionary.timesObjectForKeyWasCalled) expectEqual(1, CustomImmutableNSDictionary.timesKeyEnumeratorWasCalled) expectNotEqual(0, CustomImmutableNSDictionary.timesCountWasCalled) expectEqual(3, TestBridgedValueTy.bridgeOperations) var bridgedBack: NSDictionary = convertDictionaryToNSDictionary(d) expectNotEqual( unsafeBitCast(nsd, to: Int.self), unsafeBitCast(bridgedBack, to: Int.self)) _fixLifetime(nsd) _fixLifetime(d) _fixLifetime(bridgedBack) } DictionaryTestSuite.test("BridgedFromObjC.Verbatim.IndexForKey") { var d = getBridgedVerbatimDictionary() var identity1 = d._rawIdentifier() assert(isCocoaDictionary(d)) // Find an existing key. do { var kv = d[d.index(forKey: TestObjCKeyTy(10))!] assert(kv.0 == TestObjCKeyTy(10)) assert((kv.1 as! TestObjCValueTy).value == 1010) kv = d[d.index(forKey: TestObjCKeyTy(20))!] assert(kv.0 == TestObjCKeyTy(20)) assert((kv.1 as! TestObjCValueTy).value == 1020) kv = d[d.index(forKey: TestObjCKeyTy(30))!] assert(kv.0 == TestObjCKeyTy(30)) assert((kv.1 as! TestObjCValueTy).value == 1030) } // Try to find a key that does not exist. assert(d.index(forKey: TestObjCKeyTy(40)) == nil) assert(identity1 == d._rawIdentifier()) } DictionaryTestSuite.test("BridgedFromObjC.Nonverbatim.IndexForKey") { var d = getBridgedNonverbatimDictionary() var identity1 = d._rawIdentifier() assert(isNativeDictionary(d)) // Find an existing key. do { var kv = d[d.index(forKey: TestBridgedKeyTy(10))!] assert(kv.0 == TestBridgedKeyTy(10)) assert(kv.1.value == 1010) kv = d[d.index(forKey: TestBridgedKeyTy(20))!] assert(kv.0 == TestBridgedKeyTy(20)) assert(kv.1.value == 1020) kv = d[d.index(forKey: TestBridgedKeyTy(30))!] assert(kv.0 == TestBridgedKeyTy(30)) assert(kv.1.value == 1030) } // Try to find a key that does not exist. assert(d.index(forKey: TestBridgedKeyTy(40)) == nil) assert(identity1 == d._rawIdentifier()) } DictionaryTestSuite.test("BridgedFromObjC.Verbatim.SubscriptWithIndex") { var d = getBridgedVerbatimDictionary() var identity1 = d._rawIdentifier() assert(isCocoaDictionary(d)) var startIndex = d.startIndex var endIndex = d.endIndex assert(startIndex != endIndex) assert(startIndex < endIndex) assert(startIndex <= endIndex) assert(!(startIndex >= endIndex)) assert(!(startIndex > endIndex)) assert(identity1 == d._rawIdentifier()) var pairs = Array<(Int, Int)>() for i in d.indices { var (key, value) = d[i] let kv = ((key as! TestObjCKeyTy).value, (value as! TestObjCValueTy).value) pairs += [kv] } assert(equalsUnordered(pairs, [ (10, 1010), (20, 1020), (30, 1030) ])) assert(identity1 == d._rawIdentifier()) // Keep indexes alive during the calls above. _fixLifetime(startIndex) _fixLifetime(endIndex) } DictionaryTestSuite.test("BridgedFromObjC.Nonverbatim.SubscriptWithIndex") { var d = getBridgedNonverbatimDictionary() var identity1 = d._rawIdentifier() assert(isNativeDictionary(d)) var startIndex = d.startIndex var endIndex = d.endIndex assert(startIndex != endIndex) assert(startIndex < endIndex) assert(startIndex <= endIndex) assert(!(startIndex >= endIndex)) assert(!(startIndex > endIndex)) assert(identity1 == d._rawIdentifier()) var pairs = Array<(Int, Int)>() for i in d.indices { var (key, value) = d[i] let kv = (key.value, value.value) pairs += [kv] } assert(equalsUnordered(pairs, [ (10, 1010), (20, 1020), (30, 1030) ])) assert(identity1 == d._rawIdentifier()) // Keep indexes alive during the calls above. _fixLifetime(startIndex) _fixLifetime(endIndex) } DictionaryTestSuite.test("BridgedFromObjC.Verbatim.SubscriptWithIndex_Empty") { var d = getBridgedVerbatimDictionary([:]) var identity1 = d._rawIdentifier() assert(isCocoaDictionary(d)) var startIndex = d.startIndex var endIndex = d.endIndex assert(startIndex == endIndex) assert(!(startIndex < endIndex)) assert(startIndex <= endIndex) assert(startIndex >= endIndex) assert(!(startIndex > endIndex)) assert(identity1 == d._rawIdentifier()) // Keep indexes alive during the calls above. _fixLifetime(startIndex) _fixLifetime(endIndex) } DictionaryTestSuite.test("BridgedFromObjC.Nonverbatim.SubscriptWithIndex_Empty") { var d = getBridgedNonverbatimDictionary([:]) var identity1 = d._rawIdentifier() assert(isNativeDictionary(d)) var startIndex = d.startIndex var endIndex = d.endIndex assert(startIndex == endIndex) assert(!(startIndex < endIndex)) assert(startIndex <= endIndex) assert(startIndex >= endIndex) assert(!(startIndex > endIndex)) assert(identity1 == d._rawIdentifier()) // Keep indexes alive during the calls above. _fixLifetime(startIndex) _fixLifetime(endIndex) } DictionaryTestSuite.test("BridgedFromObjC.Verbatim.SubscriptWithKey") { var d = getBridgedVerbatimDictionary() var identity1 = d._rawIdentifier() assert(isCocoaDictionary(d)) // Read existing key-value pairs. var v = d[TestObjCKeyTy(10)] as! TestObjCValueTy assert(v.value == 1010) v = d[TestObjCKeyTy(20)] as! TestObjCValueTy assert(v.value == 1020) v = d[TestObjCKeyTy(30)] as! TestObjCValueTy assert(v.value == 1030) assert(identity1 == d._rawIdentifier()) // Insert a new key-value pair. d[TestObjCKeyTy(40)] = TestObjCValueTy(2040) var identity2 = d._rawIdentifier() assert(identity1 != identity2) assert(isNativeDictionary(d)) assert(d.count == 4) v = d[TestObjCKeyTy(10)] as! TestObjCValueTy assert(v.value == 1010) v = d[TestObjCKeyTy(20)] as! TestObjCValueTy assert(v.value == 1020) v = d[TestObjCKeyTy(30)] as! TestObjCValueTy assert(v.value == 1030) v = d[TestObjCKeyTy(40)] as! TestObjCValueTy assert(v.value == 2040) // Overwrite value in existing binding. d[TestObjCKeyTy(10)] = TestObjCValueTy(2010) assert(identity2 == d._rawIdentifier()) assert(isNativeDictionary(d)) assert(d.count == 4) v = d[TestObjCKeyTy(10)] as! TestObjCValueTy assert(v.value == 2010) v = d[TestObjCKeyTy(20)] as! TestObjCValueTy assert(v.value == 1020) v = d[TestObjCKeyTy(30)] as! TestObjCValueTy assert(v.value == 1030) v = d[TestObjCKeyTy(40)] as! TestObjCValueTy assert(v.value == 2040) } DictionaryTestSuite.test("BridgedFromObjC.Nonverbatim.SubscriptWithKey") { var d = getBridgedNonverbatimDictionary() var identity1 = d._rawIdentifier() assert(isNativeDictionary(d)) // Read existing key-value pairs. var v = d[TestBridgedKeyTy(10)] assert(v!.value == 1010) v = d[TestBridgedKeyTy(20)] assert(v!.value == 1020) v = d[TestBridgedKeyTy(30)] assert(v!.value == 1030) assert(identity1 == d._rawIdentifier()) // Insert a new key-value pair. d[TestBridgedKeyTy(40)] = TestBridgedValueTy(2040) var identity2 = d._rawIdentifier() assert(identity1 != identity2) assert(isNativeDictionary(d)) assert(d.count == 4) v = d[TestBridgedKeyTy(10)] assert(v!.value == 1010) v = d[TestBridgedKeyTy(20)] assert(v!.value == 1020) v = d[TestBridgedKeyTy(30)] assert(v!.value == 1030) v = d[TestBridgedKeyTy(40)] assert(v!.value == 2040) // Overwrite value in existing binding. d[TestBridgedKeyTy(10)] = TestBridgedValueTy(2010) assert(identity2 == d._rawIdentifier()) assert(isNativeDictionary(d)) assert(d.count == 4) v = d[TestBridgedKeyTy(10)] assert(v!.value == 2010) v = d[TestBridgedKeyTy(20)] assert(v!.value == 1020) v = d[TestBridgedKeyTy(30)] assert(v!.value == 1030) v = d[TestBridgedKeyTy(40)] assert(v!.value == 2040) } DictionaryTestSuite.test("BridgedFromObjC.Verbatim.UpdateValueForKey") { // Insert a new key-value pair. do { var d = getBridgedVerbatimDictionary() var identity1 = d._rawIdentifier() assert(isCocoaDictionary(d)) var oldValue: AnyObject? = d.updateValue(TestObjCValueTy(2040), forKey: TestObjCKeyTy(40)) assert(oldValue == nil) var identity2 = d._rawIdentifier() assert(identity1 != identity2) assert(isNativeDictionary(d)) assert(d.count == 4) assert((d[TestObjCKeyTy(10)] as! TestObjCValueTy).value == 1010) assert((d[TestObjCKeyTy(20)] as! TestObjCValueTy).value == 1020) assert((d[TestObjCKeyTy(30)] as! TestObjCValueTy).value == 1030) assert((d[TestObjCKeyTy(40)] as! TestObjCValueTy).value == 2040) } // Overwrite a value in existing binding. do { var d = getBridgedVerbatimDictionary() var identity1 = d._rawIdentifier() assert(isCocoaDictionary(d)) var oldValue: AnyObject? = d.updateValue(TestObjCValueTy(2010), forKey: TestObjCKeyTy(10)) assert((oldValue as! TestObjCValueTy).value == 1010) var identity2 = d._rawIdentifier() assert(identity1 != identity2) assert(isNativeDictionary(d)) assert(d.count == 3) assert((d[TestObjCKeyTy(10)] as! TestObjCValueTy).value == 2010) assert((d[TestObjCKeyTy(20)] as! TestObjCValueTy).value == 1020) assert((d[TestObjCKeyTy(30)] as! TestObjCValueTy).value == 1030) } } DictionaryTestSuite.test("BridgedFromObjC.Nonverbatim.UpdateValueForKey") { // Insert a new key-value pair. do { var d = getBridgedNonverbatimDictionary() var identity1 = d._rawIdentifier() assert(isNativeDictionary(d)) var oldValue = d.updateValue(TestBridgedValueTy(2040), forKey: TestBridgedKeyTy(40)) assert(oldValue == nil) var identity2 = d._rawIdentifier() assert(identity1 != identity2) assert(isNativeDictionary(d)) assert(d.count == 4) assert(d[TestBridgedKeyTy(10)]!.value == 1010) assert(d[TestBridgedKeyTy(20)]!.value == 1020) assert(d[TestBridgedKeyTy(30)]!.value == 1030) assert(d[TestBridgedKeyTy(40)]!.value == 2040) } // Overwrite a value in existing binding. do { var d = getBridgedNonverbatimDictionary() var identity1 = d._rawIdentifier() assert(isNativeDictionary(d)) var oldValue = d.updateValue(TestBridgedValueTy(2010), forKey: TestBridgedKeyTy(10))! assert(oldValue.value == 1010) var identity2 = d._rawIdentifier() assert(identity1 == identity2) assert(isNativeDictionary(d)) assert(d.count == 3) assert(d[TestBridgedKeyTy(10)]!.value == 2010) assert(d[TestBridgedKeyTy(20)]!.value == 1020) assert(d[TestBridgedKeyTy(30)]!.value == 1030) } } DictionaryTestSuite.test("BridgedFromObjC.Verbatim.RemoveAt") { var d = getBridgedVerbatimDictionary() var identity1 = d._rawIdentifier() assert(isCocoaDictionary(d)) let foundIndex1 = d.index(forKey: TestObjCKeyTy(10))! assert(d[foundIndex1].0 == TestObjCKeyTy(10)) assert((d[foundIndex1].1 as! TestObjCValueTy).value == 1010) assert(identity1 == d._rawIdentifier()) let removedElement = d.remove(at: foundIndex1) assert(identity1 != d._rawIdentifier()) assert(isNativeDictionary(d)) assert(removedElement.0 == TestObjCKeyTy(10)) assert((removedElement.1 as! TestObjCValueTy).value == 1010) assert(d.count == 2) assert(d.index(forKey: TestObjCKeyTy(10)) == nil) } DictionaryTestSuite.test("BridgedFromObjC.Nonverbatim.RemoveAt") .xfail(.custom({ _isStdlibDebugConfiguration() }, reason: "rdar://33358110")) .code { var d = getBridgedNonverbatimDictionary() var identity1 = d._rawIdentifier() assert(isNativeDictionary(d)) let foundIndex1 = d.index(forKey: TestBridgedKeyTy(10))! assert(d[foundIndex1].0 == TestBridgedKeyTy(10)) assert(d[foundIndex1].1.value == 1010) assert(identity1 == d._rawIdentifier()) let removedElement = d.remove(at: foundIndex1) assert(identity1 == d._rawIdentifier()) assert(isNativeDictionary(d)) assert(removedElement.0 == TestObjCKeyTy(10) as TestBridgedKeyTy) assert(removedElement.1.value == 1010) assert(d.count == 2) assert(d.index(forKey: TestBridgedKeyTy(10)) == nil) } DictionaryTestSuite.test("BridgedFromObjC.Verbatim.RemoveValueForKey") { do { var d = getBridgedVerbatimDictionary() var identity1 = d._rawIdentifier() assert(isCocoaDictionary(d)) var deleted: AnyObject? = d.removeValue(forKey: TestObjCKeyTy(0)) assert(deleted == nil) assert(identity1 == d._rawIdentifier()) assert(isCocoaDictionary(d)) deleted = d.removeValue(forKey: TestObjCKeyTy(10)) assert((deleted as! TestObjCValueTy).value == 1010) var identity2 = d._rawIdentifier() assert(identity1 != identity2) assert(isNativeDictionary(d)) assert(d.count == 2) assert(d[TestObjCKeyTy(10)] == nil) assert((d[TestObjCKeyTy(20)] as! TestObjCValueTy).value == 1020) assert((d[TestObjCKeyTy(30)] as! TestObjCValueTy).value == 1030) assert(identity2 == d._rawIdentifier()) } do { var d1 = getBridgedVerbatimDictionary() var identity1 = d1._rawIdentifier() var d2 = d1 assert(isCocoaDictionary(d1)) assert(isCocoaDictionary(d2)) var deleted: AnyObject? = d2.removeValue(forKey: TestObjCKeyTy(0)) assert(deleted == nil) assert(identity1 == d1._rawIdentifier()) assert(identity1 == d2._rawIdentifier()) assert(isCocoaDictionary(d1)) assert(isCocoaDictionary(d2)) deleted = d2.removeValue(forKey: TestObjCKeyTy(10)) assert((deleted as! TestObjCValueTy).value == 1010) var identity2 = d2._rawIdentifier() assert(identity1 != identity2) assert(isCocoaDictionary(d1)) assert(isNativeDictionary(d2)) assert(d2.count == 2) assert((d1[TestObjCKeyTy(10)] as! TestObjCValueTy).value == 1010) assert((d1[TestObjCKeyTy(20)] as! TestObjCValueTy).value == 1020) assert((d1[TestObjCKeyTy(30)] as! TestObjCValueTy).value == 1030) assert(identity1 == d1._rawIdentifier()) assert(d2[TestObjCKeyTy(10)] == nil) assert((d2[TestObjCKeyTy(20)] as! TestObjCValueTy).value == 1020) assert((d2[TestObjCKeyTy(30)] as! TestObjCValueTy).value == 1030) assert(identity2 == d2._rawIdentifier()) } } DictionaryTestSuite.test("BridgedFromObjC.Nonverbatim.RemoveValueForKey") .xfail(.custom({ _isStdlibDebugConfiguration() }, reason: "rdar://33358110")) .code { do { var d = getBridgedNonverbatimDictionary() var identity1 = d._rawIdentifier() assert(isNativeDictionary(d)) var deleted = d.removeValue(forKey: TestBridgedKeyTy(0)) assert(deleted == nil) assert(identity1 == d._rawIdentifier()) assert(isNativeDictionary(d)) deleted = d.removeValue(forKey: TestBridgedKeyTy(10)) assert(deleted!.value == 1010) var identity2 = d._rawIdentifier() assert(identity1 == identity2) assert(isNativeDictionary(d)) assert(d.count == 2) assert(d[TestBridgedKeyTy(10)] == nil) assert(d[TestBridgedKeyTy(20)]!.value == 1020) assert(d[TestBridgedKeyTy(30)]!.value == 1030) assert(identity2 == d._rawIdentifier()) } do { var d1 = getBridgedNonverbatimDictionary() var identity1 = d1._rawIdentifier() var d2 = d1 assert(isNativeDictionary(d1)) assert(isNativeDictionary(d2)) var deleted = d2.removeValue(forKey: TestBridgedKeyTy(0)) assert(deleted == nil) assert(identity1 == d1._rawIdentifier()) assert(identity1 == d2._rawIdentifier()) assert(isNativeDictionary(d1)) assert(isNativeDictionary(d2)) deleted = d2.removeValue(forKey: TestBridgedKeyTy(10)) assert(deleted!.value == 1010) var identity2 = d2._rawIdentifier() assert(identity1 != identity2) assert(isNativeDictionary(d1)) assert(isNativeDictionary(d2)) assert(d2.count == 2) assert(d1[TestBridgedKeyTy(10)]!.value == 1010) assert(d1[TestBridgedKeyTy(20)]!.value == 1020) assert(d1[TestBridgedKeyTy(30)]!.value == 1030) assert(identity1 == d1._rawIdentifier()) assert(d2[TestBridgedKeyTy(10)] == nil) assert(d2[TestBridgedKeyTy(20)]!.value == 1020) assert(d2[TestBridgedKeyTy(30)]!.value == 1030) assert(identity2 == d2._rawIdentifier()) } } DictionaryTestSuite.test("BridgedFromObjC.Verbatim.RemoveAll") { do { var d = getBridgedVerbatimDictionary([:]) var identity1 = d._rawIdentifier() assert(isCocoaDictionary(d)) assert(d.count == 0) d.removeAll() assert(identity1 == d._rawIdentifier()) assert(d.count == 0) } do { var d = getBridgedVerbatimDictionary() var identity1 = d._rawIdentifier() assert(isCocoaDictionary(d)) let originalCapacity = d.count assert(d.count == 3) assert((d[TestObjCKeyTy(10)] as! TestObjCValueTy).value == 1010) d.removeAll() assert(identity1 != d._rawIdentifier()) assert(d._variantBuffer.asNative.capacity < originalCapacity) assert(d.count == 0) assert(d[TestObjCKeyTy(10)] == nil) } do { var d = getBridgedVerbatimDictionary() var identity1 = d._rawIdentifier() assert(isCocoaDictionary(d)) let originalCapacity = d.count assert(d.count == 3) assert((d[TestObjCKeyTy(10)] as! TestObjCValueTy).value == 1010) d.removeAll(keepingCapacity: true) assert(identity1 != d._rawIdentifier()) assert(d._variantBuffer.asNative.capacity >= originalCapacity) assert(d.count == 0) assert(d[TestObjCKeyTy(10)] == nil) } do { var d1 = getBridgedVerbatimDictionary() var identity1 = d1._rawIdentifier() assert(isCocoaDictionary(d1)) let originalCapacity = d1.count assert(d1.count == 3) assert((d1[TestObjCKeyTy(10)] as! TestObjCValueTy).value == 1010) var d2 = d1 d2.removeAll() var identity2 = d2._rawIdentifier() assert(identity1 == d1._rawIdentifier()) assert(identity2 != identity1) assert(d1.count == 3) assert((d1[TestObjCKeyTy(10)] as! TestObjCValueTy).value == 1010) assert(d2._variantBuffer.asNative.capacity < originalCapacity) assert(d2.count == 0) assert(d2[TestObjCKeyTy(10)] == nil) } do { var d1 = getBridgedVerbatimDictionary() var identity1 = d1._rawIdentifier() assert(isCocoaDictionary(d1)) let originalCapacity = d1.count assert(d1.count == 3) assert((d1[TestObjCKeyTy(10)] as! TestObjCValueTy).value == 1010) var d2 = d1 d2.removeAll(keepingCapacity: true) var identity2 = d2._rawIdentifier() assert(identity1 == d1._rawIdentifier()) assert(identity2 != identity1) assert(d1.count == 3) assert((d1[TestObjCKeyTy(10)] as! TestObjCValueTy).value == 1010) assert(d2._variantBuffer.asNative.capacity >= originalCapacity) assert(d2.count == 0) assert(d2[TestObjCKeyTy(10)] == nil) } } DictionaryTestSuite.test("BridgedFromObjC.Nonverbatim.RemoveAll") { do { var d = getBridgedNonverbatimDictionary([:]) var identity1 = d._rawIdentifier() assert(isNativeDictionary(d)) assert(d.count == 0) d.removeAll() assert(identity1 == d._rawIdentifier()) assert(d.count == 0) } do { var d = getBridgedNonverbatimDictionary() var identity1 = d._rawIdentifier() assert(isNativeDictionary(d)) let originalCapacity = d.count assert(d.count == 3) assert(d[TestBridgedKeyTy(10)]!.value == 1010) d.removeAll() assert(identity1 != d._rawIdentifier()) assert(d._variantBuffer.asNative.capacity < originalCapacity) assert(d.count == 0) assert(d[TestBridgedKeyTy(10)] == nil) } do { var d = getBridgedNonverbatimDictionary() var identity1 = d._rawIdentifier() assert(isNativeDictionary(d)) let originalCapacity = d.count assert(d.count == 3) assert(d[TestBridgedKeyTy(10)]!.value == 1010) d.removeAll(keepingCapacity: true) assert(identity1 == d._rawIdentifier()) assert(d._variantBuffer.asNative.capacity >= originalCapacity) assert(d.count == 0) assert(d[TestBridgedKeyTy(10)] == nil) } do { var d1 = getBridgedNonverbatimDictionary() var identity1 = d1._rawIdentifier() assert(isNativeDictionary(d1)) let originalCapacity = d1.count assert(d1.count == 3) assert(d1[TestBridgedKeyTy(10)]!.value == 1010) var d2 = d1 d2.removeAll() var identity2 = d2._rawIdentifier() assert(identity1 == d1._rawIdentifier()) assert(identity2 != identity1) assert(d1.count == 3) assert(d1[TestBridgedKeyTy(10)]!.value == 1010) assert(d2._variantBuffer.asNative.capacity < originalCapacity) assert(d2.count == 0) assert(d2[TestBridgedKeyTy(10)] == nil) } do { var d1 = getBridgedNonverbatimDictionary() var identity1 = d1._rawIdentifier() assert(isNativeDictionary(d1)) let originalCapacity = d1.count assert(d1.count == 3) assert(d1[TestBridgedKeyTy(10)]!.value == 1010) var d2 = d1 d2.removeAll(keepingCapacity: true) var identity2 = d2._rawIdentifier() assert(identity1 == d1._rawIdentifier()) assert(identity2 != identity1) assert(d1.count == 3) assert(d1[TestBridgedKeyTy(10)]!.value == 1010) assert(d2._variantBuffer.asNative.capacity >= originalCapacity) assert(d2.count == 0) assert(d2[TestBridgedKeyTy(10)] == nil) } } DictionaryTestSuite.test("BridgedFromObjC.Verbatim.Count") { var d = getBridgedVerbatimDictionary() var identity1 = d._rawIdentifier() assert(isCocoaDictionary(d)) assert(d.count == 3) assert(identity1 == d._rawIdentifier()) } DictionaryTestSuite.test("BridgedFromObjC.Nonverbatim.Count") { var d = getBridgedNonverbatimDictionary() var identity1 = d._rawIdentifier() assert(isNativeDictionary(d)) assert(d.count == 3) assert(identity1 == d._rawIdentifier()) } DictionaryTestSuite.test("BridgedFromObjC.Verbatim.Generate") { var d = getBridgedVerbatimDictionary() var identity1 = d._rawIdentifier() assert(isCocoaDictionary(d)) var iter = d.makeIterator() var pairs = Array<(Int, Int)>() while let (key, value) = iter.next() { let kv = ((key as! TestObjCKeyTy).value, (value as! TestObjCValueTy).value) pairs.append(kv) } assert(equalsUnordered(pairs, [ (10, 1010), (20, 1020), (30, 1030) ])) assert(iter.next() == nil) assert(iter.next() == nil) assert(iter.next() == nil) assert(identity1 == d._rawIdentifier()) } DictionaryTestSuite.test("BridgedFromObjC.Nonverbatim.Generate") { var d = getBridgedNonverbatimDictionary() var identity1 = d._rawIdentifier() assert(isNativeDictionary(d)) var iter = d.makeIterator() var pairs = Array<(Int, Int)>() while let (key, value) = iter.next() { let kv = (key.value, value.value) pairs.append(kv) } assert(equalsUnordered(pairs, [ (10, 1010), (20, 1020), (30, 1030) ])) assert(iter.next() == nil) assert(iter.next() == nil) assert(iter.next() == nil) assert(identity1 == d._rawIdentifier()) } DictionaryTestSuite.test("BridgedFromObjC.Verbatim.Generate_Empty") { var d = getBridgedVerbatimDictionary([:]) var identity1 = d._rawIdentifier() assert(isCocoaDictionary(d)) var iter = d.makeIterator() // Cannot write code below because of // <rdar://problem/16811736> Optional tuples are broken as optionals regarding == comparison // assert(iter.next() == .none) assert(iter.next() == nil) assert(iter.next() == nil) assert(iter.next() == nil) assert(iter.next() == nil) assert(identity1 == d._rawIdentifier()) } DictionaryTestSuite.test("BridgedFromObjC.Nonverbatim.Generate_Empty") { var d = getBridgedNonverbatimDictionary([:]) var identity1 = d._rawIdentifier() assert(isNativeDictionary(d)) var iter = d.makeIterator() // Cannot write code below because of // <rdar://problem/16811736> Optional tuples are broken as optionals regarding == comparison // assert(iter.next() == .none) assert(iter.next() == nil) assert(iter.next() == nil) assert(iter.next() == nil) assert(iter.next() == nil) assert(identity1 == d._rawIdentifier()) } DictionaryTestSuite.test("BridgedFromObjC.Verbatim.Generate_Huge") { var d = getHugeBridgedVerbatimDictionary() var identity1 = d._rawIdentifier() assert(isCocoaDictionary(d)) var iter = d.makeIterator() var pairs = Array<(Int, Int)>() while let (key, value) = iter.next() { let kv = ((key as! TestObjCKeyTy).value, (value as! TestObjCValueTy).value) pairs.append(kv) } var expectedPairs = Array<(Int, Int)>() for i in 1...32 { expectedPairs += [(i, 1000 + i)] } assert(equalsUnordered(pairs, expectedPairs)) assert(iter.next() == nil) assert(iter.next() == nil) assert(iter.next() == nil) assert(identity1 == d._rawIdentifier()) } DictionaryTestSuite.test("BridgedFromObjC.Nonverbatim.Generate_Huge") { var d = getHugeBridgedNonverbatimDictionary() var identity1 = d._rawIdentifier() assert(isNativeDictionary(d)) var iter = d.makeIterator() var pairs = Array<(Int, Int)>() while let (key, value) = iter.next() { let kv = (key.value, value.value) pairs.append(kv) } var expectedPairs = Array<(Int, Int)>() for i in 1...32 { expectedPairs += [(i, 1000 + i)] } assert(equalsUnordered(pairs, expectedPairs)) assert(iter.next() == nil) assert(iter.next() == nil) assert(iter.next() == nil) assert(identity1 == d._rawIdentifier()) } DictionaryTestSuite.test("BridgedFromObjC.Verbatim.Generate_ParallelArray") { autoreleasepoolIfUnoptimizedReturnAutoreleased { // Add an autorelease pool because ParallelArrayDictionary autoreleases // values in objectForKey. var d = getParallelArrayBridgedVerbatimDictionary() var identity1 = d._rawIdentifier() assert(isCocoaDictionary(d)) var iter = d.makeIterator() var pairs = Array<(Int, Int)>() while let (key, value) = iter.next() { let kv = ((key as! TestObjCKeyTy).value, (value as! TestObjCValueTy).value) pairs.append(kv) } var expectedPairs = [ (10, 1111), (20, 1111), (30, 1111), (40, 1111) ] assert(equalsUnordered(pairs, expectedPairs)) assert(iter.next() == nil) assert(iter.next() == nil) assert(iter.next() == nil) assert(identity1 == d._rawIdentifier()) } } DictionaryTestSuite.test("BridgedFromObjC.Nonverbatim.Generate_ParallelArray") { autoreleasepoolIfUnoptimizedReturnAutoreleased { // Add an autorelease pool because ParallelArrayDictionary autoreleases // values in objectForKey. var d = getParallelArrayBridgedNonverbatimDictionary() var identity1 = d._rawIdentifier() assert(isNativeDictionary(d)) var iter = d.makeIterator() var pairs = Array<(Int, Int)>() while let (key, value) = iter.next() { let kv = (key.value, value.value) pairs.append(kv) } var expectedPairs = [ (10, 1111), (20, 1111), (30, 1111), (40, 1111) ] assert(equalsUnordered(pairs, expectedPairs)) assert(iter.next() == nil) assert(iter.next() == nil) assert(iter.next() == nil) assert(identity1 == d._rawIdentifier()) } } DictionaryTestSuite.test("BridgedFromObjC.Verbatim.EqualityTest_Empty") { var d1 = getBridgedVerbatimEquatableDictionary([:]) var identity1 = d1._rawIdentifier() assert(isCocoaDictionary(d1)) var d2 = getBridgedVerbatimEquatableDictionary([:]) var identity2 = d2._rawIdentifier() assert(isCocoaDictionary(d2)) // We can't check that `identity1 != identity2` because Foundation might be // returning the same singleton NSDictionary for empty dictionaries. assert(d1 == d2) assert(identity1 == d1._rawIdentifier()) assert(identity2 == d2._rawIdentifier()) d2[TestObjCKeyTy(10)] = TestObjCEquatableValueTy(2010) assert(isNativeDictionary(d2)) assert(identity2 != d2._rawIdentifier()) identity2 = d2._rawIdentifier() assert(d1 != d2) assert(identity1 == d1._rawIdentifier()) assert(identity2 == d2._rawIdentifier()) } DictionaryTestSuite.test("BridgedFromObjC.Nonverbatim.EqualityTest_Empty") { var d1 = getBridgedNonverbatimEquatableDictionary([:]) var identity1 = d1._rawIdentifier() assert(isNativeDictionary(d1)) var d2 = getBridgedNonverbatimEquatableDictionary([:]) var identity2 = d2._rawIdentifier() assert(isNativeDictionary(d2)) assert(identity1 != identity2) assert(d1 == d2) assert(identity1 == d1._rawIdentifier()) assert(identity2 == d2._rawIdentifier()) d2[TestBridgedKeyTy(10)] = TestBridgedEquatableValueTy(2010) assert(isNativeDictionary(d2)) assert(identity2 == d2._rawIdentifier()) assert(d1 != d2) assert(identity1 == d1._rawIdentifier()) assert(identity2 == d2._rawIdentifier()) } DictionaryTestSuite.test("BridgedFromObjC.Verbatim.EqualityTest_Small") { func helper(_ nd1: Dictionary<Int, Int>, _ nd2: Dictionary<Int, Int>, _ expectedEq: Bool) { let d1 = getBridgedVerbatimEquatableDictionary(nd1) let identity1 = d1._rawIdentifier() assert(isCocoaDictionary(d1)) var d2 = getBridgedVerbatimEquatableDictionary(nd2) var identity2 = d2._rawIdentifier() assert(isCocoaDictionary(d2)) do { let eq1 = (d1 == d2) assert(eq1 == expectedEq) let eq2 = (d2 == d1) assert(eq2 == expectedEq) let neq1 = (d1 != d2) assert(neq1 != expectedEq) let neq2 = (d2 != d1) assert(neq2 != expectedEq) } assert(identity1 == d1._rawIdentifier()) assert(identity2 == d2._rawIdentifier()) d2[TestObjCKeyTy(1111)] = TestObjCEquatableValueTy(1111) d2[TestObjCKeyTy(1111)] = nil assert(isNativeDictionary(d2)) assert(identity2 != d2._rawIdentifier()) identity2 = d2._rawIdentifier() do { let eq1 = (d1 == d2) assert(eq1 == expectedEq) let eq2 = (d2 == d1) assert(eq2 == expectedEq) let neq1 = (d1 != d2) assert(neq1 != expectedEq) let neq2 = (d2 != d1) assert(neq2 != expectedEq) } assert(identity1 == d1._rawIdentifier()) assert(identity2 == d2._rawIdentifier()) } helper([:], [:], true) helper([10: 1010], [10: 1010], true) helper([10: 1010, 20: 1020], [10: 1010, 20: 1020], true) helper([10: 1010, 20: 1020, 30: 1030], [10: 1010, 20: 1020, 30: 1030], true) helper([10: 1010, 20: 1020, 30: 1030], [10: 1010, 20: 1020, 1111: 1030], false) helper([10: 1010, 20: 1020, 30: 1030], [10: 1010, 20: 1020, 30: 1111], false) helper([10: 1010, 20: 1020, 30: 1030], [10: 1010, 20: 1020], false) helper([10: 1010, 20: 1020, 30: 1030], [10: 1010], false) helper([10: 1010, 20: 1020, 30: 1030], [:], false) helper([10: 1010, 20: 1020, 30: 1030], [10: 1010, 20: 1020, 30: 1030, 40: 1040], false) } DictionaryTestSuite.test("BridgedFromObjC.Verbatim.ArrayOfDictionaries") { var nsa = NSMutableArray() for i in 0..<3 { nsa.add( getAsNSDictionary([10: 1010 + i, 20: 1020 + i, 30: 1030 + i])) } var a = nsa as [AnyObject] as! [Dictionary<NSObject, AnyObject>] for i in 0..<3 { var d = a[i] var iter = d.makeIterator() var pairs = Array<(Int, Int)>() while let (key, value) = iter.next() { let kv = ((key as! TestObjCKeyTy).value, (value as! TestObjCValueTy).value) pairs.append(kv) } var expectedPairs = [ (10, 1010 + i), (20, 1020 + i), (30, 1030 + i) ] assert(equalsUnordered(pairs, expectedPairs)) } } DictionaryTestSuite.test("BridgedFromObjC.Nonverbatim.ArrayOfDictionaries") { var nsa = NSMutableArray() for i in 0..<3 { nsa.add( getAsNSDictionary([10: 1010 + i, 20: 1020 + i, 30: 1030 + i])) } var a = nsa as [AnyObject] as! [Dictionary<TestBridgedKeyTy, TestBridgedValueTy>] for i in 0..<3 { var d = a[i] var iter = d.makeIterator() var pairs = Array<(Int, Int)>() while let (key, value) = iter.next() { let kv = (key.value, value.value) pairs.append(kv) } var expectedPairs = [ (10, 1010 + i), (20, 1020 + i), (30, 1030 + i) ] assert(equalsUnordered(pairs, expectedPairs)) } } //===--- // Dictionary -> NSDictionary bridging tests. // // Key and Value are bridged verbatim. //===--- DictionaryTestSuite.test("BridgedToObjC.Verbatim.Count") { let d = getBridgedNSDictionaryOfRefTypesBridgedVerbatim() assert(d.count == 3) } DictionaryTestSuite.test("BridgedToObjC.Verbatim.ObjectForKey") { let d = getBridgedNSDictionaryOfRefTypesBridgedVerbatim() var v: AnyObject? = d.object(forKey: TestObjCKeyTy(10)).map { $0 as AnyObject } expectEqual(1010, (v as! TestObjCValueTy).value) let idValue10 = unsafeBitCast(v, to: UInt.self) v = d.object(forKey: TestObjCKeyTy(20)).map { $0 as AnyObject } expectEqual(1020, (v as! TestObjCValueTy).value) let idValue20 = unsafeBitCast(v, to: UInt.self) v = d.object(forKey: TestObjCKeyTy(30)).map { $0 as AnyObject } expectEqual(1030, (v as! TestObjCValueTy).value) let idValue30 = unsafeBitCast(v, to: UInt.self) expectNil(d.object(forKey: TestObjCKeyTy(40))) // NSDictionary can store mixed key types. Swift's Dictionary is typed, but // when bridged to NSDictionary, it should behave like one, and allow queries // for mismatched key types. expectNil(d.object(forKey: TestObjCInvalidKeyTy())) for i in 0..<3 { expectEqual(idValue10, unsafeBitCast( d.object(forKey: TestObjCKeyTy(10)).map { $0 as AnyObject }, to: UInt.self)) expectEqual(idValue20, unsafeBitCast( d.object(forKey: TestObjCKeyTy(20)).map { $0 as AnyObject }, to: UInt.self)) expectEqual(idValue30, unsafeBitCast( d.object(forKey: TestObjCKeyTy(30)).map { $0 as AnyObject }, to: UInt.self)) } expectAutoreleasedKeysAndValues(unopt: (0, 3)) } DictionaryTestSuite.test("BridgedToObjC.Verbatim.KeyEnumerator.NextObject") { let d = getBridgedNSDictionaryOfRefTypesBridgedVerbatim() var capturedIdentityPairs = Array<(UInt, UInt)>() for i in 0..<3 { let enumerator = d.keyEnumerator() var dataPairs = Array<(Int, Int)>() var identityPairs = Array<(UInt, UInt)>() while let key = enumerator.nextObject() { let keyObj = key as AnyObject let value: AnyObject = d.object(forKey: keyObj)! as AnyObject let dataPair = ((keyObj as! TestObjCKeyTy).value, (value as! TestObjCValueTy).value) dataPairs.append(dataPair) let identityPair = (unsafeBitCast(keyObj, to: UInt.self), unsafeBitCast(value, to: UInt.self)) identityPairs.append(identityPair) } expectTrue( equalsUnordered(dataPairs, [ (10, 1010), (20, 1020), (30, 1030) ])) if capturedIdentityPairs.isEmpty { capturedIdentityPairs = identityPairs } else { expectTrue(equalsUnordered(capturedIdentityPairs, identityPairs)) } assert(enumerator.nextObject() == nil) assert(enumerator.nextObject() == nil) assert(enumerator.nextObject() == nil) } expectAutoreleasedKeysAndValues(unopt: (3, 3)) } DictionaryTestSuite.test("BridgedToObjC.Verbatim.KeyEnumerator.NextObject_Empty") { let d = getBridgedEmptyNSDictionary() let enumerator = d.keyEnumerator() assert(enumerator.nextObject() == nil) assert(enumerator.nextObject() == nil) assert(enumerator.nextObject() == nil) } DictionaryTestSuite.test("BridgedToObjC.Verbatim.KeyEnumerator.FastEnumeration.UseFromSwift") { let d = getBridgedNSDictionaryOfRefTypesBridgedVerbatim() checkDictionaryFastEnumerationFromSwift( [ (10, 1010), (20, 1020), (30, 1030) ], d, { d.keyEnumerator() }, { ($0 as! TestObjCKeyTy).value }, { ($0 as! TestObjCValueTy).value }) expectAutoreleasedKeysAndValues(unopt: (3, 3)) } DictionaryTestSuite.test("BridgedToObjC.Verbatim.KeyEnumerator.FastEnumeration.UseFromObjC") { let d = getBridgedNSDictionaryOfRefTypesBridgedVerbatim() checkDictionaryFastEnumerationFromObjC( [ (10, 1010), (20, 1020), (30, 1030) ], d, { d.keyEnumerator() }, { ($0 as! TestObjCKeyTy).value }, { ($0 as! TestObjCValueTy).value }) expectAutoreleasedKeysAndValues(unopt: (3, 3)) } DictionaryTestSuite.test("BridgedToObjC.Verbatim.KeyEnumerator.FastEnumeration_Empty") { let d = getBridgedEmptyNSDictionary() checkDictionaryFastEnumerationFromSwift( [], d, { d.keyEnumerator() }, { ($0 as! TestObjCKeyTy).value }, { ($0 as! TestObjCValueTy).value }) checkDictionaryFastEnumerationFromObjC( [], d, { d.keyEnumerator() }, { ($0 as! TestObjCKeyTy).value }, { ($0 as! TestObjCValueTy).value }) } DictionaryTestSuite.test("BridgedToObjC.Verbatim.FastEnumeration.UseFromSwift") { let d = getBridgedNSDictionaryOfRefTypesBridgedVerbatim() checkDictionaryFastEnumerationFromSwift( [ (10, 1010), (20, 1020), (30, 1030) ], d, { d }, { ($0 as! TestObjCKeyTy).value }, { ($0 as! TestObjCValueTy).value }) expectAutoreleasedKeysAndValues(unopt: (0, 3)) } DictionaryTestSuite.test("BridgedToObjC.Verbatim.FastEnumeration.UseFromObjC") { let d = getBridgedNSDictionaryOfRefTypesBridgedVerbatim() checkDictionaryFastEnumerationFromObjC( [ (10, 1010), (20, 1020), (30, 1030) ], d, { d }, { ($0 as! TestObjCKeyTy).value }, { ($0 as! TestObjCValueTy).value }) expectAutoreleasedKeysAndValues(unopt: (0, 3)) } DictionaryTestSuite.test("BridgedToObjC.Verbatim.FastEnumeration_Empty") { let d = getBridgedEmptyNSDictionary() checkDictionaryFastEnumerationFromSwift( [], d, { d }, { ($0 as! TestObjCKeyTy).value }, { ($0 as! TestObjCValueTy).value }) checkDictionaryFastEnumerationFromObjC( [], d, { d }, { ($0 as! TestObjCKeyTy).value }, { ($0 as! TestObjCValueTy).value }) } //===--- // Dictionary -> NSDictionary bridging tests. // // Key type and value type are bridged non-verbatim. //===--- DictionaryTestSuite.test("BridgedToObjC.KeyValue_ValueTypesCustomBridged") { let d = getBridgedNSDictionaryOfKeyValue_ValueTypesCustomBridged() let enumerator = d.keyEnumerator() var pairs = Array<(Int, Int)>() while let key = enumerator.nextObject() { let value: AnyObject = d.object(forKey: key)! as AnyObject let kv = ((key as! TestObjCKeyTy).value, (value as! TestObjCValueTy).value) pairs.append(kv) } assert(equalsUnordered(pairs, [ (10, 1010), (20, 1020), (30, 1030) ])) expectAutoreleasedKeysAndValues(unopt: (3, 3)) } DictionaryTestSuite.test("BridgedToObjC.Custom.KeyEnumerator.FastEnumeration.UseFromSwift") { let d = getBridgedNSDictionaryOfKeyValue_ValueTypesCustomBridged() checkDictionaryFastEnumerationFromSwift( [ (10, 1010), (20, 1020), (30, 1030) ], d, { d.keyEnumerator() }, { ($0 as! TestObjCKeyTy).value }, { ($0 as! TestObjCValueTy).value }) expectAutoreleasedKeysAndValues(unopt: (3, 3)) } DictionaryTestSuite.test("BridgedToObjC.Custom.KeyEnumerator.FastEnumeration.UseFromSwift.Partial") { let d = getBridgedNSDictionaryOfKeyValue_ValueTypesCustomBridged( numElements: 9) checkDictionaryEnumeratorPartialFastEnumerationFromSwift( [ (10, 1010), (20, 1020), (30, 1030), (40, 1040), (50, 1050), (60, 1060), (70, 1070), (80, 1080), (90, 1090) ], d, maxFastEnumerationItems: 5, { ($0 as! TestObjCKeyTy).value }, { ($0 as! TestObjCValueTy).value }) expectAutoreleasedKeysAndValues(unopt: (9, 9)) } DictionaryTestSuite.test("BridgedToObjC.Custom.KeyEnumerator.FastEnumeration.UseFromObjC") { let d = getBridgedNSDictionaryOfKeyValue_ValueTypesCustomBridged() checkDictionaryFastEnumerationFromObjC( [ (10, 1010), (20, 1020), (30, 1030) ], d, { d.keyEnumerator() }, { ($0 as! TestObjCKeyTy).value }, { ($0 as! TestObjCValueTy).value }) expectAutoreleasedKeysAndValues(unopt: (3, 3)) } DictionaryTestSuite.test("BridgedToObjC.Custom.FastEnumeration.UseFromSwift") { let d = getBridgedNSDictionaryOfKeyValue_ValueTypesCustomBridged() checkDictionaryFastEnumerationFromSwift( [ (10, 1010), (20, 1020), (30, 1030) ], d, { d }, { ($0 as! TestObjCKeyTy).value }, { ($0 as! TestObjCValueTy).value }) expectAutoreleasedKeysAndValues(unopt: (0, 3)) } DictionaryTestSuite.test("BridgedToObjC.Custom.FastEnumeration.UseFromObjC") { let d = getBridgedNSDictionaryOfKeyValue_ValueTypesCustomBridged() checkDictionaryFastEnumerationFromObjC( [ (10, 1010), (20, 1020), (30, 1030) ], d, { d }, { ($0 as! TestObjCKeyTy).value }, { ($0 as! TestObjCValueTy).value }) expectAutoreleasedKeysAndValues(unopt: (0, 3)) } DictionaryTestSuite.test("BridgedToObjC.Custom.FastEnumeration_Empty") { let d = getBridgedNSDictionaryOfKeyValue_ValueTypesCustomBridged( numElements: 0) checkDictionaryFastEnumerationFromSwift( [], d, { d }, { ($0 as! TestObjCKeyTy).value }, { ($0 as! TestObjCValueTy).value }) checkDictionaryFastEnumerationFromObjC( [], d, { d }, { ($0 as! TestObjCKeyTy).value }, { ($0 as! TestObjCValueTy).value }) } func getBridgedNSDictionaryOfKey_ValueTypeCustomBridged() -> NSDictionary { assert(!_isBridgedVerbatimToObjectiveC(TestBridgedKeyTy.self)) assert(_isBridgedVerbatimToObjectiveC(TestObjCValueTy.self)) var d = Dictionary<TestBridgedKeyTy, TestObjCValueTy>() d[TestBridgedKeyTy(10)] = TestObjCValueTy(1010) d[TestBridgedKeyTy(20)] = TestObjCValueTy(1020) d[TestBridgedKeyTy(30)] = TestObjCValueTy(1030) let bridged = convertDictionaryToNSDictionary(d) assert(isNativeNSDictionary(bridged)) return bridged } DictionaryTestSuite.test("BridgedToObjC.Key_ValueTypeCustomBridged") { let d = getBridgedNSDictionaryOfKey_ValueTypeCustomBridged() let enumerator = d.keyEnumerator() var pairs = Array<(Int, Int)>() while let key = enumerator.nextObject() { let value: AnyObject = d.object(forKey: key)! as AnyObject let kv = ((key as! TestObjCKeyTy).value, (value as! TestObjCValueTy).value) pairs.append(kv) } assert(equalsUnordered(pairs, [ (10, 1010), (20, 1020), (30, 1030) ])) expectAutoreleasedKeysAndValues(unopt: (3, 3)) } func getBridgedNSDictionaryOfValue_ValueTypeCustomBridged() -> NSDictionary { assert(_isBridgedVerbatimToObjectiveC(TestObjCKeyTy.self)) assert(!_isBridgedVerbatimToObjectiveC(TestBridgedValueTy.self)) var d = Dictionary<TestObjCKeyTy, TestBridgedValueTy>() d[TestObjCKeyTy(10)] = TestBridgedValueTy(1010) d[TestObjCKeyTy(20)] = TestBridgedValueTy(1020) d[TestObjCKeyTy(30)] = TestBridgedValueTy(1030) let bridged = convertDictionaryToNSDictionary(d) assert(isNativeNSDictionary(bridged)) return bridged } DictionaryTestSuite.test("BridgedToObjC.Value_ValueTypeCustomBridged") { let d = getBridgedNSDictionaryOfValue_ValueTypeCustomBridged() let enumerator = d.keyEnumerator() var pairs = Array<(Int, Int)>() while let key = enumerator.nextObject() { let value: AnyObject = d.object(forKey: key)! as AnyObject let kv = ((key as! TestObjCKeyTy).value, (value as! TestObjCValueTy).value) pairs.append(kv) } assert(equalsUnordered(pairs, [ (10, 1010), (20, 1020), (30, 1030) ])) expectAutoreleasedKeysAndValues(unopt: (3, 3)) } //===--- // NSDictionary -> Dictionary -> NSDictionary bridging tests. //===--- func getRoundtripBridgedNSDictionary() -> NSDictionary { let keys = [ 10, 20, 30 ].map { TestObjCKeyTy($0) } let values = [ 1010, 1020, 1030 ].map { TestObjCValueTy($0) } let nsd = NSDictionary(objects: values, forKeys: keys) let d: Dictionary<NSObject, AnyObject> = convertNSDictionaryToDictionary(nsd) let bridgedBack = convertDictionaryToNSDictionary(d) assert(isCocoaNSDictionary(bridgedBack)) // FIXME: this should be true. //assert(unsafeBitCast(nsd, Int.self) == unsafeBitCast(bridgedBack, Int.self)) return bridgedBack } DictionaryTestSuite.test("BridgingRoundtrip") { let d = getRoundtripBridgedNSDictionary() let enumerator = d.keyEnumerator() var pairs = Array<(key: Int, value: Int)>() while let key = enumerator.nextObject() { let value: AnyObject = d.object(forKey: key)! as AnyObject let kv = ((key as! TestObjCKeyTy).value, (value as! TestObjCValueTy).value) pairs.append(kv) } expectEqualsUnordered([ (10, 1010), (20, 1020), (30, 1030) ], pairs) } //===--- // NSDictionary -> Dictionary implicit conversion. //===--- DictionaryTestSuite.test("NSDictionaryToDictionaryConversion") { let keys = [ 10, 20, 30 ].map { TestObjCKeyTy($0) } let values = [ 1010, 1020, 1030 ].map { TestObjCValueTy($0) } let nsd = NSDictionary(objects: values, forKeys: keys) let d: Dictionary = nsd as Dictionary var pairs = Array<(Int, Int)>() for (key, value) in d { let kv = ((key as! TestObjCKeyTy).value, (value as! TestObjCValueTy).value) pairs.append(kv) } assert(equalsUnordered(pairs, [ (10, 1010), (20, 1020), (30, 1030) ])) } DictionaryTestSuite.test("DictionaryToNSDictionaryConversion") { var d = Dictionary<TestObjCKeyTy, TestObjCValueTy>(minimumCapacity: 32) d[TestObjCKeyTy(10)] = TestObjCValueTy(1010) d[TestObjCKeyTy(20)] = TestObjCValueTy(1020) d[TestObjCKeyTy(30)] = TestObjCValueTy(1030) let nsd: NSDictionary = d as NSDictionary checkDictionaryFastEnumerationFromSwift( [ (10, 1010), (20, 1020), (30, 1030) ], d as NSDictionary, { d as NSDictionary }, { ($0 as! TestObjCKeyTy).value }, { ($0 as! TestObjCValueTy).value }) expectAutoreleasedKeysAndValues(unopt: (0, 3)) } //===--- // Dictionary upcasts //===--- DictionaryTestSuite.test("DictionaryUpcastEntryPoint") { var d = Dictionary<TestObjCKeyTy, TestObjCValueTy>(minimumCapacity: 32) d[TestObjCKeyTy(10)] = TestObjCValueTy(1010) d[TestObjCKeyTy(20)] = TestObjCValueTy(1020) d[TestObjCKeyTy(30)] = TestObjCValueTy(1030) var dAsAnyObject: Dictionary<NSObject, AnyObject> = _dictionaryUpCast(d) assert(dAsAnyObject.count == 3) var v: AnyObject? = dAsAnyObject[TestObjCKeyTy(10)] assert((v! as! TestObjCValueTy).value == 1010) v = dAsAnyObject[TestObjCKeyTy(20)] assert((v! as! TestObjCValueTy).value == 1020) v = dAsAnyObject[TestObjCKeyTy(30)] assert((v! as! TestObjCValueTy).value == 1030) } DictionaryTestSuite.test("DictionaryUpcast") { var d = Dictionary<TestObjCKeyTy, TestObjCValueTy>(minimumCapacity: 32) d[TestObjCKeyTy(10)] = TestObjCValueTy(1010) d[TestObjCKeyTy(20)] = TestObjCValueTy(1020) d[TestObjCKeyTy(30)] = TestObjCValueTy(1030) var dAsAnyObject: Dictionary<NSObject, AnyObject> = d assert(dAsAnyObject.count == 3) var v: AnyObject? = dAsAnyObject[TestObjCKeyTy(10)] assert((v! as! TestObjCValueTy).value == 1010) v = dAsAnyObject[TestObjCKeyTy(20)] assert((v! as! TestObjCValueTy).value == 1020) v = dAsAnyObject[TestObjCKeyTy(30)] assert((v! as! TestObjCValueTy).value == 1030) } DictionaryTestSuite.test("DictionaryUpcastBridgedEntryPoint") { var d = Dictionary<TestBridgedKeyTy, TestBridgedValueTy>(minimumCapacity: 32) d[TestBridgedKeyTy(10)] = TestBridgedValueTy(1010) d[TestBridgedKeyTy(20)] = TestBridgedValueTy(1020) d[TestBridgedKeyTy(30)] = TestBridgedValueTy(1030) do { var dOO: Dictionary<NSObject, AnyObject> = _dictionaryBridgeToObjectiveC(d) assert(dOO.count == 3) var v: AnyObject? = dOO[TestObjCKeyTy(10)] assert((v! as! TestBridgedValueTy).value == 1010) v = dOO[TestObjCKeyTy(20)] assert((v! as! TestBridgedValueTy).value == 1020) v = dOO[TestObjCKeyTy(30)] assert((v! as! TestBridgedValueTy).value == 1030) } do { var dOV: Dictionary<NSObject, TestBridgedValueTy> = _dictionaryBridgeToObjectiveC(d) assert(dOV.count == 3) var v = dOV[TestObjCKeyTy(10)] assert(v!.value == 1010) v = dOV[TestObjCKeyTy(20)] assert(v!.value == 1020) v = dOV[TestObjCKeyTy(30)] assert(v!.value == 1030) } do { var dVO: Dictionary<TestBridgedKeyTy, AnyObject> = _dictionaryBridgeToObjectiveC(d) assert(dVO.count == 3) var v: AnyObject? = dVO[TestBridgedKeyTy(10)] assert((v! as! TestBridgedValueTy).value == 1010) v = dVO[TestBridgedKeyTy(20)] assert((v! as! TestBridgedValueTy).value == 1020) v = dVO[TestBridgedKeyTy(30)] assert((v! as! TestBridgedValueTy).value == 1030) } } DictionaryTestSuite.test("DictionaryUpcastBridged") { var d = Dictionary<TestBridgedKeyTy, TestBridgedValueTy>(minimumCapacity: 32) d[TestBridgedKeyTy(10)] = TestBridgedValueTy(1010) d[TestBridgedKeyTy(20)] = TestBridgedValueTy(1020) d[TestBridgedKeyTy(30)] = TestBridgedValueTy(1030) do { var dOO = d as! Dictionary<NSObject, AnyObject> assert(dOO.count == 3) var v: AnyObject? = dOO[TestObjCKeyTy(10)] assert((v! as! TestBridgedValueTy).value == 1010) v = dOO[TestObjCKeyTy(20)] assert((v! as! TestBridgedValueTy).value == 1020) v = dOO[TestObjCKeyTy(30)] assert((v! as! TestBridgedValueTy).value == 1030) } do { var dOV = d as! Dictionary<NSObject, TestBridgedValueTy> assert(dOV.count == 3) var v = dOV[TestObjCKeyTy(10)] assert(v!.value == 1010) v = dOV[TestObjCKeyTy(20)] assert(v!.value == 1020) v = dOV[TestObjCKeyTy(30)] assert(v!.value == 1030) } do { var dVO = d as Dictionary<TestBridgedKeyTy, AnyObject> assert(dVO.count == 3) var v: AnyObject? = dVO[TestBridgedKeyTy(10)] assert((v! as! TestBridgedValueTy).value == 1010) v = dVO[TestBridgedKeyTy(20)] assert((v! as! TestBridgedValueTy).value == 1020) v = dVO[TestBridgedKeyTy(30)] assert((v! as! TestBridgedValueTy).value == 1030) } } //===--- // Dictionary downcasts //===--- DictionaryTestSuite.test("DictionaryDowncastEntryPoint") { var d = Dictionary<NSObject, AnyObject>(minimumCapacity: 32) d[TestObjCKeyTy(10)] = TestObjCValueTy(1010) d[TestObjCKeyTy(20)] = TestObjCValueTy(1020) d[TestObjCKeyTy(30)] = TestObjCValueTy(1030) // Successful downcast. let dCC: Dictionary<TestObjCKeyTy, TestObjCValueTy> = _dictionaryDownCast(d) assert(dCC.count == 3) var v = dCC[TestObjCKeyTy(10)] assert(v!.value == 1010) v = dCC[TestObjCKeyTy(20)] assert(v!.value == 1020) v = dCC[TestObjCKeyTy(30)] assert(v!.value == 1030) expectAutoreleasedKeysAndValues(unopt: (0, 3)) } DictionaryTestSuite.test("DictionaryDowncast") { var d = Dictionary<NSObject, AnyObject>(minimumCapacity: 32) d[TestObjCKeyTy(10)] = TestObjCValueTy(1010) d[TestObjCKeyTy(20)] = TestObjCValueTy(1020) d[TestObjCKeyTy(30)] = TestObjCValueTy(1030) // Successful downcast. let dCC = d as! Dictionary<TestObjCKeyTy, TestObjCValueTy> assert(dCC.count == 3) var v = dCC[TestObjCKeyTy(10)] assert(v!.value == 1010) v = dCC[TestObjCKeyTy(20)] assert(v!.value == 1020) v = dCC[TestObjCKeyTy(30)] assert(v!.value == 1030) expectAutoreleasedKeysAndValues(unopt: (0, 3)) } DictionaryTestSuite.test("DictionaryDowncastConditionalEntryPoint") { var d = Dictionary<NSObject, AnyObject>(minimumCapacity: 32) d[TestObjCKeyTy(10)] = TestObjCValueTy(1010) d[TestObjCKeyTy(20)] = TestObjCValueTy(1020) d[TestObjCKeyTy(30)] = TestObjCValueTy(1030) // Successful downcast. if let dCC = _dictionaryDownCastConditional(d) as Dictionary<TestObjCKeyTy, TestObjCValueTy>? { assert(dCC.count == 3) var v = dCC[TestObjCKeyTy(10)] assert(v!.value == 1010) v = dCC[TestObjCKeyTy(20)] assert(v!.value == 1020) v = dCC[TestObjCKeyTy(30)] assert(v!.value == 1030) } else { assert(false) } // Unsuccessful downcast d["hello" as NSString] = 17 as NSNumber if let dCC = _dictionaryDownCastConditional(d) as Dictionary<TestObjCKeyTy, TestObjCValueTy>? { assert(false) } } DictionaryTestSuite.test("DictionaryDowncastConditional") { var d = Dictionary<NSObject, AnyObject>(minimumCapacity: 32) d[TestObjCKeyTy(10)] = TestObjCValueTy(1010) d[TestObjCKeyTy(20)] = TestObjCValueTy(1020) d[TestObjCKeyTy(30)] = TestObjCValueTy(1030) // Successful downcast. if let dCC = d as? Dictionary<TestObjCKeyTy, TestObjCValueTy> { assert(dCC.count == 3) var v = dCC[TestObjCKeyTy(10)] assert(v!.value == 1010) v = dCC[TestObjCKeyTy(20)] assert(v!.value == 1020) v = dCC[TestObjCKeyTy(30)] assert(v!.value == 1030) } else { assert(false) } // Unsuccessful downcast d["hello" as NSString] = 17 as NSNumber if let dCC = d as? Dictionary<TestObjCKeyTy, TestObjCValueTy> { assert(false) } } DictionaryTestSuite.test("DictionaryBridgeFromObjectiveCEntryPoint") { var d = Dictionary<NSObject, AnyObject>(minimumCapacity: 32) d[TestObjCKeyTy(10)] = TestObjCValueTy(1010) d[TestObjCKeyTy(20)] = TestObjCValueTy(1020) d[TestObjCKeyTy(30)] = TestObjCValueTy(1030) // Successful downcast. let dCV: Dictionary<TestObjCKeyTy, TestBridgedValueTy> = _dictionaryBridgeFromObjectiveC(d) do { assert(dCV.count == 3) var v = dCV[TestObjCKeyTy(10)] assert(v!.value == 1010) v = dCV[TestObjCKeyTy(20)] assert(v!.value == 1020) v = dCV[TestObjCKeyTy(30)] assert(v!.value == 1030) } // Successful downcast. let dVC: Dictionary<TestBridgedKeyTy, TestObjCValueTy> = _dictionaryBridgeFromObjectiveC(d) do { assert(dVC.count == 3) var v = dVC[TestBridgedKeyTy(10)] assert(v!.value == 1010) v = dVC[TestBridgedKeyTy(20)] assert(v!.value == 1020) v = dVC[TestBridgedKeyTy(30)] assert(v!.value == 1030) } // Successful downcast. let dVV: Dictionary<TestBridgedKeyTy, TestBridgedValueTy> = _dictionaryBridgeFromObjectiveC(d) do { assert(dVV.count == 3) var v = dVV[TestBridgedKeyTy(10)] assert(v!.value == 1010) v = dVV[TestBridgedKeyTy(20)] assert(v!.value == 1020) v = dVV[TestBridgedKeyTy(30)] assert(v!.value == 1030) } } DictionaryTestSuite.test("DictionaryBridgeFromObjectiveC") { var d = Dictionary<NSObject, AnyObject>(minimumCapacity: 32) d[TestObjCKeyTy(10)] = TestObjCValueTy(1010) d[TestObjCKeyTy(20)] = TestObjCValueTy(1020) d[TestObjCKeyTy(30)] = TestObjCValueTy(1030) // Successful downcast. let dCV = d as! Dictionary<TestObjCKeyTy, TestBridgedValueTy> do { assert(dCV.count == 3) var v = dCV[TestObjCKeyTy(10)] assert(v!.value == 1010) v = dCV[TestObjCKeyTy(20)] assert(v!.value == 1020) v = dCV[TestObjCKeyTy(30)] assert(v!.value == 1030) } // Successful downcast. let dVC = d as! Dictionary<TestBridgedKeyTy, TestObjCValueTy> do { assert(dVC.count == 3) var v = dVC[TestBridgedKeyTy(10)] assert(v!.value == 1010) v = dVC[TestBridgedKeyTy(20)] assert(v!.value == 1020) v = dVC[TestBridgedKeyTy(30)] assert(v!.value == 1030) } // Successful downcast. let dVV = d as! Dictionary<TestBridgedKeyTy, TestBridgedValueTy> do { assert(dVV.count == 3) var v = dVV[TestBridgedKeyTy(10)] assert(v!.value == 1010) v = dVV[TestBridgedKeyTy(20)] assert(v!.value == 1020) v = dVV[TestBridgedKeyTy(30)] assert(v!.value == 1030) } } DictionaryTestSuite.test("DictionaryBridgeFromObjectiveCConditionalEntryPoint") { var d = Dictionary<NSObject, AnyObject>(minimumCapacity: 32) d[TestObjCKeyTy(10)] = TestObjCValueTy(1010) d[TestObjCKeyTy(20)] = TestObjCValueTy(1020) d[TestObjCKeyTy(30)] = TestObjCValueTy(1030) // Successful downcast. if let dCV = _dictionaryBridgeFromObjectiveCConditional(d) as Dictionary<TestObjCKeyTy, TestBridgedValueTy>? { assert(dCV.count == 3) var v = dCV[TestObjCKeyTy(10)] assert(v!.value == 1010) v = dCV[TestObjCKeyTy(20)] assert(v!.value == 1020) v = dCV[TestObjCKeyTy(30)] assert(v!.value == 1030) } else { assert(false) } // Successful downcast. if let dVC = _dictionaryBridgeFromObjectiveCConditional(d) as Dictionary<TestBridgedKeyTy, TestObjCValueTy>? { assert(dVC.count == 3) var v = dVC[TestBridgedKeyTy(10)] assert(v!.value == 1010) v = dVC[TestBridgedKeyTy(20)] assert(v!.value == 1020) v = dVC[TestBridgedKeyTy(30)] assert(v!.value == 1030) } else { assert(false) } // Successful downcast. if let dVV = _dictionaryBridgeFromObjectiveCConditional(d) as Dictionary<TestBridgedKeyTy, TestBridgedValueTy>? { assert(dVV.count == 3) var v = dVV[TestBridgedKeyTy(10)] assert(v!.value == 1010) v = dVV[TestBridgedKeyTy(20)] assert(v!.value == 1020) v = dVV[TestBridgedKeyTy(30)] assert(v!.value == 1030) } else { assert(false) } // Unsuccessful downcasts d["hello" as NSString] = 17 as NSNumber if let dCV = _dictionaryBridgeFromObjectiveCConditional(d) as Dictionary<TestObjCKeyTy, TestBridgedValueTy>?{ assert(false) } if let dVC = _dictionaryBridgeFromObjectiveCConditional(d) as Dictionary<TestBridgedKeyTy, TestObjCValueTy>?{ assert(false) } if let dVV = _dictionaryBridgeFromObjectiveCConditional(d) as Dictionary<TestBridgedKeyTy, TestBridgedValueTy>?{ assert(false) } } DictionaryTestSuite.test("DictionaryBridgeFromObjectiveCConditional") { var d = Dictionary<NSObject, AnyObject>(minimumCapacity: 32) d[TestObjCKeyTy(10)] = TestObjCValueTy(1010) d[TestObjCKeyTy(20)] = TestObjCValueTy(1020) d[TestObjCKeyTy(30)] = TestObjCValueTy(1030) // Successful downcast. if let dCV = d as? Dictionary<TestObjCKeyTy, TestBridgedValueTy> { assert(dCV.count == 3) var v = dCV[TestObjCKeyTy(10)] assert(v!.value == 1010) v = dCV[TestObjCKeyTy(20)] assert(v!.value == 1020) v = dCV[TestObjCKeyTy(30)] assert(v!.value == 1030) } else { assert(false) } // Successful downcast. if let dVC = d as? Dictionary<TestBridgedKeyTy, TestObjCValueTy> { assert(dVC.count == 3) var v = dVC[TestBridgedKeyTy(10)] assert(v!.value == 1010) v = dVC[TestBridgedKeyTy(20)] assert(v!.value == 1020) v = dVC[TestBridgedKeyTy(30)] assert(v!.value == 1030) } else { assert(false) } // Successful downcast. if let dVV = d as? Dictionary<TestBridgedKeyTy, TestBridgedValueTy> { assert(dVV.count == 3) var v = dVV[TestBridgedKeyTy(10)] assert(v!.value == 1010) v = dVV[TestBridgedKeyTy(20)] assert(v!.value == 1020) v = dVV[TestBridgedKeyTy(30)] assert(v!.value == 1030) } else { assert(false) } // Unsuccessful downcasts d["hello" as NSString] = 17 as NSNumber if let dCV = d as? Dictionary<TestObjCKeyTy, TestBridgedValueTy> { assert(false) } if let dVC = d as? Dictionary<TestBridgedKeyTy, TestObjCValueTy> { assert(false) } if let dVV = d as? Dictionary<TestBridgedKeyTy, TestBridgedValueTy> { assert(false) } } #endif // _runtime(_ObjC) //===--- // Tests for APIs implemented strictly based on public interface. We only need // to test them once, not for every storage type. //===--- func getDerivedAPIsDictionary() -> Dictionary<Int, Int> { var d = Dictionary<Int, Int>(minimumCapacity: 10) d[10] = 1010 d[20] = 1020 d[30] = 1030 return d } var DictionaryDerivedAPIs = TestSuite("DictionaryDerivedAPIs") DictionaryDerivedAPIs.test("isEmpty") { do { var empty = Dictionary<Int, Int>() expectTrue(empty.isEmpty) } do { var d = getDerivedAPIsDictionary() expectFalse(d.isEmpty) } } #if _runtime(_ObjC) @objc class MockDictionaryWithCustomCount : NSDictionary { init(count: Int) { self._count = count super.init() } override init() { expectUnreachable() super.init() } override init( objects: UnsafePointer<AnyObject>?, forKeys keys: UnsafePointer<NSCopying>?, count: Int) { expectUnreachable() super.init(objects: objects, forKeys: keys, count: count) } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) not implemented by MockDictionaryWithCustomCount") } @objc(copyWithZone:) override func copy(with zone: NSZone?) -> Any { // Ensure that copying this dictionary produces an object of the same // dynamic type. return self } override func object(forKey aKey: Any) -> Any? { expectUnreachable() return NSObject() } override var count: Int { MockDictionaryWithCustomCount.timesCountWasCalled += 1 return _count } var _count: Int = 0 static var timesCountWasCalled = 0 } func getMockDictionaryWithCustomCount(count: Int) -> Dictionary<NSObject, AnyObject> { return MockDictionaryWithCustomCount(count: count) as Dictionary } func callGenericIsEmpty<C : Collection>(_ collection: C) -> Bool { return collection.isEmpty } DictionaryDerivedAPIs.test("isEmpty/ImplementationIsCustomized") { do { var d = getMockDictionaryWithCustomCount(count: 0) MockDictionaryWithCustomCount.timesCountWasCalled = 0 expectTrue(d.isEmpty) expectEqual(1, MockDictionaryWithCustomCount.timesCountWasCalled) } do { var d = getMockDictionaryWithCustomCount(count: 0) MockDictionaryWithCustomCount.timesCountWasCalled = 0 expectTrue(callGenericIsEmpty(d)) expectEqual(1, MockDictionaryWithCustomCount.timesCountWasCalled) } do { var d = getMockDictionaryWithCustomCount(count: 4) MockDictionaryWithCustomCount.timesCountWasCalled = 0 expectFalse(d.isEmpty) expectEqual(1, MockDictionaryWithCustomCount.timesCountWasCalled) } do { var d = getMockDictionaryWithCustomCount(count: 4) MockDictionaryWithCustomCount.timesCountWasCalled = 0 expectFalse(callGenericIsEmpty(d)) expectEqual(1, MockDictionaryWithCustomCount.timesCountWasCalled) } } #endif // _runtime(_ObjC) DictionaryDerivedAPIs.test("keys") { do { var empty = Dictionary<Int, Int>() var keys = Array(empty.keys) expectTrue(equalsUnordered(keys, [])) } do { var d = getDerivedAPIsDictionary() var keys = Array(d.keys) expectTrue(equalsUnordered(keys, [ 10, 20, 30 ])) } } DictionaryDerivedAPIs.test("values") { do { var empty = Dictionary<Int, Int>() var values = Array(empty.values) expectTrue(equalsUnordered(values, [])) } do { var d = getDerivedAPIsDictionary() var values = Array(d.values) expectTrue(equalsUnordered(values, [ 1010, 1020, 1030 ])) d[11] = 1010 values = Array(d.values) expectTrue(equalsUnordered(values, [ 1010, 1010, 1020, 1030 ])) } } #if _runtime(_ObjC) var ObjCThunks = TestSuite("ObjCThunks") class ObjCThunksHelper : NSObject { dynamic func acceptArrayBridgedVerbatim(_ array: [TestObjCValueTy]) { expectEqual(10, array[0].value) expectEqual(20, array[1].value) expectEqual(30, array[2].value) } dynamic func acceptArrayBridgedNonverbatim(_ array: [TestBridgedValueTy]) { // Cannot check elements because doing so would bridge them. expectEqual(3, array.count) } dynamic func returnArrayBridgedVerbatim() -> [TestObjCValueTy] { return [ TestObjCValueTy(10), TestObjCValueTy(20), TestObjCValueTy(30) ] } dynamic func returnArrayBridgedNonverbatim() -> [TestBridgedValueTy] { return [ TestBridgedValueTy(10), TestBridgedValueTy(20), TestBridgedValueTy(30) ] } dynamic func acceptDictionaryBridgedVerbatim( _ d: [TestObjCKeyTy : TestObjCValueTy]) { expectEqual(3, d.count) expectEqual(1010, d[TestObjCKeyTy(10)]!.value) expectEqual(1020, d[TestObjCKeyTy(20)]!.value) expectEqual(1030, d[TestObjCKeyTy(30)]!.value) } dynamic func acceptDictionaryBridgedNonverbatim( _ d: [TestBridgedKeyTy : TestBridgedValueTy]) { expectEqual(3, d.count) // Cannot check elements because doing so would bridge them. } dynamic func returnDictionaryBridgedVerbatim() -> [TestObjCKeyTy : TestObjCValueTy] { return [ TestObjCKeyTy(10): TestObjCValueTy(1010), TestObjCKeyTy(20): TestObjCValueTy(1020), TestObjCKeyTy(30): TestObjCValueTy(1030), ] } dynamic func returnDictionaryBridgedNonverbatim() -> [TestBridgedKeyTy : TestBridgedValueTy] { return [ TestBridgedKeyTy(10): TestBridgedValueTy(1010), TestBridgedKeyTy(20): TestBridgedValueTy(1020), TestBridgedKeyTy(30): TestBridgedValueTy(1030), ] } } ObjCThunks.test("Array/Accept") { var helper = ObjCThunksHelper() do { helper.acceptArrayBridgedVerbatim( [ TestObjCValueTy(10), TestObjCValueTy(20), TestObjCValueTy(30) ]) } do { TestBridgedValueTy.bridgeOperations = 0 helper.acceptArrayBridgedNonverbatim( [ TestBridgedValueTy(10), TestBridgedValueTy(20), TestBridgedValueTy(30) ]) expectEqual(0, TestBridgedValueTy.bridgeOperations) } } ObjCThunks.test("Array/Return") { var helper = ObjCThunksHelper() do { let a = helper.returnArrayBridgedVerbatim() expectEqual(10, a[0].value) expectEqual(20, a[1].value) expectEqual(30, a[2].value) } do { TestBridgedValueTy.bridgeOperations = 0 let a = helper.returnArrayBridgedNonverbatim() expectEqual(0, TestBridgedValueTy.bridgeOperations) TestBridgedValueTy.bridgeOperations = 0 expectEqual(10, a[0].value) expectEqual(20, a[1].value) expectEqual(30, a[2].value) expectEqual(0, TestBridgedValueTy.bridgeOperations) } } ObjCThunks.test("Dictionary/Accept") { var helper = ObjCThunksHelper() do { helper.acceptDictionaryBridgedVerbatim( [ TestObjCKeyTy(10): TestObjCValueTy(1010), TestObjCKeyTy(20): TestObjCValueTy(1020), TestObjCKeyTy(30): TestObjCValueTy(1030) ]) } do { TestBridgedKeyTy.bridgeOperations = 0 TestBridgedValueTy.bridgeOperations = 0 helper.acceptDictionaryBridgedNonverbatim( [ TestBridgedKeyTy(10): TestBridgedValueTy(1010), TestBridgedKeyTy(20): TestBridgedValueTy(1020), TestBridgedKeyTy(30): TestBridgedValueTy(1030) ]) expectEqual(0, TestBridgedKeyTy.bridgeOperations) expectEqual(0, TestBridgedValueTy.bridgeOperations) } } ObjCThunks.test("Dictionary/Return") { var helper = ObjCThunksHelper() do { let d = helper.returnDictionaryBridgedVerbatim() expectEqual(3, d.count) expectEqual(1010, d[TestObjCKeyTy(10)]!.value) expectEqual(1020, d[TestObjCKeyTy(20)]!.value) expectEqual(1030, d[TestObjCKeyTy(30)]!.value) } do { TestBridgedKeyTy.bridgeOperations = 0 TestBridgedValueTy.bridgeOperations = 0 let d = helper.returnDictionaryBridgedNonverbatim() expectEqual(0, TestBridgedKeyTy.bridgeOperations) expectEqual(0, TestBridgedValueTy.bridgeOperations) TestBridgedKeyTy.bridgeOperations = 0 TestBridgedValueTy.bridgeOperations = 0 expectEqual(3, d.count) expectEqual(1010, d[TestBridgedKeyTy(10)]!.value) expectEqual(1020, d[TestBridgedKeyTy(20)]!.value) expectEqual(1030, d[TestBridgedKeyTy(30)]!.value) expectEqual(0, TestBridgedKeyTy.bridgeOperations) expectEqual(0, TestBridgedValueTy.bridgeOperations) } } #endif // _runtime(_ObjC) //===--- // Check that iterators traverse a snapshot of the collection. //===--- DictionaryTestSuite.test("mutationDoesNotAffectIterator/subscript/store") { var dict = getDerivedAPIsDictionary() var iter = dict.makeIterator() dict[10] = 1011 expectEqualsUnordered( [ (10, 1010), (20, 1020), (30, 1030) ], Array(IteratorSequence(iter))) } DictionaryTestSuite.test("mutationDoesNotAffectIterator/removeValueForKey,1") { var dict = getDerivedAPIsDictionary() var iter = dict.makeIterator() expectOptionalEqual(1010, dict.removeValue(forKey: 10)) expectEqualsUnordered( [ (10, 1010), (20, 1020), (30, 1030) ], Array(IteratorSequence(iter))) } DictionaryTestSuite.test("mutationDoesNotAffectIterator/removeValueForKey,all") { var dict = getDerivedAPIsDictionary() var iter = dict.makeIterator() expectOptionalEqual(1010, dict.removeValue(forKey: 10)) expectOptionalEqual(1020, dict.removeValue(forKey: 20)) expectOptionalEqual(1030, dict.removeValue(forKey: 30)) expectEqualsUnordered( [ (10, 1010), (20, 1020), (30, 1030) ], Array(IteratorSequence(iter))) } DictionaryTestSuite.test( "mutationDoesNotAffectIterator/removeAll,keepingCapacity=false") { var dict = getDerivedAPIsDictionary() var iter = dict.makeIterator() dict.removeAll(keepingCapacity: false) expectEqualsUnordered( [ (10, 1010), (20, 1020), (30, 1030) ], Array(IteratorSequence(iter))) } DictionaryTestSuite.test( "mutationDoesNotAffectIterator/removeAll,keepingCapacity=true") { var dict = getDerivedAPIsDictionary() var iter = dict.makeIterator() dict.removeAll(keepingCapacity: true) expectEqualsUnordered( [ (10, 1010), (20, 1020), (30, 1030) ], Array(IteratorSequence(iter))) } //===--- // Misc tests. //===--- DictionaryTestSuite.test("misc") { do { // Dictionary literal var dict = ["Hello": 1, "World": 2] // Insertion dict["Swift"] = 3 // Access expectOptionalEqual(1, dict["Hello"]) expectOptionalEqual(2, dict["World"]) expectOptionalEqual(3, dict["Swift"]) expectNil(dict["Universe"]) // Overwriting existing value dict["Hello"] = 0 expectOptionalEqual(0, dict["Hello"]) expectOptionalEqual(2, dict["World"]) expectOptionalEqual(3, dict["Swift"]) expectNil(dict["Universe"]) } do { // Dictionaries with other types var d = [ 1.2: 1, 2.6: 2 ] d[3.3] = 3 expectOptionalEqual(1, d[1.2]) expectOptionalEqual(2, d[2.6]) expectOptionalEqual(3, d[3.3]) } do { var d = Dictionary<String, Int>(minimumCapacity: 13) d["one"] = 1 d["two"] = 2 d["three"] = 3 d["four"] = 4 d["five"] = 5 expectOptionalEqual(1, d["one"]) expectOptionalEqual(2, d["two"]) expectOptionalEqual(3, d["three"]) expectOptionalEqual(4, d["four"]) expectOptionalEqual(5, d["five"]) // Iterate over (key, value) tuples as a silly copy var d3 = Dictionary<String,Int>(minimumCapacity: 13) for (k, v) in d { d3[k] = v } expectOptionalEqual(1, d3["one"]) expectOptionalEqual(2, d3["two"]) expectOptionalEqual(3, d3["three"]) expectOptionalEqual(4, d3["four"]) expectOptionalEqual(5, d3["five"]) expectEqual(3, d.values[d.keys.index(of: "three")!]) expectEqual(4, d.values[d.keys.index(of: "four")!]) expectEqual(3, d3.values[d3.keys.index(of: "three")!]) expectEqual(4, d3.values[d3.keys.index(of: "four")!]) } } #if _runtime(_ObjC) DictionaryTestSuite.test("dropsBridgedCache") { // rdar://problem/18544533 // Previously this code would segfault due to a double free in the Dictionary // implementation. // This test will only fail in address sanitizer. var dict = [0:10] do { var bridged: NSDictionary = dict as NSDictionary expectEqual(10, bridged[0 as NSNumber] as! Int) } dict[0] = 11 do { var bridged: NSDictionary = dict as NSDictionary expectEqual(11, bridged[0 as NSNumber] as! Int) } } DictionaryTestSuite.test("getObjects:andKeys:") { let d = ([1: "one", 2: "two"] as Dictionary<Int, String>) as NSDictionary var keys = UnsafeMutableBufferPointer( start: UnsafeMutablePointer<NSNumber>.allocate(capacity: 2), count: 2) var values = UnsafeMutableBufferPointer( start: UnsafeMutablePointer<NSString>.allocate(capacity: 2), count: 2) var kp = AutoreleasingUnsafeMutablePointer<AnyObject?>(keys.baseAddress!) var vp = AutoreleasingUnsafeMutablePointer<AnyObject?>(values.baseAddress!) var null: AutoreleasingUnsafeMutablePointer<AnyObject?>? d.available_getObjects(null, andKeys: null) // don't segfault d.available_getObjects(null, andKeys: kp) expectEqual([2, 1] as [NSNumber], Array(keys)) d.available_getObjects(vp, andKeys: null) expectEqual(["two", "one"] as [NSString], Array(values)) d.available_getObjects(vp, andKeys: kp) expectEqual([2, 1] as [NSNumber], Array(keys)) expectEqual(["two", "one"] as [NSString], Array(values)) } #endif DictionaryTestSuite.test("popFirst") { // Empty do { var d = [Int: Int]() let popped = d.popFirst() expectNil(popped) } do { var popped = [(Int, Int)]() var d: [Int: Int] = [ 1010: 1010, 2020: 2020, 3030: 3030, ] let expected = Array(d.map{($0.0, $0.1)}) while let element = d.popFirst() { popped.append(element) } expectEqualSequence(expected, Array(popped)) { (lhs: (Int, Int), rhs: (Int, Int)) -> Bool in lhs.0 == rhs.0 && lhs.1 == rhs.1 } expectTrue(d.isEmpty) } } DictionaryTestSuite.test("removeAt") { // Test removing from the startIndex, the middle, and the end of a dictionary. for i in 1...3 { var d: [Int: Int] = [ 10: 1010, 20: 2020, 30: 3030, ] let removed = d.remove(at: d.index(forKey: i*10)!) expectEqual(i*10, removed.0) expectEqual(i*1010, removed.1) expectEqual(2, d.count) expectNil(d.index(forKey: i)) let origKeys: [Int] = [10, 20, 30] expectEqual(origKeys.filter { $0 != (i*10) }, d.keys.sorted()) } } DictionaryTestSuite.setUp { resetLeaksOfDictionaryKeysValues() #if _runtime(_ObjC) resetLeaksOfObjCDictionaryKeysValues() #endif } DictionaryTestSuite.tearDown { expectNoLeaksOfDictionaryKeysValues() #if _runtime(_ObjC) expectNoLeaksOfObjCDictionaryKeysValues() #endif } runAllTests()
apache-2.0
a106bdf834915586bc8e434468185cc5
28.049213
285
0.67559
3.961216
false
true
false
false
Byjuanamn/AzureStorageMobileiOS
Azure/Storage/MyVideoBlog/MyVideoBlog/DetailPostController.swift
1
4860
// // DetailPostController.swift // MyVideoBlog // // Created by Juan Antonio Martin Noguera on 23/02/16. // Copyright © 2016 Cloud On Mobile S.L. All rights reserved. // import UIKit import MediaPlayer import MobileCoreServices class DetailPostController: UIViewController { var client : MSClient? var record : AnyObject? @IBOutlet weak var webView : UIWebView! @IBOutlet weak var titulo : UILabel! override func viewDidLoad() { super.viewDidLoad() print(record) // Do any additional setup after loading the view. titulo.text = record!["titulo"] as? String loadBlobFromAzure() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func showBlob (sender: AnyObject){ loadBlobWithAZSSdk() } // Cargar la url del blob /* 1) obtenemos la sas url de la property record, esto es un diccionario con la info del post que hemos selecionado, esto significa que tenemo el nombre del container y del blob. Tenemos que hacer un invoke a nuestra Custom API 2) Esta sas url la usaremos para cargarla en la webview */ func loadBlobFromAzure(){ //1: extraemos del record el nombre del blob y el contenedor let blobName = record!["blobName"] as! String let containerName = record!["containername"] as! String //2: Invocar la Api client?.invokeAPI("urlsastoblobandcontainer", body: nil, HTTPMethod: "GET", parameters: ["blobName" : blobName, "containerName" : containerName], headers: nil, completion: { (result : AnyObject?, response : NSHTTPURLResponse?, error: NSError?) -> Void in if error == nil{ // 2: Tenemos solo la ruta del container/blob + la SASURL let sasURL = result!["sasUrl"] as? String // 3: url del endpoint de Storage var endPoint = "https://videoblogapp.blob.core.windows.net" endPoint += sasURL! // ahora le pasamo la url a la webView dispatch_async(dispatch_get_main_queue(), { () -> Void in self.webView.loadRequest(NSURLRequest(URL: NSURL(string: endPoint)!)) }) } }) } /* // MARK: en esta funcion usamos el SDK para descargar el blob del registro */ func loadBlobWithAZSSdk(){ //1: extraemos del record el nombre del blob y el contenedor let blobName = record!["blobName"] as! String let containerName = record!["containername"] as! String //2: Invocar la Api client?.invokeAPI("urlsastoblobandcontainer", body: nil, HTTPMethod: "GET", parameters: ["blobName" : blobName, "containerName" : containerName], headers: nil, completion: { (result : AnyObject?, response : NSHTTPURLResponse?, error: NSError?) -> Void in if error == nil{ // 2: Tenemos solo la ruta del container/blob + la SASURL let sasURL = result!["sasUrl"] as? String // 3: url del endpoint de Storage var endPoint = kEndpointAzureStorage endPoint += sasURL! let blob = AZSCloudBlockBlob(url: NSURL(string: endPoint)!) blob.downloadToDataWithCompletionHandler({ (error: NSError?, data : NSData?) -> Void in if let _ = error { print("Tenemos un error --> \(error)") } else { let path = saveInDocuments(data!) dispatch_async(dispatch_get_main_queue(), { () -> Void in let moviPlayer = MPMoviePlayerViewController(contentURL: path) self.presentMoviePlayerViewControllerAnimated(moviPlayer) }) } }) } }) } } extension UINavigationControllerDelegate { }
mit
eceb0d33a8752cb767edd2722e903b1b
31.393333
232
0.4929
5.416945
false
false
false
false
urdnot-ios/ShepardAppearanceConverter
ShepardAppearanceConverter/ShepardAppearanceConverter/Views/Shepards/ShepardsController.swift
1
4555
// // ShepardsController.swift // ShepardAppearanceConverter // // Created by Emily Ivie on 8/12/15. // Copyright © 2015 urdnot. All rights reserved. // import UIKit class ShepardsController: UITableViewController { lazy var games: [GameSequence] = [] var updating = true override func viewDidLoad() { super.viewDidLoad() if isInterfaceBuilder { dummyData() } setupPage() App.onCurrentShepardChange.listen(self) { [weak self] (shepard) in if self?.updating == false { self?.setupPage(reloadData: true) } } // don't think we need this? // SavedGames.onShepardsListChange.listen(self) { [weak self] (shepard) in // if self?.updating == false { // self?.setupPage(reloadData: true) // } // } } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) } //MARK: Actions //MARK: Setup Page Elements func setupPage(reloadData reloadData: Bool = false) { tableView.allowsMultipleSelectionDuringEditing = false setupTableCustomCells() setupGames() if reloadData { tableView.reloadData() } updating = false } //MARK: Protocol - UITableViewDelegate override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return games.count } // override func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { // return 1 // } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { if let cell = tableView.dequeueReusableCellWithIdentifier("Shepard Row") as? ShepardRowCell { setupGameRow(indexPath.row, cell: cell) return cell } return super.tableView(tableView, cellForRowAtIndexPath: indexPath) } override func tableView(tableView: UITableView, estimatedHeightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return 91 } var prepareAfterIBIncludedSegue: PrepareAfterIBIncludedSegueType = { destination in } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { if indexPath.row < games.count { view.userInteractionEnabled = false let game = games[indexPath.row] App.changeGame(game) parentViewController?.performSegueWithIdentifier("Select Shepard", sender: nil) view.userInteractionEnabled = true } } override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { return true } override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { if indexPath.row < games.count { view.userInteractionEnabled = false updating = true var game = games.removeAtIndex(indexPath.row) game.delete() setupGames() tableView.beginUpdates() tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Automatic) tableView.endUpdates() updating = false view.userInteractionEnabled = true } } } //MARK: Table Elements func setupTableCustomCells() { let bundle = NSBundle(forClass: self.dynamicType) tableView.registerNib(UINib(nibName: "ShepardRowCell", bundle: bundle), forCellReuseIdentifier: "Shepard Row") } //MARK: Table Data func dummyData() { App.addNewGame() App.addNewGame() } func setupGames() { games = App.allGames.sortedUnfaultedGames() } func setupGameRow(row: Int, cell: ShepardRowCell) { if row < games.count { let shepard = games[row].shepard cell.photo = shepard.photo.image() cell.name = shepard.fullName cell.title = shepard.title cell.date = shepard.modifiedDate.format(.Typical) } } }
mit
7cd44fb9b49e1fbdb8ba86a8935f77f3
29.77027
157
0.612648
5.408551
false
false
false
false
xedin/swift
test/Serialization/extension-of-typealias.swift
3
1311
// RUN: %empty-directory(%t) // RUN: %target-swift-frontend -emit-module -module-name Library -o %t -D LIBRARY %s // RUN: %target-swift-ide-test -print-module -module-to-print=Library -I %t -source-filename=%s | %FileCheck %s // RUN: %target-swift-frontend -typecheck -I %t %s -verify // Check that base types of extensions are desugared. This isn't necessarily // the behavior we want long-term, but it's the behavior we need right now. #if LIBRARY public typealias Zahl = Int // CHECK: typealias List // CHECK: typealias Zahl // CHECK-LABEL: extension Int { extension Zahl { // CHECK-NEXT: addedMember() public func addedMember() {} } // CHECK-NEXT: {{^}$}} public typealias List<T> = Array<T> // CHECK-LABEL: extension Array { extension List { // CHECK-NEXT: addedMember() public func addedMember() {} } // CHECK-NEXT: {{^}$}} // CHECK-LABEL: extension Array where Element == Int { extension List where Element == Int { // CHECK-NEXT: addedMemberInt() public func addedMemberInt() {} } // CHECK-NEXT: {{^}$}} #else import Library func test(x: Int) { x.addedMember() [x].addedMember() [x].addedMemberInt() ([] as [Bool]).addedMemberInt() // expected-error {{referencing instance method 'addedMemberInt()' on 'Array' requires the types 'Bool' and 'Int' be equivalent}} } #endif
apache-2.0
899e1d24e0a28eb20d2866dd867f0bcb
26.893617
163
0.680397
3.361538
false
false
false
false
alexbasson/postit-note
PostItNote/Controllers/RequestBuilderViewController.swift
1
2100
import Cocoa class RequestBuilderViewController: NSViewController { @IBOutlet weak var requestView: RequestView? @IBOutlet weak var responseView: ResponseView? var session = NSURLSession.sharedSession() func configure(session: NSURLSession) { self.session = session } override func viewDidLoad() { super.viewDidLoad() setupHTTPMethodMenu() } @IBAction func sendButtonTapped(sender: NSButton) { let task = session.dataTaskWithRequest(self.requestFromFields()) { (data: NSData?, response: NSURLResponse?, error: NSError?) -> Void in if let data = data, response = response as? NSHTTPURLResponse, responseView = self.responseView, httpStatusLabel = responseView.httpStatusLabel, responseBodyTextView = responseView.responseBodyTextView { performOnMainQueue() { httpStatusLabel.stringValue = "\(response.statusCode)" responseBodyTextView.string = String(data: data, encoding: NSUTF8StringEncoding)! } } } task.resume() } } extension RequestBuilderViewController { func requestFromFields() -> NSURLRequest { let request = NSMutableURLRequest() if let requestView = self.requestView, httpMethodPopUpButton = requestView.httpMethodPopUpButton, method = httpMethodPopUpButton.titleOfSelectedItem, urlTextField = requestView.urlTextField { request.HTTPMethod = method request.URL = NSURL(string: urlTextField.stringValue) } return request } } extension RequestBuilderViewController { func setupHTTPMethodMenu() { if let requestView = self.requestView, httpMethodPopUpButton = requestView.httpMethodPopUpButton { let menu = NSMenu(title: "method") menu.addItemWithTitle("GET", action: nil, keyEquivalent: "") menu.addItemWithTitle("POST", action: nil, keyEquivalent: "") menu.addItemWithTitle("PATCH", action: nil, keyEquivalent: "") menu.addItemWithTitle("DELETE", action: nil, keyEquivalent: "") httpMethodPopUpButton.menu = menu } } }
mit
3ca56465030180ae3c0438cc8daa7c86
29.897059
91
0.695714
4.988124
false
false
false
false
rshankras/WordPress-iOS
WordPress/Classes/ViewRelated/Notifications/Tools/NotificationMediaDownloader.swift
10
10424
import Foundation /** * @class NotificationMediaDownloader * @brief The purpose of this class is to provide a simple API to download assets from the web. * @details Assets are downloaded, and resized to fit a maximumWidth, specified in the initial download call. * Internally, images get downloaded and resized: both copies of the image get cached. * Since the user may rotate the device, we also provide a second helper (resizeMediaWithIncorrectSize), * which will take care of resizing the original image, to fit the new orientation. */ @objc public class NotificationMediaDownloader : NSObject { // // MARK: - Public Methods // deinit { downloadQueue.cancelAllOperations() } /** * @brief Downloads a set of assets, resizes them (if needed), and hits a completion block. * @details The completion block will get called just once all of the assets are downloaded, and properly sized. * * @param urls Is the collection of unique Image URL's we'd need to download. * @param maximumWidth Represents the maximum width that a returned image should have * @param completion Is a closure that will get executed once all of the assets are ready */ public func downloadMedia(#urls: Set<NSURL>, maximumWidth: CGFloat, completion: SuccessBlock) { let missingUrls = filter(urls) { self.shouldDownloadImage(url: $0) } let group = dispatch_group_create() var shouldHitCompletion = !missingUrls.isEmpty for url in missingUrls { dispatch_group_enter(group) downloadImage(url) { (error: NSError?, image: UIImage?) in // On error: Don't proceed any further if error != nil || image == nil { dispatch_group_leave(group) return } // On success: Cache the original image, and resize (if needed) self.originalImagesMap[url] = image! self.resizeImageIfNeeded(image!, maximumWidth: maximumWidth) { self.resizedImagesMap[url] = $0 dispatch_group_leave(group) } } } // When all of the workers are ready, hit the completion callback, *if needed* if !shouldHitCompletion { return } dispatch_group_notify(group, dispatch_get_main_queue()) { completion() } } /** * @brief Resizes the downloaded media to fit a "new" maximumWidth ***if needed**. * @details This method will check the cache of "resized images", and will verify if the original image * *could* be resized again, so that it better fits the *maximumWidth* received. * Once all of the images get resized, we'll hit the completion block * * Useful to handle rotation events: the downloaded images may need to be resized, again, to * fit onscreen. * * @param maximumWidth Represents the maximum width that a returned image should have * @param completion Is a closure that will get executed just one time, after all of the assets get resized */ public func resizeMediaWithIncorrectSize(maximumWidth: CGFloat, completion: SuccessBlock) { let group = dispatch_group_create() var shouldHitCompletion = false for (url, originalImage) in originalImagesMap { let targetSize = cappedImageSize(originalImage.size, maximumWidth: maximumWidth) let resizedImage = resizedImagesMap[url] if resizedImage == nil || resizedImage?.size == targetSize { continue } dispatch_group_enter(group) shouldHitCompletion = true resizeImageIfNeeded(originalImage, maximumWidth: maximumWidth) { self.resizedImagesMap[url] = $0 dispatch_group_leave(group) } } dispatch_group_notify(group, dispatch_get_main_queue()) { if shouldHitCompletion { completion() } } } /** * @brief Returns a collection of images, ready to be displayed onscreen. * @details For convenience, we return a map with URL as Key, and Image as Value, so that each asset can be * easily addressed. * * @param urls The collection of URL's of the assets you'd need. * @returns A dictionary with URL as Key, and Image as Value. */ public func imagesForUrls(urls: [NSURL]) -> [NSURL: UIImage] { var filtered = [NSURL: UIImage]() for (url, image) in resizedImagesMap { if contains(urls, url) { filtered[url] = image } } return filtered } // // MARK: - Private Helpers // /** * @brief Downloads an asset, given its URL * @details On failure, this method will attempt the download *maximumRetryCount* times. * If the URL cannot be downloaded, it'll be marked to be skipped. * * @param url The URL of the media we should download * @param retryCount Number of times the download has been attempted * @param success A closure to be executed, on success. */ private func downloadImage(url: NSURL, retryCount: Int = 0, completion: ((NSError?, UIImage?) -> ())) { let request = NSMutableURLRequest(URL: url) request.HTTPShouldHandleCookies = false request.addValue("image/*", forHTTPHeaderField: "Accept") let operation = AFHTTPRequestOperation(request: request) operation.responseSerializer = responseSerializer operation.setCompletionBlockWithSuccess({ (AFHTTPRequestOperation operation, AnyObject responseObject) -> Void in if let unwrappedImage = responseObject as? UIImage { completion(nil, unwrappedImage) } else { let error = NSError(domain: self.downloaderDomain, code: self.emptyMediaErrorCode, userInfo: nil) completion(error, nil) } self.urlsBeingDownloaded.remove(url) }, failure: { (AFHTTPRequestOperation operation, NSError error) -> Void in // If possible, retry if retryCount < self.maximumRetryCount { self.downloadImage(url, retryCount: retryCount + 1, completion: completion) // Otherwise, we just failed! } else { completion(error, nil) self.urlsBeingDownloaded.remove(url) self.urlsFailed.insert(url) } }) downloadQueue.addOperation(operation) urlsBeingDownloaded.insert(url) } /** * @brief Checks if an image should be downloaded, or not. * @details An image should be downloaded if: * * - It's not already being downloaded * - Isn't already in the cache! * - Hasn't exceeded the retry count * * @param urls The collection of URL's of the assets you'd need. * @returns A dictionary with URL as Key, and Image as Value. */ private func shouldDownloadImage(#url: NSURL) -> Bool { return originalImagesMap[url] == nil && !urlsBeingDownloaded.contains(url) && !urlsFailed.contains(url) } /** * @brief Resizes -in background- a given image, if needed, to fit a maximum width * * @param image The image to resize * @param maximumWidth The maximum width in which the image should fit * @param callback A closure to be called, on the main thread, on completion */ private func resizeImageIfNeeded(image: UIImage, maximumWidth: CGFloat, callback: ((UIImage) -> ())) { let targetSize = cappedImageSize(image.size, maximumWidth: maximumWidth) if image.size == targetSize { callback(image) return } dispatch_async(resizeQueue) { let resizedImage = image.resizedImage(targetSize, interpolationQuality: kCGInterpolationHigh) dispatch_async(dispatch_get_main_queue()) { callback(resizedImage) } } } /** * @brief Returns the scaled size, scaled down proportionally (if needed) to fit a maximumWidth * * @param originalSize The original size of the image * @param maximumWidth The maximum width we've got available * @return The size, scaled down proportionally (if needed) to fit a maximum width */ private func cappedImageSize(originalSize: CGSize, maximumWidth: CGFloat) -> CGSize { var targetSize = originalSize if targetSize.width > maximumWidth { targetSize.height = round(maximumWidth * targetSize.height / targetSize.width) targetSize.width = maximumWidth } return targetSize } // MARK: - Public Aliases public typealias SuccessBlock = (Void -> Void) // MARK: - Private Constants private let maximumRetryCount = 3 private let emptyMediaErrorCode = -1 private let downloaderDomain = "notifications.media.downloader" // MARK: - Private Properties private let responseSerializer = AFImageResponseSerializer() private let downloadQueue = NSOperationQueue() private let resizeQueue = dispatch_queue_create("notifications.media.resize", DISPATCH_QUEUE_CONCURRENT) private var originalImagesMap = [NSURL: UIImage]() private var resizedImagesMap = [NSURL: UIImage]() private var urlsBeingDownloaded = Set<NSURL>() private var urlsFailed = Set<NSURL>() }
gpl-2.0
4ad24181dd54d086a29f4d86305fb9ae
40.52988
122
0.582502
5.060194
false
false
false
false
honghaoz/CrackingTheCodingInterview
Swift/LeetCode/Trivial - 不需要看的题目/509_Fibonacci Number.swift
1
1437
// 509_Fibonacci Number // https://leetcode.com/problems/fibonacci-number/ // // Created by Honghao Zhang on 10/5/19. // Copyright © 2019 Honghaoz. All rights reserved. // // Description: // The Fibonacci numbers, commonly denoted F(n) form a sequence, called the Fibonacci sequence, such that each number is the sum of the two preceding ones, starting from 0 and 1. That is, // //F(0) = 0, F(1) = 1 //F(N) = F(N - 1) + F(N - 2), for N > 1. //Given N, calculate F(N). // // // //Example 1: // //Input: 2 //Output: 1 //Explanation: F(2) = F(1) + F(0) = 1 + 0 = 1. //Example 2: // //Input: 3 //Output: 2 //Explanation: F(3) = F(2) + F(1) = 1 + 1 = 2. //Example 3: // //Input: 4 //Output: 3 //Explanation: F(4) = F(3) + F(2) = 2 + 1 = 3. // // //Note: // //0 ≤ N ≤ 30. // import Foundation class Num509 { // Iterative, keep last two numbers func fib(_ N: Int) -> Int { if N == 0 { return 0 } if N == 1 { return 1 } var last1 = 1 var last2 = 0 var n = 2 while n < N { let last = last1 + last2 last2 = last1 last1 = last n += 1 } return last1 + last2 } // MARK: - Recursive Top Down var cache: [Int: Int] = [:] func fib_recursive(_ N: Int) -> Int { if let result = cache[N] { return result } if N <= 1 { cache[N] = N return N } let num = fib(N - 1) + fib(N - 2) cache[N] = num return num } }
mit
ab4261fe558b244f11b05f7f09bb7b79
17.126582
187
0.52933
2.824458
false
false
false
false
soapyigu/LeetCode_Swift
DP/MaximumSumThreeNonOverlappingSubarrays.swift
1
2385
/** * Question Link: https://leetcode.com/problems/maximum-sum-of-3-non-overlapping-subarrays/ * Primary idea: Dynamic Programming, find point where sum of [0, i - 1], [i, i + k - 1], [i + k, count - 1] is largest, where k <= i <= count - 2k * Time Complexity: O(n), Space Complexity: O(n) * */ class MaximumSumThreeNonOverlappingSubarrays { func maxSumOfThreeSubarrays(_ nums: [Int], _ k: Int) -> [Int] { let sums = createSums(nums), n = nums.count let leftIndices = createLeftIndices(sums, n, k), rightIndices = createRightIndices(sums, n, k) var total = 0, res = [-1, -1, -1] for i in k...n - 2 * k { let l = leftIndices[i - 1], r = rightIndices[i + k] let currentTotal = (sums[i+k] - sums[i]) + (sums[l + k] - sums[l]) + (sums[r + k] - sums[r]) if currentTotal > total { total = currentTotal res = [l, i, r] } } return res } fileprivate func createSums(_ nums: [Int]) -> [Int] { var sums = [0], currentSum = 0 for num in nums { currentSum += num sums.append(currentSum) } return sums } // DP for starting index of left fileprivate func createLeftIndices(_ sums: [Int], _ n: Int, _ k: Int) -> [Int] { var leftIndices = Array(repeating: 0, count: n), maxSum = sums[k] - sums[0] for i in k..<n { if sums[i + 1] - sums[i + 1 - k] > maxSum { leftIndices[i] = i + 1 - k maxSum = sums[i + 1] - sums[i + 1 - k] } else { leftIndices[i] = leftIndices[i - 1] } } return leftIndices } // DP for starting index of right fileprivate func createRightIndices(_ sums: [Int], _ n: Int, _ k: Int) -> [Int] { var rightIndices = Array(repeating: 0, count: n), maxSum = sums[n] - sums[n - k] rightIndices[n - k] = n - k for i in (0...n - k - 1).reversed() { if sums[i + k] - sums[i] >= maxSum { rightIndices[i] = i maxSum = sums[i + k] - sums[i] } else { rightIndices[i] = rightIndices[i + 1] } } return rightIndices } }
mit
60ce0906d75d65cde56ec5c823aca511
32.605634
147
0.477568
3.591867
false
false
false
false
One-self/ZhihuDaily
ZhihuDaily/ZhihuDaily/Classes/View/ZDHeadImageView.swift
1
3675
// // ZDHeadImageView.swift // ZhihuDaily // // Created by Oneselfly on 2017/5/26. // Copyright © 2017年 Oneself. All rights reserved. // import UIKit class ZDHeadImageView: UIView { fileprivate var currentPage = 0 @IBOutlet weak var leftImageView: UIImageView! @IBOutlet weak var leftlabel: UILabel! @IBOutlet weak var centerImageView: UIImageView! @IBOutlet weak var centerLabel: UILabel! @IBOutlet weak var rightImageView: UIImageView! @IBOutlet weak var rightLabel: UILabel! @IBOutlet weak var pageControl: UIPageControl! var topStories: [ZDStory] = [ZDStory]() { didSet { let centerStory = topStories[(currentPage + topStories.count) % topStories.count] centerLabel.text = centerStory.title centerImageView.setImage(url: centerStory.image) let leftStory = getLeftStory(currentPage: currentPage) leftlabel.text = leftStory.title leftImageView.setImage(url: leftStory.image) let rightStory = getRightStory(currentPage: currentPage) rightLabel.text = rightStory.title rightImageView.setImage(url: rightStory.image) pageControl.numberOfPages = topStories.count } } @IBOutlet weak var scrollView: ZDScrollView! @IBOutlet weak var stackView: UIStackView! class func headImageView() -> ZDHeadImageView { let nib = UINib(nibName: "ZDHeadImageView", bundle: nil) let view = nib.instantiate(withOwner: nil, options: nil)[0] as! ZDHeadImageView view.bounds = CGRect(x: 0, y: 0, width: 0, height: 200) return view } fileprivate func leftPage(currentPage: Int) -> Int { return (currentPage - 1 + topStories.count) % topStories.count } fileprivate func rightPage(currentPage: Int) -> Int { return (currentPage + 1 + topStories.count) % topStories.count } fileprivate func getLeftStory(currentPage: Int) -> ZDStory { return topStories[leftPage(currentPage: currentPage)] } fileprivate func getRightStory(currentPage: Int) -> ZDStory { return topStories[rightPage(currentPage: currentPage)] } } extension ZDHeadImageView: UIScrollViewDelegate { func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) { if scrollView.contentOffset.x > scrollView.width { let currentStory = getRightStory(currentPage: currentPage) centerLabel.text = currentStory.title centerImageView.setImage(url: currentStory.image) currentPage = rightPage(currentPage: currentPage) } else if scrollView.contentOffset.x < scrollView.width { let currentStory = getLeftStory(currentPage: currentPage) centerLabel.text = currentStory.title centerImageView.setImage(url: currentStory.image) currentPage = leftPage(currentPage: currentPage) } else { } scrollView.setContentOffset(CGPoint(x: scrollView.width, y: 0), animated: false) let leftStory = getLeftStory(currentPage: currentPage) leftlabel.text = leftStory.title leftImageView.setImage(url: leftStory.image) let rightStory = getRightStory(currentPage: currentPage) rightLabel.text = rightStory.title rightImageView.setImage(url: rightStory.image) pageControl.currentPage = currentPage } }
mit
9ef0ea76b3e1aa01addcbb2e66fc3c0c
31.785714
93
0.631808
5.016393
false
false
false
false
iAugux/Zoom-Contacts
Phonetic/Extensions/UIColor+Extension.swift
1
1077
// // UIColor+Extension.swift // // Created by Augus on 9/4/15. // Copyright © 2015 iAugus. All rights reserved. // import UIKit extension UIColor { class func randomColor() -> UIColor{ let randomRed = CGFloat(drand48()) let randomGreen = CGFloat(drand48()) let randomBlue = CGFloat(drand48()) return UIColor(red: randomRed, green: randomGreen, blue: randomBlue, alpha: 1.0) } func darkerColor(delta: CGFloat) -> UIColor { var h = CGFloat(0) var s = CGFloat(0) var b = CGFloat(0) var a = CGFloat(0) self.getHue(&h, saturation: &s, brightness: &b, alpha: &a) return UIColor(hue: h, saturation: s, brightness: b * delta, alpha: a) } func lighterColor(delta: CGFloat) -> UIColor { var h = CGFloat(0) var s = CGFloat(0) var b = CGFloat(0) var a = CGFloat(0) self.getHue(&h, saturation: &s, brightness: &b, alpha: &a) return UIColor(hue: h, saturation: s * delta, brightness: b, alpha: a) } }
mit
7a661796106f6ced05f58c506d31ed60
28.888889
96
0.57342
3.723183
false
false
false
false
andyyardley/React
React/RHashObject.swift
1
2032
// // RHashObject.swift // placesapp // // Created by Andy on 10/12/2015. // Copyright © 2015 niveusrosea. All rights reserved. // import Foundation import NSHash //func __hashFromString(string: String) -> String //{ // let data = (string as NSString).dataUsingEncoding(NSUTF8StringEncoding) // assert(data != nil) // return __sha256(data!).hexString() as String //} // //func __sha256(data : NSData) -> NSData //{ // var hash = [UInt8](count: Int(CC_SHA256_DIGEST_LENGTH), repeatedValue: 0) // CC_SHA256(data.bytes, CC_LONG(data.length), &hash) // let res = NSData(bytes: hash, length: Int(CC_SHA256_DIGEST_LENGTH)) // return res //} enum RHashObjectError: ErrorType { case CannotGenerateHash } public protocol RHashObject { func contentsHash() -> String } extension RHashObject { public func hashFromString(string: String) -> String { return string.SHA256() } } extension NSData { func hexString() -> NSString { let str = NSMutableString() let bytes = UnsafeBufferPointer<UInt8>(start: UnsafePointer(self.bytes), count:self.length) for byte in bytes { str.appendFormat("%02hhx", byte) } return str } } extension CustomStringConvertible { public func contentsHash() -> String { return description.SHA256() } } extension Array: RHashObject { public func contentsHash() -> String { var output = "" for item in self { if let item = item as? RHashObject { output += item.contentsHash() } else if let item = item as? CustomStringConvertible { output += item.description } else { print("Cannot Hash") } } return hashFromString(output) } } extension Int: RHashObject { public func contentsHash() -> String { return hashFromString(String(self)) } }
apache-2.0
d60265a8d4981dd98abfd3d777b2c53e
19.32
99
0.583949
3.982353
false
false
false
false
kpiteira/MobileAzureDevDays
Swift/MobileAzureDevDays/MobileAzureDevDays/SentimentKeyResponse.swift
2
566
// // SentimentKeyResponse.swift // MobileAzureDevDays // // Created by Karl Piteira on 10/9/17. // Copyright © 2017 Colby Williams. All rights reserved. // import Foundation class SentimentApiKeyDocument { let regionKey = "region" let keyKey = "key" var region:String! var key:String! init?(fromJson dict: [String:Any]) { if let region = dict[regionKey] as? String, let key = dict[keyKey] as? String { self.region = region self.key = key } else { return nil } } }
mit
8e7ae7de9f1ace2acd5526a4e23be160
20.730769
87
0.59115
3.668831
false
false
false
false
RyanMacG/poppins
Poppins/Models/Async.swift
3
422
private let queue = AsyncQueue(name: "PoppinsSyncQueue", maxOperations: 10) class Async { private var _done: (() -> ())? class func map<U, T>(u: [U], f: U -> T) -> Async { var proc = Async() u.map { x in queue.addOperationWithBlock { _ = f(x) } } queue.finally { _ = proc._done?() } return proc } func done(f: () -> ()) { _done = f } }
mit
32b38193501cc9043c4b63f101fc9b86
19.095238
75
0.471564
3.487603
false
false
false
false
mixalich7b/SwiftTBot
Sources/SwiftTBot/Helper/TBLimitedLengthTextTransform.swift
1
1032
// // TBLimitedLengthTextTransform.swift // SwiftTBot // // Created by Тупицин Константин on 26.04.16. // Copyright © 2016 mixalich7b. All rights reserved. // import ObjectMapper public final class TBLimitedLengthTextTransform: TransformType { public typealias Object = String public typealias JSON = String private let maxLength: Int // in bytes public init(maxLength: Int) { self.maxLength = maxLength } public func transformFromJSON(_ value: Any?) -> String? { if let text = value as? String { return text } return nil } public func transformToJSON(_ value: String?) -> String? { if let text = value { let buffer = text.utf8 if buffer.count > self.maxLength { return String(buffer[buffer.startIndex..<buffer.index(buffer.startIndex, offsetBy: self.maxLength)]) } else { return text } } return nil } }
gpl-3.0
663312f63c022da8cfbcea8e8f7f56e4
25
116
0.593688
4.46696
false
false
false
false
alessiobrozzi/firefox-ios
ClientTests/SearchTests.swift
2
6915
/* 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 GCDWebServers @testable import Client import UIKit import XCTest class SearchTests: XCTestCase { func testParsing() { let parser = OpenSearchParser(pluginMode: true) let file = Bundle.main.path(forResource: "google", ofType: "xml", inDirectory: "SearchPlugins/en") let engine: OpenSearchEngine! = parser.parse(file!, engineID: "google") XCTAssertEqual(engine.shortName, "Google") // Test regular search queries. XCTAssertEqual(engine.searchURLForQuery("foobar")!.absoluteString, "https://www.google.com/search?q=foobar&ie=utf-8&oe=utf-8&client=firefox-b") // Test search suggestion queries. XCTAssertEqual(engine.suggestURLForQuery("foobar")!.absoluteString, "https://www.google.com/complete/search?client=firefox&q=foobar") } func testURIFixup() { // Check valid URLs. We can load these after some fixup. checkValidURL("http://www.mozilla.org", afterFixup: "http://www.mozilla.org") checkValidURL("about:", afterFixup: "about:") checkValidURL("about:config", afterFixup: "about:config") checkValidURL("about: config", afterFixup: "about:%20config") checkValidURL("file:///f/o/o", afterFixup: "file:///f/o/o") checkValidURL("ftp://ftp.mozilla.org", afterFixup: "ftp://ftp.mozilla.org") checkValidURL("foo.bar", afterFixup: "http://foo.bar") checkValidURL(" foo.bar ", afterFixup: "http://foo.bar") checkValidURL("1.2.3", afterFixup: "http://1.2.3") checkValidURL("http://创业咖啡.中国/", afterFixup: "http://xn--vhq70hq9bhxa.xn--fiqs8s/") checkValidURL("创业咖啡.中国", afterFixup: "http://xn--vhq70hq9bhxa.xn--fiqs8s") checkValidURL(" 创业咖啡.中国 ", afterFixup: "http://xn--vhq70hq9bhxa.xn--fiqs8s") // Check invalid URLs. These are passed along to the default search engine. checkInvalidURL("foobar") checkInvalidURL("foo bar") checkInvalidURL("mozilla. org") checkInvalidURL("123") checkInvalidURL("a/b") checkInvalidURL("创业咖啡") checkInvalidURL("创业咖啡 中国") checkInvalidURL("创业咖啡. 中国") } fileprivate func checkValidURL(_ beforeFixup: String, afterFixup: String) { XCTAssertEqual(URIFixup.getURL(beforeFixup)!.absoluteString, afterFixup) } fileprivate func checkInvalidURL(_ beforeFixup: String) { XCTAssertNil(URIFixup.getURL(beforeFixup)) } func testSuggestClient() { let webServerBase = startMockSuggestServer() let engine = OpenSearchEngine(engineID: "mock", shortName: "Mock engine", image: UIImage(), searchTemplate: "", suggestTemplate: "\(webServerBase)?q={searchTerms}", isCustomEngine: false) let client = SearchSuggestClient(searchEngine: engine, userAgent: "Fx-testSuggestClient") let query1 = self.expectation(description: "foo query") client.query("foo", callback: { response, error in withExtendedLifetime(client) { if error != nil { XCTFail("Error: \(error?.description)") } XCTAssertEqual(response![0], "foo") XCTAssertEqual(response![1], "foo2") XCTAssertEqual(response![2], "foo you") query1.fulfill() } }) waitForExpectations(timeout: 10, handler: nil) let query2 = self.expectation(description: "foo bar query") client.query("foo bar", callback: { response, error in withExtendedLifetime(client) { if error != nil { XCTFail("Error: \(error?.description)") } XCTAssertEqual(response![0], "foo bar soap") XCTAssertEqual(response![1], "foo barstool") XCTAssertEqual(response![2], "foo bartender") query2.fulfill() } }) waitForExpectations(timeout: 10, handler: nil) } func testExtractingOfSearchTermsFromURL() { let parser = OpenSearchParser(pluginMode: true) var file = Bundle.main.path(forResource: "google", ofType: "xml", inDirectory: "SearchPlugins/en") let googleEngine: OpenSearchEngine! = parser.parse(file!, engineID: "google") // create URL let searchTerm = "Foo Bar" let encodedSeachTerm = searchTerm.replacingOccurrences(of: " ", with: "+") let googleSearchURL = URL(string: "https://www.google.com/search?q=\(encodedSeachTerm)&ie=utf-8&oe=utf-8&gws_rd=cr&ei=I0UyVp_qK4HtUoytjagM") let duckDuckGoSearchURL = URL(string: "https://duckduckgo.com/?q=\(encodedSeachTerm)&ia=about") let invalidSearchURL = URL(string: "https://www.google.co.uk") // check it correctly matches google search term given google config XCTAssertEqual(searchTerm, googleEngine.queryForSearchURL(googleSearchURL)) // check it doesn't match when the URL is not a search URL XCTAssertNil(googleEngine.queryForSearchURL(invalidSearchURL)) // check that it matches given a different configuration file = Bundle.main.path(forResource: "duckduckgo", ofType: "xml", inDirectory: "SearchPlugins/en") let duckDuckGoEngine: OpenSearchEngine! = parser.parse(file!, engineID: "duckduckgo") XCTAssertEqual(searchTerm, duckDuckGoEngine.queryForSearchURL(duckDuckGoSearchURL)) // check it doesn't match search URLs for different configurations XCTAssertNil(duckDuckGoEngine.queryForSearchURL(googleSearchURL)) // check that if you pass in a nil URL that everything works XCTAssertNil(duckDuckGoEngine.queryForSearchURL(nil)) } fileprivate func startMockSuggestServer() -> String { let webServer: GCDWebServer = GCDWebServer() webServer.addHandler(forMethod: "GET", path: "/", request: GCDWebServerRequest.self) { (request) -> GCDWebServerResponse! in var suggestions: [String]! let query = request?.query["q"] as! String switch query { case "foo": suggestions = ["foo", "foo2", "foo you"] case "foo bar": suggestions = ["foo bar soap", "foo barstool", "foo bartender"] default: XCTFail("Unexpected query: \(query)") } return GCDWebServerDataResponse(jsonObject: [query, suggestions]) } if !webServer.start(withPort: 0, bonjourName: nil) { XCTFail("Can't start the GCDWebServer") } return "http://localhost:\(webServer.port)" } }
mpl-2.0
f92107f49884722e0dd29bbfafcfd6f5
44.046053
172
0.636629
4.263387
false
true
false
false
mozilla-mobile/firefox-ios
Client/Frontend/Contextual Hint/ContextualHintCopyProvider.swift
2
3837
// 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 enum ContextualHintCopyType { case action, description } /// `ContextualHintCopyProvider` exists to provide the requested description or action strings back /// for the specified `ContextualHintType`. struct ContextualHintCopyProvider: FeatureFlaggable { typealias CFRStrings = String.ContextualHints /// Arrow direction infuences toolbar copy, so it exists here. private var arrowDirection: UIPopoverArrowDirection? init(arrowDirecton: UIPopoverArrowDirection? = nil) { self.arrowDirection = arrowDirecton } // MARK: - Public interface /// Returns the copy for the requested part of the CFR (`ContextualHintCopyType`) for the specified /// hint. /// /// - Parameters: /// - copyType: The requested part of the CFR copy to return. /// - hint: The `ContextualHintType` for which a consumer wants copy for. /// - Returns: The requested copy. func getCopyFor(_ copyType: ContextualHintCopyType, of hint: ContextualHintType) -> String { var copyToReturn: String switch copyType { case .action: copyToReturn = getActionCopyFor(hint) case .description: copyToReturn = getDescriptionCopyFor(hint) } return copyToReturn } // MARK: - Private helpers private func getDescriptionCopyFor(_ hint: ContextualHintType) -> String { var descriptionCopy = "" switch hint { case .inactiveTabs: descriptionCopy = CFRStrings.TabsTray.InactiveTabs.Body case .jumpBackIn: let shouldShowNew = featureFlags.isFeatureEnabled(.copyForJumpBackIn, checking: .buildOnly) if shouldShowNew { descriptionCopy = CFRStrings.FirefoxHomepage.JumpBackIn.PersonalizedHome } else { descriptionCopy = CFRStrings.FirefoxHomepage.JumpBackIn.PersonalizedHomeOldCopy } case .jumpBackInSyncedTab: descriptionCopy = CFRStrings.FirefoxHomepage.JumpBackIn.SyncedTab /// Toolbar description copy depends on the arrow direction. case .toolbarLocation: let shouldShowNew = featureFlags.isFeatureEnabled(.copyForToolbar, checking: .buildOnly) return getToolbarDescriptionCopy(with: arrowDirection, and: shouldShowNew) } return descriptionCopy } private func getActionCopyFor(_ hint: ContextualHintType) -> String { var actionCopy: String switch hint { case .inactiveTabs: actionCopy = CFRStrings.TabsTray.InactiveTabs.Action case .toolbarLocation: actionCopy = CFRStrings.Toolbar.SearchBarPlacementButtonText case .jumpBackIn, .jumpBackInSyncedTab: actionCopy = "" } return actionCopy } // MARK: - Private helpers private func getToolbarDescriptionCopy(with arrowDirection: UIPopoverArrowDirection?, and shouldShowNew: Bool) -> String { /// Toolbar description should never be empty! If it is, find where this struct is being /// created for toolbar and ensure there's an arrowDirection passed. guard let arrowDirection = arrowDirection else { return "" } switch arrowDirection { case .up: return shouldShowNew ? CFRStrings.Toolbar.SearchBarTopPlacement : CFRStrings.Toolbar.SearchBarPlacementForExistingUsers case .down: return shouldShowNew ? CFRStrings.Toolbar.SearchBarBottomPlacement : CFRStrings.Toolbar.SearchBarPlacementForNewUsers default: return "" } } }
mpl-2.0
3f1e210fa0508ecb9a748f847da8d905
34.201835
131
0.676049
4.850822
false
false
false
false
sysatom/OSC
OSC/OSChinaAPI.swift
1
4112
// // OSChinaAPI.swift // OSC // // Created by yuan on 15/11/17. // Copyright © 2015年 yuan. All rights reserved. // import UIKit import Alamofire import Moya // MARK: - Provider setup // (Endpoint<Target>, NSURLRequest -> Void) -> Void func endpointResolver() -> MoyaProvider<OSChinaAPI>.RequestClosure { return { (endpoint, closure) in let request: NSMutableURLRequest = endpoint.urlRequest.mutableCopy() as! NSMutableURLRequest request.HTTPShouldHandleCookies = false closure(request) } } class RubyChinaProvider<Target where Target: MoyaTarget>: MoyaProvider<Target>{ /// Initializes a provider. override internal init(endpointClosure: MoyaProvider<Target>.EndpointClosure = MoyaProvider.DefaultEndpointMapping, requestClosure: MoyaProvider<Target>.RequestClosure = MoyaProvider.DefaultRequestMapping, stubClosure: MoyaProvider<Target>.StubClosure = MoyaProvider.NeverStub, manager: Manager = Alamofire.Manager.sharedInstance, plugins: [Plugin<Target>] = []) { super.init(endpointClosure: endpointClosure, requestClosure: requestClosure, stubClosure: stubClosure, manager: manager, plugins: plugins) } } // MARK: - Provider support public enum OSChinaAPI { case NewsList case NewsDetail } extension OSChinaAPI : MoyaTarget { public var baseURL: NSURL { return NSURL(string: "http://www.oschina.net")! } public var path: String { switch self{ case .NewsList: return "/action/openapi/news_list" case .NewsDetail: return "/action/openapi/news_detail" } } public var method: Moya.Method { return .GET } public var parameters: [String: AnyObject]? { switch self { default: var res: [String: AnyObject] = [:] res["access_token"] = "b09c6aa3-3cc4-4d5c-8e64-d69d86fef354" return res } } public var sampleData: NSData { switch self { default: return "".dataUsingEncoding(NSUTF8StringEncoding)! } } } public struct Provider { private static var endpointsClosure = { (target: OSChinaAPI) -> Endpoint<OSChinaAPI> in var endpoint: Endpoint<OSChinaAPI> = Endpoint<OSChinaAPI>(URL: url(target), sampleResponseClosure: {.NetworkResponse(200, target.sampleData)}, method: target.method, parameters: target.parameters) // Sign all non-XApp token requests switch target { case .NewsList: return endpoint default: return endpoint.endpointByAddingHTTPHeaderFields(["X-Xapp-Token": "token" ?? ""]) } } static func DefaultProvider() -> RubyChinaProvider<OSChinaAPI> { return RubyChinaProvider(endpointClosure: MoyaProvider.DefaultEndpointMapping, requestClosure: MoyaProvider.DefaultRequestMapping, stubClosure: MoyaProvider.NeverStub, plugins: Provider.plugins) } private struct SharedProvider { static var instance = Provider.DefaultProvider() } static var sharedProvider: RubyChinaProvider<OSChinaAPI> { get { return SharedProvider.instance } set (newSharedProvider) { SharedProvider.instance = newSharedProvider } } static var plugins: [Plugin<OSChinaAPI>] { return [NetworkLogger<OSChinaAPI>(whitelist: { (target: OSChinaAPI) -> Bool in switch target { default: return false } }, blacklist: { target -> Bool in switch target { default: return false } })] } } public func url(route: MoyaTarget) -> String { return route.baseURL.URLByAppendingPathComponent(route.path).absoluteString } func stubbedresponse(filename: String) -> NSData! { @objc class TestClass: NSObject { } let bundle = NSBundle(forClass: TestClass.self) let path = bundle.pathForResource(filename, ofType: "json") return NSData(contentsOfFile: path!) }
mit
4881ee4d0a8ec0d53d71f269e580cfe8
31.109375
204
0.644439
4.679954
false
false
false
false
skywinder/DOFavoriteButton
DOFavoriteButton/DOFavoriteButton.swift
1
15872
// // DOFavoriteButton.swift // DOFavoriteButton // // Created by Daiki Okumura on 2015/07/09. // Copyright (c) 2015 Daiki Okumura. All rights reserved. // // This software is released under the MIT License. // http://opensource.org/licenses/mit-license.php // import UIKit @IBDesignable public class DOFavoriteButton: UIButton { private var imageShape: CAShapeLayer! @IBInspectable public var image: UIImage! { didSet { createLayers(image: image) } } @IBInspectable public var imageColorOn: UIColor! = UIColor(red: 255/255, green: 172/255, blue: 51/255, alpha: 1.0) { didSet { if (selected) { imageShape.fillColor = imageColorOn.CGColor } } } @IBInspectable public var imageColorOff: UIColor! = UIColor(red: 136/255, green: 153/255, blue: 166/255, alpha: 1.0) { didSet { if (!selected) { imageShape.fillColor = imageColorOff.CGColor } } } private var circleShape: CAShapeLayer! private var circleMask: CAShapeLayer! @IBInspectable public var circleColor: UIColor! = UIColor(red: 255/255, green: 172/255, blue: 51/255, alpha: 1.0) { didSet { circleShape.fillColor = circleColor.CGColor } } private var lines: [CAShapeLayer]! @IBInspectable public var lineColor: UIColor! = UIColor(red: 250/255, green: 120/255, blue: 68/255, alpha: 1.0) { didSet { for line in lines { line.strokeColor = lineColor.CGColor } } } private let circleTransform = CAKeyframeAnimation(keyPath: "transform") private let circleMaskTransform = CAKeyframeAnimation(keyPath: "transform") private let lineStrokeStart = CAKeyframeAnimation(keyPath: "strokeStart") private let lineStrokeEnd = CAKeyframeAnimation(keyPath: "strokeEnd") private let lineOpacity = CAKeyframeAnimation(keyPath: "opacity") private let imageTransform = CAKeyframeAnimation(keyPath: "transform") @IBInspectable public var duration: Double = 1.0 { didSet { circleTransform.duration = 0.333 * duration // 0.0333 * 10 circleMaskTransform.duration = 0.333 * duration // 0.0333 * 10 lineStrokeStart.duration = 0.6 * duration //0.0333 * 18 lineStrokeEnd.duration = 0.6 * duration //0.0333 * 18 lineOpacity.duration = 1.0 * duration //0.0333 * 30 imageTransform.duration = 1.0 * duration //0.0333 * 30 } } override public var selected : Bool { didSet { if (selected != oldValue) { if selected { imageShape.fillColor = imageColorOn.CGColor } else { deselect() } } } } public convenience init() { self.init(frame: CGRectZero) } public override convenience init(frame: CGRect) { self.init(frame: frame, image: UIImage()) } public init(frame: CGRect, image: UIImage!) { super.init(frame: frame) self.image = image createLayers(image: image) addTargets() } public required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) createLayers(image: UIImage()) addTargets() } private func createLayers(#image: UIImage!) { self.layer.sublayers = nil let imageFrame = CGRectMake(frame.size.width / 2 - frame.size.width / 4, frame.size.height / 2 - frame.size.height / 4, frame.size.width / 2, frame.size.height / 2) let imgCenterPoint = CGPointMake(imageFrame.origin.x + imageFrame.width / 2, imageFrame.origin.y + imageFrame.height / 2) let lineFrame = CGRectMake(imageFrame.origin.x - imageFrame.width / 4, imageFrame.origin.y - imageFrame.height / 4 , imageFrame.width * 1.5, imageFrame.height * 1.5) //=============== // circle layer //=============== circleShape = CAShapeLayer() circleShape.bounds = imageFrame circleShape.position = imgCenterPoint circleShape.path = UIBezierPath(ovalInRect: imageFrame).CGPath circleShape.fillColor = circleColor.CGColor circleShape.transform = CATransform3DMakeScale(0.0, 0.0, 1.0) self.layer.addSublayer(circleShape) circleMask = CAShapeLayer() circleMask.bounds = imageFrame circleMask.position = imgCenterPoint circleMask.fillRule = kCAFillRuleEvenOdd circleShape.mask = circleMask let maskPath = UIBezierPath(rect: imageFrame) maskPath.addArcWithCenter(imgCenterPoint, radius: 0.1, startAngle: CGFloat(0.0), endAngle: CGFloat(M_PI * 2), clockwise: true) circleMask.path = maskPath.CGPath //=============== // line layer //=============== lines = [] for i in 0 ..< 5 { let line = CAShapeLayer() line.bounds = lineFrame line.position = imgCenterPoint line.masksToBounds = true line.actions = ["strokeStart": NSNull(), "strokeEnd": NSNull()] line.strokeColor = lineColor.CGColor line.lineWidth = 1.25 line.miterLimit = 1.25 line.path = { let path = CGPathCreateMutable() CGPathMoveToPoint(path, nil, lineFrame.origin.x + lineFrame.width / 2, lineFrame.origin.y + lineFrame.height / 2) CGPathAddLineToPoint(path, nil, lineFrame.origin.x + lineFrame.width / 2, lineFrame.origin.y) return path }() line.lineCap = kCALineCapRound line.lineJoin = kCALineJoinRound line.strokeStart = 0.0 line.strokeEnd = 0.0 line.opacity = 0.0 line.transform = CATransform3DMakeRotation(CGFloat(M_PI) / 5 * (CGFloat(i) * 2 + 1), 0.0, 0.0, 1.0) self.layer.addSublayer(line) lines.append(line) } //=============== // image layer //=============== imageShape = CAShapeLayer() imageShape.bounds = imageFrame imageShape.position = imgCenterPoint imageShape.path = UIBezierPath(rect: imageFrame).CGPath imageShape.fillColor = imageColorOff.CGColor imageShape.actions = ["fillColor": NSNull()] self.layer.addSublayer(imageShape) imageShape.mask = CALayer() imageShape.mask.contents = image.CGImage imageShape.mask.bounds = imageFrame imageShape.mask.position = imgCenterPoint //============================== // circle transform animation //============================== circleTransform.duration = 0.333 // 0.0333 * 10 circleTransform.values = [ NSValue(CATransform3D: CATransform3DMakeScale(0.0, 0.0, 1.0)), // 0/10 NSValue(CATransform3D: CATransform3DMakeScale(0.5, 0.5, 1.0)), // 1/10 NSValue(CATransform3D: CATransform3DMakeScale(1.0, 1.0, 1.0)), // 2/10 NSValue(CATransform3D: CATransform3DMakeScale(1.2, 1.2, 1.0)), // 3/10 NSValue(CATransform3D: CATransform3DMakeScale(1.3, 1.3, 1.0)), // 4/10 NSValue(CATransform3D: CATransform3DMakeScale(1.37, 1.37, 1.0)), // 5/10 NSValue(CATransform3D: CATransform3DMakeScale(1.4, 1.4, 1.0)), // 6/10 NSValue(CATransform3D: CATransform3DMakeScale(1.4, 1.4, 1.0)) // 10/10 ] circleTransform.keyTimes = [ 0.0, // 0/10 0.1, // 1/10 0.2, // 2/10 0.3, // 3/10 0.4, // 4/10 0.5, // 5/10 0.6, // 6/10 1.0 // 10/10 ] circleMaskTransform.duration = 0.333 // 0.0333 * 10 circleMaskTransform.values = [ NSValue(CATransform3D: CATransform3DIdentity), // 0/10 NSValue(CATransform3D: CATransform3DIdentity), // 2/10 NSValue(CATransform3D: CATransform3DMakeScale(imageFrame.width * 1.25, imageFrame.height * 1.25, 1.0)), // 3/10 NSValue(CATransform3D: CATransform3DMakeScale(imageFrame.width * 2.688, imageFrame.height * 2.688, 1.0)), // 4/10 NSValue(CATransform3D: CATransform3DMakeScale(imageFrame.width * 3.923, imageFrame.height * 3.923, 1.0)), // 5/10 NSValue(CATransform3D: CATransform3DMakeScale(imageFrame.width * 4.375, imageFrame.height * 4.375, 1.0)), // 6/10 NSValue(CATransform3D: CATransform3DMakeScale(imageFrame.width * 4.731, imageFrame.height * 4.731, 1.0)), // 7/10 NSValue(CATransform3D: CATransform3DMakeScale(imageFrame.width * 5.0, imageFrame.height * 5.0, 1.0)), // 9/10 NSValue(CATransform3D: CATransform3DMakeScale(imageFrame.width * 5.0, imageFrame.height * 5.0, 1.0)) // 10/10 ] circleMaskTransform.keyTimes = [ 0.0, // 0/10 0.2, // 2/10 0.3, // 3/10 0.4, // 4/10 0.5, // 5/10 0.6, // 6/10 0.7, // 7/10 0.9, // 9/10 1.0 // 10/10 ] //============================== // line stroke animation //============================== lineStrokeStart.duration = 0.6 //0.0333 * 18 lineStrokeStart.values = [ 0.0, // 0/18 0.0, // 1/18 0.18, // 2/18 0.2, // 3/18 0.26, // 4/18 0.32, // 5/18 0.4, // 6/18 0.6, // 7/18 0.71, // 8/18 0.89, // 17/18 0.92 // 18/18 ] lineStrokeStart.keyTimes = [ 0.0, // 0/18 0.056, // 1/18 0.111, // 2/18 0.167, // 3/18 0.222, // 4/18 0.278, // 5/18 0.333, // 6/18 0.389, // 7/18 0.444, // 8/18 0.944, // 17/18 1.0, // 18/18 ] lineStrokeEnd.duration = 0.6 //0.0333 * 18 lineStrokeEnd.values = [ 0.0, // 0/18 0.0, // 1/18 0.32, // 2/18 0.48, // 3/18 0.64, // 4/18 0.68, // 5/18 0.92, // 17/18 0.92 // 18/18 ] lineStrokeEnd.keyTimes = [ 0.0, // 0/18 0.056, // 1/18 0.111, // 2/18 0.167, // 3/18 0.222, // 4/18 0.278, // 5/18 0.944, // 17/18 1.0, // 18/18 ] lineOpacity.duration = 1.0 //0.0333 * 30 lineOpacity.values = [ 1.0, // 0/30 1.0, // 12/30 0.0 // 17/30 ] lineOpacity.keyTimes = [ 0.0, // 0/30 0.4, // 12/30 0.567 // 17/30 ] //============================== // image transform animation //============================== imageTransform.duration = 1.0 //0.0333 * 30 imageTransform.values = [ NSValue(CATransform3D: CATransform3DMakeScale(0.0, 0.0, 1.0)), // 0/30 NSValue(CATransform3D: CATransform3DMakeScale(0.0, 0.0, 1.0)), // 3/30 NSValue(CATransform3D: CATransform3DMakeScale(1.2, 1.2, 1.0)), // 9/30 NSValue(CATransform3D: CATransform3DMakeScale(1.25, 1.25, 1.0)), // 10/30 NSValue(CATransform3D: CATransform3DMakeScale(1.2, 1.2, 1.0)), // 11/30 NSValue(CATransform3D: CATransform3DMakeScale(0.9, 0.9, 1.0)), // 14/30 NSValue(CATransform3D: CATransform3DMakeScale(0.875, 0.875, 1.0)), // 15/30 NSValue(CATransform3D: CATransform3DMakeScale(0.875, 0.875, 1.0)), // 16/30 NSValue(CATransform3D: CATransform3DMakeScale(0.9, 0.9, 1.0)), // 17/30 NSValue(CATransform3D: CATransform3DMakeScale(1.013, 1.013, 1.0)), // 20/30 NSValue(CATransform3D: CATransform3DMakeScale(1.025, 1.025, 1.0)), // 21/30 NSValue(CATransform3D: CATransform3DMakeScale(1.013, 1.013, 1.0)), // 22/30 NSValue(CATransform3D: CATransform3DMakeScale(0.96, 0.96, 1.0)), // 25/30 NSValue(CATransform3D: CATransform3DMakeScale(0.95, 0.95, 1.0)), // 26/30 NSValue(CATransform3D: CATransform3DMakeScale(0.96, 0.96, 1.0)), // 27/30 NSValue(CATransform3D: CATransform3DMakeScale(0.99, 0.99, 1.0)), // 29/30 NSValue(CATransform3D: CATransform3DIdentity) // 30/30 ] imageTransform.keyTimes = [ 0.0, // 0/30 0.1, // 3/30 0.3, // 9/30 0.333, // 10/30 0.367, // 11/30 0.467, // 14/30 0.5, // 15/30 0.533, // 16/30 0.567, // 17/30 0.667, // 20/30 0.7, // 21/30 0.733, // 22/30 0.833, // 25/30 0.867, // 26/30 0.9, // 27/30 0.967, // 29/30 1.0 // 30/30 ] } private func addTargets() { //=============== // add target //=============== self.addTarget(self, action: "touchDown:", forControlEvents: UIControlEvents.TouchDown) self.addTarget(self, action: "touchUpInside:", forControlEvents: UIControlEvents.TouchUpInside) self.addTarget(self, action: "touchDragExit:", forControlEvents: UIControlEvents.TouchDragExit) self.addTarget(self, action: "touchDragEnter:", forControlEvents: UIControlEvents.TouchDragEnter) self.addTarget(self, action: "touchCancel:", forControlEvents: UIControlEvents.TouchCancel) } func touchDown(sender: DOFavoriteButton) { self.layer.opacity = 0.4 } func touchUpInside(sender: DOFavoriteButton) { self.layer.opacity = 1.0 } func touchDragExit(sender: DOFavoriteButton) { self.layer.opacity = 1.0 } func touchDragEnter(sender: DOFavoriteButton) { self.layer.opacity = 0.4 } func touchCancel(sender: DOFavoriteButton) { self.layer.opacity = 1.0 } public func select() { selected = true imageShape.fillColor = imageColorOn.CGColor CATransaction.begin() circleShape.addAnimation(circleTransform, forKey: "transform") circleMask.addAnimation(circleMaskTransform, forKey: "transform") imageShape.addAnimation(imageTransform, forKey: "transform") for i in 0 ..< 5 { lines[i].addAnimation(lineStrokeStart, forKey: "strokeStart") lines[i].addAnimation(lineStrokeEnd, forKey: "strokeEnd") lines[i].addAnimation(lineOpacity, forKey: "opacity") } CATransaction.commit() } public func deselect() { selected = false imageShape.fillColor = imageColorOff.CGColor // remove all animations circleShape.removeAllAnimations() circleMask.removeAllAnimations() imageShape.removeAllAnimations() lines[0].removeAllAnimations() lines[1].removeAllAnimations() lines[2].removeAllAnimations() lines[3].removeAllAnimations() lines[4].removeAllAnimations() } }
mit
b21870c0a6ea227523ccb3c7150b5d42
38.979849
173
0.527722
3.957118
false
false
false
false
wireapp/wire-ios
Wire-iOS/Sources/Helpers/StylableButton.swift
1
2706
// // Wire // Copyright (C) 2022 Wire Swiss GmbH // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see http://www.gnu.org/licenses/. // import Foundation import UIKit class StylableButton: UIButton, Stylable { var buttonStyle: ButtonStyle? public func applyStyle(_ style: ButtonStyle) { self.buttonStyle = style setTitleColor(style.normalStateColors.title, for: .normal) setTitleColor(style.highlightedStateColors.title, for: .highlighted) setTitleColor(style.selectedStateColors?.title, for: .selected) applyStyleToNonDynamicProperties(style: style) } private func applyStyleToNonDynamicProperties(style: ButtonStyle) { setBackgroundImageColor(style.normalStateColors.background, for: .normal) setBackgroundImageColor(style.highlightedStateColors.background, for: .highlighted) setBackgroundImageColor(style.selectedStateColors?.background, for: .selected) self.layer.borderWidth = 1 self.layer.borderColor = isHighlighted ? style.highlightedStateColors.border.cgColor : style.normalStateColors.border.cgColor self.layer.borderColor = isSelected ? style.selectedStateColors?.border.cgColor : style.normalStateColors.border.cgColor } override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) { super.traitCollectionDidChange(previousTraitCollection) guard previousTraitCollection?.userInterfaceStyle != traitCollection.userInterfaceStyle else { return } guard let style = buttonStyle else { return } // We need to call this method here because the background, // and the border color of the button when switching from dark to light mode // or vice versa can be updated only inside traitCollectionDidChange. applyStyleToNonDynamicProperties(style: style) } func setBackgroundImageColor(_ color: UIColor?, for state: UIControl.State) { if let color = color { setBackgroundImage(UIImage.singlePixelImage(with: color), for: state) } else { setBackgroundImage(nil, for: state) } } }
gpl-3.0
8afe770d464e81ae4460ba7ce6d497e8
41.28125
133
0.732446
4.946984
false
false
false
false
mattiasjahnke/Swift2048
Swift2048/GameBoardView.swift
2
5252
// // GameBoardView.swift // CloneA2048 // // Created by Mattias Jähnke on 2015-06-30. // Copyright © 2015 Nearedge. All rights reserved. // import UIKit typealias BoardPosition = (x: Int, y: Int) class GameBoardView: UIView { let contentInset: CGFloat = 10 var size = 4 { didSet { updatePlaceholderLayers() } } var tiles = [GameTileView]() var placeholderLayers = [CALayer]() var colorScheme: [String : [String : String]] = { let data = try! Data(contentsOf: URL(fileURLWithPath: Bundle.main.path(forResource: "default-color", ofType: "json")!)) do { let json = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions(rawValue: 0)) as! [String : [String : String]] return json } catch { return [String : [String : String]]() } }() override func layoutSubviews() { super.layoutSubviews() updatePlaceholderLayers() animateTiles() } func spawnTile(at position: BoardPosition) -> GameTileView { let tile = GameTileView(frame: frame(at: position)) tiles.append(tile) addSubview(tile) tile.colorScheme = colorScheme tile.position = position tile.cornerRadius = 5 tile.transform = CGAffineTransform(scaleX: 0.1, y: 0.1).concatenating(CGAffineTransform(rotationAngle: 3.14)) UIView.animate(withDuration: 0.3) { tile.alpha = 1 tile.transform = CGAffineTransform.identity } return tile } func moveTile(from: BoardPosition, to: BoardPosition) { tile(at: from)?.position = to } func moveAndRemoveTile(from: BoardPosition, to: BoardPosition) { if let fromTile = tile(at: from), let toTile = tile(at: to) { fromTile.destroy = true moveTile(from: from, to: to) UIView.animate(withDuration: 0.1, animations: { toTile.transform = CGAffineTransform(scaleX: 1.2, y: 1.2) }, completion: { _ in UIView.animate(withDuration: 0.1) { toTile.transform = CGAffineTransform.identity } }) } } func animateTiles() { var destroyed = [GameTileView]() for tile in tiles { UIView.animate(withDuration: 0.1, animations: { let dest = self.frame(at: tile.position) tile.bounds = CGRect(x: 0, y: 0, width: dest.width, height: dest.height) tile.layer.position = CGPoint(x: dest.origin.x + dest.width / 2, y: dest.origin.y + dest.height / 2) tile.alpha = tile.destroy ? 0 : 1 }, completion: { _ in if tile.destroy { tile.removeFromSuperview() destroyed.append(tile) } }) } tiles = tiles.filter({ tile -> Bool in return !destroyed.contains(tile) }) } func updateValuesWithModel(_ model: [Int], canSpawn: Bool) { for y in 0..<model.size { for x in 0..<model.size { var t = tile(at: (x: x, y: y)) if canSpawn && model[x, y] > 0 && t == nil { t = spawnTile(at: (x: x, y: y)) } if canSpawn && model[x, y] == 0 && t != nil { tiles.remove(at: tiles.index(of: t!)!) t!.removeFromSuperview() } assert(!(t == nil && model[x, y] > 0)) if let tile = t { tile.value = model[x, y] } } } } fileprivate func updatePlaceholderLayers() { while placeholderLayers.count != size * size { if placeholderLayers.count < size * size { placeholderLayers.append(CALayer()) layer.addSublayer(placeholderLayers.last!) } else { placeholderLayers.last!.removeFromSuperlayer() placeholderLayers.removeLast() } } for y in 0..<size { for x in 0..<size { let layer = placeholderLayers[size * x + y] layer.backgroundColor = UIColor(red: 204.0/255.0, green: 192.0/255.0, blue: 181.0/255.0, alpha: 1).cgColor layer.cornerRadius = 5 layer.anchorPoint = CGPoint(x: 0, y: 0) let rect = frame(at: (x: x, y: y)).insetBy(dx: 5, dy: 5) layer.position = rect.origin layer.bounds = rect } } } fileprivate func tile(at position: BoardPosition) -> GameTileView? { return tiles.filter { $0.position == position && !$0.destroy }.first } fileprivate func frame(at position: BoardPosition) -> CGRect { let minSize = min(frame.size.width, frame.size.height) - contentInset * 2 let s = round(minSize / CGFloat(size)) return CGRect(x: CGFloat(position.x) * s + contentInset, y: CGFloat(position.y) * s + contentInset, width: s, height: s) } }
mit
5be2d1728b53cf51f058b3d5ac35590f
34.958904
156
0.525333
4.353234
false
false
false
false
jianghongbing/APIReferenceDemo
UIKit/UIViewControllerTransitioningDelegate/UIViewControllerTransitioningDelegate/TableViewController.swift
1
2597
// // TableViewController.swift // UIViewControllerTransitioningDelegate // // Created by pantosoft on 2018/7/23. // Copyright © 2018年 jianghongbing. All rights reserved. // import UIKit class TableViewController: UITableViewController { @IBOutlet var gestureRecognizer: UIScreenEdgePanGestureRecognizer! var customTransitionDelegate: UIViewControllerTransitioningDelegate? enum SegueIdentifier: String{ case customTransition1 = "CustomTransition1" case customTransition2 = "CustomTransition2" case customInteractiveTransition1 = "CustomInteractiveTransition1" // case customInteractiveTransition2 = "CustomInteractiveTransition2" init?(rawValue:String) { switch rawValue { case SegueIdentifier.customTransition1.rawValue: self = .customTransition1 case SegueIdentifier.customTransition2.rawValue: self = .customTransition2 case SegueIdentifier.customInteractiveTransition1.rawValue: self = .customInteractiveTransition1 // case SegueIdentifier.customInteractiveTransition2.rawValue: // self = .customInteractiveTransition2 default: return nil } } init?(identifier: String?) { guard let rawValue = identifier else { return nil } self.init(rawValue: rawValue) } } @IBAction func unwindToTableViewController(segue: UIStoryboardSegue) {} override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if let segueIdentifer = SegueIdentifier(identifier: segue.identifier) { let desitination = segue.destination switch segueIdentifer { case SegueIdentifier.customTransition1: customTransitionDelegate = CustomTransition1Delegate() case SegueIdentifier.customTransition2: customTransitionDelegate = CustomTransition2Delegate() case SegueIdentifier.customInteractiveTransition1: customTransitionDelegate = CustomInteractiveTransition1Delegate(gestureRecognizer: gestureRecognizer) } desitination.transitioningDelegate = customTransitionDelegate } } @IBAction func handleGestureRecognizerEvent(_ sender: UIScreenEdgePanGestureRecognizer) { if sender.state == .began { performSegue(withIdentifier: SegueIdentifier.customInteractiveTransition1.rawValue, sender: sender) } } }
mit
c1d9ce1155ac6b62eeecec0dbc1ca7d3
39.53125
117
0.672706
6.296117
false
false
false
false
fulldecent/FDWaveformView
Sources/FDWaveformView/FDWaveformRenderOperation.swift
1
14301
// // Copyright 2013 - 2017, William Entriken and the FDWaveformView contributors. // import UIKit import AVFoundation import Accelerate /// Format options for FDWaveformRenderOperation //MAYBE: Make this public struct FDWaveformRenderFormat { /// The type of waveform to render //TODO: make this public after reconciling FDWaveformView.WaveformType and FDWaveformType var type: FDWaveformType /// The color of the waveform internal var wavesColor: UIColor /// The scale factor to apply to the rendered image (usually the current screen's scale) public var scale: CGFloat /// Whether the resulting image size should be as close as possible to imageSize (approximate) /// or whether it should match it exactly. Right now there is no support for matching exactly. // TODO: Support rendering operations that always match the desired imageSize passed in. // Right now the imageSize passed in to the render operation might not match the // resulting image's size. This flag is hard coded here to convey that. public let constrainImageSizeToExactlyMatch = false // To make these public, you must implement them // See http://stackoverflow.com/questions/26224693/how-can-i-make-public-by-default-the-member-wise-initialiser-for-structs-in-swif public init() { self.init(type: .linear, wavesColor: .black, scale: UIScreen.main.scale) } init(type: FDWaveformType, wavesColor: UIColor, scale: CGFloat) { self.type = type self.wavesColor = wavesColor self.scale = scale } } /// Operation used for rendering waveform images final public class FDWaveformRenderOperation: Operation { /// The audio context used to build the waveform let audioContext: FDAudioContext /// Size of waveform image to render public let imageSize: CGSize /// Range of samples within audio asset to build waveform for public let sampleRange: CountableRange<Int> /// Format of waveform image let format: FDWaveformRenderFormat // MARK: - NSOperation Overrides public override var isAsynchronous: Bool { return true } private var _isExecuting = false public override var isExecuting: Bool { return _isExecuting } private var _isFinished = false public override var isFinished: Bool { return _isFinished } // MARK: - Private /// Handler called when the rendering has completed. nil UIImage indicates that there was an error during processing. private let completionHandler: (UIImage?) -> () /// Final rendered image. Used to hold image for completionHandler. private var renderedImage: UIImage? init(audioContext: FDAudioContext, imageSize: CGSize, sampleRange: CountableRange<Int>? = nil, format: FDWaveformRenderFormat = FDWaveformRenderFormat(), completionHandler: @escaping (_ image: UIImage?) -> ()) { self.audioContext = audioContext self.imageSize = imageSize self.sampleRange = sampleRange ?? 0..<audioContext.totalSamples self.format = format self.completionHandler = completionHandler super.init() self.completionBlock = { [weak self] in guard let `self` = self else { return } self.completionHandler(self.renderedImage) self.renderedImage = nil } } public override func start() { guard !isExecuting && !isFinished && !isCancelled else { return } willChangeValue(forKey: "isExecuting") _isExecuting = true didChangeValue(forKey: "isExecuting") if #available(iOS 8.0, *) { DispatchQueue.global(qos: .background).async { self.render() } } else { DispatchQueue.global(priority: .background).async { self.render() } } } private func finish(with image: UIImage?) { guard !isFinished && !isCancelled else { return } renderedImage = image // completionBlock called automatically by NSOperation after these values change willChangeValue(forKey: "isExecuting") willChangeValue(forKey: "isFinished") _isExecuting = false _isFinished = true didChangeValue(forKey: "isExecuting") didChangeValue(forKey: "isFinished") } private func render() { guard !sampleRange.isEmpty, imageSize.width > 0, imageSize.height > 0 else { finish(with: nil) return } let targetSamples = Int(imageSize.width * format.scale) let image: UIImage? = { guard let (samples, sampleMax) = sliceAsset(withRange: sampleRange, andDownsampleTo: targetSamples), let image = plotWaveformGraph(samples, maximumValue: sampleMax, zeroValue: format.type.floorValue) else { return nil } return image }() finish(with: image) } /// Read the asset and create a lower resolution set of samples func sliceAsset(withRange slice: CountableRange<Int>, andDownsampleTo targetSamples: Int) -> (samples: [CGFloat], sampleMax: CGFloat)? { guard !isCancelled else { return nil } guard !slice.isEmpty, targetSamples > 0, let reader = try? AVAssetReader(asset: audioContext.asset) else { return nil } var channelCount = 1 var sampleRate: CMTimeScale = 44100 let formatDescriptions = audioContext.assetTrack.formatDescriptions as! [CMAudioFormatDescription] for item in formatDescriptions { guard let fmtDesc = CMAudioFormatDescriptionGetStreamBasicDescription(item) else { return nil } channelCount = Int(fmtDesc.pointee.mChannelsPerFrame) sampleRate = Int32(fmtDesc.pointee.mSampleRate) } reader.timeRange = CMTimeRange(start: CMTime(value: Int64(slice.lowerBound), timescale: sampleRate), duration: CMTime(value: Int64(slice.count), timescale: sampleRate)) let outputSettingsDict: [String : Any] = [ AVFormatIDKey: Int(kAudioFormatLinearPCM), AVLinearPCMBitDepthKey: 16, AVLinearPCMIsBigEndianKey: false, AVLinearPCMIsFloatKey: false, AVLinearPCMIsNonInterleaved: false ] let readerOutput = AVAssetReaderTrackOutput(track: audioContext.assetTrack, outputSettings: outputSettingsDict) readerOutput.alwaysCopiesSampleData = false reader.add(readerOutput) var sampleMax = format.type.floorValue let samplesPerPixel = max(1, channelCount * slice.count / targetSamples) let filter = [Float](repeating: 1.0 / Float(samplesPerPixel), count: samplesPerPixel) var outputSamples = [CGFloat]() var sampleBuffer = Data() // 16-bit samples reader.startReading() defer { reader.cancelReading() } // Cancel reading if we exit early or if operation is cancelled while reader.status == .reading { guard !isCancelled else { return nil } guard let readSampleBuffer = readerOutput.copyNextSampleBuffer(), let readBuffer = CMSampleBufferGetDataBuffer(readSampleBuffer) else { break } // Append audio sample buffer into our current sample buffer var readBufferLength = 0 var readBufferPointer: UnsafeMutablePointer<Int8>? CMBlockBufferGetDataPointer(readBuffer, atOffset: 0, lengthAtOffsetOut: &readBufferLength, totalLengthOut: nil, dataPointerOut: &readBufferPointer) sampleBuffer.append(UnsafeBufferPointer(start: readBufferPointer, count: readBufferLength)) CMSampleBufferInvalidate(readSampleBuffer) let totalSamples = sampleBuffer.count / MemoryLayout<Int16>.size let downSampledLength = totalSamples / samplesPerPixel let samplesToProcess = downSampledLength * samplesPerPixel guard samplesToProcess > 0 else { continue } processSamples(fromData: &sampleBuffer, sampleMax: &sampleMax, outputSamples: &outputSamples, samplesToProcess: samplesToProcess, downSampledLength: downSampledLength, samplesPerPixel: samplesPerPixel, filter: filter) //print("Status: \(reader.status)") } // Process the remaining samples that did not fit into samplesPerPixel at the end let samplesToProcess = sampleBuffer.count / MemoryLayout<Int16>.size if samplesToProcess > 0 { guard !isCancelled else { return nil } let downSampledLength = 1 let samplesPerPixel = samplesToProcess let filter = [Float](repeating: 1.0 / Float(samplesPerPixel), count: samplesPerPixel) processSamples(fromData: &sampleBuffer, sampleMax: &sampleMax, outputSamples: &outputSamples, samplesToProcess: samplesToProcess, downSampledLength: downSampledLength, samplesPerPixel: samplesPerPixel, filter: filter) //print("Status: \(reader.status)") } // if (reader.status == AVAssetReaderStatusFailed || reader.status == AVAssetReaderStatusUnknown) // Something went wrong. Handle it or do not, depending on if you can get above to work if reader.status == .completed || true{ return (outputSamples, sampleMax) } else { print("FDWaveformRenderOperation failed to read audio: \(String(describing: reader.error))") return nil } } // TODO: report progress? (for issue #2) func processSamples(fromData sampleBuffer: inout Data, sampleMax: inout CGFloat, outputSamples: inout [CGFloat], samplesToProcess: Int, downSampledLength: Int, samplesPerPixel: Int, filter: [Float]) { sampleBuffer.withUnsafeBytes { bytes in guard let samples = bytes.bindMemory(to: Int16.self).baseAddress else { return } var processingBuffer = [Float](repeating: 0.0, count: samplesToProcess) let sampleCount = vDSP_Length(samplesToProcess) //Convert 16bit int samples to floats vDSP_vflt16(samples, 1, &processingBuffer, 1, sampleCount) //Take the absolute values to get amplitude vDSP_vabs(processingBuffer, 1, &processingBuffer, 1, sampleCount) //Let current type further process the samples format.type.process(normalizedSamples: &processingBuffer) //Downsample and average var downSampledData = [Float](repeating: 0.0, count: downSampledLength) vDSP_desamp(processingBuffer, vDSP_Stride(samplesPerPixel), filter, &downSampledData, vDSP_Length(downSampledLength), vDSP_Length(samplesPerPixel)) let downSampledDataCG = downSampledData.map { (value: Float) -> CGFloat in let element = CGFloat(value) if element > sampleMax { sampleMax = element } return element } // Remove processed samples sampleBuffer.removeFirst(samplesToProcess * MemoryLayout<Int16>.size) outputSamples += downSampledDataCG } } // TODO: report progress? (for issue #2) func plotWaveformGraph(_ samples: [CGFloat], maximumValue max: CGFloat, zeroValue min: CGFloat) -> UIImage? { guard !isCancelled else { return nil } let imageSize = CGSize(width: CGFloat(samples.count) / format.scale, height: self.imageSize.height) UIGraphicsBeginImageContextWithOptions(imageSize, false, format.scale) defer { UIGraphicsEndImageContext() } guard let context = UIGraphicsGetCurrentContext() else { NSLog("FDWaveformView failed to get graphics context") return nil } context.scaleBy(x: 1 / format.scale, y: 1 / format.scale) // Scale context to account for scaling applied to image context.setShouldAntialias(false) context.setAlpha(1.0) context.setLineWidth(1.0 / format.scale) context.setStrokeColor(format.wavesColor.cgColor) let sampleDrawingScale: CGFloat if max == min { sampleDrawingScale = 0 } else { sampleDrawingScale = (imageSize.height * format.scale) / 2 / (max - min) } let verticalMiddle = (imageSize.height * format.scale) / 2 for (x, sample) in samples.enumerated() { let height = (sample - min) * sampleDrawingScale context.move(to: CGPoint(x: CGFloat(x), y: verticalMiddle - height)) context.addLine(to: CGPoint(x: CGFloat(x), y: verticalMiddle + height)) context.strokePath(); } guard let image = UIGraphicsGetImageFromCurrentImageContext() else { NSLog("FDWaveformView failed to get waveform image from context") return nil } return image } } extension AVAssetReader.Status : CustomStringConvertible{ public var description: String{ switch self{ case .reading: return "reading" case .unknown: return "unknown" case .completed: return "completed" case .failed: return "failed" case .cancelled: return "cancelled" @unknown default: fatalError() } } }
mit
96866e321f6d21079a1f480911dafeb5
40.815789
215
0.614433
5.390501
false
false
false
false
vegather/MOON-Graph
Sample Code/OS X (deprecated)/OS X Example/MOONGraphView/MOONGraphView.swift
2
24935
// // GraphView.swift // OS X Example // // Created by Vegard Solheim Theriault on 28/02/16. // Copyright © 2016 MOON Wearables. All rights reserved. // // .___ ___. ______ ______ .__ __. // | \/ | / __ \ / __ \ | \ | | // | \ / | | | | | | | | | | \| | // | |\/| | | | | | | | | | | . ` | // | | | | | `--' | | `--' | | |\ | // |__| |__| \______/ \______/ |__| \__| // ___ _____ _____ _ ___ ___ ___ ___ // | \| __\ \ / / __| | / _ \| _ \ __| _ \ // | |) | _| \ V /| _|| |_| (_) | _/ _|| / // |___/|___| \_/ |___|____\___/|_| |___|_|_\ // import Cocoa private struct Constants { static let FontName = "HelveticaNeue" static let ValueLabelWidth : CGFloat = 70.0 static let TickMargin : CGFloat = 15.0 static let TickWidth : CGFloat = 10.0 static let Alpha : CGFloat = 0.6 static let CornerRadius : CGFloat = 10.0 static let GraphWidth : CGFloat = 2.0 static let ScatterPointRadius : CGFloat = 4.0 } @IBDesignable public class MOONGraphView: NSView { public enum GraphColor { case Gray case Red case Green case Blue case Turquoise case Yellow case Purple private func colors() -> [CGColorRef] { switch self { case Gray: return [NSColor(red: 141.0/255.0, green: 140.0/255.0, blue: 146.0/255.0, alpha: 1.0).CGColor, NSColor(red: 210.0/255.0, green: 209.0/255.0, blue: 215.0/255.0, alpha: 1.0).CGColor] case .Red: return [NSColor(red: 253.0/255.0, green: 58.0/255.0, blue: 52.0/255.0, alpha: 1.0).CGColor, NSColor(red: 255.0/255.0, green: 148.0/255.0, blue: 86.0/255.0, alpha: 1.0).CGColor] case .Green: return [NSColor(red: 28.0/255.0, green: 180.0/255.0, blue: 28.0/255.0, alpha: 1.0).CGColor, NSColor(red: 78.0/255.0, green: 238.0/255.0, blue: 92.0/255.0, alpha: 1.0).CGColor] case .Blue: return [NSColor(red: 0.0/255.0, green: 108.0/255.0, blue: 250.0/255.0, alpha: 1.0).CGColor, NSColor(red: 90.0/255.0, green: 202.0/255.0, blue: 251.0/255.0, alpha: 1.0).CGColor] case .Turquoise: return [NSColor(red: 54.0/255.0, green: 174.0/255.0, blue: 220.0/255.0, alpha: 1.0).CGColor, NSColor(red: 82.0/255.0, green: 234.0/255.0, blue: 208.0/255.0, alpha: 1.0).CGColor] case .Yellow: return [NSColor(red: 255.0/255.0, green: 160.0/255.0, blue: 33.0/255.0, alpha: 1.0).CGColor, NSColor(red: 254.0/255.0, green: 209.0/255.0, blue: 48.0/255.0, alpha: 1.0).CGColor] case .Purple: return [NSColor(red: 140.0/255.0, green: 70.0/255.0, blue: 250.0/255.0, alpha: 1.0).CGColor, NSColor(red: 217.0/255.0, green: 168.0/255.0, blue: 252.0/255.0, alpha: 1.0).CGColor] } } } public enum GraphDirection { case LeftToRight case RightToLeft } public enum GraphType { case Line case Scatter } private let gradientBackground = CAGradientLayer() private var lineView: LineView? private var accessoryView: AccessoryView? // ------------------------------- // MARK: Initialization // ------------------------------- override public func awakeFromNib() { super.awakeFromNib() addSubviews() } private func addSubviews() { wantsLayer = true guard let layer = layer else { return } NSBezierPath.setDefaultLineWidth(Constants.GraphWidth) gradientBackground.frame = layer.bounds gradientBackground.colors = themeColor.colors() gradientBackground.cornerRadius = roundedCorners ? Constants.CornerRadius : 0.0 gradientBackground.removeAllAnimations() layer.addSublayer(gradientBackground) lineView = LineView(frame: bounds) lineView!.maxSamples = maxSamples lineView!.maxValue = maxValue lineView!.minValue = minValue lineView!.graphDirection = graphDirection lineView!.numberOfGraphs = numberOfGraphs lineView!.cornerRadius = roundedCorners ? Constants.CornerRadius : 0.0 lineView!.graphType = graphType addSubview(lineView!) accessoryView = AccessoryView(frame: bounds) accessoryView!.title = title accessoryView!.subtitle = subtitle accessoryView!.maxValue = maxValue accessoryView!.minValue = minValue accessoryView!.graphDirection = graphDirection addSubview(accessoryView!) } // ------------------------------- // MARK: Public API // ------------------------------- /// Used to set the title of the graph in one of the upper corners. The default value for this is `""`, meaning that it will not be displayed. @IBInspectable public var title: String = "" { didSet { accessoryView?.title = title } } /// Used to set a subtitle that will go right underneath the title. The default value for this is `""`, and will thus not be displayed. @IBInspectable public var subtitle: String = "" { didSet { accessoryView?.subtitle = subtitle } } /// Specifies which way the graph will go. This is an enum with two possible options: `.LeftToRight`, and `.RightToLeft`. Setting this will also change which corner the title and subtitle will get drawn in (upper left corner for `.RightToLeft`, and vice versa). It also changes which side the values for the y-axis gets drawn (right side for `.RightToLeft`, and vice versa). The default is `.RightToLeft`. public var graphDirection = GraphDirection.RightToLeft { didSet { accessoryView?.graphDirection = graphDirection lineView?.graphDirection = graphDirection } } /// This will set the background gradient of the graph. It's an enum with seven colors to pick from: `.Gray`, `.Red`, `.Green`, `.Blue`, `.Turquoise`, `.Yellow`, and `.Purple`. The default is `.Red`. public var themeColor = GraphColor.Red { didSet { gradientBackground.colors = themeColor.colors() } } /// This sets how many samples will fit within the view. E.g., if you set this to 200, what you will see in the view is the last 200 samples. You can't set it to any lower than 2 (for obvious reasons). The default value of this is 150. public var maxSamples = 150 { didSet { lineView?.maxSamples = max(2, maxSamples) } } /// Determines what the maximum expected value is. It is used as an upper limit for the view. The default is 1.0. @IBInspectable public var maxValue: CGFloat = 1.0 { didSet { accessoryView?.maxValue = maxValue lineView?.maxValue = maxValue } } /// Determines what the minimum expected value is. It is used as an lower limit for the view. The default is -1.0. @IBInspectable public var minValue: CGFloat = -1.0 { didSet { accessoryView?.minValue = minValue lineView?.minValue = minValue } } /// If you want your view to draw more than one graph at the same time (say x, y, z values of an accelerometer), you can specify that using this property. Notice that the `addSamples` method takes an argument of type `Double...` (called a variadic parameter). Whatever value you set for the `numberOfGraphs` property, you need to pass in the same number of arguments to this method, otherwise it will do nothing. If you change this property, all the samples you've added so far will be removed. The default is 1, meaning the `addSamples` method takes 1 argument. public var numberOfGraphs = 1 { didSet { lineView?.numberOfGraphs = max(1, numberOfGraphs) } } /// Use this to make the corners rounded or square. The default is true, meaning rounded corners. @IBInspectable public var roundedCorners = true { didSet { gradientBackground.cornerRadius = roundedCorners ? Constants.CornerRadius : 0.0 lineView?.cornerRadius = roundedCorners ? Constants.CornerRadius : 0.0 } } /// Changes how the samples are drawn. The current options are .Line and .Scatter. The default is .Line public var graphType = GraphType.Line { didSet { lineView?.graphType = graphType } } /// This method is where you add your data to the graph. The value of the samples you add should be within the range `[minValue, maxValue]`, otherwise the graph will draw outside the view. Notice that this takes `Double...` as an argument (called a variadic parameter), which means that you can pass it one or more `Double` values as arguments. This is so that you can draw multiple graphs in the same view at the same time (say x, y, z data from an accelerometer). The number of arguments you pass needs to correspond to the `numberOfGraphs` property, otherwise this method will do nothing. public func addSamples(newSamples: Double...) { lineView?.addSamples(newSamples) } /// Removes all the samples you've added to the graph. All the other properties like `roundedCorners` and `maxSamples` etc are kept the same. Useful if you want to reuse the same graph view. public func reset() { lineView?.reset() } // ------------------------------- // MARK: Drawing // ------------------------------- override public func layoutSublayersOfLayer(layer: CALayer) { if let selfLayer = self.layer { gradientBackground.frame = selfLayer.bounds accessoryView?.frame = selfLayer.bounds lineView?.frame = selfLayer.bounds } gradientBackground.removeAllAnimations() } override public func prepareForInterfaceBuilder() { addSubviews() if title == "" { title = "Heading" } if subtitle == "" { subtitle = "Subtitle" } for i in 0..<maxSamples { addSamples(sin(Double(i) * 0.1)) } } } private class LineView: NSView { private var sampleArrays = [[Double]]() // ------------------------------- // MARK: Properties // ------------------------------- var maxSamples = 0 { didSet { setNeedsDisplayInRect(bounds) } } var maxValue: CGFloat = 0.0 { didSet { setNeedsDisplayInRect(bounds) } } var minValue: CGFloat = 0.0 { didSet { setNeedsDisplayInRect(bounds) } } var cornerRadius = Constants.CornerRadius { didSet { layer?.cornerRadius = cornerRadius } } var graphType = MOONGraphView.GraphType.Line { didSet { setNeedsDisplayInRect(bounds) } } var graphDirection = MOONGraphView.GraphDirection.LeftToRight { didSet { setNeedsDisplayInRect(bounds) } } var numberOfGraphs = 1 { didSet { sampleArrays = [[Double]](count: numberOfGraphs, repeatedValue: [Double]()) setNeedsDisplayInRect(bounds) } } // ------------------------------- // MARK: Initialization // ------------------------------- override init(frame frameRect: NSRect) { super.init(frame: frameRect) setup() } required init?(coder: NSCoder) { super.init(coder: coder) setup() } private func setup() { wantsLayer = true layer?.cornerRadius = cornerRadius } // ------------------------------- // MARK: Methods // ------------------------------- func addSamples(newSamples: [Double]) { guard newSamples.count == sampleArrays.count else { return } for (index, samples) in sampleArrays.enumerate() { if samples.count == maxSamples { sampleArrays[index].removeFirst() } sampleArrays[index].append(newSamples[index]) } setNeedsDisplayInRect(bounds) } func reset() { sampleArrays = [[Double]()] setNeedsDisplayInRect(bounds) } // ------------------------------- // MARK: Drawing // ------------------------------- override func drawRect(dirtyRect: NSRect) { NSColor(white: 1.0, alpha: Constants.Alpha).set() // Sets both stroke and fill drawGraph() } private func drawGraph() { let widthPerSample = (bounds.width - Constants.ValueLabelWidth) / CGFloat(maxSamples - 1) let pointsToSampleValueRatio = (bounds.height - Constants.TickMargin * 2) / (maxValue - minValue) let progress = CGFloat(sampleArrays[0].count - 1) / CGFloat(maxSamples) let window = bounds.width - Constants.ValueLabelWidth for samples in sampleArrays { var currentXValue: CGFloat switch graphDirection { case .RightToLeft: currentXValue = (progress - 1.0) * -1.0 * window case .LeftToRight: currentXValue = progress * window + Constants.ValueLabelWidth } for (index, sample) in samples.enumerate() { guard index > 0 else { continue } // Skip the first one let x1: CGFloat = currentXValue let y1: CGFloat = (CGFloat(sample) - minValue) * pointsToSampleValueRatio + Constants.TickMargin let point1 = NSPoint(x: x1, y: y1) switch graphType { case .Line: var x2 = currentXValue switch graphDirection { case .RightToLeft: x2 -= widthPerSample case .LeftToRight: x2 += widthPerSample } let y2: CGFloat = (CGFloat(samples[index - 1]) - minValue) * pointsToSampleValueRatio + Constants.TickMargin let point2 = NSPoint(x: x2, y: y2) NSBezierPath.strokeLineFromPoint(point1, toPoint: point2) case .Scatter: NSBezierPath(ovalInRect: NSRect( x: x1 - Constants.ScatterPointRadius / 2.0, y: y1 - Constants.ScatterPointRadius / 2.0, width: Constants.ScatterPointRadius, height: Constants.ScatterPointRadius ) ).fill() } switch graphDirection { case .RightToLeft: currentXValue += widthPerSample case .LeftToRight: currentXValue -= widthPerSample } } } } } private class AccessoryView: NSView { // ------------------------------- // MARK: Properties // ------------------------------- var title = "" { didSet { setNeedsDisplayInRect(bounds) } } var subtitle = "" { didSet { setNeedsDisplayInRect(bounds) } } var maxValue: CGFloat = 0.0 { didSet { setNeedsDisplayInRect(bounds) } } var minValue: CGFloat = 0.0 { didSet { setNeedsDisplayInRect(bounds) } } var graphDirection = MOONGraphView.GraphDirection.LeftToRight { didSet { setNeedsDisplayInRect(bounds) } } // ------------------------------- // MARK: Drawing // ------------------------------- override func drawRect(dirtyRect: NSRect) { // drawValueLabelsFill() // Not yet sure if I prefer this on or off drawSeparatorLine() drawTicks() drawValueLabels() drawInformationLabels() } private func drawValueLabelsFill() { let fill = NSBezierPath() switch graphDirection { case .RightToLeft: fill.moveToPoint(NSPoint(x: bounds.width - Constants.ValueLabelWidth, y: 0.0)) fill.lineToPoint(NSPoint(x: bounds.width, y: 0.0)) fill.lineToPoint(NSPoint(x: bounds.width, y: bounds.height)) fill.lineToPoint(NSPoint(x: bounds.width - Constants.ValueLabelWidth, y: bounds.height)) case .LeftToRight: fill.moveToPoint(NSPoint(x: 0.0, y: 0.0)) fill.lineToPoint(NSPoint(x: Constants.ValueLabelWidth, y: 0.0)) fill.lineToPoint(NSPoint(x: Constants.ValueLabelWidth, y: bounds.height)) fill.lineToPoint(NSPoint(x: 0.0, y: bounds.height)) } NSColor(white: 1.0, alpha: 0.2).setFill() fill.fill() } private func drawSeparatorLine() { let separatorLine = NSBezierPath() switch graphDirection { case .RightToLeft: separatorLine.moveToPoint(NSPoint(x: bounds.width - Constants.ValueLabelWidth, y: 0.0)) separatorLine.lineToPoint(NSPoint(x: bounds.width - Constants.ValueLabelWidth, y: bounds.height)) case .LeftToRight: separatorLine.moveToPoint(NSPoint(x: Constants.ValueLabelWidth, y: 0.0)) separatorLine.lineToPoint(NSPoint(x: Constants.ValueLabelWidth, y: bounds.height)) } NSColor(white: 1.0, alpha: Constants.Alpha).setStroke() separatorLine.lineWidth = 1.0 separatorLine.stroke() } private func drawTicks() { let tick1 = NSBezierPath() let tick2 = NSBezierPath() let tick3 = NSBezierPath() switch graphDirection { case .RightToLeft: tick1.moveToPoint(NSPoint(x: bounds.width - Constants.ValueLabelWidth, y: Constants.TickMargin)) tick1.lineToPoint(NSPoint(x: bounds.width - Constants.ValueLabelWidth + Constants.TickWidth, y: Constants.TickMargin)) tick2.moveToPoint(NSPoint(x: bounds.width - Constants.ValueLabelWidth, y: bounds.height / 2.0)) tick2.lineToPoint(NSPoint(x: bounds.width - Constants.ValueLabelWidth + Constants.TickWidth / 2.0, y: bounds.height / 2.0)) tick3.moveToPoint(NSPoint(x: bounds.width - Constants.ValueLabelWidth, y: bounds.height - Constants.TickMargin)) tick3.lineToPoint(NSPoint(x: bounds.width - Constants.ValueLabelWidth + Constants.TickWidth, y: bounds.height - Constants.TickMargin)) case .LeftToRight: tick1.moveToPoint(NSPoint(x: Constants.ValueLabelWidth, y: Constants.TickMargin)) tick1.lineToPoint(NSPoint(x: Constants.ValueLabelWidth - Constants.TickWidth, y: Constants.TickMargin)) tick2.moveToPoint(NSPoint(x: Constants.ValueLabelWidth, y: bounds.height / 2.0)) tick2.lineToPoint(NSPoint(x: Constants.ValueLabelWidth - Constants.TickWidth / 2.0, y: bounds.height / 2.0)) tick3.moveToPoint(NSPoint(x: Constants.ValueLabelWidth, y: bounds.height - Constants.TickMargin)) tick3.lineToPoint(NSPoint(x: Constants.ValueLabelWidth - Constants.TickWidth, y: bounds.height - Constants.TickMargin)) } NSColor(white: 1.0, alpha: Constants.Alpha).setStroke() tick1.lineWidth = 1.0 tick2.lineWidth = 1.0 tick3.lineWidth = 1.0 tick1.stroke() tick2.stroke() tick3.stroke() } private func drawValueLabels() { let attributes = [ NSFontAttributeName : NSFont(name: Constants.FontName, size: 15)!, NSForegroundColorAttributeName: NSColor(white: 1.0, alpha: 0.8) ] as Dictionary<String, AnyObject> let label1 = NSAttributedString(string: String(format: "%.2f", arguments: [minValue]), attributes: attributes) let label2 = NSAttributedString(string: String(format: "%.2f", arguments: [(maxValue-minValue)/2.0 + minValue]), attributes: attributes) let label3 = NSAttributedString(string: String(format: "%.2f", arguments: [maxValue]), attributes: attributes) let alignmentCoefficient: CGFloat = 2.0 switch graphDirection { case .RightToLeft: let x = bounds.width - Constants.ValueLabelWidth + Constants.TickWidth + 5.0 label1.drawInRect(NSRect( x : x, y : Constants.TickMargin - (label1.size().height / 2.0) + alignmentCoefficient, width : label1.size().width, height : label1.size().height) ) label2.drawInRect(NSRect( x : x, y: bounds.height / 2.0 - (label2.size().height / 2.0) + alignmentCoefficient, width : label2.size().width, height : label2.size().height) ) label3.drawInRect(NSRect( x : x, y : bounds.height - Constants.TickMargin - (label3.size().height / 2.0) + alignmentCoefficient, width : label3.size().width, height : label3.size().height) ) case .LeftToRight: let x = Constants.ValueLabelWidth - Constants.TickWidth - 5.0 label1.drawInRect(NSRect( x : x - label1.size().width, y : Constants.TickMargin - (label1.size().height / 2.0) + alignmentCoefficient, width : label1.size().width, height : label1.size().height) ) label2.drawInRect(NSRect( x : x - label2.size().width, y : bounds.height / 2.0 - (label2.size().height / 2.0) + alignmentCoefficient, width : label2.size().width, height : label2.size().height) ) label3.drawInRect(NSRect( x : x - label3.size().width, y : bounds.height - Constants.TickMargin - (label3.size().height / 2.0) + alignmentCoefficient, width : label3.size().width, height : label3.size().height) ) } } private func drawInformationLabels() { let titleAttributes = [ NSFontAttributeName : NSFont(name: Constants.FontName, size: 30)!, NSForegroundColorAttributeName: NSColor.whiteColor() ] as Dictionary<String, AnyObject> let subTitleAttributes = [ NSFontAttributeName : NSFont(name: Constants.FontName, size: 20)!, NSForegroundColorAttributeName: NSColor(white: 1.0, alpha: Constants.Alpha) ] as Dictionary<String, AnyObject> let titleLabel = NSAttributedString(string: title, attributes: titleAttributes) let subTitleLabel = NSAttributedString(string: subtitle, attributes: subTitleAttributes) let horizontalMargin : CGFloat = 20.0 let verticalMargin : CGFloat = 30.0 let titleY = bounds.height - titleLabel.size().height - horizontalMargin let subTitleY = titleY - subTitleLabel.size().height switch graphDirection { case .RightToLeft: titleLabel .drawInRect(NSRect( x : verticalMargin, y : titleY, width : titleLabel.size().width, height : titleLabel.size().height) ) subTitleLabel.drawInRect(NSRect( x : verticalMargin, y : subTitleY, width : subTitleLabel.size().width, height : subTitleLabel.size().height)) case .LeftToRight: let x = bounds.width - verticalMargin - max(titleLabel.size().width, subTitleLabel.size().width) titleLabel .drawInRect(NSRect( x : x, y : titleY, width : titleLabel.size().width, height : titleLabel.size().height) ) subTitleLabel.drawInRect(NSRect( x : x, y : subTitleY, width : subTitleLabel.size().width, height : subTitleLabel.size().height) ) } } }
mit
8076263bc46e7bf16aba48658698b0cf
37.959375
595
0.550934
4.610577
false
false
false
false
aotian16/SwiftColor
TestColorPlayground.playground/Contents.swift
1
2631
//: Playground - noun: a place where people can play import UIKit public extension UIColor { public convenience init(hexString: String, alpha: Float = 1, defaultColor: UIColor = UIColor.whiteColor()) { var hex = hexString // Check for hash and remove the hash if hex.hasPrefix("#") { hex = hex.substringFromIndex(hex.startIndex.advancedBy(1)) } if (hex.rangeOfString("(^[0-9A-Fa-f]{6}$)|(^[0-9A-Fa-f]{3}$)", options: .RegularExpressionSearch) != nil) { // Deal with 3 character Hex strings if hex.characters.count == 3 { let redHex = hex.substringToIndex(hex.startIndex.advancedBy(1)) let greenHex = hex.substringWithRange(Range<String.Index>(start: hex.startIndex.advancedBy(1), end: hex.startIndex.advancedBy(2))) let blueHex = hex.substringFromIndex(hex.startIndex.advancedBy(2)) hex = redHex + redHex + greenHex + greenHex + blueHex + blueHex } let startIndex = hex.startIndex let endIndex = hex.endIndex let redRange = Range(start: startIndex, end: startIndex.advancedBy(2)) let greenRange = Range(start: startIndex.advancedBy(2), end: startIndex.advancedBy(4)) let blueRange = Range(start: startIndex.advancedBy(4), end: endIndex) let redHex = hex.substringWithRange(redRange) let greenHex = hex.substringWithRange(greenRange) let blueHex = hex.substringWithRange(blueRange) let redInt = Int(redHex,radix: 16)! let greenInt = Int(greenHex,radix: 16)! let blueInt = Int(blueHex,radix: 16)! self.init(red: CGFloat(redInt) / 255.0, green: CGFloat(greenInt) / 255.0, blue: CGFloat(blueInt) / 255.0, alpha: CGFloat(alpha)) } else { var r: CGFloat = 0 var g: CGFloat = 0 var b: CGFloat = 0 var a: CGFloat = 0 defaultColor.getRed(&r, green: &g, blue: &b, alpha: &a) self.init(red: r, green: g, blue: b, alpha: a) } } } let color1 = UIColor(hexString: "#66ccff")// default alpha = 1 let color2 = UIColor(hexString: "#66ccff", alpha: 0.5)// with alpha param let color3 = UIColor(hexString: "66ccff", alpha: 0.5)// without # let color4 = UIColor(hexString: "6cf", alpha: 0.5)// short version let color5 = UIColor(hexString: "#error", defaultColor: UIColor.redColor())// return default color when error.
mit
f4bd54ec22d02dba8afeb378492f7bdb
43.59322
146
0.583428
4.257282
false
false
false
false
gottesmm/swift
test/ClangImporter/optional.swift
2
3078
// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -Xllvm -new-mangling-for-tests -I %S/Inputs/custom-modules -emit-silgen -o - %s | %FileCheck %s // REQUIRES: objc_interop import ObjectiveC import Foundation import objc_ext import TestProtocols class A { @objc func foo() -> String? { return "" } // CHECK-LABEL: sil hidden [thunk] @_T08optional1AC3fooSSSgyFTo : $@convention(objc_method) (A) -> @autoreleased Optional<NSString> // CHECK: bb0([[SELF:%.*]] : $A): // CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]] // CHECK: [[T0:%.*]] = function_ref @_T08optional1AC3fooSSSgyF // CHECK-NEXT: [[T1:%.*]] = apply [[T0]]([[SELF_COPY]]) // CHECK-NEXT: destroy_value [[SELF_COPY]] // CHECK: [[T2:%.*]] = select_enum [[T1]] // CHECK-NEXT: cond_br [[T2]] // Something branch: project value, translate, inject into result. // CHECK: [[STR:%.*]] = unchecked_enum_data [[T1]] // CHECK: [[T0:%.*]] = function_ref @_T0SS10FoundationE19_bridgeToObjectiveCSo8NSStringCyF // CHECK-NEXT: [[T1:%.*]] = apply [[T0]]([[STR]]) // CHECK-NEXT: enum $Optional<NSString>, #Optional.some!enumelt.1, [[T1]] // CHECK-NEXT: destroy_value [[STR]] // CHECK-NEXT: br // Nothing branch: inject nothing into result. // CHECK: enum $Optional<NSString>, #Optional.none!enumelt // CHECK-NEXT: br // Continuation. // CHECK: bb3([[T0:%.*]] : $Optional<NSString>): // CHECK-NEXT: return [[T0]] @objc func bar(x x : String?) {} // CHECK-LABEL: sil hidden [thunk] @_T08optional1AC3barySSSg1x_tFTo : $@convention(objc_method) (Optional<NSString>, A) -> () // CHECK: bb0([[ARG:%.*]] : $Optional<NSString>, [[SELF:%.*]] : $A): // CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]] // CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]] // CHECK: [[T1:%.*]] = select_enum [[ARG_COPY]] // CHECK-NEXT: cond_br [[T1]] // Something branch: project value, translate, inject into result. // CHECK: [[NSSTR:%.*]] = unchecked_enum_data [[ARG_COPY]] // CHECK: [[T0:%.*]] = function_ref @_T0SS10FoundationE36_unconditionallyBridgeFromObjectiveCSSSo8NSStringCSgFZ // Make a temporary initialized string that we're going to clobber as part of the conversion process (?). // CHECK-NEXT: [[NSSTR_BOX:%.*]] = enum $Optional<NSString>, #Optional.some!enumelt.1, [[NSSTR]] : $NSString // CHECK-NEXT: [[STRING_META:%.*]] = metatype $@thin String.Type // CHECK-NEXT: [[T1:%.*]] = apply [[T0]]([[NSSTR_BOX]], [[STRING_META]]) // CHECK-NEXT: enum $Optional<String>, #Optional.some!enumelt.1, [[T1]] // CHECK-NEXT: br // Nothing branch: inject nothing into result. // CHECK: enum $Optional<String>, #Optional.none!enumelt // CHECK-NEXT: br // Continuation. // CHECK: bb3([[T0:%.*]] : $Optional<String>): // CHECK: [[T1:%.*]] = function_ref @_T08optional1AC3barySSSg1x_tF // CHECK-NEXT: [[T2:%.*]] = apply [[T1]]([[T0]], [[SELF_COPY]]) // CHECK-NEXT: destroy_value [[SELF_COPY]] // CHECK-NEXT: return [[T2]] : $() } // rdar://15144951 class TestWeak : NSObject { weak var b : WeakObject? = nil } class WeakObject : NSObject {}
apache-2.0
e619349840530498f9ed8c8b6374a0c8
44.264706
157
0.621507
3.264051
false
false
false
false
VBVMI/VerseByVerse-iOS
VBVMI/TopicLabel.swift
1
1828
// // TagLabel.swift // VBVMI // // Created by Thomas Carey on 26/03/16. // Copyright © 2016 Tom Carey. All rights reserved. // import Foundation import UIKit import UIImage_Color class TopicAttachment : NSTextAttachment { var topic: Topic? } class TopicButton: UIButton { override dynamic var tintColor: UIColor! { get { return super.tintColor } set { super.tintColor = newValue configureColor() } } fileprivate func configureColor() { self.setTitleColor(tintColor, for: UIControlState()) self.setTitleColor(StyleKit.white, for: .highlighted) self.setTitleColor(StyleKit.white, for: .selected) self.layer.borderColor = tintColor.cgColor let image = StyleKit.imageOfTopicLabelBackground.cl_change(tintColor).resizableImage(withCapInsets: UIEdgeInsets(top: 2, left: 2, bottom: 2, right: 2)) self.setBackgroundImage(image, for: .highlighted) self.setBackgroundImage(image, for: .selected) } var text: String? { didSet { self.setTitle(text, for: UIControlState()) self.invalidateIntrinsicContentSize() } } var topic: Topic? { didSet { self.text = topic?.name } } override init(frame: CGRect) { super.init(frame: frame) self.titleLabel?.font = UIFont.preferredFont(forTextStyle: UIFontTextStyle.caption1) self.layer.borderWidth = 1.0 / UIScreen.main.scale self.layer.cornerRadius = 2 // self.layer.masksToBounds = true self.contentEdgeInsets = UIEdgeInsets(top: 2, left: 4, bottom: 2, right: 4) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
mit
4806d2488a755c48d5858d33abf8b08e
27.546875
159
0.624521
4.445255
false
false
false
false
flowsprenger/RxLifx-Swift
RxLifxExample/RxLifxExample/AppDelegate.swift
1
2757
/* Copyright 2017 Florian Sprenger 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 @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate, UISplitViewControllerDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { 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) { } func applicationDidEnterBackground(_ application: UIApplication) { } func applicationWillEnterForeground(_ application: UIApplication) { } func applicationDidBecomeActive(_ application: UIApplication) { } func applicationWillTerminate(_ application: UIApplication) { } // 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 } return false } }
mit
a5e4dcc84367371105cfccb87306af96
42.761905
189
0.778745
6.099558
false
false
false
false
grandiere/box
box/View/Store/VStoreCellNotAvailable.swift
1
806
import UIKit class VStoreCellNotAvailable:VStoreCell { override init(frame:CGRect) { super.init(frame:frame) backgroundColor = UIColor.clear isUserInteractionEnabled = false let label:UILabel = UILabel() label.translatesAutoresizingMaskIntoConstraints = false label.isUserInteractionEnabled = false label.textAlignment = NSTextAlignment.center label.font = UIFont.regular(size:15) label.textColor = UIColor(white:0.8, alpha:1) label.text = NSLocalizedString("VStoreCellNotAvailable_label", comment:"") addSubview(label) NSLayoutConstraint.equals( view:label, toView:self) } required init?(coder:NSCoder) { return nil } }
mit
27114c0d32a1aebf691f89ec6f15199f
25.866667
82
0.626551
5.267974
false
false
false
false
cruisediary/Diving
Diving/Scenes/UserDetail/UserDetailConfigurator.swift
1
1604
// // UserDetailConfigurator.swift // Diving // // Created by CruzDiary on 5/23/16. // Copyright (c) 2016 DigitalNomad. All rights reserved. // // This file was generated by the Clean Swift Xcode Templates so you can apply // clean architecture to your iOS and Mac projects, see http://clean-swift.com // import UIKit // MARK: Connect View, Interactor, and Presenter extension UserDetailViewController: UserDetailPresenterOutput { override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { router.passDataToNextScene(segue) } } extension UserDetailInteractor: UserDetailViewControllerOutput { } extension UserDetailPresenter: UserDetailInteractorOutput { } class UserDetailConfigurator { // MARK: Object lifecycle class var sharedInstance: UserDetailConfigurator { struct Static { static var instance: UserDetailConfigurator? static var token: dispatch_once_t = 0 } dispatch_once(&Static.token) { Static.instance = UserDetailConfigurator() } return Static.instance! } // MARK: Configuration func configure(viewController: UserDetailViewController) { let router = UserDetailRouter() router.viewController = viewController let presenter = UserDetailPresenter() presenter.output = viewController let interactor = UserDetailInteractor() interactor.output = presenter viewController.output = interactor viewController.router = router } }
mit
88bc98bf3d14021aaa80a6c8dcc10259
26.186441
81
0.676434
5.328904
false
true
false
false
lgp123456/tiantianTV
douyuTV/douyuTV/Classes/Live/Controller/ChildVc/XTGameLiveViewController.swift
1
548
// // XTGameLiveViewController.swift // douyuTV // // Created by 李贵鹏 on 16/8/30. // Copyright © 2016年 李贵鹏. All rights reserved. // import UIKit class XTGameLiveViewController: XTBaseLiveViewController { override func viewDidLoad() { super.viewDidLoad() // url = "http://capi.douyucdn.cn/api/v1/getColumnRoom/1?aid=ios&client_sys=ios&limit=20&offset=0&time=1469008980&auth=3392837008aa8938f7dce0d8c72c321d" url = "http://capi.douyucdn.cn/api/v1/getColumnRoom/1?limit=20&offset=0" } }
mit
e4c8739d7b0248245d8eaf7c62c9573f
25.65
160
0.690432
2.820106
false
false
false
false
lanjing99/iOSByTutorials
iOS 8 by tutorials/Chapter 10 - Extensions - Share/Imgvue/Imgvue/HotGalleryViewController.swift
1
5017
/* * Copyright (c) 2014 Razeware LLC * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ import Foundation import UIKit import ImgvueKit class HotGalleryViewController: UIViewController, UICollectionViewDataSource, UIImagePickerControllerDelegate, UINavigationControllerDelegate { @IBOutlet var imagesCollectionView: UICollectionView! var progressView: UIProgressView! var images: [ImgurImage] = [] override func viewDidLoad() { super.viewDidLoad(); let progressNavigationController = navigationController as! ProgressNavigationController progressView = progressNavigationController.progressView progressView.hidden = true ImgurService.sharedService.hotViralGalleryThumbnailImagesPage(0) { images, error in if error == nil { self.images = images! dispatch_async(dispatch_get_main_queue()) { self.imagesCollectionView.reloadData() } } else { NSLog("Error fetching hot images: %@", error!) } } } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) { if segue.identifier == "ViewImage" { let imageViewController = segue.destinationViewController as! ImgurImageViewController let cell = sender as! ImageCollectionViewCell if let indexPath = imagesCollectionView.indexPathForCell(cell) { imageViewController.imgurImage = images[indexPath.row] } } } @IBAction func share(sender: UIBarButtonItem) { let imagePicker = UIImagePickerController() imagePicker.delegate = self imagePicker.sourceType = .SavedPhotosAlbum presentViewController(imagePicker, animated: true, completion: nil) } func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) { // func imagePickerController(picker: UIImagePickerController!, didFinishPickingMediaWithInfo info: NSDictionary!) { let selectedImage = info[UIImagePickerControllerOriginalImage] as! UIImage dismissViewControllerAnimated(true, completion: nil) let completedBlock: (ImgurImage?, NSError?) -> () = { image, error in if error == nil { if let imageLink = image?.link { let alertController = UIAlertController(title: "Upload Finished", message: "URL: \(imageLink.absoluteString)", preferredStyle: .Alert) let openAction = UIAlertAction(title: "Open", style: .Default) { _ in let _ = UIApplication.sharedApplication().openURL(imageLink) } let copyAction = UIAlertAction(title: "Copy", style: .Default) { _ in UIPasteboard.generalPasteboard().URL = imageLink } alertController.addAction(openAction) alertController.addAction(copyAction) self.presentViewController(alertController, animated: true, completion: nil) self.progressView.hidden = true self.progressView.setProgress(0, animated: false) } } else { NSLog("Upload error: %@", error!) self.progressView.hidden = true } } let progressBlock: (Float) -> () = { progress in if progress > 0 { self.progressView.hidden = false; self.progressView.setProgress(progress, animated: true) } } ImgurService.sharedService.uploadImage(selectedImage, title: "Swift", completion: completedBlock, progressCallback: progressBlock) } // MARK - UICollectionViewDataSource func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return images.count } func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCellWithReuseIdentifier("ImageCell", forIndexPath: indexPath) as! ImageCollectionViewCell cell.imgurImage = images[indexPath.row] return cell } }
mit
dd5e23aa3e265e96aae9373fb5275f14
38.825397
143
0.712577
5.37152
false
false
false
false
weipin/jewzruxin
Jewzruxin/Source/HTTP/Cycle+Convenience.swift
1
11198
// // Cycle+Convenience.swift // // Copyright (c) 2015 Weipin Xia // // Permission is hereby granted, free of charge, to any person obtaining a copy of // this software and associated documentation files (the "Software"), to deal in // the Software without restriction, including without limitation the rights to // use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of // the Software, and to permit persons to whom the Software is furnished to do so, // subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS // FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR // COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER // IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN // CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // import Foundation public extension HTTPCycle { public static func URLForString(URLString: String, parameters: [String: AnyObject]? = nil) -> NSURL? { var str = URLString if URLString == "" { return nil } if parameters != nil { // To leave the original URL as it was, only "merge" if `parameters` isn't empty. str = URLString.stringByMergingQueryParameters(parameters!) } var URL = NSURL(string: str) if URL == nil { // May have illegal parts in the URL parameters, try merge first // (so the query parameters in the URL part can be encoded) if we haven't. if parameters == nil { str = URLString.stringByMergingQueryParameters([:]) } URL = NSURL(string: str) if URL == nil { // If still fails, the base URL could also have illegal parts, // encode the entire URL anyway if let s = str.stringByEscapingToURLArgumentString() { URL = NSURL(string: s) } } } return URL } public class func createAndStartCycle(URLString: String, method: String, parameters: [String: AnyObject]? = nil, requestObject: AnyObject? = nil, requestProcessors: [HTTPProcessor]? = nil, responseProcessors: [HTTPProcessor]? = nil, authentications: [HTTPAuthentication]? = nil, solicited: Bool = false, completionHandler: HTTPCycle.CompletionHandler) throws -> HTTPCycle { guard let URL = self.URLForString(URLString, parameters: parameters) else { throw Error.InvalidURL } let cycle = HTTPCycle(requestURL: URL, taskType: .Data, requestMethod: method, requestObject: requestObject, requestProcessors: requestProcessors, responseProcessors: responseProcessors) if authentications != nil { cycle.authentications = authentications! } cycle.solicited = solicited cycle.start(completionHandler) return cycle } /** Send a GET request and retrieve the content of the given URL. - Parameter URLString: The URL string of the request. - Parameter parameters: The parameters of the query. - Parameter requestProcessors: An array of `HTTPProcessor` subclass objects. - Parameter responseProcessors: An array of `HTTPProcessor` subclass objects. - Parameter authentications: An array of `HTTPAuthentication` objects. - Parameter solicited: Affect the `HTTPCycle`'s retry logic. If solicited is true, the number of retries is unlimited until the transfer finishes successfully. - Parameter completionHandler: Called when the content of the given URL is retrieved or an error occurs. - Throws: `Error.InvalidURL` if the parameter `URLString` is invalid. */ public class func get(URLString: String, parameters: [String: AnyObject]? = nil, requestProcessors: [HTTPProcessor]? = nil, responseProcessors: [HTTPProcessor]? = nil, authentications: [HTTPAuthentication]? = nil, solicited: Bool = false, completionHandler: HTTPCycle.CompletionHandler) throws -> HTTPCycle { return try self.createAndStartCycle(URLString, method: "GET", parameters: parameters, requestProcessors: requestProcessors, responseProcessors:responseProcessors, authentications: authentications, solicited: solicited, completionHandler: completionHandler) } /// Send a HEAD request and retrieve the content of the given URL. public class func head(URLString: String, parameters: [String: AnyObject]? = nil, requestProcessors: [HTTPProcessor]? = nil, responseProcessors: [HTTPProcessor]? = nil, authentications: [HTTPAuthentication]? = nil, solicited: Bool = false, completionHandler: HTTPCycle.CompletionHandler) throws -> HTTPCycle { return try self.createAndStartCycle(URLString, method: "HEAD", parameters: parameters, requestProcessors: requestProcessors, responseProcessors: responseProcessors, authentications: authentications, solicited: solicited, completionHandler: completionHandler) } /// Send a POST request and retrieve the content of the given URL. public class func post(URLString: String, parameters: [String: AnyObject]? = nil, requestObject: AnyObject? = nil, requestProcessors: [HTTPProcessor]? = nil, responseProcessors: [HTTPProcessor]? = nil, authentications: [HTTPAuthentication]? = nil, solicited: Bool = false, completionHandler: HTTPCycle.CompletionHandler) throws -> HTTPCycle { return try self.createAndStartCycle(URLString, method: "POST", parameters: parameters, requestObject: requestObject, requestProcessors: requestProcessors, responseProcessors: responseProcessors, authentications: authentications, solicited: solicited, completionHandler: completionHandler) } /// Send a PUT request and retrieve the content of the given URL. public class func put(URLString: String, parameters: [String: AnyObject]? = nil, requestObject: AnyObject? = nil, requestProcessors: [HTTPProcessor]? = nil, responseProcessors: [HTTPProcessor]? = nil, authentications: [HTTPAuthentication]? = nil, solicited: Bool = false, completionHandler: HTTPCycle.CompletionHandler) throws -> HTTPCycle { return try self.createAndStartCycle(URLString, method: "PUT", parameters: parameters, requestObject: requestObject, requestProcessors: requestProcessors, responseProcessors: responseProcessors, authentications: authentications, solicited: solicited, completionHandler: completionHandler) } /// Send a PATCH request and retrieve the content of the given URL. public class func patch(URLString: String, parameters: [String: AnyObject]? = nil, requestObject: AnyObject? = nil, requestProcessors: [HTTPProcessor]? = nil, responseProcessors: [HTTPProcessor]? = nil, authentications: [HTTPAuthentication]? = nil, solicited: Bool = false, completionHandler: HTTPCycle.CompletionHandler) throws -> HTTPCycle { return try self.createAndStartCycle(URLString, method: "PATCH", parameters: parameters, requestObject: requestObject, requestProcessors: requestProcessors, responseProcessors: responseProcessors, authentications: authentications, solicited: solicited, completionHandler: completionHandler) } /// Send a DELETE request and retrieve the content of the given URL. public class func delete(URLString: String, parameters: [String: AnyObject]? = nil, requestObject: AnyObject? = nil, requestProcessors: [HTTPProcessor]? = nil, responseProcessors: [HTTPProcessor]? = nil, authentications: [HTTPAuthentication]? = nil, solicited: Bool = false, completionHandler: HTTPCycle.CompletionHandler) throws -> HTTPCycle { return try self.createAndStartCycle(URLString, method: "DELETE", parameters: parameters, requestObject: requestObject, requestProcessors: requestProcessors, responseProcessors: responseProcessors, authentications: authentications, solicited: solicited, completionHandler: completionHandler) } /** Upload data to the given URL. - Parameter URLString: The URL of the request. - Parameter source: The data to upload. - Parameter parameters: The parameters of the query. - Parameter authentications: An array of `HTTPAuthentication` objects. - Parameter didSendDataHandler: Called with upload progress information. - Parameter completionHandler: Called when the content of the given URL is retrieved or an error occurs. - Throws: `Error.InvalidURL` if the parameter `URLString` is invalid. - Returns: A new `HTTPCycle`. */ public class func upload(URLString: String, source: HTTPCycle.UploadSource, parameters: [String: AnyObject]? = nil, authentications: [HTTPAuthentication]? = nil, didSendBodyDataHandler: HTTPCycle.DidSendBodyDataHandler? = nil, completionHandler: HTTPCycle.CompletionHandler) throws -> HTTPCycle { var str = URLString if parameters != nil { str = URLString.stringByMergingQueryParameters(parameters!) } guard let URL = NSURL(string: str) else { throw Error.InvalidURL } let cycle = HTTPCycle(requestURL: URL, taskType: .Upload, requestMethod: "POST") if authentications != nil { cycle.authentications = authentications! } cycle.uploadSource = source cycle.didSendBodyDataHandler = didSendBodyDataHandler cycle.start(completionHandler) return cycle } /** Download data from the given URL. - Parameter URLString: The URL of the request. - Parameter parameters: The parameters of the query. - Parameter authentications: An array of `HTTPAuthentication` objects. - Parameter didWriteDataHandler: Called with download progress information. - Parameter downloadFileHandler: Called with the URL to a temporary file where the downloaded content is stored. - Parameter completionHandler: Called when the content of the given URL is retrieved or an error occurs. - Throws: `Error.InvalidURL` if the parameter `URLString` is invalid. - Returns: A new `HTTPCycle`. */ public class func download(URLString: String, parameters: [String: AnyObject]? = nil, authentications: [HTTPAuthentication]? = nil, didWriteDataHandler: HTTPCycle.DidWriteBodyDataHandler? = nil, downloadFileHandler: HTTPCycle.DownloadFileHander, completionHandler: HTTPCycle.CompletionHandler) throws -> HTTPCycle { var str = URLString if parameters != nil { str = URLString.stringByMergingQueryParameters(parameters!) } guard let URL = NSURL(string: str) else { throw Error.InvalidURL } let cycle = HTTPCycle(requestURL: URL, taskType: .Download, requestMethod: "GET") if authentications != nil { cycle.authentications = authentications! } cycle.didWriteDataHandler = didWriteDataHandler cycle.downloadFileHandler = downloadFileHandler cycle.start(completionHandler) return cycle } }
mit
2b981748a3e9b1ca9897cb8a3936e318
63.356322
377
0.72245
4.864466
false
false
false
false
SwiftOnEdge/Edge
Sources/HTTP/Status.swift
1
16360
// // Status.swift // Edge // // Created by Tyler Fleming Cloutier on 10/16/16. // // import Foundation public enum Status { case `continue` case switchingProtocols case processing case ok case created case accepted case nonAuthoritativeInformation case noContent case resetContent case partialContent case multiStatus case alreadyReported case imUsed case multipleChoices case movedPermanently case found case seeOther case notModified case useProxy case switchProxy case temporaryRedirect case permanentRedirect case badRequest case unauthorized case paymentRequired case forbidden case notFound case methodNotAllowed case notAcceptable case proxyAuthenticationRequired case requestTimeout case conflict case gone case lengthRequired case preconditionFailed case requestEntityTooLarge case requestURITooLong case unsupportedMediaType case requestedRangeNotSatisfiable case expectationFailed case imATeapot case authenticationTimeout case enhanceYourCalm case misdirectedRequest case unprocessableEntity case locked case failedDependency case unorderedCollection case upgradeRequired case preconditionRequired case tooManyRequests case requestHeaderFieldsTooLarge case unavailableForLegalReasons case internalServerError case notImplemented case badGateway case serviceUnavailable case gatewayTimeout case httpVersionNotSupported case variantAlsoNegotiates case insufficientStorage case loopDetected case bandwidthLimitExceeded case notExtended case networkAuthenticationRequired case other(code: Int, reasonPhrase: String) } extension Status { public init(code: Int, reasonPhrase: String? = nil) { if let reasonPhrase = reasonPhrase { self = .other(code: code, reasonPhrase: reasonPhrase) } else { switch code { case Status.`continue`.code: self = .`continue` case Status.switchingProtocols.code: self = .switchingProtocols case Status.processing.code: self = .processing case Status.ok.code: self = .ok case Status.created.code: self = .created case Status.accepted.code: self = .accepted case Status.nonAuthoritativeInformation.code: self = .nonAuthoritativeInformation case Status.noContent.code: self = .noContent case Status.resetContent.code: self = .resetContent case Status.partialContent.code: self = .partialContent case Status.alreadyReported.code: self = .alreadyReported case Status.multiStatus.code: self = .multiStatus case Status.imUsed.code: self = .imUsed case Status.multipleChoices.code: self = .multipleChoices case Status.movedPermanently.code: self = .movedPermanently case Status.found.code: self = .found case Status.seeOther.code: self = .seeOther case Status.notModified.code: self = .notModified case Status.useProxy.code: self = .useProxy case Status.switchProxy.code: self = .switchProxy case Status.temporaryRedirect.code: self = .temporaryRedirect case Status.permanentRedirect.code: self = .permanentRedirect case Status.badRequest.code: self = .badRequest case Status.unauthorized.code: self = .unauthorized case Status.paymentRequired.code: self = .paymentRequired case Status.forbidden.code: self = .forbidden case Status.notFound.code: self = .notFound case Status.methodNotAllowed.code: self = .methodNotAllowed case Status.notAcceptable.code: self = .notAcceptable case Status.proxyAuthenticationRequired.code: self = .proxyAuthenticationRequired case Status.requestTimeout.code: self = .requestTimeout case Status.conflict.code: self = .conflict case Status.gone.code: self = .gone case Status.lengthRequired.code: self = .lengthRequired case Status.preconditionFailed.code: self = .preconditionFailed case Status.requestEntityTooLarge.code: self = .requestEntityTooLarge case Status.requestURITooLong.code: self = .requestURITooLong case Status.unsupportedMediaType.code: self = .unsupportedMediaType case Status.requestedRangeNotSatisfiable.code: self = .requestedRangeNotSatisfiable case Status.expectationFailed.code: self = .expectationFailed case Status.imATeapot.code: self = .imATeapot case Status.authenticationTimeout.code: self = .authenticationTimeout case Status.enhanceYourCalm.code: self = .enhanceYourCalm case Status.misdirectedRequest.code: self = .misdirectedRequest case Status.unprocessableEntity.code: self = .unprocessableEntity case Status.locked.code: self = .locked case Status.failedDependency.code: self = .failedDependency case Status.unorderedCollection.code: self = .unorderedCollection case Status.upgradeRequired.code: self = .upgradeRequired case Status.preconditionRequired.code: self = .preconditionRequired case Status.tooManyRequests.code: self = .tooManyRequests case Status.requestHeaderFieldsTooLarge.code: self = .requestHeaderFieldsTooLarge case Status.unavailableForLegalReasons.code: self = .unavailableForLegalReasons case Status.internalServerError.code: self = .internalServerError case Status.notImplemented.code: self = .notImplemented case Status.badGateway.code: self = .badGateway case Status.serviceUnavailable.code: self = .serviceUnavailable case Status.gatewayTimeout.code: self = .gatewayTimeout case Status.httpVersionNotSupported.code: self = .httpVersionNotSupported case Status.variantAlsoNegotiates.code: self = .variantAlsoNegotiates case Status.insufficientStorage.code: self = .insufficientStorage case Status.loopDetected.code: self = .loopDetected case Status.bandwidthLimitExceeded.code: self = .bandwidthLimitExceeded case Status.notExtended.code: self = .notExtended case Status.networkAuthenticationRequired.code: self = .networkAuthenticationRequired default: self = .other(code: code, reasonPhrase: "¯\\_(ツ)_/¯") } } } } extension Status { public var code: Int { switch self { case .`continue`: return 100 case .switchingProtocols: return 101 case .processing: return 102 case .ok: return 200 case .created: return 201 case .accepted: return 202 case .nonAuthoritativeInformation: return 203 case .noContent: return 204 case .resetContent: return 205 case .partialContent: return 206 case .multiStatus: return 207 case .alreadyReported: return 208 case .imUsed: return 226 case .multipleChoices: return 300 case .movedPermanently: return 301 case .found: return 302 case .seeOther: return 303 case .notModified: return 304 case .useProxy: return 305 case .switchProxy: return 306 case .temporaryRedirect: return 307 case .permanentRedirect: return 308 case .badRequest: return 400 case .unauthorized: return 401 case .paymentRequired: return 402 case .forbidden: return 403 case .notFound: return 404 case .methodNotAllowed: return 405 case .notAcceptable: return 406 case .proxyAuthenticationRequired: return 407 case .requestTimeout: return 408 case .conflict: return 409 case .gone: return 410 case .lengthRequired: return 411 case .preconditionFailed: return 412 case .requestEntityTooLarge: return 413 case .requestURITooLong: return 414 case .unsupportedMediaType: return 415 case .requestedRangeNotSatisfiable: return 416 case .expectationFailed: return 417 case .imATeapot: return 418 case .authenticationTimeout: return 419 case .enhanceYourCalm: return 420 case .misdirectedRequest: return 421 case .unprocessableEntity: return 422 case .locked: return 423 case .failedDependency: return 424 case .unorderedCollection: return 425 case .upgradeRequired: return 426 case .preconditionRequired: return 428 case .tooManyRequests: return 429 case .requestHeaderFieldsTooLarge: return 431 case .unavailableForLegalReasons: return 451 case .internalServerError: return 500 case .notImplemented: return 501 case .badGateway: return 502 case .serviceUnavailable: return 503 case .gatewayTimeout: return 504 case .httpVersionNotSupported: return 505 case .variantAlsoNegotiates: return 506 case .insufficientStorage: return 507 case .loopDetected: return 508 case .bandwidthLimitExceeded: return 509 case .notExtended: return 510 case .networkAuthenticationRequired: return 511 case .other(let code, _): return code } } } extension Status { public var reasonPhrase: String { switch self { case .`continue`: return "Continue" case .switchingProtocols: return "Switching Protocols" case .processing: return "Processing" case .ok: return "OK" case .created: return "Created" case .accepted: return "Accepted" case .nonAuthoritativeInformation: return "Non-Authoritative Information" case .noContent: return "No Content" case .resetContent: return "Reset Content" case .partialContent: return "Partial Content" case .multiStatus: return "Multi-Status" case .alreadyReported: return "Already Reported" case .imUsed: return "IM Used" case .multipleChoices: return "Multiple Choices" case .movedPermanently: return "Moved Permanently" case .found: return "Found" case .seeOther: return "See Other" case .notModified: return "Not Modified" case .useProxy: return "Use Proxy" case .switchProxy: return "Switch Proxy" case .temporaryRedirect: return "Temporary Redirect" case .permanentRedirect: return "Permanent Redirect" case .badRequest: return "Bad Request" case .unauthorized: return "Unauthorized" case .paymentRequired: return "Payment Required" case .forbidden: return "Forbidden" case .notFound: return "Not Found" case .methodNotAllowed: return "Method Not Allowed" case .notAcceptable: return "Not Acceptable" case .proxyAuthenticationRequired: return "Proxy Authentication Required" case .requestTimeout: return "Request Timeout" case .conflict: return "Conflict" case .gone: return "Gone" case .lengthRequired: return "Length Required" case .preconditionFailed: return "Precondition Failed" case .requestEntityTooLarge: return "Request Entity Too Large" case .requestURITooLong: return "Request URI Too Long" case .unsupportedMediaType: return "Unsupported Media Type" case .requestedRangeNotSatisfiable: return "Requested Range Not Satisfiable" case .expectationFailed: return "Expectation Failed" case .imATeapot: return "I'm a teapot" case .authenticationTimeout: return "Authentication Timeout" case .enhanceYourCalm: return "Enhance Your Calm" case .misdirectedRequest: return "Misdirected Request" case .unprocessableEntity: return "Unprocessable Entity" case .locked: return "Locked" case .failedDependency: return "Failed Dependency" case .unorderedCollection: return "Unordered Collection" case .upgradeRequired: return "Upgrade Required" case .preconditionRequired: return "Precondition Required" case .tooManyRequests: return "Too Many Requests" case .requestHeaderFieldsTooLarge: return "Request Header Fields Too Large" case .unavailableForLegalReasons: return "Unavailable For Legal Reasons" case .internalServerError: return "Internal Server Error" case .notImplemented: return "Not Implemented" case .badGateway: return "Bad Gateway" case .serviceUnavailable: return "Service Unavailable" case .gatewayTimeout: return "Gateway Timeout" case .httpVersionNotSupported: return "HTTP Version Not Supported" case .variantAlsoNegotiates: return "Variant Also Negotiates" case .insufficientStorage: return "Insufficient Storage" case .loopDetected: return "Loop Detected" case .bandwidthLimitExceeded: return "Bandwidth Limit Exceeded" case .notExtended: return "Not Extended" case .networkAuthenticationRequired: return "Network Authentication Required" case .other(_, let reasonPhrase): return reasonPhrase } } } extension Status: Hashable { public var hashValue: Int { return code } } public func == (lhs: Status, rhs: Status) -> Bool { return lhs.hashValue == rhs.hashValue }
mit
c0d048c1d18378c8887ef8f15d7bcaca
48.413897
97
0.567254
5.659516
false
false
false
false
KaushalElsewhere/AllHandsOn
ReorderingLogic.playground/Contents.swift
1
1312
//: Playground - noun: a place where people can play import UIKit import Foundation var arr:[Int?] = [10, 20, 30, nil] func moveElementOfArray(arr: [Int?], fromIndex: Int, toIndex: Int) -> [Int?] { var array = arr array.insert(array.removeAtIndex(fromIndex), atIndex: toIndex) return array } moveElementOfArray(arr, fromIndex: 1, toIndex: 0) //moveElementOfArray(arr, fromIndex: 1, toIndex: 0) extension String { public var first: String { return String(self[startIndex]) } public var initialsMax2: String { if self == "" || self == " " { return "" } let innputString = self.trim let initials = innputString.componentsSeparatedByString(" ") .reduce("") { $0 + $1.first }.uppercaseString if initials.characters.count > 2 { let index = initials.startIndex.advancedBy(2) let final = initials.substringToIndex(index) return final } return initials } public var trim: String { let input = self.stringByTrimmingCharactersInSet( NSCharacterSet.whitespaceAndNewlineCharacterSet() ) return input } } "Kaushal elsehwere :P".initialsMax2 "kaushal Elsewhere".first.uppercaseString
mit
3993160faf867f05f89b9bfb4ef4b445
22.854545
78
0.61128
4.432432
false
false
false
false
mlachmish/Cryptography
Cryptography/Algorithms/Hash/SHA1.swift
1
4658
// // SHA1.swift // Cryptography // // Created by Matan Lachmish on 07/07/2016. // Copyright © 2016 The Big Fat Ninja. All rights reserved. // import Foundation internal struct SHA1: HashProtocol { static let blockSize = 64 private static func preprocessMessage(message: Array<UInt8>) -> Array<UInt8> { var preprocessedMessage = message // Pre-processing: adding a single 1 bit // Notice: the input bytes are considered as bits strings, // where the first bit is the most significant bit of the byte. preprocessedMessage.append(0x80) // Pre-processing: padding with zeros // append "0" bit until message length in bits ≡ 448 (mod 512) let desiredMessageLengthModulo = blockSize - 8 var messageLength = preprocessedMessage.count var paddingCounter = 0 while messageLength % blockSize != desiredMessageLengthModulo { paddingCounter += 1 messageLength += 1 } preprocessedMessage += Array<UInt8>(count: paddingCounter, repeatedValue: 0) // append original length in bits mod (2 pow 64) to message preprocessedMessage.reserveCapacity(preprocessedMessage.count + 4) let lengthInBits = message.count * 8 let lengthBytes = Representations.toUInt8Array(lengthInBits, length: 64/8) preprocessedMessage += lengthBytes return preprocessedMessage } // swiftlint:disable function_body_length static func hash(message: [UInt8]) -> [UInt8] { // Initialize variables: var a0: UInt32 = 0x67452301 // A var b0: UInt32 = 0xefcdab89 // B var c0: UInt32 = 0x98badcfe // C var d0: UInt32 = 0x10325476 // D var e0: UInt32 = 0xC3D2E1F0 // E // Pre-processing let preprocessedMessage = preprocessMessage(message) // Process the message in successive 512-bit chunks: let chunkSizeBytes = 512 / 8 for chunk in preprocessedMessage.splitToChuncks(chunkSizeBytes) { // Break chunk into sixteen 32-bit big-endian words w[i], 0 ≤ i ≤ 15 // Extend the sixteen 32-bit words into eighty 32-bit words: var M: Array<UInt32> = Array<UInt32>(count: 80, repeatedValue: 0) for x in 0..<M.count { switch x { case 0...15: let start = chunk.startIndex + (x * sizeofValue(M[x])) let end = start + sizeofValue(M[x]) let le = Representations.mergeToUInt32Array(chunk[start..<end])[0] M[x] = le.bigEndian break default: M[x] = (M[x-3] ^ M[x-8] ^ M[x-14] ^ M[x-16]).rotateLeft(1) break } } // Initialize hash value for this chunk: var A = a0 var B = b0 var C = c0 var D = d0 var E = e0 // Main loop: for i in 0...79 { var f: UInt32 = 0 var k: UInt32 = 0 switch i { case 0...19: f = (B & C) | ((~B) & D) k = 0x5A827999 break case 20...39: f = B ^ C ^ D k = 0x6ED9EBA1 break case 40...59: f = (B & C) | (B & D) | (C & D) k = 0x8F1BBCDC break case 60...79: f = B ^ C ^ D k = 0xCA62C1D6 break default: break } let temp = (A.rotateLeft(5) &+ f &+ E &+ M[i] &+ k) & 0xffffffff E = D D = C C = B.rotateLeft(30) B = A A = temp } // Add this chunk's hash to result so far: a0 = (a0 &+ A) b0 = (b0 &+ B) c0 = (c0 &+ C) d0 = (d0 &+ D) e0 = (e0 &+ E) } // Produce the final hash value (big-endian) as a 160 bit number: var result = Array<UInt8>() result.reserveCapacity(160/8) [a0, b0, c0, d0, e0].forEach { result += Representations.toUInt8Array($0.bigEndian.reverseBytes()) } return result } // swiftlint:enable function_body_length static func hash(message: String) -> String { return Representations.toHexadecimalString(self.hash(Array(message.utf8))) } }
mit
255a38636689750427f9ea8ed5a25469
32.702899
86
0.500538
4.205244
false
false
false
false
ahoppen/swift
test/decl/func/vararg.swift
4
3282
// RUN: %target-typecheck-verify-swift var t1a: (Int...) = (1) // expected-error@-1 {{cannot create a variadic tuple}} var t2d: (Double = 0.0) = 1 // expected-error {{default argument not permitted in a tuple type}} {{18-23=}} func f1(_ a: Int...) { for _ in a {} } f1() f1(1) f1(1,2) func f2(_ a: Int, _ b: Int...) { for _ in b {} } f2(1) f2(1,2) f2(1,2,3) func f3(_ a: (String) -> Void) { } f3({ print($0) }) func f4(_ a: Int..., b: Int) { } // rdar://16008564 func inoutVariadic(_ i: inout Int...) { // expected-error {{'inout' must not be used on variadic parameters}} } // rdar://19722429 func invalidVariadic(_ e: NonExistentType) { // expected-error {{cannot find type 'NonExistentType' in scope}} { (e: ExtraCrispy...) in }() // expected-error {{cannot find type 'ExtraCrispy' in scope}} } func twoVariadics(_ a: Int..., b: Int...) { } func unlabeledFollowingVariadic(_ a: Int..., _ b: Int) { } // expected-error {{a parameter following a variadic parameter requires a label}} func unlabeledVariadicFollowingVariadic(_ a: Int..., _ b: Int...) { } // expected-error {{a parameter following a variadic parameter requires a label}} func unlabeledFollowingTwoVariadics(_ a: Int..., b: Int..., _ c: Int) { } // expected-error {{a parameter following a variadic parameter requires a label}} func splitVariadics(_ a: Int..., b: Int, _ c: String...) { } func splitByDefaultArgVariadics(_ a: Int..., b: Int = 0, _ c: String...) { } struct HasSubscripts { subscript(a: Int...) -> Void { () } subscript(a: Int..., b b: Int...) -> Void { () } subscript(a: Int..., b: Int...) -> Void { () } // expected-error {{a parameter following a variadic parameter requires a label}} subscript(a: Int..., b: Int) -> Void { () } // expected-error {{a parameter following a variadic parameter requires a label}} subscript(a: Int..., b b: Int..., c c: Int) -> Void { () } subscript(a: Int..., b b: Int..., c: Int) -> Void { () } // expected-error {{a parameter following a variadic parameter requires a label}} subscript(a: Int..., c c: Int = 0, b: Int...) -> Void { () } subscript(a: Int..., b: String = "hello, world!") -> Bool { false } // expected-error {{a parameter following a variadic parameter requires a label}} } struct HasInitializers { init(a: Int...) {} init(a: Int..., b: Int...) {} init(a: Int..., _ b: Int...) {} // expected-error {{a parameter following a variadic parameter requires a label}} init(a: Int..., c: Int = 0, _ b: Int...) {} } let closure = {(x: Int..., y: Int...) in } // expected-error {{no parameters may follow a variadic parameter in a closure}} let closure2 = {(x: Int..., y: Int) in } // expected-error {{no parameters may follow a variadic parameter in a closure}} let closure3 = {(x: Int..., y: Int, z: Int...) in } // expected-error {{no parameters may follow a variadic parameter in a closure}} let closure4 = {(x: Int...) in } let closure5 = {(x: Int, y: Int...) in } let closure6 = {(x: Int..., y z: Int) in } // expected-error {{closure cannot have keyword arguments}} // expected-error@-1 {{no parameters may follow a variadic parameter in a closure}} // rdar://22056861 func f5(_ list: Any..., end: String = "") {} f5(String()) // rdar://18083599 enum E1 { case On, Off } func doEV(_ state: E1...) {} doEV(.On)
apache-2.0
268f853c1105f1427ed4471917fa36b2
43.351351
155
0.620049
3.285285
false
false
false
false
lforme/VisualArts
VisualArts/NetworkingLayer/SignalProducerMapping.swift
1
2073
// // SignalProducerMapping.swift // API // // Created by ET|冰琳 on 2017/3/24. // Copyright © 2017年 IB. All rights reserved. // import Foundation import ReactiveSwift import MappingAce extension SignalProducer where Value: Any, Error: NSError { /// mapping entity func doMapping<T: Mapping>() -> SignalProducer<T, Error> { return self.map({ input -> T in if let value = input as? [String : Any] { let t: T = T.init(fromDic: value) return t } let t: T = T.init(fromDic: [String: Any]()) return t }) } func doMapping<T: Mapping>(_ result: T.Type) -> SignalProducer<T, Error> { return self.map({ input -> T in if let value = input as? [String : Any] { let t: T = T.init(fromDic: value) return t } let t: T = T.init(fromDic: [String: Any]()) return t }) } /// mapping entity array func doArrayMapping<T: Mapping>() -> SignalProducer<[T], Error> { return self.map({ input -> [T] in guard let value = input as? [[String : Any]] else { return [T]() } return value.lazy.map({ (v) -> T in return T.init(fromDic: v) }) }) } func doArrayMapping<T: Mapping>(_ result: T.Type) -> SignalProducer<[T], Error> { return self.map({ input -> [T] in guard let value = input as? [[String : Any]] else { return [T]() } return value.lazy.map({ (v) -> T in return T.init(fromDic: v) }) }) } /// just map to type func doMap<T>() -> SignalProducer<T, Error> { return self.map{$0 as! T} } func doMap<T>(_ result: T.Type) -> SignalProducer<T, Error> { return self.map{$0 as! T} } }
mit
a6bac63494b1203381c06c96cc00147c
24.506173
85
0.459826
4.123752
false
false
false
false
oscarvgg/calorie-counter
CalorieCounter/SignUpTableViewController.swift
1
6925
// // SignUpTableViewController.swift // CalorieCounter // // Created by Oscar Vicente González Greco on 18/5/15. // Copyright (c) 2015 Oscarvgg. All rights reserved. // import UIKit class SignUpTableViewController: UITableViewController { var loggedUser: User? override func viewDidLoad() { super.viewDidLoad() // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false // Uncomment the following line to display an Edit button in the navigation bar for this view controller. // self.navigationItem.rightBarButtonItem = self.editButtonItem() } 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?) { if segue.identifier == "mainViewSegue" { let mainViewController = segue.destinationViewController as! MainTableViewController mainViewController.localUser = self.loggedUser } } // MARK: - Validation func isEmailValid() -> Bool { let textField = self.tableView.cellForRowAtIndexPath( NSIndexPath(forRow: 1, inSection: 0))? .viewWithTag(1) as! UITextField let candidate = textField.text let emailRegex = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,6}" return NSPredicate(format: "SELF MATCHES %@", emailRegex).evaluateWithObject(candidate) } func isFieldEmpty(candidate: String) -> Bool { if candidate.lengthOfBytesUsingEncoding(NSUTF8StringEncoding) <= 0 { return false } return true } func isUsernameValid() -> Bool { let textField = self.tableView.cellForRowAtIndexPath( NSIndexPath(forRow: 0, inSection: 0))? .viewWithTag(1) as! UITextField return self.isFieldEmpty(textField.text) } func isPasswordValid() -> Bool { let textField = self.tableView.cellForRowAtIndexPath( NSIndexPath(forRow: 2, inSection: 0))? .viewWithTag(1) as! UITextField return self.isFieldEmpty(textField.text) } func validateFields() -> Bool { let alert: UIAlertController! let action = UIAlertAction( title: "Ok", style: UIAlertActionStyle.Default) { (action: UIAlertAction!) -> Void in } if !self.isUsernameValid() { alert = UIAlertController( title: "Invalid field", message: "Username can't be empty", preferredStyle: UIAlertControllerStyle.Alert) alert.addAction(action) self.presentViewController( alert, animated: true, completion: { () -> Void in }) return false } if !self.isEmailValid() { alert = UIAlertController( title: "Invalid field", message: "Email field is not valid", preferredStyle: UIAlertControllerStyle.Alert) alert.addAction(action) self.presentViewController( alert, animated: true, completion: { () -> Void in }) return false } if !self.isPasswordValid() { alert = UIAlertController( title: "Invalid field", message: "Password can't be empty", preferredStyle: UIAlertControllerStyle.Alert) alert.addAction(action) self.presentViewController( alert, animated: true, completion: { () -> Void in }) return false } return true } // MARK: - Actions @IBAction func didTapSignUp(sender: UIButton) { // Stop editing on each text field for index in 1...self.tableView.numberOfRowsInSection(0) { let i = index - 1 // get the text field for the cell at i let textField = self.tableView.cellForRowAtIndexPath(NSIndexPath(forRow: i, inSection: 0))?.viewWithTag(1) as? UITextField textField?.resignFirstResponder() } if !self.validateFields() { return } let usernameTextField = self.tableView .cellForRowAtIndexPath(NSIndexPath(forRow: 0, inSection: 0))? .viewWithTag(1) as! UITextField let emailTextField = self.tableView .cellForRowAtIndexPath(NSIndexPath(forRow: 1, inSection: 0))? .viewWithTag(1) as! UITextField let passwordTextField = self.tableView .cellForRowAtIndexPath(NSIndexPath(forRow: 2, inSection: 0))? .viewWithTag(1) as! UITextField let user = User() user.username = usernameTextField.text user.password = passwordTextField.text user.email = emailTextField.text User.signUp(user) { (user: User?, error: NSError?) -> Void in if let user = user where error == nil { self.loggedUser = user self.performSegueWithIdentifier("mainViewSegue", sender: self) } else if error != nil { let alert = UIAlertController( title: "Error", message: "Could not sign up", preferredStyle: UIAlertControllerStyle.Alert) let action = UIAlertAction( title: "Ok", style: UIAlertActionStyle.Default, handler: { (action: UIAlertAction!) -> Void in }) alert.addAction(action) self.presentViewController( alert, animated: true, completion: { () -> Void in }) } } } }
mit
aec716a34db2ec17cad50045569ba6c4
28.21519
134
0.508666
6.111209
false
false
false
false
Isuru-Nanayakkara/Swift-Extensions
Swift+Extensions/Swift+Extensions/Utils/UIDevice+Extensions.swift
1
2583
import UIKit extension UIDevice { var isPad: Bool { return userInterfaceIdiom == .pad } var isPhone: Bool { return userInterfaceIdiom == .phone } var isTV: Bool { return userInterfaceIdiom == .tv } @available(iOS 9.0, *) var isLowPowerModeEnabled: Bool { return ProcessInfo.processInfo.isLowPowerModeEnabled } var uptime: TimeInterval { return ProcessInfo.processInfo.systemUptime } var uptimeDate: Date { return Date(timeIntervalSinceNow: -uptime) } var isJailbroken: Bool { return UIApplication.shared.canOpenURL(URL(string: "cydia://")!) || FileManager.default.fileExists(atPath: "/bin/bash") } var osVersion: String { return systemVersion } var hardwareModel: String { var name: [Int32] = [CTL_HW, HW_MACHINE] var size: Int = 2 sysctl(&name, 2, nil, &size, nil, 0) var hw_machine = [CChar](repeating: 0, count: Int(size)) sysctl(&name, 2, &hw_machine, &size, nil, 0) let hardware: String = String(cString: hw_machine) return hardware } var cpuFrequency: Int { return getSysInfo(HW_CPU_FREQ) } var busFrequency: Int { return getSysInfo(HW_TB_FREQ) } var ramSize: Int { return getSysInfo(HW_MEMSIZE) } var cpusNumber: Int { return getSysInfo(HW_NCPU) } var totalMemory: Int { return getSysInfo(HW_PHYSMEM) } var userMemory: Int { return getSysInfo(HW_USERMEM) } fileprivate func getSysInfo(_ typeSpecifier: Int32) -> Int { var name: [Int32] = [CTL_HW, typeSpecifier] var size: Int = 2 sysctl(&name, 2, nil, &size, nil, 0) var results: Int = 0 sysctl(&name, 2, &results, &size, nil, 0) return results } var totalDiskSpace: NSNumber { do { let attributes = try FileManager.default.attributesOfFileSystem(forPath: NSHomeDirectory()) return attributes[.systemSize] as? NSNumber ?? NSNumber(value: 0.0) } catch { return NSNumber(value: 0.0) } } var freeDiskSpace: NSNumber { do { let attributes = try FileManager.default.attributesOfFileSystem(forPath: NSHomeDirectory()) return attributes[.systemFreeSize] as? NSNumber ?? NSNumber(value: 0.0) } catch { return NSNumber(value: 0.0) } } }
mit
a058e880c8de02aa2258ddc8caac480f
24.574257
127
0.56988
4.333893
false
false
false
false
yuxiuyu/TrendBet
TrendBetting_0531换首页/Pods/Charts/Source/Charts/Jobs/AnimatedViewPortJob.swift
5
3011
// // AnimatedViewPortJob.swift // Charts // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/Charts // import Foundation import CoreGraphics #if !os(OSX) import UIKit #endif open class AnimatedViewPortJob: ViewPortJob { internal var phase: CGFloat = 1.0 internal var xOrigin: CGFloat = 0.0 internal var yOrigin: CGFloat = 0.0 private var _startTime: TimeInterval = 0.0 private var _displayLink: NSUIDisplayLink! private var _duration: TimeInterval = 0.0 private var _endTime: TimeInterval = 0.0 private var _easing: ChartEasingFunctionBlock? @objc public init( viewPortHandler: ViewPortHandler, xValue: Double, yValue: Double, transformer: Transformer, view: ChartViewBase, xOrigin: CGFloat, yOrigin: CGFloat, duration: TimeInterval, easing: ChartEasingFunctionBlock?) { super.init(viewPortHandler: viewPortHandler, xValue: xValue, yValue: yValue, transformer: transformer, view: view) self.xOrigin = xOrigin self.yOrigin = yOrigin self._duration = duration self._easing = easing } deinit { stop(finish: false) } open override func doJob() { start() } @objc open func start() { _startTime = CACurrentMediaTime() _endTime = _startTime + _duration _endTime = _endTime > _endTime ? _endTime : _endTime updateAnimationPhase(_startTime) _displayLink = NSUIDisplayLink(target: self, selector: #selector(animationLoop)) _displayLink.add(to: .main, forMode: .commonModes) } @objc open func stop(finish: Bool) { guard _displayLink != nil else { return } _displayLink.remove(from: .main, forMode: .commonModes) _displayLink = nil if finish { if phase != 1.0 { phase = 1.0 animationUpdate() } animationEnd() } } private func updateAnimationPhase(_ currentTime: TimeInterval) { let elapsedTime = currentTime - _startTime let duration = _duration var elapsed = elapsedTime elapsed = min(elapsed, duration) phase = CGFloat(_easing?(elapsed, duration) ?? elapsed / duration) } @objc private func animationLoop() { let currentTime: TimeInterval = CACurrentMediaTime() updateAnimationPhase(currentTime) animationUpdate() if currentTime >= _endTime { stop(finish: true) } } internal func animationUpdate() { // Override this } internal func animationEnd() { // Override this } }
apache-2.0
e34cc2a153b64fb6c93f954ad254959d
22.161538
88
0.573896
4.968647
false
false
false
false
James-swift/JMSCycleScrollView
JMSCycleScrollView/CstCollectionViewCell.swift
1
991
// // CstCollectionViewCell.swift // JMSCycleScrollView // // Created by James.xiao on 2017/7/10. // Copyright © 2017年 James.xiao. All rights reserved. // import UIKit class CstCollectionViewCell: UICollectionViewCell { private(set) var imageView: UIImageView = { let tempImageView = UIImageView() tempImageView.layer.borderColor = UIColor.red.cgColor tempImageView.layer.borderWidth = 2 return tempImageView }() override init(frame: CGRect) { super.init(frame: frame) self.setupViews() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - UI private func setupViews() { self.contentView.backgroundColor = .white self.contentView.addSubview(self.imageView) } override func layoutSubviews() { super.layoutSubviews() self.imageView.frame = self.bounds } }
mit
23e6eae383b5160651d981ca37b23053
22.52381
61
0.631579
4.638498
false
false
false
false
netyouli/WHC_Debuger
WHC_DebugerSwift/WHC_DebugerSwift/WHC_Debuger/WHC_Debuger.swift
1
2722
// // WHC_Debuger.swift // WHC_DebugerSwift // // Created by WHC on 17/1/14. // Copyright © 2017年 WHC. All rights reserved. // // Github <https://github.com/netyouli/WHC_Debuger> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. #if DEBUG import UIKit public class WHC_Debuger: NSObject { private var noteLabel: UILabel! /// 调式器单利对象 static var share: WHC_Debuger = WHC_Debuger() /// 自定义要显示的信息 public var whc_CustomNote: String! /// 显示信息标签 public var whc_NoteLabel: UILabel { if noteLabel == nil { whc_CustomNote = " 当前控制器:" noteLabel = UILabel() var noteLabelFrame = CGRect.zero if UIScreen.main.bounds.height == 812 { noteLabelFrame.origin = CGPoint(x: 0, y: 35) }else { noteLabelFrame.origin = CGPoint(x: 0, y: 16) } noteLabelFrame.size = CGSize(width: UIScreen.main.bounds.width, height: 20) noteLabel.frame = noteLabelFrame noteLabel.textColor = UIColor(red: 53.0 / 255, green: 205.0 / 255, blue: 73.0 / 255, alpha: 1.0) noteLabel.adjustsFontSizeToFitWidth = true noteLabel.minimumScaleFactor = 0.5 noteLabel.font = UIFont.systemFont(ofSize: 14) noteLabel.backgroundColor = UIColor.init(white: 0, alpha: 0.5) } if noteLabel.superview == nil { let window = UIApplication.shared.delegate?.window if window != nil && window! != nil { window!!.addSubview(noteLabel) } } return noteLabel } } #endif
mit
8898de1e9a93b82141486e539106627c
37.042857
108
0.652272
4.047112
false
false
false
false
MegaManX32/CD
CD/CD/View Controllers/SettingsViewController.swift
1
6823
// // SettingsViewController.swift // CD // // Created by Vladislav Simovic on 12/26/16. // Copyright © 2016 CustomDeal. All rights reserved. // import UIKit import AlamofireImage import MBProgressHUD import MessageUI fileprivate let revealWidthOffset: CGFloat = 60 fileprivate let avatarImageViewHeightAndWidth: CGFloat = 60 class SettingsViewController: UIViewController, MFMailComposeViewControllerDelegate { // MARK: - Properties @IBOutlet weak var avatarImageView : UIImageView! @IBOutlet weak var nameLabel: UILabel! @IBOutlet weak var emailLabel : UILabel! @IBOutlet weak var createListOrProvideServiceButton : UIButton! @IBOutlet weak var hostSwitch : UISwitch! // MARK: - View Lifecycle override func viewDidLoad() { super.viewDidLoad() // set reveal width self.revealViewController().rearViewRevealWidth = UIScreen.main.bounds.width - revealWidthOffset // set avatar self.avatarImageView.layer.cornerRadius = avatarImageViewHeightAndWidth / 2.0 self.avatarImageView.layer.masksToBounds = true // add tap gesture to all front view controllers self.revealViewController().tapGestureRecognizer() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) // update user let context = CoreDataManager.sharedInstance.mainContext let user = User.findUserWith(uid: StandardUserDefaults.userID(), context: context)! self.nameLabel.text = user.firstName! self.emailLabel.text = user.email! if let photoURL = user.photoURL { self.avatarImageView.af_setImage(withURL: URL(string:photoURL)!) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK - User Actions @IBAction func hostOptionChanged(sender: UISwitch) { if !sender.isOn { self.createListOrProvideServiceButton.setTitle("Create Rider List", for: .normal) let controller = self.storyboard?.instantiateViewController(withIdentifier: "GuestNavigationController"); self.revealViewController().pushFrontViewController(controller, animated: true) } else { self.createListOrProvideServiceButton.setTitle("Provide Service", for: .normal) let controller = self.storyboard?.instantiateViewController(withIdentifier: "HostNavigationController"); self.revealViewController().pushFrontViewController(controller, animated: true) } } @IBAction func createListOrProvideServiceAction(sender: UIButton) { if !self.hostSwitch.isOn { let controller = self.storyboard?.instantiateViewController(withIdentifier: "CreateRiderListViewController") as! CreateRiderListViewController if self.revealViewController().frontViewController is GuestHomeViewController { self.revealViewController().frontViewController.show(controller, sender: self) self.revealViewController().revealToggle(self) return } let navigationController = self.storyboard?.instantiateViewController(withIdentifier: "GuestNavigationController") as! UINavigationController navigationController.pushViewController(controller, animated: false) self.revealViewController().pushFrontViewController(navigationController, animated: true) } else { let controller = self.storyboard?.instantiateViewController(withIdentifier: "HostProvideServiceViewController") as! HostProvideServiceViewController if self.revealViewController().frontViewController is HostHomeViewController { self.revealViewController().frontViewController.show(controller, sender: self) self.revealViewController().revealToggle(self) return } let navigationController = self.storyboard?.instantiateViewController(withIdentifier: "HostNavigationController") as! UINavigationController navigationController.pushViewController(controller, animated: false) self.revealViewController().pushFrontViewController(navigationController, animated: true) } } @IBAction func profileAction(sender: UIButton) { let controller = self.storyboard?.instantiateViewController(withIdentifier: "HostProfileViewController") as! HostProfileViewController controller.userID = StandardUserDefaults.userID() controller.presentFromMainMenu = true let navigationController = UINavigationController.init(rootViewController: controller) navigationController.isNavigationBarHidden = true self.revealViewController().pushFrontViewController(navigationController, animated: true) } @IBAction func homeAction(sender: UIButton) { if !self.hostSwitch.isOn { let controller = self.storyboard?.instantiateViewController(withIdentifier: "GuestNavigationController"); self.revealViewController().pushFrontViewController(controller, animated: true) } else { let controller = self.storyboard?.instantiateViewController(withIdentifier: "HostNavigationController"); self.revealViewController().pushFrontViewController(controller, animated: true) } } @IBAction func logOut(sender : UIButton) { // do log out NetworkManager.sharedInstance.logout() self.dismiss(animated: true, completion: nil) } @IBAction func aboutUs(sender: UIButton) { let controller = self.storyboard?.instantiateViewController(withIdentifier: "AboutUsViewController"); self.revealViewController().pushFrontViewController(controller, animated: true) } @IBAction func helpAction(_ sender: UIButton) { if MFMailComposeViewController.canSendMail() { let mail = MFMailComposeViewController() mail.mailComposeDelegate = self mail.setSubject("Help") mail.setToRecipients(["[email protected]"]) present(mail, animated: true) } else { CustomAlert.presentAlert(message: "Please check your email settings", controller: self) } } @IBAction func comingSoon(sender: UIButton) { CustomAlert.presentAlert(message: "Coming soon :-)", controller: self) } // MARK: - MFMailComposeViewController Methods func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) { controller.dismiss(animated: true) } }
mit
96c4c2ae25ddef618d7058880d631779
43.298701
160
0.698036
5.881034
false
false
false
false
omniprog/SwiftZSTD
TestSources/SwiftZSTDBasicTests.swift
1
4895
// // SwiftZSTDBasicTests.swift // // Created by Anatoli on 1/14/20. // import XCTest @testable import SwiftZSTD class SwiftZSTDBasicTests: XCTestCase { func testWithDictionary() { checkPlatform() if let dictData = getDictionary() { let origData = Data(bytes: [123, 231, 132, 100, 20, 10, 5, 2, 1]) if let compData = compressWithDictionary(origData, dictData) { if let decompData = decompressWithDictionary(compData, dictData) { XCTAssertEqual(decompData, origData, "Decompressed data is different from original (using dictionary)") } } } } func testWithoutDictionary() { checkPlatform() let processor = ZSTDProcessor(useContext: true) let origData = Data(bytes: [3, 4, 12, 244, 32, 7, 10, 12, 13, 111, 222, 133]) do { let compressedData = try processor.compressBuffer(origData, compressionLevel: 4) let decompressedData = try processor.decompressFrame(compressedData) XCTAssertEqual(decompressedData, origData, "Decompressed data is different from original (not using dictionary") } catch ZSTDError.libraryError(let errStr) { XCTFail("Library error: \(errStr)") } catch ZSTDError.invalidCompressionLevel(let lvl){ XCTFail("Invalid compression level: \(lvl)") } catch ZSTDError.decompressedSizeUnknown { XCTFail("Unknown decompressed size.") } catch { XCTFail("Unknown error") } } private func checkPlatform() { #if os(OSX) print("TESTING ON macOS!") #elseif os(iOS) print("TESTING ON iOS!") #else XCTFail("BAD PLATFORM") #endif } private func getDictionary() -> Data? { var samples = [Data]() samples.append(Data(bytes: Array(10...250))) samples.append(Data(bytes: Array(repeating: 123, count: 100_000))) samples.append(Data(bytes: [1,3,4,7,11])) samples.append(Data(bytes: [0,0,1,1,5,5])) samples.append(Data(bytes: Array(100...240))) samples.append(Data(bytes: Array(repeating: 230, count: 100_000))) samples.append(Data(bytes: [10,30,40,70,110])) samples.append(Data(bytes: [10,20,10,1,15,50])) do { return try buildDictionary(fromSamples: samples) } catch ZDICTError.libraryError(let errStr) { XCTFail("Library error while creating dictionary: \(errStr)") } catch ZDICTError.unknownError { XCTFail("Unknown library error while creating dictionary.") } catch { XCTFail("Unknown error while creating dictionary.") } return nil } private func compressWithDictionary(_ dataIn: Data, _ dict: Data) -> Data? { // Note that we only check for the exceptions that can reasonably be // expected when compressing, excluding things like unknown decompressed size. if let dictProc = DictionaryZSTDProcessor(withDictionary: dict, andCompressionLevel: 4) { do { return try dictProc.compressBufferUsingDict(dataIn) } catch ZSTDError.libraryError(let errStr) { XCTFail("Library error while compressing data: \(errStr)") } catch ZSTDError.invalidCompressionLevel(let lvl){ XCTFail("Invalid compression level: \(lvl)") } catch { XCTFail("Unknown error while compressing data.") } return nil } else { XCTFail("Could not create dictionary-based compressor.") return nil } } private func decompressWithDictionary(_ dataIn: Data, _ dict: Data) -> Data? { // We could have re-used the same DictionaryZSTDProcessor instance that was used // to compress the data. Again, note that we only check for the exceptions that // can reasonably be expected when decompressing, excluding things like invalid // compression level. if let dictProc = DictionaryZSTDProcessor(withDictionary: dict, andCompressionLevel: 20) { do { return try dictProc.decompressFrameUsingDict(dataIn) } catch ZSTDError.libraryError(let errStr) { XCTFail("Library error while decompressing data: \(errStr)") } catch ZSTDError.decompressedSizeUnknown { XCTFail("Unknown decompressed size.") } catch { XCTFail("Unknown error while decompressing data.") } return nil } else { XCTFail("Could not create dictionary-based decompressor.") return nil } } }
bsd-3-clause
e21945dc9274c647257ded49949e63d6
38.475806
98
0.59142
4.761673
false
true
false
false
qualaroo/QualarooSDKiOS
Qualaroo/Managers/SurveyWireframe.swift
1
2218
// // SurveyWireframe.swift // Qualaroo // // Copyright (c) 2018, Qualaroo, Inc. All Rights Reserved. // // Please refer to the LICENSE.md file for the terms and conditions // under which redistribution and use of this file is permitted. // import Foundation class SurveyWireframe { private let survey: Survey private let preferredLanguages: [String] init(survey: Survey, languages: [String]) { self.survey = survey self.preferredLanguages = languages } private func supportedLanguage() -> String { let preferedLanguage = preferredLanguages.first { isLanguageSupported($0) } return preferedLanguage ?? survey.languagesList.first! } private func isLanguageSupported(_ language: String) -> Bool { return survey.languagesList.contains(language) } func nextNodeId(for nodeId: NodeId?, answerId: AnswerId?) -> NodeId? { guard let nodeId = nodeId, let node = node(nodeId) else { return nil } if let id = answerId { let chosenAnswer = answer(id, forQuestionId: nodeId) return chosenAnswer?.nextNodeId ?? node.nextId() } return node.nextId() } func node(_ nodeId: NodeId?) -> Node? { return survey.nodeList.first { $0.nodeId() == nodeId } } func answer(_ answerId: AnswerId, forQuestionId questionId: NodeId) -> Answer? { guard let question = node(questionId) as? Question else { return nil } return question.answerList.first { $0.answerId == answerId } } } extension SurveyWireframe: SurveyWireframeProtocol { func firstNode() -> Node? { return node(survey.startMap[supportedLanguage()]) } func nextNode(for nodeId: NodeId?, response: NodeResponse?) -> Node? { let answerId = selectedId(for: response) let nextId = nextNodeId(for: nodeId, answerId: answerId) return node(nextId) } private func selectedId(for response: NodeResponse?) -> AnswerId? { guard let response = response else { return nil } switch response { case .leadGen: return nil case .question(let model): return model.answerList.first?.id } } func currentSurveyId() -> Int { return survey.surveyId } func isMandatory() -> Bool { return survey.mandatory } }
mit
31debdb727f058ad05f8e4e0d19b9606
27.075949
82
0.680794
3.996396
false
false
false
false
InversePandas/Fire
Fire/AddButtonViewController.swift
1
2734
// // AddButtonViewController.swift // Fire // // Created by Karen Kennedy on 12/6/14. // Copyright (c) 2014 Karen Kennedy. All rights reserved. // import Foundation import UIKit import CoreData class AddButtonViewController: ResponsiveTextFieldViewController, UITextFieldDelegate { @IBOutlet var txtName:UITextField! @IBOutlet var txtDescription:UITextField! //@IBOutlet var txtDesc:UITextView! @IBOutlet var txtPhone:UITextField! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func saveEntry(buttonName: String, buttonMessage: String, buttonPhoneNumbers: String) { //1 let appDelegate = UIApplication.sharedApplication().delegate as AppDelegate let managedContext = appDelegate.managedObjectContext! //2 let entity = NSEntityDescription.entityForName("Buttons", inManagedObjectContext: managedContext) let entry = NSManagedObject(entity: entity!, insertIntoManagedObjectContext:managedContext) //3 entry.setValue(buttonMessage, forKey: "buttonMessage") entry.setValue(buttonName, forKey: "buttonName") entry.setValue(buttonPhoneNumbers, forKey: "buttonPhoneNumbers") //4 var error: NSError? if !managedContext.save(&error) { println("Could not save \(error), \(error?.userInfo)") } //5 //println("here") // buttons.append(entry) } // events @IBAction func btnAddContact_Click (sender:UIButton){ // TODO: Need to verify user input (in some way....) // ContactMgr.addContact(txtName.text, phone: txtPhone.text) self.saveEntry(txtName.text, buttonMessage: txtDescription.text, buttonPhoneNumbers: txtPhone.text) self.view.endEditing(true) println(txtName.text) println(txtDescription.text) println(txtPhone.text) // reset field to empty txtName.text = "" txtPhone.text = "" txtDescription.text = "" } // iOS Touch function override func touchesBegan(touches: NSSet, withEvent event: UIEvent) { self.view.endEditing(true); } // what happens if returns func textFieldShouldReturn(textField: UITextField!) -> Bool { // keyboard go away textField.resignFirstResponder(); return true; } }
gpl-3.0
e76e1a7b91803eb7b9d95a252a8ab3bb
28.397849
107
0.628383
4.998172
false
false
false
false
J-Mendes/Flickr-Viewer
Flickr Viewer/Flickr Viewer/PhotoDetailsTableViewController.swift
1
3497
// // PhotoDetailsTableViewController.swift // Flickr Viewer // // Created by Jorge Mendes on 25/10/16. // Copyright © 2016 Jorge Mendes. All rights reserved. // import UIKit class PhotoDetailsTableViewController: UITableViewController { internal var photo: Photo! fileprivate enum Rows: Int { case photo = 0, title, place, description, count } override func viewDidLoad() { super.viewDidLoad() self.initLayout() } fileprivate func initLayout() { self.title = "Photo Detail" self.tableView.tableFooterView = UIView() self.tableView.register(UINib(nibName: String(describing: PhotoTableViewCell.self), bundle: nil), forCellReuseIdentifier: String(describing: PhotoTableViewCell.self)) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return Rows.count.rawValue } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { var cell: UITableViewCell? = nil switch indexPath.row { case Rows.photo.rawValue: let photoCell: PhotoTableViewCell = tableView.dequeueReusableCell(withIdentifier: String(describing: PhotoTableViewCell.self), for: indexPath) as! PhotoTableViewCell photoCell.configure(photo: self.photo) cell = photoCell case Rows.title.rawValue: var textCell: TextTableViewCell? = tableView.dequeueReusableCell(withIdentifier: String(describing: TextTableViewCell.self)) as? TextTableViewCell if textCell == nil { textCell = TextTableViewCell() } textCell?.configureWith(label: "Title", andValue: self.photo.title) cell = textCell case Rows.place.rawValue: var textCell: TextTableViewCell? = tableView.dequeueReusableCell(withIdentifier: String(describing: TextTableViewCell.self)) as? TextTableViewCell if textCell == nil { textCell = TextTableViewCell() } textCell?.configureWith(label: "Location", andValue: self.photo.getPlace()) cell = textCell case Rows.description.rawValue: var textCell: TextTableViewCell? = tableView.dequeueReusableCell(withIdentifier: String(describing: TextTableViewCell.self)) as? TextTableViewCell if textCell == nil { textCell = TextTableViewCell() } textCell?.configureWith(label: "Description", andValue: self.photo.descriptionText) cell = textCell default: break } return cell! } override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { switch indexPath.row { case Rows.photo.rawValue: return PhotoTableViewCell.height case Rows.title.rawValue: return TextTableViewCell.heightWith(value: self.photo.title) case Rows.place.rawValue: return TextTableViewCell.heightWith(value: self.photo.getPlace()) case Rows.description.rawValue: return TextTableViewCell.heightWith(value: self.photo.descriptionText) default: return 0.0 } } }
lgpl-3.0
aa532e15d354b44d0e80922c73377989
36.191489
177
0.657323
5.163959
false
false
false
false
xivol/MCS-V3-Mobile
examples/uiKit/UIKitCatalog.playground/Pages/UITextField.xcplaygroundpage/Contents.swift
1
2534
import UIKit import PlaygroundSupport class Controller: NSObject, UITextViewDelegate { let label: UILabel! @objc func editingDidEnd(sender: UITextField) { if let newValue = sender.text { label.text = newValue } } init(with label: UILabel){ self.label = label } // MARK: UITextViewDelegate func textViewDidEndEditing(_ textView: UITextView) { label.text = textView.text } } let containerView = UIView(frame: CGRect(x: 0, y: 0, width: 250, height: 250)) containerView.backgroundColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1) let textField = UITextField(frame: CGRect(x: 0, y: 0, width: 250, height: 30)) textField.borderStyle = .roundedRect textField.placeholder = "username" containerView.addSubview(textField) let pass = UITextField(frame: CGRect(x: 0, y: 50, width: 250, height: 30)) pass.borderStyle = .line pass.textColor = #colorLiteral(red: 0.7254902124, green: 0.4784313738, blue: 0.09803921729, alpha: 1) pass.placeholder = "password" pass.isSecureTextEntry = true pass.autocorrectionType = .no pass.clearButtonMode = .always containerView.addSubview(pass) let imageBack = UITextField(frame: CGRect(x: 0, y: 100, width: 250, height: 30)) imageBack.background = #imageLiteral(resourceName: "gradient.png") imageBack.textColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1) imageBack.tintColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1) imageBack.textAlignment = NSTextAlignment.center imageBack.tag = 3 containerView.addSubview(imageBack) let textView = UITextView(frame: CGRect(x: 0, y: 150, width: 250, height: 30)) textView.backgroundColor = #colorLiteral(red: 0.8039215803, green: 0.8039215803, blue: 0.8039215803, alpha: 1) textView.textAlignment = NSTextAlignment.justified containerView.addSubview(textView) let displayLabel = UILabel(frame: CGRect(x: 0, y: 200, width: 250, height: 30)) displayLabel.textAlignment = .center containerView.addSubview(displayLabel) let controller = Controller(with: displayLabel) textField.addTarget(controller, action: #selector(Controller.editingDidEnd(sender:)), for: .editingDidEnd) pass.addTarget(controller, action: #selector(Controller.editingDidEnd(sender:)), for: .editingDidEnd) imageBack.addTarget(controller, action: #selector(Controller.editingDidEnd(sender:)), for: .editingDidEnd) textView.delegate = controller PlaygroundPage.current.liveView = containerView //: [Previous](@previous) | [Table of Contents](TableOfContents) | [Next](@next)
mit
2728cb33ea33cf1fa3378b295199efe4
35.724638
110
0.738753
3.868702
false
false
false
false
marinehero/LeetCode-Solutions-in-Swift
Solutions/Solutions/Medium/Medium_079_Word_Search.swift
3
2034
/* https://leetcode.com/problems/word-search/ #79 Word Search Level: medium Given a 2D board and a word, find if the word exists in the grid. The word can be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once. For example, Given board = [ ["ABCE"], ["SFCS"], ["ADEE"] ] word = "ABCCED", -> returns true, word = "SEE", -> returns true, word = "ABCB", -> returns false. Inspired by @pavel-shlyk at https://leetcode.com/discuss/23165/accepted-very-short-java-solution-no-additional-space */ import Foundation private extension String { subscript (index: Int) -> Character { return self[self.startIndex.advancedBy(index)] } } struct Medium_079_Word_Search { static func exist(var board: [[Character]], word: String) -> Bool { for var x = 0; x < board.count; x++ { for var y = 0; y < board[x].count; y++ { if exist_recursion_helper(board: &board, x: x, y: y, word: word, i: 0) { return true } } } return false } static private func exist_recursion_helper(inout board board: [[Character]], x: Int, y: Int, word: String, i: Int) -> Bool { if i == word.characters.count { return true } if x < 0 || y < 0 || x == board.count || y == board[x].count { return false } if board[x][y] != word[i] { return false } let tmp: Character = board[x][y] board[x][y] = "_" let exist: Bool = exist_recursion_helper(board: &board, x: x, y: y+1, word: word, i: i+1) || exist_recursion_helper(board: &board, x: x, y: y-1, word: word, i: i+1) || exist_recursion_helper(board: &board, x: x-1, y: y, word: word, i: i+1) || exist_recursion_helper(board: &board, x: x+1, y: y, word: word, i: i+1) board[x][y] = tmp return exist } }
mit
2d8ee21f0315ed7ff81fb850fb5bdd5c
28.926471
197
0.573746
3.373134
false
false
false
false
wireapp/wire-ios-data-model
Source/Model/LoginCredentials.swift
1
2419
// // Wire // Copyright (C) 2018 Wire Swiss GmbH // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see http://www.gnu.org/licenses/. // import Foundation /** * Contains the credentials used by a user to sign into the app. */ @objc public class LoginCredentials: NSObject, Codable { @objc public let emailAddress: String? @objc public let phoneNumber: String? @objc public let hasPassword: Bool @objc public let usesCompanyLogin: Bool public init(emailAddress: String?, phoneNumber: String?, hasPassword: Bool, usesCompanyLogin: Bool) { self.emailAddress = emailAddress self.phoneNumber = phoneNumber self.hasPassword = hasPassword self.usesCompanyLogin = usesCompanyLogin } public override var debugDescription: String { return "<LoginCredentials>:\n\temailAddress: \(String(describing: emailAddress))\n\tphoneNumber: \(String(describing: phoneNumber))\n\thasPassword: \(hasPassword)\n\tusesCompanyLogin: \(usesCompanyLogin)" } public override func isEqual(_ object: Any?) -> Bool { guard let otherCredentials = object as? LoginCredentials else { return false } let emailEquals = self.emailAddress == otherCredentials.emailAddress let phoneNumberEquals = self.phoneNumber == otherCredentials.phoneNumber let passwordEquals = self.hasPassword == otherCredentials.hasPassword let companyLoginEquals = self.usesCompanyLogin == otherCredentials.usesCompanyLogin return emailEquals && phoneNumberEquals && passwordEquals && companyLoginEquals } public override var hash: Int { var hasher = Hasher() hasher.combine(emailAddress) hasher.combine(phoneNumber) hasher.combine(hasPassword) hasher.combine(usesCompanyLogin) return hasher.finalize() } }
gpl-3.0
ed6f4b6b1bc38f2e880351e3d1b9cba9
36.215385
212
0.713931
4.7154
false
false
false
false
freak4pc/netfox
netfox_ios_demo/ImageViewController.swift
1
2378
// // ImageViewController.swift // netfox_ios_demo // // Created by Nathan Jangula on 10/12/17. // Copyright © 2017 kasketis. All rights reserved. // import UIKit class ImageViewController: UIViewController { @IBOutlet weak var imageView: UIImageView! let session: URLSession! var dataTask: URLSessionDataTask? required init?(coder aDecoder: NSCoder) { session = URLSession(configuration: URLSessionConfiguration.default) super.init(coder: aDecoder) } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func tappedLoadImage(_ sender: Any) { dataTask?.cancel() if let url = URL(string: "https://picsum.photos/\(imageView.frame.size.width)/\(imageView.frame.size.height)/?random") { dataTask = session.dataTask(with: url, completionHandler: { (data, response, error) in if let error = error { self.handleCompletion(error: error.localizedDescription, data: data) } else { guard let data = data else { self.handleCompletion(error: "Invalid data", data: nil); return } guard let response = response as? HTTPURLResponse else { self.handleCompletion(error: "Invalid response", data: data); return } guard response.statusCode >= 200 && response.statusCode < 300 else { self.handleCompletion(error: "Invalid response code", data: data); return } self.handleCompletion(error: error?.localizedDescription, data: data) } }) dataTask?.resume() } } private func handleCompletion(error: String?, data: Data?) { DispatchQueue.main.async { if let error = error { NSLog(error) return } if let data = data { let image = UIImage(data: data) NSLog("\(image?.size.width ?? 0),\(image?.size.height ?? 0)") self.imageView.image = image } } } }
mit
c36323c0f31a01f48f5b2fdf1416595f
33.955882
164
0.57804
5.057447
false
false
false
false
PopcornTimeTV/PopcornTimeTV
PopcornTime/UI/iOS/Extensions/DownloadDetailViewController+iOS.swift
1
3990
import Foundation import MediaPlayer.MPMediaItem import class PopcornTorrent.PTTorrentDownloadManager extension DownloadDetailViewController: DownloadDetailTableViewCellDelegate { override func viewDidLoad() { super.viewDidLoad() navigationItem.title = show.title navigationItem.rightBarButtonItem = editButtonItem tableView.tableFooterView = UIView() tableView.register(UINib(nibName: "DownloadTableViewHeader", bundle: nil), forHeaderFooterViewReuseIdentifier: "header") } override func numberOfSections(in tableView: UITableView) -> Int { return seasons.count } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return dataSource(for: seasons[section]).count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! DownloadDetailTableViewCell let download = dataSource(for: seasons[indexPath.section])[indexPath.row] cell.delegate = self cell.downloadButton.downloadState = DownloadButton.buttonState(download.downloadStatus) cell.downloadButton.invalidateAppearance() let episodeNumber = NumberFormatter.localizedString(from: NSNumber(value: download.mediaMetadata[MPMediaItemPropertyEpisode] as? Int ?? 0), number: .none) let episodeTitle = download.mediaMetadata[MPMediaItemPropertyTitle] as? String ?? "" cell.textLabel?.text = "\(episodeNumber). \(episodeTitle)" cell.detailTextLabel?.text = download.fileSize.stringValue if let image = download.mediaMetadata[MPMediaItemPropertyBackgroundArtwork] as? String, let url = URL(string: image) { cell.imageView?.af_setImage(withURL: url) } else { cell.imageView?.image = UIImage(named: "Episode Placeholder") } return cell } override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let header = tableView.dequeueReusableHeaderFooterView(withIdentifier: "header") let label = header?.viewWithTag(1) as? UILabel let localizedSeason = NumberFormatter.localizedString(from: NSNumber(value: seasons[section]), number: .none) label?.text = "Season".localized + " \(localizedSeason)" return header } override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return 40 } override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) { guard editingStyle == .delete else { return } let download = dataSource(for: seasons[indexPath.section])[indexPath.row] tableView.beginUpdates() if dataSource(for: seasons[indexPath.section]).count == 1{ tableView.deleteSections(IndexSet(integer: indexPath.section), with: .fade) self.navigationController?.pop(animated: true) }else{ tableView.deleteRows(at: [indexPath], with: .fade) } PTTorrentDownloadManager.shared().delete(download) tableView.endUpdates() } func cell(_ cell: DownloadDetailTableViewCell, accessoryButtonPressed button: DownloadButton) { guard let indexPath = tableView.indexPath(for: cell) else { return } let download = dataSource(for: seasons[indexPath.section])[indexPath.row] AppDelegate.shared.downloadButton(button, wasPressedWith: download) { [unowned self] in if self.episodes.count == 0 && self.seasons.count == 1{ self.tableView.deleteSections(IndexSet(integer: 1), with: .none) } self.tableView.reloadData() } } }
gpl-3.0
12b3b3e89b5e7c532b27165d156720e5
42.369565
162
0.674436
5.465753
false
false
false
false
TigerWolf/LoginKit
LoginKit/AppearanceController.swift
1
508
// // Appearance.swift // LoginKit // // Created by Kieran Andrews on 14/02/2016. // Copyright © 2016 CocoaPods. All rights reserved. // import UIKit import SVProgressHUD public let Appearance = AppearanceController.sharedInstance open class AppearanceController { static let sharedInstance = AppearanceController() open var backgroundColor = UIColor.blue open var whiteColor = UIColor.white open var buttonColor = UIColor.red open var buttonBorderColor = UIColor.white }
bsd-3-clause
9b19b687fa4e22700a37317ff0bfe5b5
20.125
59
0.739645
4.486726
false
false
false
false
apple/swift-async-algorithms
Tests/AsyncAlgorithmsTests/Support/Failure.swift
1
620
//===----------------------------------------------------------------------===// // // This source file is part of the Swift Async Algorithms open source project // // Copyright (c) 2022 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // //===----------------------------------------------------------------------===// struct Failure: Error, Equatable { } func throwOn<T: Equatable>(_ toThrowOn: T, _ value: T) throws -> T { if value == toThrowOn { throw Failure() } return value }
apache-2.0
367d30804b7f4519cc1adae84b96c9af
31.631579
80
0.519355
5.081967
false
false
false
false
skedgo/tripkit-ios
Sources/TripKitUI/views/TKUITripSegmentsView.swift
1
16217
// // TKUITripSegmentsView.swift // TripKitUI-iOS // // Created by Adrian Schönig on 31/1/21. // Copyright © 2021 SkedGo Pty Ltd. All rights reserved. // import UIKit import TripKit public class TKUITripSegmentsView : UIView { /// Whether the trip should be shown as cancelled, i.e., with a line through it /// - default: `false` public var isCanceled: Bool = false /// Whether to show wheelchair accessibility and inaccessibility icons /// - default: `false` public var allowWheelchairIcon: Bool = false /// This property determines if the transit icon in the view should be color coded. public var colorCodingTransitIcon: Bool = false /// This color is used for darker texts. In addition, this is also the color which /// will be used to tint the transport mode icons if `colorCodingTransitIcon` is /// set to `false`. /// - default: `UIColor.tkLabelPrimary` public var darkTextColor: UIColor = .tkLabelPrimary /// This color is used on lighter texts. In addition, this is also the color which /// will be used to tint non-PT modes if `colorCodingTransitIcon` is set to `YES`. /// - default: `UIColor.tkLabelSecondary` public var lightTextColor: UIColor = .tkLabelSecondary public override init(frame: CGRect) { super.init(frame: frame) } public required init?(coder: NSCoder) { super.init(coder: coder) } public func configure(_ segments: [TKUITripSegmentDisplayable], allowSubtitles: Bool = true, allowInfoIcons: Bool = true) { configure(segments, allowTitles: allowSubtitles, allowSubtitles: allowSubtitles, allowInfoIcons: allowInfoIcons) } public func selectSegment(atIndex index: Int) { segmentIndexToSelect = index guard index >= 0, index < segmentLeftyValues.count else { return } let minX = segmentLeftyValues[index] let maxX = index + 1 < segmentLeftyValues.count ? segmentLeftyValues[index + 1] : .greatestFiniteMagnitude let isRightToLeft = effectiveUserInterfaceLayoutDirection == .rightToLeft for view in subviews { let midX = isRightToLeft ? bounds.width - view.frame.midX : view.frame.midX view.alpha = midX >= minX && midX < maxX ? Self.alphaSelected : Self.alphaDeselected } } public func segmentIndex(atX x: CGFloat) -> Int { let target = effectiveUserInterfaceLayoutDirection == .leftToRight ? x : bounds.width - x return segmentLeftyValues.lastIndex { $0 <= target } ?? 0 } public override var intrinsicContentSize: CGSize { if desiredSize == .zero, let onLayout = self.onLayout { didLayoutSubviews = true onLayout() self.onLayout = nil } return desiredSize } public override func layoutSubviews() { super.layoutSubviews() didLayoutSubviews = true if let onLayout = self.onLayout { onLayout() self.onLayout = nil } } // MARK: - Constants private static let alphaSelected: CGFloat = 1 private static let alphaDeselected: CGFloat = 0.25 private static let padding: CGFloat = 12 // MARK: - Internals private var desiredSize: CGSize = .zero private var didLayoutSubviews: Bool = false private var onLayout: (() -> Void)? = nil /// These are from the left, i.e., same for left-to-right and right-to-left private var segmentLeftyValues: [CGFloat] = [] private var segmentIndexToSelect: Int? = nil private func configure(_ segments: [TKUITripSegmentDisplayable], allowTitles: Bool, allowSubtitles: Bool, allowInfoIcons: Bool) { if !didLayoutSubviews { // When calling `configureForSegments` before `layoutSubviews` was called // the frame information of this view is most likely not yet what it'll // be before this view will be visible, so we'll delay configuring this view // until after `layoutSubviews` was called. self.onLayout = { [weak self] in self?.configure(segments, allowTitles: allowTitles, allowSubtitles: allowSubtitles, allowInfoIcons: allowInfoIcons) } return } subviews.forEach { $0.removeFromSuperview() } var accessibileElements: [UIAccessibilityElement] = [] var nextX = Self.padding / 2 // We might not yet have a frame, if the Auto Layout engine wants to get the // intrinsic size of this view, before it's been added. In that case, we // let it grow as big as it wants to be. let limitSize = frame.size != .zero let maxHeight = limitSize ? frame.height : 44 var newSegmentXValues: [CGFloat] = [] let segmentIndexToSelect = self.segmentIndexToSelect.flatMap { $0 < segments.count ? $0 : nil } let isRightToLeft = effectiveUserInterfaceLayoutDirection == .rightToLeft contentMode = isRightToLeft ? .right : .left autoresizingMask = isRightToLeft ? [.flexibleLeftMargin, .flexibleBottomMargin] : [.flexibleRightMargin, .flexibleBottomMargin] var count = 0 for segment in segments { let mask: UIView.AutoresizingMask = autoresizingMask let isSelected = (segmentIndexToSelect ?? count) == count let alpha = isSelected ? Self.alphaSelected : Self.alphaDeselected guard let modeImage = segment.tripSegmentModeImage else { continue // this can happen if a trip was visible while TripKit got cleared } // 1. The mode and brand images, maybe with circled behind them let color = segment.tripSegmentModeColor let modeImageView = UIImageView(image: modeImage) modeImageView.autoresizingMask = mask modeImageView.alpha = alpha // remember that color will be nil for non-PT modes. In these cases, since the // PT mode will be colored, we use the lighter grey to reduce the contrast. modeImageView.tintColor = colorCodingTransitIcon ? (color ?? lightTextColor) : darkTextColor newSegmentXValues.append(nextX) modeImageView.frame.origin.x = nextX modeImageView.frame.origin.y = (maxHeight - modeImage.size.height) / 2 var newFrame = modeImageView.frame var brandImageView: UIImageView? = nil if let modeImageURL = segment.tripSegmentModeImageURL { let asTemplate = segment.tripSegmentModeImageIsTemplate @discardableResult func addCircle(frame: CGRect) -> UIView { let circleFrame = frame.insetBy(dx: -1, dy: -1) let modeCircleBackground = UIView(frame: circleFrame) modeCircleBackground.autoresizingMask = mask modeCircleBackground.backgroundColor = .white modeCircleBackground.layer.cornerRadius = circleFrame.width / 2 modeCircleBackground.alpha = alpha addSubview(modeCircleBackground) return modeCircleBackground } if segment.tripSegmentModeImageIsBranding { var brandFrame = newFrame brandFrame.origin.x += brandFrame.width + 4 // Always add a circle first as these look weird on background color addCircle(frame: brandFrame) // brand images are not overlaid over the mode icon, but appear next // to them let brandImage = UIImageView(frame: brandFrame) brandImage.autoresizingMask = mask brandImage.alpha = alpha brandImage.setImage(with: modeImageURL, asTemplate: false) brandImageView = brandImage newFrame = brandFrame } else { // remote images that aren't templates look weird on the background colour let modeCircleBackground = asTemplate ? nil : addCircle(frame: newFrame) modeImageView.setImage(with: modeImageURL, asTemplate: asTemplate, placeholder: modeImage) { succeeded in guard succeeded else { return } modeCircleBackground?.removeFromSuperview() } } if !asTemplate { // add a little bit more spacing next to the circle background newFrame.origin.x += 2 } } addSubview(modeImageView) if let brandImageView = brandImageView { addSubview(brandImageView) } // 2. Optional info icon if allowInfoIcons, let image = TKInfoIcon.image(for: segment.tripSegmentModeInfoIconType, usage: .overlay) { let infoIconImageView = UIImageView(image: image) infoIconImageView.autoresizingMask = mask infoIconImageView.frame.origin.x = newFrame.minX infoIconImageView.frame.origin.y = newFrame.maxY - image.size.height infoIconImageView.alpha = modeImageView.alpha addSubview(infoIconImageView) } // we put mode codes, colours and subtitles to the side // subtitle, we are allowed to var modeSideWith: CGFloat = 0 let x = newFrame.maxX var modeSubtitleSize = CGSize.zero let modeTitleFont = TKStyleManager.customFont(forTextStyle: .caption1) let modeSubtitleFont = TKStyleManager.customFont(forTextStyle: .caption2) let modeTitle = allowTitles ? segment.tripSegmentModeTitle.flatMap { $0.isEmpty ? nil : $0 } : nil let modeTitleSize = modeTitle?.size(font: modeTitleFont) ?? color.map { _ in .init(width: 10, height: 10) } ?? .zero let modeTitleAccessoryImageView = allowTitles && allowWheelchairIcon ? TKUISemaphoreView.accessibilityImageView(for: segment) : nil var modeSubtitle: String? = nil var modeSubtitleAccessoryImageViews: [UIImageView] = [] if allowSubtitles { // We prefer the time + real-time indicator as the subtitle, and fall back // to the subtitle if let fixedTime = segment.tripSegmentFixedDepartureTime { modeSubtitle = TKStyleManager.timeString(fixedTime, for: segment.tripSegmentTimeZone ?? .current) } if segment.tripSegmentTimesAreRealTime { modeSubtitleAccessoryImageViews.append(UIImageView(asRealTimeAccessoryImageAnimated: true, tintColor: lightTextColor)) } if modeSubtitle == nil, let subtitle = segment.tripSegmentModeSubtitle, !subtitle.isEmpty { modeSubtitle = subtitle } if let subtitle = modeSubtitle { modeSubtitleSize = subtitle.size(font: modeSubtitleFont) } if allowInfoIcons, let subtitleIcon = TKInfoIcon.image(for: segment.tripSegmentSubtitleIconType, usage: .overlay) { modeSubtitleAccessoryImageViews.append(UIImageView(image: subtitleIcon)) } } if let modeTitle = modeTitle { var y = (maxHeight - modeSubtitleSize.height - modeTitleSize.height) / 2 if modeSubtitleSize.height > 0 || !modeSubtitleAccessoryImageViews.isEmpty { y += 2 } let label = TKUIStyledLabel(frame: .init(origin: .init(x: x + 2, y: y), size: modeTitleSize)) label.autoresizingMask = mask label.font = modeTitleFont label.text = modeTitle label.textColor = colorCodingTransitIcon ? lightTextColor : darkTextColor label.alpha = modeImageView.alpha addSubview(label) modeSideWith = max(modeSideWith, modeTitleSize.width) } else if allowSubtitles, let color = color { let y = (maxHeight - modeSubtitleSize.height - modeTitleSize.height) / 2 let stripe = UIView(frame: .init(origin: .init(x: x, y: y), size: modeTitleSize)) stripe.autoresizingMask = mask stripe.layer.borderColor = color.cgColor stripe.layer.borderWidth = modeTitleSize.width / 4 stripe.layer.cornerRadius = modeTitleSize.width / 2 stripe.alpha = modeImageView.alpha addSubview(stripe) modeSideWith = max(modeSideWith, modeTitleSize.width) } if let accessoryImageView = modeTitleAccessoryImageView, let accessoryImage = accessoryImageView.image { let viewHeight = modeTitleSize.height > 0 ? min(accessoryImage.size.height, modeTitleSize.height) : min(accessoryImage.size.height, 20) let viewWidth = viewHeight * accessoryImage.size.width / accessoryImage.size.height var y = (maxHeight - modeSubtitleSize.height - viewHeight) / 2 if modeSubtitleSize.height > 0 || !modeSubtitleAccessoryImageViews.isEmpty { y += 2 } accessoryImageView.frame = .init(x: x + modeTitleSize.width + 2, y: y, width: viewWidth, height: viewHeight) accessoryImageView.alpha = modeImageView.alpha addSubview(accessoryImageView) modeSideWith = max(modeSideWith, modeTitleSize.width + 2 + viewWidth) } if let subtitle = modeSubtitle, !subtitle.isEmpty { // label goes under the mode code (if we have one) let y = (maxHeight - modeSubtitleSize.height - modeTitleSize.height) / 2 + modeTitleSize.height let label = TKUIStyledLabel(frame: .init(origin: .init(x: x + 2, y: y), size: modeSubtitleSize)) label.autoresizingMask = mask label.font = modeSubtitleFont label.text = subtitle label.textColor = lightTextColor label.alpha = modeImageView.alpha addSubview(label) modeSideWith = max(modeSideWith, modeSubtitleSize.width) } var subtitleWidth = modeSubtitleSize.width for imageView in modeSubtitleAccessoryImageViews { guard let image = imageView.image else { assertionFailure(); continue } imageView.autoresizingMask = mask let viewHeight = modeSubtitleSize.height > 0 ? min(image.size.height, modeSubtitleSize.height) : min(image.size.height, 20) let viewWidth = viewHeight * image.size.width / image.size.height let y = (maxHeight - viewHeight - modeTitleSize.height) / 2 + modeTitleSize.height imageView.frame = .init(x: x + subtitleWidth + 2, y: y, width: viewWidth, height: viewHeight) imageView.alpha = modeImageView.alpha addSubview(imageView) modeSideWith = max(modeSideWith, subtitleWidth + 2 + viewWidth) subtitleWidth += 2 + viewWidth } newFrame.size.width += modeSideWith let accessibleElement = UIAccessibilityElement(accessibilityContainer: self) accessibleElement.accessibilityLabel = segment.tripSegmentAccessibilityLabel accessibleElement.accessibilityFrameInContainerSpace = newFrame if segmentIndexToSelect != nil { accessibleElement.accessibilityTraits = isSelected ? [.button, .selected] : [.button] } accessibileElements.append(accessibleElement) nextX = newFrame.maxX + Self.padding count += 1 if allowSubtitles { desiredSize = .init(width: nextX, height: maxHeight) } if limitSize, nextX > frame.width { // try to shrink if allowSubtitles { configure(segments, allowTitles: allowTitles, allowSubtitles: false, allowInfoIcons: allowInfoIcons) return } else if allowTitles { configure(segments, allowTitles: false, allowSubtitles: false, allowInfoIcons: allowInfoIcons) return } } } if isCanceled { let lineHeight: CGFloat = 1 let strikethrough = UIView(frame: .init(x: 0, y: (maxHeight - lineHeight) / 2, width: nextX, height: lineHeight)) strikethrough.backgroundColor = darkTextColor addSubview(strikethrough) } if isRightToLeft { for view in subviews { view.frame.origin.x = frame.width - view.frame.maxX } } self.segmentLeftyValues = newSegmentXValues if segmentIndexToSelect != nil { self.accessibilityElements = accessibileElements self.isAccessibilityElement = false } } } extension String { fileprivate func size(font: UIFont, maximumWidth: CGFloat = .greatestFiniteMagnitude) -> CGSize { let context = NSStringDrawingContext() context.minimumScaleFactor = 1 let box = (self as NSString).boundingRect( with: .init(width: maximumWidth, height: 0), options: .usesLineFragmentOrigin, attributes: [.font: font], context: context ) return .init( width: box.width.rounded(.up), height: box.height.rounded(.up) ) } }
apache-2.0
54d901dc3733b9df5c343bd9d9665cad
40.050633
137
0.672587
4.636832
false
false
false
false
andrebng/Food-Diary
Food Snap/View Controllers/New Meal View Controller/Meal Predictions View Controller/MealPredictionsViewController.swift
1
3294
//MIT License // //Copyright (c) 2017 Andre Nguyen // //Permission is hereby granted, free of charge, to any person obtaining a copy //of this software and associated documentation files (the "Software"), to deal //in the Software without restriction, including without limitation the rights //to use, copy, modify, merge, publish, distribute, sublicense, and/or sell //copies of the Software, and to permit persons to whom the Software is //furnished to do so, subject to the following conditions: // //The above copyright notice and this permission notice shall be included in all //copies or substantial portions of the Software. // //THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR //IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, //FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE //AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER //LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, //OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE //SOFTWARE. // FoodDetailViewController.swift // Food Snap // // Created by Andre Nguyen on 7/27/17. // Copyright © 2017 Andre Nguyen. All rights reserved. // import UIKit //MARK: CardCellDelegate Protocol protocol MealPredictionsDelegate { func chooseMeal(viewModel: MealViewViewModel) } class MealPredictionsViewController : UIViewController { static let segueIdentifier = "NutritionSelectionSegue" // MARK: - Properties var delegate : NewMealDelegate? // MARK: - var mealPredictions: [Meal]? @IBOutlet weak var tableView: UITableView! override func viewDidLoad() { super.viewDidLoad() self.tableView.delegate = self self.tableView.dataSource = self self.tableView.separatorColor = UIColor.clear } } // MARK: - UITableView Delegate, UITableView Datasource extension MealPredictionsViewController : UITableViewDelegate, UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { guard let count = mealPredictions?.count else { return 0 } return count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { guard let cell = tableView.dequeueReusableCell(withIdentifier: CardCell.reuseIdentifier, for: indexPath) as? CardCell else { fatalError("Unexpected Table View Cell") } cell.delegate = self guard let meals = mealPredictions else { fatalError("Uninitialized meal predictions array") } let meal = meals[indexPath.row] cell.configure(viewModel: MealViewViewModel(meal: meal)) return cell } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 200 } } // MARK: - Meal Prediction Delegate extension MealPredictionsViewController : MealPredictionsDelegate { func chooseMeal(viewModel: MealViewViewModel) { self.delegate?.setMealData(viewModel: viewModel) self.navigationController?.popViewController(animated: true) } }
mit
56eb8b4bac3f221fe5f3a84ed83394d0
32.262626
132
0.709384
4.981846
false
false
false
false
darrarski/SharedShopping-iOS
SharedShoppingApp/UI/CreateShopping/ViewModels/CreateShoppingViewModel.swift
1
1856
import RxSwift class CreateShoppingViewModel: CreateShoppingViewControllerInputs, CreateShoppingViewControllerOutputs { init(shoppingCreator: ShoppingCreating, createdShoppingPresenter: CreatedShoppingPresenting) { self.shoppingCreator = shoppingCreator self.createdShoppingPresenter = createdShoppingPresenter } // MARK: CreateShoppingViewControllerInputs var title: Observable<String?> { return Observable.just("Shopping") } var startEditing: Observable<Void> { return startEditingSubject.asObservable() } var shoppingName: Observable<String?> { return shoppingNameVar.asObservable() } var selectShoppingNameText: Observable<Void> { return startEditingSubject.asObservable().single().catchError { _ in Observable.never() } } var createButtonTitle: Observable<String?> { return Observable.just("Create") } var createButtonEnabled: Observable<Bool> { return shoppingNameVar.asObservable().map { guard let name = $0 else { return false } return !name.isEmpty } } // MARK: CreateShoppingViewControllerOutputs func viewDidAppear() { startEditingSubject.onNext(()) } func shoppingNameDidChange(_ name: String?) { shoppingNameVar.value = name } func createShopping() { guard let name = shoppingNameVar.value else { return } let shopping = shoppingCreator.createShopping(name: name) createdShoppingPresenter.presentCreatedShopping(shopping) } // MARK: Private private let shoppingCreator: ShoppingCreating private let createdShoppingPresenter: CreatedShoppingPresenting private let startEditingSubject = PublishSubject<Void>() private let shoppingNameVar = Variable<String?>("New Shopping") }
mit
43edea778d392f5074fbf7688222576a
28.460317
104
0.699353
5.213483
false
false
false
false
mxclove/compass
毕业设计_指南针最新3.2/毕业设计_指南针/DrawerViewController.swift
1
8677
// // DrawerViewController.swift // 毕业设计_指南针 // // Created by 马超 on 15/10/18. // Copyright © 2015年 马超. All rights reserved. // import UIKit let leftViewWidth: CGFloat = deviceWidth let leftViewController = CompassViewController() let mainViewController = MapViewController() class DrawerViewController: UIViewController , UIGestureRecognizerDelegate{ var leftView = UIView() var mainView = UIView() var isOpen = true var startX: CGFloat = 0.0 let panGesture = UIPanGestureRecognizer() let pageControl = UIPageControl () override func viewDidLoad() { super.viewDidLoad() // UIApplication.sharedApplication().setStatusBarHidden(true, withAnimation: UIStatusBarAnimation.Fade) pageControl.frame = CGRect(x: deviceWidth * 0.5 - 20, y: deviceHeight * 0.92, width: 40, height: 37) pageControl.numberOfPages = 2 pageControl.currentPage = 0 self.view.addSubview(pageControl) leftView.frame = self.view.frame leftView.backgroundColor = UIColor.redColor() leftViewController.view.frame = leftView.frame leftView = leftViewController.view self.view.addSubview(leftView) mainView.frame = self.view.frame mainView.backgroundColor = UIColor.greenColor() mainViewController.view.frame = CGRect(x: leftViewWidth, y: 0, width: deviceWidth, height: deviceHeight) mainView = mainViewController.view self.view.addSubview(mainView) mainViewController.delegate = leftViewController panGesture.addTarget(self, action: "panBegan:") panGesture.delegate = self self.view.addGestureRecognizer(panGesture) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } func figerOutNetworkOfType() { let statusType = IJReachability.isConnectedToNetworkOfType() switch statusType { case .WWAN: // print("Connection Type: Mobile") let alert = UIAlertController(title: "您正在使用流量上网,注意", message: "您可以进入设置,开启流量保护", preferredStyle: UIAlertControllerStyle.Alert) let Action = UIAlertAction(title: "好", style: UIAlertActionStyle.Default, handler: nil) alert.addAction(Action) presentViewController(alert, animated: true, completion: nil) case .WiFi: // print("Connection Type: WiFi") break case .NotConnected: let alert = UIAlertController(title: "无法连接到网络,请检查您的网络", message: nil, preferredStyle: UIAlertControllerStyle.Alert) let Action = UIAlertAction(title: "好", style: UIAlertActionStyle.Default, handler: { (_) -> Void in }) alert.addAction(Action) presentViewController(alert, animated: true, completion: nil) } } func panBegan(recongnizer: UIPanGestureRecognizer) { // let location = recongnizer.translationInView(self.view) let location = recongnizer.locationInView(self.view) // print(location.x) if recongnizer.state == UIGestureRecognizerState.Began { startX = location.x } var differX = location.x - startX // print("differX = \(differX)") if differX > leftViewWidth { differX = leftViewWidth } if differX < -leftViewWidth { differX = -leftViewWidth } // if !isOpen { if borderAnimationEnable { if differX > 0 { self.leftView.x(differX - leftViewWidth) self.mainView.x(leftView.frame.origin.x + leftView.frame.width) } else { self.leftView.x(differX * 0.3 - leftViewWidth) self.mainView.x(leftView.frame.origin.x + leftView.frame.width) } } else { if differX > 0 { self.leftView.x(differX - leftViewWidth) self.mainView.x(leftView.frame.origin.x + leftView.frame.width) } } } else { if borderAnimationEnable { if differX < 0 { self.leftView.x(differX) self.mainView.x(leftView.frame.origin.x + leftView.frame.width) } else { self.leftView.x(differX * 0.3) self.mainView.x(leftView.frame.origin.x + leftView.frame.width) } } else { if differX < 0 { self.leftView.x(differX) self.mainView.x(leftView.frame.origin.x + leftView.frame.width) } } } if mainView.frame.origin.x < leftViewWidth * 0.5 { self.pageControl.currentPage = 1 } else { self.pageControl.currentPage = 0 } // if (differX + leftView.frame.origin.x) <= 0 && (differX + leftView.frame.origin.x) >= -leftView.frame.width { // self.leftView.x(differX - leftViewWidth) // self.mainView.x(leftView.frame.origin.x + leftView.frame.width) // } if recongnizer.state == UIGestureRecognizerState.Ended { if isOpen { if mainView.frame.origin.x < leftViewWidth * 0.9 { UIView.animateWithDuration(0.2, delay: 0.0, options: UIViewAnimationOptions.AllowAnimatedContent, animations: { () -> Void in self.leftView.x(-leftViewWidth) self.mainView.x(0) self.pageControl.currentPage = 1 self.mainView.userInteractionEnabled = true self.isOpen = false }, completion: nil) } else { UIView.animateWithDuration(0.2, delay: 0.0, options: UIViewAnimationOptions.BeginFromCurrentState, animations: { () -> Void in self.leftView.x(0) self.mainView.x(leftViewWidth) self.pageControl.currentPage = 0 self.mainView.userInteractionEnabled = false self.isOpen = true }, completion: nil) } } else { if mainView.frame.origin.x > leftViewWidth * 0.1 { UIView.animateWithDuration(0.2, delay: 0.0, options: UIViewAnimationOptions.AllowAnimatedContent, animations: { () -> Void in self.leftView.x(0) self.mainView.x(leftViewWidth) self.pageControl.currentPage = 0 self.mainView.userInteractionEnabled = false self.isOpen = true }, completion: nil) } else { UIView.animateWithDuration(0.2, delay: 0.0, options: UIViewAnimationOptions.BeginFromCurrentState, animations: { () -> Void in self.leftView.x(-leftViewWidth) self.mainView.x(0) self.pageControl.currentPage = 1 self.mainView.userInteractionEnabled = true self.isOpen = false }, completion: nil) } } } } } //extension DrawerViewController: MenuViewControllerDelegate { // func MenuSelectedControllerChanged(selectedNum: Int) { // mainViewController.view.frame = mainView.frame // mainView = mainViewController.view // mainView.userInteractionEnabled = false // self.view.addSubview(mainView) // // UIView.animateWithDuration(0.2, delay: 0, options: UIViewAnimationOptions.CurveEaseIn, animations: { () -> Void in // self.leftView.x(-leftViewWidth) // self.mainView.x(0) // }) { (finish) -> Void in // self.isOpen = false // self.mainView.userInteractionEnabled = true // } // //// self.leftView.x(-leftViewWidth) //// self.mainView.x(0) //// self.isOpen = false //// self.mainView.userInteractionEnabled = true // // print("self.view.subviews.count = === \(self.view.subviews.count)") // } //}
apache-2.0
7a86bf53a654f41c97ad24e9570a17bf
37.08
146
0.55077
4.984293
false
false
false
false
jvesala/teknappi
teknappi/Pods/RxSwift/RxSwift/Observables/Implementations/ObserveOnSerialDispatchQueue.swift
29
2341
// // ObserveOnSerialDispatchQueue.swift // RxSwift // // Created by Krunoslav Zaher on 5/31/15. // Copyright (c) 2015 Krunoslav Zaher. All rights reserved. // import Foundation #if TRACE_RESOURCES /** Counts number of `SerialDispatchQueueObservables`. Purposed for unit tests. */ public var numberOfSerialDispatchQueueObservables: Int32 = 0 #endif class ObserveOnSerialDispatchQueueSink<O: ObserverType> : ObserverBase<O.E> { let scheduler: SerialDispatchQueueScheduler let observer: O var disposeLock = SpinLock() var cancel: Disposable init(scheduler: SerialDispatchQueueScheduler, observer: O, cancel: Disposable) { self.cancel = cancel self.scheduler = scheduler self.observer = observer super.init() } override func onCore(event: Event<E>) { self.scheduler.schedule(()) { (_) -> Disposable in self.observer.on(event) if event.isStopEvent { self.dispose() } return NopDisposable.instance } } override func dispose() { super.dispose() let toDispose = disposeLock.calculateLocked { () -> Disposable in let originalCancel = self.cancel self.cancel = NopDisposable.instance return originalCancel } toDispose.dispose() } } class ObserveOnSerialDispatchQueue<E> : Producer<E> { let scheduler: SerialDispatchQueueScheduler let source: Observable<E> init(source: Observable<E>, scheduler: SerialDispatchQueueScheduler) { self.scheduler = scheduler self.source = source #if TRACE_RESOURCES OSAtomicIncrement32(&resourceCount) OSAtomicIncrement32(&numberOfSerialDispatchQueueObservables) #endif } override func run<O : ObserverType where O.E == E>(observer: O, cancel: Disposable, setSink: (Disposable) -> Void) -> Disposable { let sink = ObserveOnSerialDispatchQueueSink(scheduler: scheduler, observer: observer, cancel: cancel) setSink(sink) return source.subscribeSafe(sink) } #if TRACE_RESOURCES deinit { OSAtomicDecrement32(&resourceCount) OSAtomicDecrement32(&numberOfSerialDispatchQueueObservables) } #endif }
gpl-3.0
b90661e3755861c9e3a6c6f9ff1f9cc4
25.91954
134
0.646305
4.89749
false
false
false
false
SanctionCo/pilot-ios
Pods/Gallery/Sources/Camera/TripleButton.swift
1
1054
import UIKit class TripleButton: UIButton { struct State { let title: String let image: UIImage } let states: [State] var selectedIndex: Int = 0 // MARK: - Initialization init(states: [State]) { self.states = states super.init(frame: .zero) setup() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - Setup func setup() { titleLabel?.font = Config.Font.Text.semibold.withSize(12) imageEdgeInsets = UIEdgeInsets(top: 0, left: -10, bottom: 0, right: 0) setTitleColor(UIColor.gray, for: .highlighted) select(index: selectedIndex) } // MARK: - Logic @discardableResult func toggle() -> Int { selectedIndex = (selectedIndex + 1) % states.count select(index: selectedIndex) return selectedIndex } func select(index: Int) { guard index < states.count else { return } let state = states[index] setTitle(state.title, for: UIControlState()) setImage(state.image, for: UIControlState()) } }
mit
36e8e4f3277eed1daa1ae85b8e857f45
19.269231
74
0.652751
3.992424
false
false
false
false
andrewgrant/TodoApp
TodoApp/EditRemindersViewController.swift
1
3866
// // EditRemindersViewController.swift // EditReminders // // Created by Andrew Grant on 5/28/15. // Copyright (c) Andrew Grant. All rights reserved. // import UIKit class EditReminderViewController : UITableViewController { // MARK: - Properties @IBOutlet var eventNameTextField : UITextField! @IBOutlet var listTableViewCell : UITableViewCell! @IBOutlet var prioritySegments : UISegmentedControl! @IBOutlet var cancelButton : UIBarButtonItem! @IBOutlet var saveButton : UIBarButtonItem! var item : TodoEntry! var owningList : TodoList? var defaultReminderName = "New Reminder" deinit { NSNotificationCenter.defaultCenter().removeObserver(self) } // MARK: - View lifecycle override func viewDidLoad() { if item == nil { // If no reminder provided create a new one and set buttons to save/cancel item = TodoEntry(title: self.defaultReminderName) item.parentUuid = owningList?.uuid self.navigationItem.rightBarButtonItem = self.saveButton self.navigationItem.leftBarButtonItem = self.cancelButton } NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("onObjectChange:"), name: TodoStore.TSObjectsUpdatedNotification, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("onObjectChange:"), name: TodoStore.TSObjectsRemovedNotification, object: nil) } func onObjectChange(notification: NSNotification) { let userInfo = notification.userInfo as? [String: AnyObject] if let uuids = userInfo?["uuids"] as? [String] { if uuids.indexOf(item.uuid) != nil { updateObject() } } } func updateObject() { self.eventNameTextField?.text = self.item?.title self.listTableViewCell.detailTextLabel!.text = self.owningList?.title if self.item.priority <= 4 { self.prioritySegments.selectedSegmentIndex = self.item.priority } } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) self.updateObject() } override func viewWillDisappear(animated: Bool) { if let item = self.item { if self.eventNameTextField.text!.characters.count > 0 { item.title = eventNameTextField.text } item.priority = prioritySegments.selectedSegmentIndex var error : NSError? TodoStore.sharedInstance.saveObject(item, error: &error) if error != nil { let msg = UIAlertController(title: nil, message: "Error Saving Reminder: " + error!.description, preferredStyle: UIAlertControllerStyle.Alert) self.presentViewController(msg, animated: true, completion: nil) } } } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "SelectList" { if let cvc = segue.destinationViewController as? ChangeListViewController { cvc.item = self.item cvc.title = "Select List" } } } // MARK: - Actions @IBAction func onSave(sender : UIBarButtonItem?) { if self.eventNameTextField.text!.characters.count == 0 { self.eventNameTextField.text = self.defaultReminderName } self.navigationController?.popViewControllerAnimated(true) } @IBAction func onCancel(sender : UIBarButtonItem?) { // set to nil so nothing is saved self.item = nil self.navigationController?.popViewControllerAnimated(true) } }
mit
226d49d0259c6f1272c01f8422f1340a
32.617391
160
0.623901
5.29589
false
false
false
false
viktorasl/FuzzySearch
Source/FuzzySearch.swift
1
5860
// // FuzzySearch.swift // FuzzySearch // // Created by Viktoras Laukevičius on 05/08/16. // Copyright © 2016 Treatwell. All rights reserved. // import Foundation internal struct CharOpts { let ch: String let normalized: String } /// A private cache containing pre-parsed metadata from a previous `.fuzzyMatch` /// call. /// Used by CachedFuzzySearchable<T> bellow. internal class FuzzyCache { /// Hash of last fuzzed string internal var hash: Int? /// Array of last parsed fuzzy characters internal var lastTokenization = FuzzyTokens(tokens: []) internal init() { } } /// Opaque struct containing the results of a pre-tokenization phase that is /// applied to a fuzzy searchable value. public struct FuzzyTokens { fileprivate var tokens: [CharOpts] } internal extension String { func tokenize() -> [CharOpts] { return characters.map{ let str = String($0).lowercased() guard let data = str.data(using: .ascii, allowLossyConversion: true), let accentFoldedStr = String(data: data, encoding: .ascii) else { return CharOpts(ch: str, normalized: str) } return CharOpts(ch: str, normalized: accentFoldedStr) } } // checking if string has prefix and returning prefix length on success func hasPrefix(_ prefix: CharOpts, atIndex index: Int) -> Int? { for pfx in [prefix.ch, prefix.normalized] { if (self as NSString).substring(from: index).hasPrefix(pfx) { return pfx.characters.count } } return nil } } public struct FuzzySearchResult { public let weight: Int public let parts: [NSRange] } /// Specifies that a value exposes a string fit for fuzzy-matching against string /// patterns. public protocol FuzzySearchable { var fuzzyStringToMatch: String { get } func fuzzyMatch(_ pattern: String) -> FuzzySearchResult } /// Container over a FuzzySearchable that allows caching of metadata generated /// while fuzzying. /// /// This allows for improved performance when fuzzy-searching multiple times /// objects that don't change the contents of `fuzzyStringToMatch` too often. public struct CachedFuzzySearchable<T> : FuzzySearchable where T : FuzzySearchable { internal let searchable: T internal let fuzzyCache: FuzzyCache public init(wrapping searchable: T) { self.searchable = searchable self.fuzzyCache = FuzzyCache() } public var fuzzyStringToMatch: String { return searchable.fuzzyStringToMatch } } // Private implementation of fuzzy matcher that is used by `FuzzySearchable` and // the specialized `CachedFuzzySearchable` bellow. extension FuzzySearchable { func fuzzyMatch(_ pattern: String, with tokens: FuzzyTokens) -> FuzzySearchResult { let compareString = tokens.tokens let pattern = pattern.lowercased() var totalScore = 0 var parts: [NSRange] = [] var patternIdx = 0 var currScore = 0 var currPart = NSRange(location: 0, length: 0) for (idx, strChar) in compareString.enumerated() { if let prefixLength = pattern.hasPrefix(strChar, atIndex: patternIdx) { patternIdx += prefixLength currScore += 1 + currScore currPart.length += 1 } else { currScore = 0 if currPart.length != 0 { parts.append(currPart) } currPart = NSRange(location: idx + 1, length: 0) } totalScore += currScore } if currPart.length != 0 { parts.append(currPart) } if patternIdx == pattern.characters.count { // if all pattern chars were found return FuzzySearchResult(weight: totalScore, parts: parts) } else { return FuzzySearchResult(weight: 0, parts: []) } } } extension FuzzySearchable { func fuzzyTokenized() -> FuzzyTokens { return FuzzyTokens(tokens: fuzzyStringToMatch.tokenize()) } } extension CachedFuzzySearchable { func fuzzyTokenized() -> FuzzyTokens { // Re-create fuzzy cache, if stale if fuzzyCache.hash == nil || fuzzyCache.hash != fuzzyStringToMatch.hashValue { let tokens = fuzzyStringToMatch.tokenize() fuzzyCache.hash = fuzzyStringToMatch.hashValue fuzzyCache.lastTokenization = FuzzyTokens(tokens: tokens) } return fuzzyCache.lastTokenization } } public extension FuzzySearchable { func fuzzyMatch(_ pattern: String) -> FuzzySearchResult { let tokens = fuzzyTokenized() return fuzzyMatch(pattern, with: tokens) } } public extension CachedFuzzySearchable { // Note: Extension here is required to use the internal `CachedFuzzySearchable.fuzzyTokenized` // method, otherwise we end up using the `FuzzySearchable.fuzzyTokenized` // implementation which, since it's declared in an extension, cannot be overriden // by `CachedFuzzySearchable` (but `fuzzyMatch` can, and so we implement // the call to the custom cached `fuzzyTokenized` method here). func fuzzyMatch(_ pattern: String) -> FuzzySearchResult { let tokens = fuzzyTokenized() return fuzzyMatch(pattern, with: tokens) } } public extension Collection where Iterator.Element: FuzzySearchable { func fuzzyMatch(_ pattern: String) -> [(item: Iterator.Element, result: FuzzySearchResult)] { return map{ (item: $0, result: $0.fuzzyMatch(pattern)) }.filter{ $0.result.weight > 0 }.sorted{ $0.result.weight > $1.result.weight } } }
mit
844255528836fc5cca44cbcc69ade27c
31.010929
98
0.635712
4.447988
false
false
false
false
duliodenis/blocstagram2
Blocstagram/Blocstagram/Controller/CommentViewController.swift
1
5951
// // CommentViewController.swift // Blocstagram // // Created by ddenis on 1/20/17. // Copyright © 2017 ddApps. All rights reserved. // import UIKit class CommentViewController: UIViewController { @IBOutlet weak var commentTextField: UITextField! @IBOutlet weak var sendButton: UIButton! @IBOutlet weak var tableView: UITableView! @IBOutlet weak var constraintToBottom: NSLayoutConstraint! var postID: String! var comments = [Comment]() var users = [User]() // MARK: - View Lifecycle override func viewDidLoad() { super.viewDidLoad() title = "Comments" // for performance set an estimated row height tableView.estimatedRowHeight = 70 // but also request to dynamically adjust to content using AutoLayout tableView.rowHeight = UITableViewAutomaticDimension tableView.dataSource = self handleTextField() prepareForNewComment() loadComments() // Set Keyboard Observers NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(_:)), name: .UIKeyboardDidShow, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(_:)), name: .UIKeyboardWillHide, object: nil) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.tabBarController?.tabBar.isHidden = true } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) self.tabBarController?.tabBar.isHidden = false } // MARK: - Keyboard Notification Response Methods func keyboardWillShow(_ notification: NSNotification) { let keyboardFrame = (notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as AnyObject).cgRectValue UIView.animate(withDuration: 0.3) { self.constraintToBottom.constant = keyboardFrame!.height self.view.layoutIfNeeded() } } func keyboardWillHide(_ notification: NSNotification) { UIView.animate(withDuration: 0.3) { self.constraintToBottom.constant = 0 self.view.layoutIfNeeded() } } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { view.endEditing(true) } // MARK: - Firebase Save Operation @IBAction func send(_ sender: Any) { let commentsReference = API.Comment.REF_COMMENTS let newCommentID = commentsReference.childByAutoId().key let newCommentsReference = commentsReference.child(newCommentID) guard let currentUser = API.User.CURRENT_USER else { return } let currentUserID = currentUser.uid newCommentsReference.setValue(["uid": currentUserID, "commentText": commentTextField.text!]) { (error, reference) in if error != nil { ProgressHUD.showError("Photo Save Error: \(error?.localizedDescription)") return } let postCommentRef = API.PostComment.REF_POST_COMMENTS.child(self.postID).child(newCommentID) postCommentRef.setValue("true", withCompletionBlock: { (error, dbRef) in if error != nil { ProgressHUD.showError(error?.localizedDescription) return } }) self.prepareForNewComment() self.view.endEditing(true) } } // MARK: - Load Comments from Firebase func loadComments() { let postCommentRef = API.PostComment.REF_POST_COMMENTS.child(self.postID) postCommentRef.observe(.childAdded) { snapshot in API.Comment.observeComments(withPostID: snapshot.key, completion: { (newComment) in self.fetchUser(uid: newComment.uid!, completed: { // append the new Comment and Reload after the user // has been cached self.comments.append(newComment) self.tableView.reloadData() }) }) } } // fetch all user info at once and cache it into the users array func fetchUser(uid: String, completed: @escaping () -> Void) { API.User.observeUser(withID: uid) { user in self.users.append(user) completed() } } // MARK: - UI Methods func prepareForNewComment() { commentTextField.text = "" disableButton() } func handleTextField() { commentTextField.addTarget(self, action: #selector(textFieldDidChange), for: .editingChanged) } func textFieldDidChange() { guard let comment = commentTextField.text, !comment.isEmpty else { // disable Send button if comment is blank and return disableButton() return } // otherwise enable the Send button enableButton() } func enableButton() { sendButton.alpha = 1.0 sendButton.isEnabled = true } func disableButton() { sendButton.alpha = 0.2 sendButton.isEnabled = false } } // MARK: - TableView Delegate and Data Source Methods extension CommentViewController: UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return comments.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "CommentCell", for: indexPath) as! CommentTableViewCell cell.comment = comments[indexPath.row] cell.user = users[indexPath.row] return cell } }
mit
4214a7a31e33eee13a48c4b8caf60b2b
30.315789
135
0.610924
5.379747
false
false
false
false
VincentPuget/vigenere
vigenere/class/AppDelegate.swift
1
8156
// // AppDelegate.swift // Vigenere // // Created by Vincent PUGET on 05/08/2015. // Copyright (c) 2015 Vincent PUGET. All rights reserved. // import Cocoa @NSApplicationMain class AppDelegate: NSObject, NSApplicationDelegate { func applicationDidFinishLaunching(_ aNotification: Notification) { // Insert code here to initialize your application } func applicationWillTerminate(_ aNotification: Notification) { // Insert code here to tear down your application } //qui l'app si la dernière fenetre active est fermée func applicationShouldTerminateAfterLastWindowClosed(_ theApplication: NSApplication) -> Bool { return true; } // // MARK: - Core Data stack // // lazy var applicationDocumentsDirectory: NSURL = { // // The directory the application uses to store the Core Data store file. This code uses a directory named "mao.macos.vigenere.test" in the user's Application Support directory. // let urls = NSFileManager.defaultManager().URLsForDirectory(.ApplicationSupportDirectory, inDomains: .UserDomainMask) // let appSupportURL = urls[urls.count - 1] as! NSURL // return appSupportURL.URLByAppendingPathComponent("mao.macos.vigenere.test") // }() // // lazy var managedObjectModel: NSManagedObjectModel = { // // The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model. // let modelURL = NSBundle.mainBundle().URLForResource("test", withExtension: "momd")! // return NSManagedObjectModel(contentsOfURL: modelURL)! // }() // // lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = { // // The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it. (The directory for the store is created, if necessary.) This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. // let fileManager = NSFileManager.defaultManager() // var shouldFail = false // var error: NSError? = nil // var failureReason = "There was an error creating or loading the application's saved data." // // // Make sure the application files directory is there // let propertiesOpt = self.applicationDocumentsDirectory.resourceValuesForKeys([NSURLIsDirectoryKey], error: &error) // if let properties = propertiesOpt { // if !properties[NSURLIsDirectoryKey]!.boolValue { // failureReason = "Expected a folder to store application data, found a file \(self.applicationDocumentsDirectory.path)." // shouldFail = true // } // } else if error!.code == NSFileReadNoSuchFileError { // error = nil // fileManager.createDirectoryAtPath(self.applicationDocumentsDirectory.path!, withIntermediateDirectories: true, attributes: nil, error: &error) // } // // // Create the coordinator and store // var coordinator: NSPersistentStoreCoordinator? // if !shouldFail && (error == nil) { // coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel) // let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("test.storedata") // if coordinator!.addPersistentStoreWithType(NSXMLStoreType, configuration: nil, URL: url, options: nil, error: &error) == nil { // coordinator = nil // } // } // // if shouldFail || (error != nil) { // // Report any error we got. // var dict = [String: AnyObject]() // dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" // dict[NSLocalizedFailureReasonErrorKey] = failureReason // if error != nil { // dict[NSUnderlyingErrorKey] = error // } // error = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict) // NSApplication.sharedApplication().presentError(error!) // return nil // } else { // return coordinator // } // }() // // lazy var managedObjectContext: NSManagedObjectContext? = { // // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail. // let coordinator = self.persistentStoreCoordinator // if coordinator == nil { // return nil // } // var managedObjectContext = NSManagedObjectContext() // managedObjectContext.persistentStoreCoordinator = coordinator // return managedObjectContext // }() // // // MARK: - Core Data Saving and Undo support // // @IBAction func saveAction(sender: AnyObject!) { // // Performs the save action for the application, which is to send the save: message to the application's managed object context. Any encountered errors are presented to the user. // if let moc = self.managedObjectContext { // if !moc.commitEditing() { // NSLog("\(NSStringFromClass(self.dynamicType)) unable to commit editing before saving") // } // var error: NSError? = nil // if moc.hasChanges && !moc.save(&error) { // NSApplication.sharedApplication().presentError(error!) // } // } // } // // func windowWillReturnUndoManager(window: NSWindow) -> NSUndoManager? { // // Returns the NSUndoManager for the application. In this case, the manager returned is that of the managed object context for the application. // if let moc = self.managedObjectContext { // return moc.undoManager // } else { // return nil // } // } // // func applicationShouldTerminate(sender: NSApplication) -> NSApplicationTerminateReply { // // Save changes in the application's managed object context before the application terminates. // // if let moc = managedObjectContext { // if !moc.commitEditing() { // NSLog("\(NSStringFromClass(self.dynamicType)) unable to commit editing to terminate") // return .TerminateCancel // } // // if !moc.hasChanges { // return .TerminateNow // } // // var error: NSError? = nil // if !moc.save(&error) { // // Customize this code block to include application-specific recovery steps. // let result = sender.presentError(error!) // if (result) { // return .TerminateCancel // } // // let question = NSLocalizedString("Could not save changes while quitting. Quit anyway?", comment: "Quit without saves error question message") // let info = NSLocalizedString("Quitting now will lose any changes you have made since the last successful save", comment: "Quit without saves error question info"); // let quitButton = NSLocalizedString("Quit anyway", comment: "Quit anyway button title") // let cancelButton = NSLocalizedString("Cancel", comment: "Cancel button title") // let alert = NSAlert() // alert.messageText = question // alert.informativeText = info // alert.addButtonWithTitle(quitButton) // alert.addButtonWithTitle(cancelButton) // // let answer = alert.runModal() // if answer == NSAlertFirstButtonReturn { // return .TerminateCancel // } // } // } // // If we got here, it is time to quit. // return .TerminateNow // } }
mit
d68fb4ff5f72cf0190b5d213de7f279f
48.719512
348
0.624847
5.020936
false
false
false
false
CandyTrace/CandyTrace
Always Write/Controllers/TraceVC.swift
1
6423
// // TraceVC.swift // Always Write // // Created by Sam Raudabaugh on 3/10/17. // Copyright © 2017 Cornell Tech. All rights reserved. // import UIKit import CoreText extension UINavigationBar { override open func sizeThatFits(_ size: CGSize) -> CGSize { return CGSize(width: UIScreen.main.bounds.size.width, height: 65.0) } } class TraceVC: UIViewController { var rawPoints = [Int]() @IBOutlet var drawingView: DrawingView! @IBOutlet weak var referenceView: ReferenceView! var inCount = 0 var outCount = 0 override func viewDidLoad() { super.viewDidLoad() navigationController?.navigationBar.setBackgroundImage(UIImage(named: "nav-pink"), for: .default) navigationController?.navigationBar.titleTextAttributes = [NSFontAttributeName: UIFont(name: "Futura-Bold", size: 32)!] title = "LESSON 3" let profileButton = UIBarButtonItem(image: UIImage(named: "profile-icon"), style: .plain, target: self, action: #selector(profileTapped)) profileButton.tintColor = .black navigationItem.setLeftBarButton(profileButton, animated: true) let graphButton = UIBarButtonItem(title: "", style: .plain, target: self, action: #selector(graphTapped)) graphButton.setTitleTextAttributes([NSFontAttributeName: UIFont(name: "FontAwesome", size: 26)!], for: .normal) graphButton.tintColor = .black navigationItem.setRightBarButton(graphButton, animated: true) } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { rawPoints = [] let touch = touches.first let location = touch!.location(in: drawingView) rawPoints.append(Int(location.x)) rawPoints.append(Int(location.y)) } override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) { let touch = touches.first let location = touch!.location(in: drawingView) if rawPoints[rawPoints.count-2] != Int(location.x) || rawPoints[rawPoints.count-1] != Int(location.y) { rawPoints.append(Int(location.x)) rawPoints.append(Int(location.y)) } drawingView.pointsBuffer.append(rawPoints) draw() if referenceView.traceInBounds(location) { inCount += 1 } else { outCount += 1 } } override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { } @IBAction func sliderChanged(_ sender: UISlider) { referenceView.size = CGFloat(sender.value*1000) drawingView.image = nil inCount = 0 outCount = 0 } func draw() { UIGraphicsBeginImageContext(drawingView.frame.size) let context = UIGraphicsGetCurrentContext() context?.clear(drawingView.frame) context!.setLineWidth(referenceView.size/10) context?.setLineCap(.round) guard let pointsToDraw = drawingView.pointsBuffer.last else { return } drawingView.image?.draw(in: CGRect(x: 0, y: 0, width: drawingView.frame.size.width, height: drawingView.frame.size.height)) if pointsToDraw.count >= 4 { context?.move(to: CGPoint(x: CGFloat(pointsToDraw[0]), y: CGFloat(pointsToDraw[1]))) for i in 2..<pointsToDraw.count { if i % 2 == 0 { context?.addLine(to: CGPoint(x: CGFloat(pointsToDraw[i]), y: CGFloat(pointsToDraw[i + 1]))) } } } context!.strokePath() drawingView.image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() } @IBAction func donePressed(_ sender: Any) { grade() } func grade() { let traceFill = drawingView.image?.fillCount(bitmapInfo: Constants.traceFillBitmapInfo) ?? 0 print("traceFill = \(traceFill)") let expectFill = referenceView.expectedFill() print("expectFill = \(expectFill)") if inCount+outCount == 0 { return } let accuracy = Double(inCount)/Double(inCount+outCount) let completeness = Double(traceFill)/Double(expectFill) let formatter = NumberFormatter() formatter.numberStyle = .percent let scoreString = formatter.string(from: NSNumber(value: score(accuracy: accuracy, completeness: completeness))) ?? "" let alert = UIAlertController(title: "Great Job!", message: "You scored \(scoreString)!", preferredStyle: .alert) let close = UIAlertAction(title: "OK", style: .default) { action in self.drawingView.image = nil self.inCount = 0 self.outCount = 0 } alert.addAction(close) present(alert, animated: true, completion: nil) } func score(accuracy: Double, completeness: Double) -> Double { var score = accuracy if completeness > 1 { score -= 0.6212 * (completeness-1) } else { score -= 1.12 * (1-completeness) } return max(0, score) } func profileTapped() { let _ = navigationController?.popViewController(animated: true) } func graphTapped() { performSegue(withIdentifier: "ShowChart", sender: self) } @IBAction func tTapped(_ sender: Any) { chooseShape("T") } @IBAction func lTapped(_ sender: Any) { chooseShape("L") } @IBAction func iTapped(_ sender: Any) { chooseShape("I") } @IBAction func hTapped(_ sender: Any) { chooseShape("H") } @IBAction func fTapped(_ sender: Any) { chooseShape("F") } @IBAction func eTapped(_ sender: Any) { chooseShape("E") } func chooseShape(_ shape: String) { referenceView.shape = shape drawingView.image = nil inCount = 0 outCount = 0 } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ } struct Constants { static let traceFillBitmapInfo = CGImageAlphaInfo.premultipliedLast.rawValue }
mit
0e88fd95f46b9f927912df26171cb619
33.891304
145
0.618536
4.442907
false
false
false
false
aojet/Aojet
Sources/Aojet/actors/ActorScope.swift
1
1053
// // ActorScope.swift // Aojet // // Created by Qihe Bian on 6/6/16. // Copyright © 2016 Qihe Bian. All rights reserved. // public class ActorScope { public let actorSystem: ActorSystem public let mailbox: Mailbox public let dispatcher: ActorDispatcher public let path: String public let props: Props public let endpoint: ActorEndpoint private(set) var ref: ActorRef private(set) var actor: Actor! = nil public var message: Any? public var sender: ActorRef? init(actorSystem: ActorSystem, mailbox: Mailbox, dispatcher: ActorDispatcher, path: String, props: Props, endpoint: ActorEndpoint) { self.actorSystem = actorSystem self.mailbox = mailbox self.ref = ActorRef(endpoint: endpoint, system: actorSystem, path: path) self.dispatcher = dispatcher self.path = path self.props = props self.endpoint = endpoint } func onActorCreated(actor: Actor) { self.actor = actor } func onActorDie() { actor = nil sender = nil message = nil } }
mit
bead85803e6b0b326d0a7632c4be0410
21.869565
76
0.673954
3.770609
false
false
false
false
Paulinechi/Swift-Pauline
day1/Cai Su Shu/Cai Su Shu/ViewController.swift
1
1186
// ViewController.swift // Cai Su Shu // // Created by 池菲暄 on 15-2-2. // Copyright (c) 2015年 池菲暄. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var numberTextField: UITextField! @IBOutlet weak var Insertanumber: UILabel! @IBOutlet weak var resultLabel: UILabel! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBOutlet weak var buttonClicked: UIButton! @IBAction func buttonClicked(sender: AnyObject) { var number = numberTextField.text.toInt()! println(number) var flag = 1 for index in 2...number - 1 { if (number % index) == 0 { flag = 0 println(index) break } } if flag == 1 { resultLabel.text = "Prime" }else { resultLabel.text = "Not prime" } } }
mit
cb0b109c68cd084e2a3f48f6ada51022
24.5
80
0.571672
4.542636
false
false
false
false
weirdindiankid/Tinder-Clone
TinderClone/Tabs/MessagesViewController.swift
1
2054
// // MessagesViewController.swift // TinderClone // // Created by Dharmesh Tarapore on 21/01/2015. // Copyright (c) 2015 Dharmesh Tarapore. All rights reserved. // import UIKit class MessagesViewController: UIViewController { var selectedUser:PFUser = PFUser() var profileImage:UIImage = UIImage() @IBOutlet var profilePicture : UIImageView? @IBOutlet var messages : UILabel? @IBOutlet weak var messageTableView: UITableView! override func viewDidLoad() { super.viewDidLoad() self.profilePicture!.image = profileImage let dateOfBirth:String = self.calculateAge(selectedUser["dobstring"] as String) let gender:String = selectedUser["gender"] as String let interest:String = selectedUser["interestedin"] as String let emailID:String = selectedUser.email as String self.messages!.text = NSString(format: "%@, %@, %@ \nInterested In: %@\nEmail ID: %@", selectedUser.username, dateOfBirth, gender, interest, emailID) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func calculateAge(dobString:String) -> String { let dateFormatter = NSDateFormatter() dateFormatter.dateFormat = "dd/MM/yyyy" var date = dateFormatter.dateFromString(dobString) as NSDate! if (date==nil) { return "10"; } var timeInterval = date.timeIntervalSinceNow let age = Int(abs(timeInterval / (60 * 60 * 24 * 365))) as Int println(age) return String(age) } /* // 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
b168b611e2892159cad9b6974ecadf42
31.603175
158
0.652386
4.799065
false
false
false
false
vapor/vapor
Sources/Vapor/Utilities/FileIO.swift
1
11634
import NIO import Logging extension Request { public var fileio: FileIO { return .init( io: self.application.fileio, allocator: self.application.allocator, request: self ) } } // MARK: FileIO /// `FileIO` is a convenience wrapper around SwiftNIO's `NonBlockingFileIO`. /// /// It can read files, both in their entirety and chunked. /// /// let fileio = try c.make(FileIO.self) /// /// fileio.readFile(at: "/path/to/file.txt") { chunk in /// print(chunk) // part of file /// } /// /// fileio.collectFile(at: "/path/to/file.txt").map { file in /// print(file) // entire file /// } /// /// It can also create streaming HTTP responses. /// /// let fileio = try c.make(FileIO.self) /// router.get("file-stream") { req -> Response in /// return fileio.streamFile(at: "/path/to/file.txt", for: req) /// } /// /// Streaming file responses respect `E-Tag` headers present in the request. public struct FileIO { /// Wrapped non-blocking file io from SwiftNIO private let io: NonBlockingFileIO /// ByteBufferAllocator to use for generating buffers. private let allocator: ByteBufferAllocator /// HTTP request context. let request: Request /// Creates a new `FileIO`. /// /// See `Request.fileio()` to create one. internal init(io: NonBlockingFileIO, allocator: ByteBufferAllocator, request: Request) { self.io = io self.allocator = allocator self.request = request } /// Reads the contents of a file at the supplied path. /// /// let data = try req.fileio().read(file: "/path/to/file.txt").wait() /// print(data) // file data /// /// - parameters: /// - path: Path to file on the disk. /// - returns: `Future` containing the file data. public func collectFile(at path: String) -> EventLoopFuture<ByteBuffer> { var data = self.allocator.buffer(capacity: 0) return self.readFile(at: path) { new in var new = new data.writeBuffer(&new) return self.request.eventLoop.makeSucceededFuture(()) }.map { data } } /// Reads the contents of a file at the supplied path in chunks. /// /// try req.fileio().readChunked(file: "/path/to/file.txt") { chunk in /// print("chunk: \(data)") /// }.wait() /// /// - parameters: /// - path: Path to file on the disk. /// - chunkSize: Maximum size for the file data chunks. /// - onRead: Closure to be called sequentially for each file data chunk. /// - returns: `Future` that will complete when the file read is finished. public func readFile( at path: String, chunkSize: Int = NonBlockingFileIO.defaultChunkSize, onRead: @escaping (ByteBuffer) -> EventLoopFuture<Void> ) -> EventLoopFuture<Void> { guard let attributes = try? FileManager.default.attributesOfItem(atPath: path), let fileSize = attributes[.size] as? NSNumber else { return self.request.eventLoop.makeFailedFuture(Abort(.internalServerError)) } return self.read( path: path, fromOffset: 0, byteCount: fileSize.intValue, chunkSize: chunkSize, onRead: onRead ) } /// Generates a chunked `Response` for the specified file. This method respects values in /// the `"ETag"` header and is capable of responding `304 Not Modified` if the file in question /// has not been modified since last served. This method will also set the `"Content-Type"` header /// automatically if an appropriate `MediaType` can be found for the file's suffix. /// /// router.get("file-stream") { req in /// return req.fileio.streamFile(at: "/path/to/file.txt") /// } /// /// - parameters: /// - path: Path to file on the disk. /// - chunkSize: Maximum size for the file data chunks. /// - mediaType: HTTPMediaType, if not specified, will be created from file extension. /// - onCompleted: Closure to be run on completion of stream. /// - returns: A `200 OK` response containing the file stream and appropriate headers. public func streamFile( at path: String, chunkSize: Int = NonBlockingFileIO.defaultChunkSize, mediaType: HTTPMediaType? = nil, onCompleted: @escaping (Result<Void, Error>) -> () = { _ in } ) -> Response { // Get file attributes for this file. guard let attributes = try? FileManager.default.attributesOfItem(atPath: path), let modifiedAt = attributes[.modificationDate] as? Date, let fileSize = (attributes[.size] as? NSNumber)?.intValue else { return Response(status: .internalServerError) } let contentRange: HTTPHeaders.Range? if let rangeFromHeaders = request.headers.range { if rangeFromHeaders.unit == .bytes && rangeFromHeaders.ranges.count == 1 { contentRange = rangeFromHeaders } else { contentRange = nil } } else if request.headers.contains(name: .range) { // Range header was supplied but could not be parsed i.e. it was invalid request.logger.debug("Range header was provided in request but was invalid") let response = Response(status: .badRequest) return response } else { contentRange = nil } // Create empty headers array. var headers: HTTPHeaders = [:] // Generate ETag value, "HEX value of last modified date" + "-" + "file size" let fileETag = "\(modifiedAt.timeIntervalSince1970)-\(fileSize)" headers.replaceOrAdd(name: .eTag, value: fileETag) // Check if file has been cached already and return NotModified response if the etags match if fileETag == request.headers.first(name: .ifNoneMatch) { return Response(status: .notModified) } // Create the HTTP response. let response = Response(status: .ok, headers: headers) let offset: Int64 let byteCount: Int if let contentRange = contentRange { response.status = .partialContent response.headers.add(name: .accept, value: contentRange.unit.serialize()) if let firstRange = contentRange.ranges.first { do { let range = try firstRange.asResponseContentRange(limit: fileSize) response.headers.contentRange = HTTPHeaders.ContentRange(unit: contentRange.unit, range: range) (offset, byteCount) = try firstRange.asByteBufferBounds(withMaxSize: fileSize, logger: request.logger) } catch { let response = Response(status: .badRequest) return response } } else { offset = 0 byteCount = fileSize } } else { offset = 0 byteCount = fileSize } // Set Content-Type header based on the media type // Only set Content-Type if file not modified and returned above. if let fileExtension = path.components(separatedBy: ".").last, let type = mediaType ?? HTTPMediaType.fileExtension(fileExtension) { response.headers.contentType = type } response.body = .init(stream: { stream in self.read(path: path, fromOffset: offset, byteCount: byteCount, chunkSize: chunkSize) { chunk in return stream.write(.buffer(chunk)) }.whenComplete { result in switch result { case .failure(let error): stream.write(.error(error), promise: nil) case .success: stream.write(.end, promise: nil) } onCompleted(result) } }, count: byteCount, byteBufferAllocator: request.byteBufferAllocator) return response } /// Private read method. `onRead` closure uses ByteBuffer and expects future return. /// There may be use in publicizing this in the future for reads that must be async. private func read( path: String, fromOffset offset: Int64, byteCount: Int, chunkSize: Int, onRead: @escaping (ByteBuffer) -> EventLoopFuture<Void> ) -> EventLoopFuture<Void> { do { let fd = try NIOFileHandle(path: path) let done = self.io.readChunked( fileHandle: fd, fromOffset: offset, byteCount: byteCount, chunkSize: chunkSize, allocator: allocator, eventLoop: self.request.eventLoop ) { chunk in return onRead(chunk) } done.whenComplete { _ in try? fd.close() } return done } catch { return self.request.eventLoop.makeFailedFuture(error) } } /// Write the contents of buffer to a file at the supplied path. /// /// let data = ByteBuffer(string: "ByteBuffer") /// try req.fileio.writeFile(data, at: "/path/to/file.txt").wait() /// /// - parameters: /// - path: Path to file on the disk. /// - buffer: The `ByteBuffer` to write. /// - returns: `Future` that will complete when the file write is finished. public func writeFile(_ buffer: ByteBuffer, at path: String) -> EventLoopFuture<Void> { do { let fd = try NIOFileHandle(path: path, mode: .write, flags: .allowFileCreation()) let done = io.write(fileHandle: fd, buffer: buffer, eventLoop: self.request.eventLoop) done.whenComplete { _ in try? fd.close() } return done } catch { return self.request.eventLoop.makeFailedFuture(error) } } } extension HTTPHeaders.Range.Value { fileprivate func asByteBufferBounds(withMaxSize size: Int, logger: Logger) throws -> (offset: Int64, byteCount: Int) { switch self { case .start(let value): guard value <= size, value >= 0 else { logger.debug("Requested range start was invalid: \(value)") throw Abort(.badRequest) } return (offset: numericCast(value), byteCount: size - value) case .tail(let value): guard value <= size, value >= 0 else { logger.debug("Requested range end was invalid: \(value)") throw Abort(.badRequest) } return (offset: numericCast(size - value), byteCount: value) case .within(let start, let end): guard start >= 0, end >= 0, start < end, start <= size, end <= size else { logger.debug("Requested range was invalid: \(start)-\(end)") throw Abort(.badRequest) } let (byteCount, overflow) = (end - start).addingReportingOverflow(1) guard !overflow else { logger.debug("Requested range was invalid: \(start)-\(end)") throw Abort(.badRequest) } return (offset: numericCast(start), byteCount: byteCount) } } }
mit
0af47356d4c10c663dd0a3414915f258
38.571429
122
0.571429
4.655462
false
false
false
false
nirmankarta/eddystone
tools/gatt-config/ios/Beaconfig/Beaconfig/HorizontalScrollButtonList.swift
2
6634
// Copyright 2016 Google Inc. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. let globalButtonIndex = 0 import UIKit /// /// Displays a custom made horizontal scroll button list, which appears on top of the view. /// There can be only one selected button at a time and the class deselects the previously /// selected button. The first button to be pressed is the Global one, since the Global view is /// the default view to be displayed. /// class HorizontalScrollButtonList: UIView { /// Keeps track of the previous slelected button in order to be able to deselect it var previousButtonPressed: UIButton? /// Displays a line under the selected button var previousUnderlineView: UIView? var linesArray: [UIView] = [] var buttonsArray: [UIButton] = [] /// /// Callback to the main class in order for it to handle displaying a different view /// for each one of the buttons /// var buttonPressedCallback: ((buttonNumber: Int) -> Void)? required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } init(buttonSize:CGSize, buttonNames: NSMutableArray, callback: (buttonNumber: Int) -> Void) { buttonPressedCallback = callback super.init(frame: CGRectMake(0, 0, 0, 0)) let buttonCount = buttonNames.count self.frame.origin = CGPointMake(0,0) self.frame.size.width = buttonSize.width * CGFloat(buttonCount) self.frame.size.height = buttonSize.height self.backgroundColor = UIColor.whiteColor() configureLine(buttonSize.width * CGFloat(buttonCount)) var buttonPosition = CGPointMake(0, 0) let padding: CGFloat = 1 let buttonIncrement = buttonSize.width + padding for i in 0..<buttonCount { var button: UIButton! if let title = buttonNames[i] as? String { button = configureButtonDesign(buttonSize, buttonPosition: buttonPosition, title: title) } let underlineView = configureButtonUnderlineView(buttonSize, buttonPosition: buttonPosition) /// Show the Global button pressed, as the Global view is the first one to be displayed if i == globalButtonIndex { button.selected = true underlineView.hidden = false previousButtonPressed = button previousUnderlineView = underlineView } buttonPosition.x = buttonPosition.x + buttonIncrement let separatorPadding: CGFloat = 20 if i != buttonCount - 1 { configureButtonSeparatorView(buttonSize.height - separatorPadding, position: CGPointMake(buttonPosition.x - padding, buttonPosition.y + separatorPadding / 2)) } self.addSubview(underlineView) } } func configureButtonSeparatorView(height: CGFloat, position: CGPoint) { let rightView = UIView() rightView.backgroundColor = UIColor.lightGrayColor() rightView.frame.size = CGSize(width: 1, height: height) rightView.frame.origin = position self.addSubview(rightView) } func configureButtonDesign(buttonSize: CGSize, buttonPosition: CGPoint, title: String) -> UIButton { let button = UIButton(type: .Custom) button.frame.size = buttonSize button.frame.origin = buttonPosition button.setTitle(title, forState: UIControlState.Normal) button.setTitleColor(UIColor.darkGrayColor(), forState: UIControlState.Normal) button.setTitleColor(UIColor.grayColor(), forState: UIControlState.Selected) button.titleLabel?.font = UIFont(name: "Arial-BoldMT", size: kTextFontSize) button.addTarget(self, action: #selector(HorizontalScrollButtonList.slotButtonPressed(_:)), forControlEvents: .TouchUpInside) button.backgroundColor = UIColor.whiteColor() buttonsArray.append(button) self.addSubview(button) return button } func configureButtonUnderlineView(buttonSize: CGSize, buttonPosition: CGPoint) -> UIView { let view = UIView() let lineHeight: CGFloat = 3 view.frame.size = CGSizeMake(buttonSize.width, lineHeight) view.frame.origin = CGPointMake(buttonPosition.x, buttonPosition.y + buttonSize.height) view.backgroundColor = kGreenColor view.hidden = true linesArray.append(view) return view } func configureLine(width: CGFloat) -> UIView { let line = UIView() line.backgroundColor = UIColor.whiteColor() line.frame.size.height = 2 line.frame.size.width = width line.frame.origin = CGPointMake(0, self.frame.height) CustomViews.addShadow(line) self.addSubview(line) return line } /// /// Handle the swipe motions between the views, changing the selected button with /// the one that coresponds to the view the user is currently seeing. /// func swipeLeft() { if previousButtonPressed != buttonsArray[buttonsArray.count - 1] { for i in 0 ..< buttonsArray.count { if previousButtonPressed == buttonsArray[i] { slotButtonPressed(buttonsArray[i + 1]) break } } } } func swipeRight() { if previousButtonPressed != buttonsArray[globalButtonIndex] { for i in 0 ..< buttonsArray.count { if previousButtonPressed == buttonsArray[i] { slotButtonPressed(buttonsArray[i - 1]) break } } } } func slotButtonPressed(sender: UIButton) { if previousButtonPressed != nil { previousButtonPressed!.selected = false previousUnderlineView!.hidden = true } sender.selected = true if let character = sender.titleLabel?.text?.characters.last, buttonNumber = Int(String(character)), callback = buttonPressedCallback { linesArray[buttonNumber].hidden = false previousUnderlineView = linesArray[buttonNumber] callback(buttonNumber: buttonNumber) } else if let callback = buttonPressedCallback { linesArray[globalButtonIndex].hidden = false previousUnderlineView = linesArray[globalButtonIndex] callback(buttonNumber: globalButtonIndex) } previousButtonPressed = sender } }
apache-2.0
bf7c609544d08c9e93a0ae1c2cb46587
34.859459
98
0.691438
4.711648
false
false
false
false
mozilla-magnet/magnet-client
ios/Analytics.swift
1
3381
// // Analytics.swift // Magnet // // Created by sam on 11/21/16. // Copyright © 2016 Mozilla. All rights reserved. // import Foundation import SwiftyJSON class Analytics { var tracker: GAITracker let apiPreferences = ApiPreferences() init() { let gai = GAI.sharedInstance() self.tracker = gai.trackerWithTrackingId(kGaTrackerId) } // Wrap a tracking function around a preference check. func doTrack(track: () -> Void,_ callback: ApiCallback) { func onPreferencesReceived(json: JSON) { // If telemetry is not enabled, return early. if !asBoolean(json["enableTelemetry"].string) { callback.onSuccess(true); return } track(); callback.onSuccess(true) } apiPreferences.get("", callback: ApiCallback(success: onPreferencesReceived, error: callback.onError)); } func trackEvent(data: JSON, callback: ApiCallback) { doTrack({() in self.doTrackEvent(data) }, callback); } func trackScreenView(data: JSON, callback: ApiCallback) { doTrack({() in self.doTrackScreenView(data) }, callback); } func trackTiming(data: JSON, callback: ApiCallback) { doTrack({() in self.doTrackTiming(data) }, callback); } func doTrackEvent(data: JSON) { let category = data["category"].string! let action = data["action"].string! let label = data["label"].string let value = data["value"].int64 self.doTrackEvent(category, action: action, label: label, value: value) } func doTrackEvent(category: String, action: String, label: String?, value: Int64?) { var hit: GAIDictionaryBuilder if let _value = value { hit = GAIDictionaryBuilder.createEventWithCategory( category, action: action, label: nil, value: NSNumber(longLong: _value)) } else { hit = GAIDictionaryBuilder.createEventWithCategory( category, action: action, label: nil, value: nil) } if let _label = label { hit.set(_label, forKey: kGAIEventLabel) } self.tracker.send(hit.build() as [NSObject : AnyObject]) } func doTrackScreenView(data: JSON) { let screenName = data["name"].string! self.doTrackScreenView(screenName) } func doTrackScreenView(screenName: String) { self.tracker.set(kGAIScreenName, value: screenName) let hit = GAIDictionaryBuilder.createScreenView() self.tracker.send(hit.build() as [NSObject : AnyObject]) } func doTrackTiming(data: JSON) { let category = data["category"].string! let value = data["value"].double! let name = data["name"].string! let label = data["label"].string self.doTrackTiming(category, value: value, name: name, label: label) } func doTrackTiming(category: String, value: Double, name: String, label: String?) { let hit:GAIDictionaryBuilder = GAIDictionaryBuilder.createTimingWithCategory(category, interval: NSNumber(double: value), name: name, label: nil) if let _label = label { hit.set(kGAITimingLabel, forKey: _label) } self.tracker.send(hit.build() as [NSObject : AnyObject]) } } func asBoolean(string: String?) -> Bool { if let _string = string { switch(_string) { case "0": return false case "1": return true case "true": return true case "false": return false default: return false } } return false }
mpl-2.0
45d5ef4d0556ac1fe12db37d1a674a70
25.20155
149
0.658876
3.990555
false
false
false
false
quire-io/SwiftyChrono
Sources/Parsers/EN/ENISOFormatParser.swift
1
3404
// // ENISOFormatParser.swift // SwiftyChrono // // Created by Jerry Chen on 1/20/17. // Copyright © 2017 Potix. All rights reserved. // import Foundation /* ISO 8601 http://www.w3.org/TR/NOTE-datetime - YYYY-MM-DD - YYYY-MM-DDThh:mmTZD - YYYY-MM-DDThh:mm:ssTZD - YYYY-MM-DDThh:mm:ss.sTZD - TZD = (Z or +hh:mm or -hh:mm) */ private let PATTERN = "(\\W|^)" + "([0-9]{4})\\-([0-9]{1,2})\\-([0-9]{1,2})" + "(?:T" + //.. "([0-9]{1,2}):([0-9]{1,2})" + // hh:mm "(?::([0-9]{1,2})(?:\\.(\\d{1,4}))?)?" + // :ss.s "(?:Z|([+-]\\d{2}):?(\\d{2})?)?" + // TZD (Z or ±hh:mm or ±hhmm or ±hh) ")?" + //.. "(?=\\W|$)" private let yearNumberGroup = 2 private let monthNumberGroup = 3 private let dayNumberGroup = 4 private let hourNumberGroup = 5 private let minuteNumberGroup = 6 private let secondNumberGroup = 7 private let millisecondNumberGroup = 8 private let tzdHourOffsetGroup = 9 private let tzdMinuteOffsetGroup = 10 public class ENISOFormatParser: Parser { override var pattern: String { return PATTERN } override public func extract(text: String, ref: Date, match: NSTextCheckingResult, opt: [OptionType: Int]) -> ParsedResult? { let (matchText, index) = matchTextAndIndex(from: text, andMatchResult: match) var result = ParsedResult(ref: ref, index: index, text: matchText) result.start.assign(.year, value: Int(match.string(from: text, atRangeIndex: yearNumberGroup))) result.start.assign(.month, value: Int(match.string(from: text, atRangeIndex: monthNumberGroup))) result.start.assign(.day, value: Int(match.string(from: text, atRangeIndex: dayNumberGroup))) guard let month = result.start[.month], let day = result.start[.day] else { return nil } if month > 12 || month < 1 || day > 31 || day < 1 { return nil } if match.isNotEmpty(atRangeIndex: hourNumberGroup) { result.start.assign(.hour, value: Int(match.string(from: text, atRangeIndex: hourNumberGroup))) result.start.assign(.minute, value: Int(match.string(from: text, atRangeIndex: minuteNumberGroup))) if match.isNotEmpty(atRangeIndex: secondNumberGroup) { result.start.assign(.second, value: Int(match.string(from: text, atRangeIndex: secondNumberGroup))) } if match.isNotEmpty(atRangeIndex: millisecondNumberGroup) { result.start.assign(.millisecond, value: Int(match.string(from: text, atRangeIndex: millisecondNumberGroup))) } if match.isNotEmpty(atRangeIndex: tzdHourOffsetGroup) { let hourOffset = Int(match.string(from: text, atRangeIndex: tzdHourOffsetGroup)) ?? 0 let minuteOffset = match.isNotEmpty(atRangeIndex: tzdMinuteOffsetGroup) ? Int(match.string(from: text, atRangeIndex: tzdMinuteOffsetGroup)) ?? 0 : 0 var offset = hourOffset * 60 offset = offset + (offset < 0 ? -minuteOffset : minuteOffset) result.start.assign(.timeZoneOffset, value: offset) } else { result.start.assign(.timeZoneOffset, value: 0) } } result.tags[.enCasualTimeParser] = true return result } }
mit
01adbc5934ad83795b55dc20dbf147f5
38.08046
164
0.598235
3.78198
false
false
false
false
Alexiuce/Tip-for-day
iFeiBo/iFeiBo/HomeStatusView.swift
1
1252
// // HomeStatusView.swift // iFeiBo // // Created by alexiuce  on 2017/9/18. // Copyright © 2017年 Alexcai. All rights reserved. // import Cocoa import Kingfisher class HomeStatusView: NSView { var status : WBStatus? { didSet{ guard let name = status?.user?.name else {return} nameLabel.stringValue = name guard let time = status?.created_at else {return} timeLabel.stringValue = time guard let url = status?.user?.avatar_hd else { return } headerImageView.kf.setImage(with: URL(string: url)) textLabel.stringValue = status?.text ?? "" } } @IBOutlet weak var headerImageView: NSImageView! @IBOutlet weak var nameLabel: NSTextField! @IBOutlet weak var timeLabel: NSTextField! @IBOutlet weak var textLabel: NSTextField! func caculateHeight(_ tableView: NSTableView, targetStatus: WBStatus) -> CGFloat{ bounds.size.width = tableView.bounds.width status = targetStatus layoutSubtreeIfNeeded() return bounds.height } override func draw(_ dirtyRect: NSRect) { super.draw(dirtyRect) // Drawing code here. } }
mit
22d04a8ee13a21b009c435f579d4fbf1
24.469388
85
0.610577
4.656716
false
false
false
false