repo_name
stringlengths
6
91
path
stringlengths
8
968
copies
stringclasses
210 values
size
stringlengths
2
7
content
stringlengths
61
1.01M
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6
99.8
line_max
int64
12
1k
alpha_frac
float64
0.3
0.91
ratio
float64
2
9.89
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
ainopara/Stage1st-Reader
Stage1st/Manager/DiscuzClient/Models/RawFloorList.swift
1
3668
// // RawFloorList.swift // Stage1st // // Created by Zheng Li on 2019/1/6. // Copyright © 2019 Renaissance. All rights reserved. // import Foundation public struct RawFloorList: Decodable { public struct Variables: Decodable { public let memberUid: String? public let memberUsername: String? public let memberAvatar: URL? public let formhash: String? public let notice: NoticeCount public struct Thread: Decodable { public let tid: String public let fid: String public let subject: String? public let authorid: String public let views: String public let author: String public let lastpost: String public let replies: String private enum CodingKeys: String, CodingKey { case tid case fid case subject case authorid case views case author case lastpost case replies } } public let thread: Thread public struct Post: Decodable { public let pid: String public let tid: String public let first: String public let author: String public let authorid: String public let dateline: String? public let message: String? public let anonymous: String? public let attachment: String? public let status: String? public let username: String? public let adminid: String? public let groupid: String? public let memberstatus: String? public let number: String? public let dbdateline: String public struct Attachment: Decodable { public let aid: String? public let tid: String? public let pid: String? public let uid: String? public let dateline: String? public let filename: String? public let filesize: String? public let attachment: String? public let remote: String? public let description: String? public let readperm: String? public let price: String? public let isimage: String? public let width: String? public let thumb: String? public let picid: String? public let ext: String? public let imgalt: String? public let attachicon: String? public let attachsize: String? public let attachimg: String? public let payed: String? public let url: URL? public let dbdateline: String? public let downloads: String? } public let attachments: [String: Attachment]? public let imageList: [String]? } public let postList: [Post] private enum CodingKeys: String, CodingKey { case memberUid = "member_uid" case memberUsername = "member_username" case memberAvatar = "member_avatar" case formhash case notice case thread case postList = "postlist" } } public let variables: Variables? public let message: RawMessage? public let error: String? private enum CodingKeys: String, CodingKey { case variables = "Variables" case message = "Message" case error } }
bsd-3-clause
bc99505dff6fff69a3edf3912cd33570
32.953704
57
0.539951
5.53092
false
false
false
false
marko628/Playground
BuildingURLs.playground/Contents.swift
1
2588
//: ## Building URLs //: In this playground, we will build URLs from **String** objects. Consider the following **String**: it represents a URL like the ones required in the *Flick Finder* app. Note: The API key used here is invalid; you will need to use your API key. let desiredURLString: String = "https://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=d50f31bf5d7d1ef66c3d3f128f25638a&text=baby+asian+elephant&format=json&nojsoncallback=1" //: How can we build this URL in a clean, reusable way that is not hard-coded? Let's start by breaking it into its component parts. For example, here is the baseURL. This baseURL is always the same no matter the Flickr method. let baseURL: String = "https://api.flickr.com/services/rest/" //: Next are those pesky key-value pairs. Remember, by using key-value pairs, we are able to pass information along to an API in a structured way. A good way of organizing key-value pairs is by using a **Dictionary**. Note: I have substituted the spaces in "baby asian elephant" with "+" signs, but substituting with "%20" would also work (see this [w3schools article](http://www.w3schools.com/tags/ref_urlencode.asp) for an explanation). Of course, you cannot expect your users to know these nuance when they enter their searches, so will need to handle this in your code. Also, you may need to add extra key-value pairs! let keyValuePairs = [ "method": "flickr.photos.search", "api_key": "d50f31bf5d7d1ef66c3d3f128f25638a", "text": "baby+asian+elephant", "format": "json", "nojsoncallback": "1" ] //: Now, let's build that **String**! Here I do it in a very ugly, manual way. But, for your code, I recommend that you write a function which iterates through the key-value pairs and creates the URL. var ourURLString = "\(baseURL)" ourURLString += "?method=" + keyValuePairs["method"]! ourURLString += "&api_key=" + keyValuePairs["api_key"]! ourURLString += "&text=" + keyValuePairs["text"]! ourURLString += "&format=" + keyValuePairs["format"]! ourURLString += "&nojsoncallback=" + keyValuePairs["nojsoncallback"]! //: Now, you will need to use the **String** to build a URL and issue your request. Hint: Refer to the *Sleeping in the Library* code as a guide, and adapt it for your needs! if ourURLString == desiredURLString { println("Success!") } else { println("😓 Not quite...") } baseURL var myURL = baseURL myURL += ("?method=" + keyValuePairs["method"]!) for (key, value) in keyValuePairs { if key != "method" { myURL += ("&" + key + "=") myURL += value } } myURL
mit
0b99ced3ada4fc0d685a0750b7bea77e
56.444444
622
0.71412
3.757267
false
false
false
false
avinassh/FoodPin
FoodPin/MapViewController.swift
1
2786
// // MapViewController.swift // FoodPin // // Created by avi on 15/02/15. // Copyright (c) 2015 avi. All rights reserved. // import UIKit import MapKit class MapViewController: UIViewController, MKMapViewDelegate { @IBOutlet weak var mapView: MKMapView! var restaurant: Restaurant! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. mapView.delegate = self // use GeoCoder to convert the address to co-ords let geoCoder = CLGeocoder() geoCoder.geocodeAddressString(restaurant.location, completionHandler: { (placemarks, error) in if error != nil { println(error) return } if placemarks != nil && placemarks.count > 0 { let placemark = placemarks[0] as CLPlacemark // add annotation let annotation = MKPointAnnotation() annotation.title = self.restaurant.name annotation.subtitle = self.restaurant.type annotation.coordinate = placemark.location.coordinate // display on map self.mapView.showAnnotations([annotation], animated: true) self.mapView.selectAnnotation(annotation, animated: true) } }) } func mapView(mapView: MKMapView!, viewForAnnotation annotation: MKAnnotation!) -> MKAnnotationView! { let identifier = "MyPin" if annotation.isKindOfClass(MKUserLocation) { return nil } // reuse annotations, like table view cells var annotationView = mapView.dequeueReusableAnnotationViewWithIdentifier(identifier) if annotationView == nil { annotationView = MKAnnotationView(annotation: annotation, reuseIdentifier: identifier) annotationView.canShowCallout = true } let leftIconView = UIImageView(frame: CGRectMake(0, 0, 53, 53)) leftIconView.image = UIImage(data: restaurant.image) annotationView.leftCalloutAccessoryView = leftIconView return annotationView } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
mit
3d6ebbece5c1a214f6527547996cc71a
32.166667
106
0.618449
5.780083
false
false
false
false
OSzhou/MyTestDemo
17_SwiftTestCode/TestCode/CustomCamera/WBCameraView.swift
1
13490
// // WBCameraView.swift // TestCode // // Created by Zhouheng on 2020/6/29. // Copyright © 2020 tataUFO. All rights reserved. // import UIKit enum WBCameraType { case photo case video } protocol WBCameraViewDelegate: class { /// 闪光灯 func flashLightAction(_ cameraView: WBCameraView, handler: ((Error?) -> ())) /// 补光 func torchLightAction(_ cameraView: WBCameraView, handler: ((Error?) -> ())) /// 转换摄像头 func swicthCameraAction(_ cameraView: WBCameraView, handler: ((Error?) -> ())) /// 自动聚焦曝光 func autoFocusAndExposureAction(_ cameraView: WBCameraView, handler: ((Error?) -> ())) /// 聚焦 func focusAction(_ cameraView: WBCameraView, point: CGPoint, handler: ((Error?) -> ())) /// 曝光 func exposAction(_ cameraView: WBCameraView, point: CGPoint, handler: ((Error?) -> ())) /// 缩放 func zoomAction(_ cameraView: WBCameraView, factor: CGFloat) /// 取消 func cancelAction(_ cameraView: WBCameraView) /// 拍照 func takePhotoAction(_ cameraView: WBCameraView) /// 停止录制视频 func stopRecordVideoAction(_ cameraView: WBCameraView) /// 开始录制视频 func startRecordVideoAction(_ cameraView: WBCameraView) /// 改变拍摄类型 photo:拍照 video:视频 func didChangeTypeAction(_ cameraView: WBCameraView, type: WBCameraType) } class WBCameraView: UIView { weak var delegate: WBCameraViewDelegate? fileprivate(set) var type: WBCameraType = .photo override init(frame: CGRect) { super.init(frame: frame) setupUI() } private func setupUI() { self.addSubview(previewView) self.addSubview(topView) self.addSubview(bottomView) previewView.addSubview(focusView) previewView.addSubview(exposureView) previewView.addSubview(slider) bottomView.addSubview(photoButton) photoButton.center = CGPoint(x: bottomView.center.x - 20, y: bottomView.frame.height / 2.0) bottomView.addSubview(cancelButton) cancelButton.center = CGPoint(x: 40, y: bottomView.frame.height / 2.0) bottomView.addSubview(typeButton) typeButton.center = CGPoint(x: bottomView.frame.width - 60, y: bottomView.frame.height / 2.0) topView.addSubview(switchButton) switchButton.center = CGPoint(x: switchButton.frame.width / 2.0 + 10, y: topView.frame.height / 2.0) topView.addSubview(lightButton) lightButton.center = CGPoint(x: lightButton.frame.width / 2.0 + switchButton.frame.maxX + 10, y: topView.frame.height / 2.0) topView.addSubview(flashButton) flashButton.center = CGPoint(x: flashButton.frame.width / 2.0 + lightButton.frame.maxX + 10, y: topView.frame.height / 2.0) topView.addSubview(focusAndExposureButton) focusAndExposureButton.center = CGPoint(x: focusAndExposureButton.frame.width / 2.0 + flashButton.frame.maxX + 10, y: topView.frame.height / 2.0) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } /// MARK: --- aciton /// 手电筒 开关 func changeTorch(_ on: Bool) { lightButton.isSelected = on } /// 闪光灯 开关 func changeFlash(_ on: Bool) { flashButton.isSelected = on } // 聚焦 @objc func previewTapGesture(_ gesture: UITapGestureRecognizer) { guard let del = self.delegate else { return } let point = gesture.location(in: previewView) runFocusAnimation(focusView, point: point) del.focusAction(self, point: previewView.captureDevicePointForPoint(point)) { (error) in if let err = error { print(" --- 聚焦时发生错误 --- \(String(describing: err))") } } } // 曝光 @objc func previewDoubleTapGesture(_ gesture: UITapGestureRecognizer) { guard let del = self.delegate else { return } let point = gesture.location(in: previewView) runFocusAnimation(exposureView, point: point) del.exposAction(self, point: previewView.captureDevicePointForPoint(point)) { (error) in if let err = error { print(" --- 曝光时发生错误 --- \(String(describing: err))") } } } // 缩放 @objc func previewPinchGesture(_ gesture: UIPinchGestureRecognizer) { guard let del = self.delegate else { return } if gesture.state == .began { UIView.animate(withDuration: 0.1) { self.slider.alpha = 1.0 } } else if gesture.state == .changed { if gesture.velocity > 0 { slider.value += Float(gesture.velocity / 100.0) } else { slider.value += Float(gesture.velocity / 20.0) } del.zoomAction(self, factor: pow(5, CGFloat(slider.value))) } else { UIView.animate(withDuration: 0.1) { self.slider.alpha = 0.0 } } } // 自动聚焦和曝光 @objc func focusAndExposureClick(_ sender: UIButton) { guard let del = self.delegate else { return } runResetAnimation() del.autoFocusAndExposureAction(self) { (error) in if let err = error { print(" --- 自动聚焦和曝光时发生错误 --- \(String(describing: err))") } } } // 拍照、视频 @objc func takePicture(_ sender: UIButton) { if type == .photo { self.delegate?.takePhotoAction(self) } else { if sender.isSelected { sender.isSelected = false photoButton.setTitle("开始", for: .normal) self.delegate?.stopRecordVideoAction(self) } else { sender.isSelected = true photoButton.setTitle("结束", for: .selected) self.delegate?.startRecordVideoAction(self) } } } // 取消 @objc func cancel(_ sender: UIButton) { self.delegate?.cancelAction(self) } // 转换拍照类型 @objc func changeType(_ sender: UIButton) { sender.isSelected = !sender.isSelected type = self.type == .photo ? .video : .photo if type == .photo { photoButton.setTitle("拍照", for: .normal) } else { photoButton.setTitle("开始", for: .normal) } self.delegate?.didChangeTypeAction(self, type: type) } // 转换前后摄像头 @objc func switchCameraClick(_ sender: UIButton) { self.delegate?.swicthCameraAction(self, handler: { (error) in if let err = error { print(" --- 转换摄像头时发生错误 --- \(String(describing: err))") } }) } // 手电筒 @objc func torchClick(_ sender: UIButton) { self.delegate?.torchLightAction(self, handler: { (error) in if let err = error, !err.localizedDescription.isEmpty { print(" --- 打开手电筒时发生错误 --- \(String(describing: error))") } else { self.flashButton.isSelected = false self.lightButton.isSelected = !self.lightButton.isSelected } }) } // 闪光灯 @objc func flashClick(_ sender: UIButton) { self.delegate?.flashLightAction(self, handler: { (error) in if let err = error, !err.localizedDescription.isEmpty { print(" --- 打开闪光灯时发生错误 --- \(String(describing: error))") } else { self.flashButton.isSelected = !self.flashButton.isSelected self.lightButton.isSelected = false } }) } // 聚焦、曝光动画 private func runFocusAnimation(_ view: UIView, point: CGPoint) { view.center = point view.isHidden = false UIView.animate(withDuration: 0.15, delay: 0.0, options: .curveEaseInOut, animations: { view.layer.transform = CATransform3DMakeScale(0.5, 0.5, 1.0) }) { (_) in DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) { view.isHidden = true view.transform = .identity } } } // 自动聚焦、曝光动画 private func runResetAnimation() { focusView.center = CGPoint(x: previewView.frame.width / 2.0, y: previewView.frame.height / 2.0) exposureView.center = CGPoint(x: previewView.frame.width / 2.0, y: previewView.frame.height / 2.0) exposureView.transform = CGAffineTransform(scaleX: 1.2, y: 1.2) focusView.isHidden = false exposureView.isHidden = false UIView.animate(withDuration: 0.15, delay: 0.0, options: .curveEaseInOut, animations: { self.focusView.layer.transform = CATransform3DMakeScale(0.5, 0.5, 1.0) self.exposureView.layer.transform = CATransform3DMakeScale(0.7, 0.7, 1.0) }) { (_) in DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) { self.focusView.isHidden = true self.exposureView.isHidden = true self.focusView.transform = .identity self.exposureView.transform = .identity } } } /// MARK: --- lazy loading lazy var topView: UIView = { let view = UIView(frame: CGRect(x: 0, y: 0, width: self.frame.width, height: 64)) view.backgroundColor = .black return view }() lazy var bottomView: UIView = { let view = UIView(frame: CGRect(x: 0, y: self.frame.height - 100, width: self.frame.width, height: 100)) view.backgroundColor = .black return view }() lazy var focusView: UIView = { let view = UIView(frame: CGRect(x: 0, y: 0, width: 150, height: 150)) view.backgroundColor = .clear view.layer.borderColor = UIColor.blue.cgColor view.layer.borderWidth = 5.0 view.isHidden = true return view }() lazy var exposureView: UIView = { let view = UIView(frame: CGRect(x: 0, y: 0, width: 150, height: 150)) view.backgroundColor = .clear view.layer.borderColor = UIColor.purple.cgColor view.layer.borderWidth = 5.0 view.isHidden = true return view }() lazy var slider: UISlider = { let slider = UISlider(frame: CGRect(x: screenWidth - 150, y: 130, width: 200, height: 10)) slider.minimumValue = 0.0 slider.maximumValue = 1.0 slider.minimumTrackTintColor = .white slider.maximumTrackTintColor = .white slider.backgroundColor = .white slider.alpha = 0.0 slider.transform = CGAffineTransform(rotationAngle: CGFloat.pi / 2.0) return slider }() fileprivate(set) lazy var previewView: WBVideoPreview = { let view = WBVideoPreview(frame: CGRect(x: 0, y: 64, width: self.frame.width, height: self.frame.height - 64 - 100)) // 单指 let tap = UITapGestureRecognizer(target: self, action: #selector(previewTapGesture(_:))) // 双指 let doubleTap = UITapGestureRecognizer(target: self, action: #selector(previewDoubleTapGesture(_:))) doubleTap.numberOfTouchesRequired = 2 tap.require(toFail: doubleTap) view.addGestureRecognizer(tap) view.addGestureRecognizer(doubleTap) // 捏合 let pinch = UIPinchGestureRecognizer(target: self, action: #selector(previewPinchGesture(_:))) view.addGestureRecognizer(pinch) return view }() private func buttonFactory(_ normolT: String, selectedT: String = "", action: Selector) -> UIButton { let button = UIButton(type: .custom) button.setTitle(normolT, for: .normal) button.setTitle(selectedT, for: .selected) button.sizeToFit() button.addTarget(self, action: action, for: .touchUpInside) return button } // 拍照 lazy var photoButton: UIButton = { let button = self.buttonFactory("拍照", action: #selector(takePicture(_:))) return button }() // 取消 lazy var cancelButton: UIButton = { let button = self.buttonFactory("取消", action: #selector(cancel(_:))) return button }() // 拍摄类型 lazy var typeButton: UIButton = { let button = self.buttonFactory("照片", selectedT: "视频", action: #selector(changeType(_:))) return button }() // 转换摄像头 lazy var switchButton: UIButton = { let button = self.buttonFactory("转换摄像头", action: #selector(switchCameraClick(_:))) return button }() // 补光 lazy var lightButton: UIButton = { let button = self.buttonFactory("补光", action: #selector(torchClick(_:))) return button }() // 闪光灯 lazy var flashButton: UIButton = { let button = self.buttonFactory("闪光灯", action: #selector(flashClick(_:))) return button }() // 重置对焦、曝光 lazy var focusAndExposureButton: UIButton = { let button = self.buttonFactory("自动聚焦/曝光", action: #selector(focusAndExposureClick(_:))) return button }() }
apache-2.0
e868b428f9a163a6fc6ba0ffe164156f
34.771978
153
0.590354
4.378278
false
false
false
false
PhillipEnglish/TIY-Assignments
TheGrailDiaryParsed/TheGrailDiary/TempleDetailViewController.swift
2
1242
// // TempleDetailViewController.swift // TheGrailDiary // // Created by Phillip English on 10/19/15. // Copyright © 2015 The Iron Yard. All rights reserved. // import UIKit class TempleDetailViewController: UIViewController { @IBOutlet weak var nameLabel: UILabel! @IBOutlet weak var deityLabel: UILabel! @IBOutlet weak var builderLabel: UILabel! @IBOutlet weak var locationLabel: UILabel! var temple = Temple?() override func viewDidLoad() { super.viewDidLoad() nameLabel.text = temple!.name deityLabel.text = temple!.deity builderLabel.text = temple!.builder locationLabel.text = temple!.location } 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. } */ }
cc0-1.0
762d6557cc329a9e03c35ea419f88799
25.404255
106
0.670427
4.964
false
false
false
false
prolificinteractive/Yoshi
Yoshi/Yoshi/Menus/Protocols/YoshiMenu/YoshiMenuCellDataSource.swift
1
1370
// // YoshiMenuCellDataSource.swift // Yoshi // // Created by Kanglei Fang on 24/02/2017. // Copyright © 2017 Prolific Interactive. All rights reserved. // /// A normal cell data source defining the layout for YoshiMenu's cell. /// By default it helps dequeue a system UITableViewCell with the given title, subtitle and the accessoryType. public struct YoshiMenuCellDataSource: YoshiReusableCellDataSource { private let title: String private let subtitle: String? private let accessoryType: UITableViewCell.AccessoryType /// Initalize the YoshiMenuCellDataSource instance /// /// - Parameters: /// - title: Main title for the cell /// - subtitle: Subtitle for the cell public init(title: String, subtitle: String?, accessoryType: UITableViewCell.AccessoryType = .none) { self.title = title self.subtitle = subtitle self.accessoryType = accessoryType } public func cellFor(tableView: UITableView) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: YoshiMenuCellDataSource.reuseIdentifier) ?? UITableViewCell(style: .subtitle, reuseIdentifier: YoshiMenuCellDataSource.reuseIdentifier) cell.textLabel?.text = title cell.detailTextLabel?.text = subtitle cell.accessoryType = accessoryType return cell } }
mit
2180dbea3d222ab2fca0830aaa35a095
32.390244
110
0.711468
5.108209
false
false
false
false
gintsmurans/SwiftCollection
Sources/Extensions/UserDefaults.swift
1
1686
// // UserDefaults.swift // Appong // // Created by Gints Murans on 02/02/2021. // import Foundation enum ObjectSavableError: String, LocalizedError { case unableToEncode = "Unable to encode object into data" case noValue = "No data object found for the given key" case unableToDecode = "Unable to decode object into given type" var errorDescription: String? { rawValue } } public extension UserDefaults { func setObject<Object: Encodable>(_ object: Object, forKey: String) throws { let encoder = JSONEncoder() #if os(macOS) if #available(macOS 10.12, *) { encoder.dateEncodingStrategy = .iso8601 } #else if #available(iOS 10.0, *) { encoder.dateEncodingStrategy = .iso8601 } #endif do { let data = try encoder.encode(object) set(data, forKey: forKey) } catch { throw ObjectSavableError.unableToEncode } } func getObject<Object: Decodable>(forKey: String, castTo type: Object.Type) throws -> Object { guard let data = data(forKey: forKey) else { throw ObjectSavableError.noValue } let decoder = JSONDecoder() #if os(macOS) if #available(macOS 10.12, *) { decoder.dateDecodingStrategy = .iso8601 } #else if #available(iOS 10.0, *) { decoder.dateDecodingStrategy = .iso8601 } #endif do { let object = try decoder.decode(type, from: data) return object } catch { throw ObjectSavableError.unableToDecode } } }
mit
afef72224b2cffc9f06fc78cd44f706b
24.938462
98
0.578292
4.472149
false
false
false
false
xibe/WordPress-iOS
WordPress/Classes/ViewRelated/Notifications/Controllers/NotificationSettingStreamsViewController.swift
3
8117
import Foundation /** * @class NotificationSettingStreamsViewController * @brief This class will simply render the collection of Streams available for a given * NotificationSettings collection. * A Stream represents a possible way in which notifications are communicated. * For instance: Push Notifications / WordPress.com Timeline / Email */ public class NotificationSettingStreamsViewController : UITableViewController { // MARK: - Initializers public convenience init(settings: NotificationSettings) { self.init(style: .Grouped) setupWithSettings(settings) } // MARK: - View Lifecycle public override func viewDidLoad() { super.viewDidLoad() setupNotifications() setupTableView() } public override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) // Manually deselect the selected row. This is required due to a bug in iOS7 / iOS8 tableView.deselectSelectedRowWithAnimation(true) WPAnalytics.track(.OpenedNotificationSettingStreams) } // MARK: - Setup Helpers private func setupNotifications() { // Reload whenever the app becomes active again since Push Settings may have changed in the meantime! let notificationCenter = NSNotificationCenter.defaultCenter() notificationCenter.addObserver(self, selector: "reloadTable", name: UIApplicationDidBecomeActiveNotification, object: nil) } private func setupTableView() { // Empty Back Button navigationItem.backBarButtonItem = UIBarButtonItem(title: String(), style: .Plain, target: nil, action: nil) // Hide the separators, whenever the table is empty tableView.tableFooterView = UIView() // Style! WPStyleGuide.configureColorsForView(view, andTableView: tableView) } // MARK: - Public Helpers public func setupWithSettings(streamSettings: NotificationSettings) { // Title switch streamSettings.channel { case let .Blog(blogId): title = streamSettings.blog?.blogName ?? streamSettings.channel.description() case .Other: title = NSLocalizedString("Other Sites", comment: "Other Notifications Streams Title") default: // Note: WordPress.com is not expected here! break } // Structures settings = streamSettings sortedStreams = streamSettings.streams.sorted { $0.kind.description() > $1.kind.description() } tableView.reloadData() } public func reloadTable() { tableView.reloadData() } // MARK: - UITableView Delegate Methods public override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return sortedStreams?.count ?? emptySectionCount } public override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return rowsCount } public override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { var cell = tableView.dequeueReusableCellWithIdentifier(reuseIdentifier) as? WPTableViewCell if cell == nil { cell = WPTableViewCell(style: .Value1, reuseIdentifier: reuseIdentifier) } configureCell(cell!, indexPath: indexPath) return cell! } public override func tableView(tableView: UITableView, viewForFooterInSection section: Int) -> UIView? { let headerView = WPTableViewSectionHeaderFooterView(reuseIdentifier: nil, style: .Footer) headerView.title = footerForStream(streamAtSection(section)) return headerView } public override func tableView(tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { let title = footerForStream(streamAtSection(section)) let width = view.frame.width return WPTableViewSectionHeaderFooterView.heightForFooter(title, width: width) } // MARK: - UITableView Delegate Methods public override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { // iOS <8: Display the 'Enable Push Notifications Alert', when needed // iOS +8: Go ahead and push the details // let stream = streamAtSection(indexPath.section) if isDisabledDeviceStream(stream) && !UIDevice.isOS8() { tableView.deselectSelectedRowWithAnimation(true) displayPushNotificationsAlert() return } let detailsViewController = NotificationSettingDetailsViewController(settings: settings!, stream: stream) navigationController?.pushViewController(detailsViewController, animated: true) } // MARK: - Helpers private func configureCell(cell: UITableViewCell, indexPath: NSIndexPath) { let stream = streamAtSection(indexPath.section) let disabled = isDisabledDeviceStream(stream) cell.textLabel?.text = stream.kind.description() ?? String() cell.detailTextLabel?.text = disabled ? NSLocalizedString("Off", comment: "Disabled") : String() cell.accessoryType = .DisclosureIndicator WPStyleGuide.configureTableViewCell(cell) } private func streamAtSection(section: Int) -> NotificationSettings.Stream { return sortedStreams![section] } // MARK: - Disabled Push Notifications Helpers private func isDisabledDeviceStream(stream: NotificationSettings.Stream) -> Bool { return stream.kind == .Device && !NotificationsManager.pushNotificationsEnabledInDeviceSettings() } private func displayPushNotificationsAlert() { let title = NSLocalizedString("Push Notifications have been turned off in iOS Settings", comment: "Displayed when Push Notifications are disabled (iOS 7)") let message = NSLocalizedString("To enable notifications:\n\n" + "1. Open **iOS Settings**\n" + "2. Tap **Notifications**\n" + "3. Select **WordPress**\n" + "4. Turn on **Allow Notifications**", comment: "Displayed when Push Notifications are disabled (iOS 7)") let button = NSLocalizedString("Dismiss", comment: "Dismiss the AlertView") let alert = AlertView(title: title, message: message, button: button, completion: nil) alert.show() } // MARK: - Footers private func footerForStream(stream: NotificationSettings.Stream) -> String { switch stream.kind { case .Device: return NSLocalizedString("Settings for push notifications that appear on your mobile device.", comment: "Descriptive text for the Push Notifications Settings") case .Email: return NSLocalizedString("Settings for notifications that are sent to the email tied to your account.", comment: "Descriptive text for the Email Notifications Settings") case .Timeline: return NSLocalizedString("Settings for notifications that appear in the Notifications tab.", comment: "Descriptive text for the Notifications Tab Settings") } } // MARK: - Private Constants private let reuseIdentifier = WPTableViewCell.classNameWithoutNamespaces() private let emptySectionCount = 0 private let rowsCount = 1 // MARK: - Private Properties private var settings : NotificationSettings? private var sortedStreams : [NotificationSettings.Stream]? }
gpl-2.0
b5234963ae596567f684c1780c8e0324
38.21256
125
0.637551
5.955246
false
false
false
false
jkereako/GitterViewer
GitterViewer/RoomRequest.swift
1
1761
// // RoomRequest.swift // GitterViewer // // Created by Jeffrey Kereakoglow on 1/28/16. // Copyright © 2016 Alexis Digital. All rights reserved. // //import Foundation import CoreData import Argo import Result import Swish // TODO: Put somewhere else let jsonDateFormatter: NSDateFormatter = { let dateFormatter = NSDateFormatter() dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'" return dateFormatter }() let toNSDate: String -> Decoded<NSDate> = { .fromOptional(jsonDateFormatter.dateFromString($0)) } struct RoomRequest { let managedObjectContext: NSManagedObjectContext } extension RoomRequest: GitterRequest { // We expect an array of rooms, so declare the response object as such. typealias ResponseObject = [DecodedRoom] var authToken: String { return "" } func baseRequest(url url: NSURL, method: RequestMethod) -> NSURLRequest { let request = NSMutableURLRequest(URL: url) request.setValue("application/json", forHTTPHeaderField: "Accept") request.setValue("Bearer \(authToken)", forHTTPHeaderField: "Authorization") request.HTTPMethod = method.rawValue return request } func makeRequest(completion: (success: Bool) -> Void) { APIClient().performRequest(self) { (response: Result<ResponseObject, NSError>) in switch response { case let .Success(decodedRooms): for decodedRoom in decodedRooms { Room(managedObjectContext: self.managedObjectContext, decodedRoom: decodedRoom) } completion(success: true) case .Failure(_): print("Unable to parse.") completion(success: false) } } } func build() -> NSURLRequest { return baseRequest(url: apiEndpointURL(route: Gitter.Rooms), method: .GET) } }
mit
b22eee401f33a62c56776e3cb118d0e7
25.268657
89
0.705114
4.422111
false
false
false
false
dabing1022/AlgorithmRocks
DataStructureAlgorithm/Playground/DataStructureAlgorithm.playground/Pages/MergeSort.xcplaygroundpage/Contents.swift
1
2433
//: [Previous](@previous) //: MergeSort1 var randomNumbers = [42, 12, 88, 62, 63, 56, 1, 77, 88, 97, 97, 20, 45, 91, 62, 2, 15, 31, 59, 5] var randomNumbers2 = [42, 12, 88, 62, 63, 56, 1, 77, 88, 97, 97, 20, 45, 91, 62, 2, 15, 31, 59, 5] class MergeSort { var aux: [Int] = [] func sort(inout a: [Int]) { aux = [Int](count: a.count, repeatedValue: 0) sort(&a, low: 0, high: a.count - 1) } func sort(inout a: [Int], low: Int, high: Int) { if (low >= high) { return } let mid = low + (high - low) >> 1 sort(&a, low: low, high: mid) print(a) sort(&a, low: mid + 1, high: high) merge(&a, low: low, mid: mid, high: high) print(a) } func merge(inout a: [Int], low: Int, mid: Int, high: Int) { var i = low var j = mid + 1 for k in low...high { aux[k] = a[k] } for k in low...high { if (i > mid) { a[k] = aux[j]; j += 1 } else if (j > high) { a[k] = aux[i]; i += 1 } else if (aux[j] < aux[i]) { a[k] = aux[j]; j += 1 } else { a[k] = aux[i]; i += 1 } } } } MergeSort().sort(&randomNumbers) randomNumbers //: MergeSort2 class MergeSort2 { func sort(inout arr: [Int], low: Int, high: Int) { if low >= high { return } let middle = (low + high) / 2 sort(&arr, low: low, high: middle) sort(&arr, low: middle + 1, high: high) var helper: [Int] = [Int](count: arr.count, repeatedValue: 0) for i in low...high { helper[i] = arr[i] } var left = low var right = middle + 1 var cur = low while left <= middle && right <= high { if helper[left] < helper[right] { arr[cur] = helper[left] left += 1 } else { arr[cur] = helper[right] right += 1 } cur += 1 } let remaining = middle - left if (remaining >= 0) { for i in 0...remaining { arr[cur + i] = helper[left + i] } } } } MergeSort2().sort(&randomNumbers2, low: 0, high: randomNumbers2.count - 1) randomNumbers2 //: [Next](@next)
mit
d2fbc4488af999553afa30e66fb9e9cd
26.033333
98
0.42499
3.379167
false
false
false
false
tkremenek/swift
test/SILOptimizer/assemblyvision_remark/cast_remarks_objc.swift
4
9771
// RUN: %target-swiftc_driver -O -Rpass-missed=sil-assembly-vision-remark-gen -Xllvm -sil-disable-pass=FunctionSignatureOpts -emit-sil %s -o /dev/null -Xfrontend -verify // REQUIRES: objc_interop // REQUIRES: optimized_stdlib // REQUIRES: swift_stdlib_no_asserts import Foundation ////////////////// // Generic Code // ////////////////// public func forcedCast<NS, T>(_ ns: NS) -> T { // Make sure the colon info is right so that the arrow is under the a. return ns as! T // expected-remark @:13 {{unconditional runtime cast of value with type 'NS' to 'T'}} // expected-note @-3:33 {{of 'ns'}} } public func forcedCast2<NS, T>(_ ns: NS) -> T { // Make sure the colon info is right so that the arrow is under the a. // // Today, we seem to completely eliminate 'x' here in the debug info. TODO: // Maybe we can recover this info somehow. let x = ns return x as! T // expected-remark @:12 {{unconditional runtime cast of value with type 'NS' to 'T'}} // expected-note @-7:34 {{of 'ns'}} } public func forcedCast3<NS, T>(_ ns: NS) -> T { // Make sure the colon info is right so that the arrow is under the a. // // Today, we seem to completely eliminate 'x' here in the debug info. TODO: // Maybe we can recover this info somehow. var x = ns // expected-warning {{variable 'x' was never mutated}} return x as! T // expected-remark @:12 {{unconditional runtime cast of value with type 'NS' to 'T'}} // expected-note @-7:34 {{of 'ns'}} } public func forcedCast4<NS, T>(_ ns: NS, _ ns2: NS) -> T { // Make sure the colon info is right so that the arrow is under the a. // // Today, we lose that x was assigned ns2. This is flow sensitive information // that we might be able to recover. We still emit that a runtime cast // occurred here, just don't say what the underlying value was. var x = ns x = ns2 return x as! T // expected-remark @:12 {{unconditional runtime cast of value with type 'NS' to 'T'}} } public func condCast<NS, T>(_ ns: NS) -> T? { // Make sure the colon info is right so that the arrow is under the a. return ns as? T // expected-remark @:13 {{conditional runtime cast of value with type 'NS' to 'T'}} // expected-note @-3:31 {{of 'ns'}} } public func condCast2<NS, T>(_ ns: NS) -> T? { // Make sure the colon info is right so that the arrow is under the a. // // Today, we seem to completely eliminate 'x' here in the debug info. TODO: // Maybe we can recover this info somehow. let x = ns return x as? T // expected-remark @:12 {{conditional runtime cast of value with type 'NS' to 'T'}} // expected-note @-7:32 {{of 'ns'}} } public func condCast3<NS, T>(_ ns: NS) -> T? { // Make sure the colon info is right so that the arrow is under the a. // // Today, we seem to completely eliminate 'x' here in the debug info. TODO: // Maybe we can recover this info somehow. var x = ns // expected-warning {{variable 'x' was never mutated}} return x as? T // expected-remark @:12 {{conditional runtime cast of value with type 'NS' to 'T'}} // expected-note @-7:32 {{of 'ns'}} } public func condCast4<NS, T>(_ ns: NS, _ ns2: NS) -> T? { // Make sure the colon info is right so that the arrow is under the a. // // Today, we lose that x was assigned ns2. This is flow sensitive information // that we might be able to recover. We still emit that a runtime cast // occurred here, just don't say what the underlying value was. var x = ns x = ns2 return x as? T // expected-remark @:12 {{conditional runtime cast of value with type 'NS' to 'T'}} } public func condCast5<NS, T>(_ ns: NS) -> T? { // Make sure the colon info is right so that the arrow is under the a. // // Today, we lose that x was assigned. if let x = ns as? T { // expected-remark @:17 {{conditional runtime cast of value with type 'NS' to 'T'}} return x // expected-note @-5:32 {{of 'ns'}} } return nil } public func condCast6<NS, T>(_ ns: NS) -> T? { // Make sure the colon info is right so that the arrow is under the a. // // Today, we lose that x was assigned. guard let x = ns as? T else { // expected-remark @:20 {{conditional runtime cast of value with type 'NS' to 'T'}} return nil // expected-note @-5:32 {{of 'ns'}} } return x } ////////////////////////////////// // Any Object Constrained Casts // ////////////////////////////////// public func forcedCast<NS: AnyObject, T: AnyObject>(_ ns: NS) -> T { // Make sure the colon info is right so that the arrow is under the a. // // TODO: We should also note the retain as being on 'ns'. return ns as! T // expected-remark @:13 {{unconditional runtime cast of value with type 'NS' to 'T'}} // expected-note @-5:55 {{of 'ns'}} // expected-remark @-2 {{retain of type 'NS'}} } public func forcedCast2<NS: AnyObject, T: AnyObject>(_ ns: NS) -> T { // Make sure the colon info is right so that the arrow is under the a. // // Today, we seem to completely eliminate 'x' here in the debug info. TODO: // Maybe we can recover this info somehow. We should also note the retain as being on 'ns' let x = ns return x as! T // expected-remark @:12 {{unconditional runtime cast of value with type 'NS' to 'T'}} // expected-note @-7:56 {{of 'ns'}} // expected-remark @-2 {{retain of type 'NS'}} } public func forcedCast3<NS: AnyObject, T: AnyObject>(_ ns: NS) -> T { // Make sure the colon info is right so that the arrow is under the a. // // Today, we seem to completely eliminate 'x' here in the debug info. TODO: // Maybe we can recover this info somehow. var x = ns // expected-warning {{variable 'x' was never mutated}} return x as! T // expected-remark @:12 {{unconditional runtime cast of value with type 'NS' to 'T'}} // expected-note @-7:56 {{of 'ns'}} // expected-remark @-2 {{retain of type 'NS'}} } // Interestingly today, with AnyObject codegen, we do not lose the assignment to // x and say the cast is on ns2! public func forcedCast4<NS: AnyObject, T: AnyObject>(_ ns: NS, _ ns2: NS) -> T { // Make sure the colon info is right so that the arrow is under the a. var x = ns x = ns2 return x as! T // expected-remark @:12 {{unconditional runtime cast of value with type 'NS' to 'T'}} // expected-note @-5:66 {{of 'ns2'}} // expected-remark @-2 {{retain of type 'NS'}} } public func condCast<NS: AnyObject, T: AnyObject>(_ ns: NS) -> T? { // Make sure the colon info is right so that the arrow is under the a. return ns as? T // expected-remark @:13 {{conditional runtime cast of value with type 'NS' to 'T'}} // expected-note @-3:53 {{of 'ns'}} // expected-remark @-2 {{retain of type 'NS'}} } public func condCast2<NS: AnyObject, T: AnyObject>(_ ns: NS) -> T? { // Make sure the colon info is right so that the arrow is under the a. // // Today, we seem to completely eliminate 'x' here in the debug info. TODO: // Maybe we can recover this info somehow. let x = ns return x as? T // expected-remark @:12 {{conditional runtime cast of value with type 'NS' to 'T'}} // expected-note @-7:54 {{of 'ns'}} // expected-remark @-2 {{retain of type 'NS'}} } public func condCast3<NS: AnyObject, T: AnyObject>(_ ns: NS) -> T? { // Make sure the colon info is right so that the arrow is under the a. // // Today, we seem to completely eliminate 'x' here in the debug info. TODO: // Maybe we can recover this info somehow. var x = ns // expected-warning {{variable 'x' was never mutated}} return x as? T // expected-remark @:12 {{conditional runtime cast of value with type 'NS' to 'T'}} // expected-note @-7:54 {{of 'ns'}} // expected-remark @-2 {{retain of type 'NS'}} } public func condCast4<NS: AnyObject, T: AnyObject>(_ ns: NS, _ ns2: NS) -> T? { // Make sure the colon info is right so that the arrow is under the a. var x = ns x = ns2 return x as? T // expected-remark @:12 {{conditional runtime cast of value with type 'NS' to 'T'}} // expected-note @-5:64 {{of 'ns2'}} // expected-remark @-2 {{retain of type 'NS'}} } public func condCast5<NS: AnyObject, T: AnyObject>(_ ns: NS) -> T? { // Make sure the colon info is right so that the arrow is under the a. // // Today, we lose that x was assigned. if let x = ns as? T { // expected-remark @:17 {{conditional runtime cast of value with type 'NS' to 'T'}} return x // expected-note @-5:54 {{of 'ns'}} } // expected-remark @-2 {{retain of type 'NS'}} return nil } public func condCast6<NS: AnyObject, T: AnyObject>(_ ns: NS) -> T? { // Make sure the colon info is right so that the arrow is under the a. // // Today, we lose that x was assigned. guard let x = ns as? T else { // expected-remark @:20 {{conditional runtime cast of value with type 'NS' to 'T'}} return nil // expected-note @-5:54 {{of 'ns'}} } // expected-remark @-2 {{retain of type 'NS'}} return x } ////////////////// // String Casts // ////////////////// // We need to be able to recognize the conformances. We can't do this yet! But // we will be able to! @inline(never) public func testForcedCastNStoSwiftString(_ nsString: NSString) -> String { let o: String = forcedCast(nsString) return o } @inline(never) public func testConditionalCastNStoSwiftString(_ nsString: NSString) -> String? { let o: String? = condCast(nsString) return o }
apache-2.0
8bea65f01f1260906ffda9516f7f5c3a
41.855263
169
0.611094
3.671928
false
false
false
false
xin-wo/kankan
kankan/kankan/Class/Home/Controller/HomeRecommendViewController.swift
1
11849
// // HomeRecommendViewController.swift // kankan // // Created by Xin on 16/10/20. // Copyright © 2016年 王鑫. All rights reserved. // import UIKit import Kingfisher import Alamofire import MJRefresh class HomeRecommendViewController: UIViewController { // collectionView 懒加载 lazy var collectionView: UICollectionView = {[unowned self] in // 1.创建 layout let flowLayout = UICollectionViewFlowLayout() // flowLayout.itemSize = self.bounds.size flowLayout.minimumInteritemSpacing = 0 flowLayout.minimumLineSpacing = 0 flowLayout.scrollDirection = .Vertical // 2.创建 collectionView let collectionView = UICollectionView(frame: CGRect(x: 0, y: 0, width: screenWidth, height: screenHeight-140), collectionViewLayout: flowLayout) collectionView.showsHorizontalScrollIndicator = false collectionView.dataSource = self collectionView.delegate = self // collectionView.autoresizingMask = [.FlexibleWidth, .FlexibleHeight] collectionView.registerNib(UINib(nibName: "FooterReusableView", bundle: nil), forSupplementaryViewOfKind: UICollectionElementKindSectionFooter, withReuseIdentifier: "footer") collectionView.registerClass(HeaderReusableView.self, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "header") collectionView.registerNib(UINib(nibName: "NormalCell", bundle: nil), forCellWithReuseIdentifier: "normal") collectionView.registerNib(UINib(nibName: "OtherReusableView", bundle: nil), forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "other") // collectionView.registerClass(FirstCollectionViewCell.self, forCellWithReuseIdentifier: "first") collectionView.backgroundColor = UIColor.whiteColor() return collectionView }() //索引栏数据 var dataArray1: [HomeBkCgModel] = [] //影片内容数据 var dataArray2: [HomeBsModel] = [] //轮滑页数据 var dataArray3: [HomeScrModel] = [] //正确数据顺序 var dataArray: [HomeBsModel] = [] //轮滑页图片地址 var scrNameArray: [String] = [] //轮滑页图片标题 var subTitleArray: [String] = [] override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) self.navigationController?.navigationBarHidden = false } override func viewDidLoad() { super.viewDidLoad() configUI() loadData() } func configUI() { self.automaticallyAdjustsScrollViewInsets = false collectionView.showsVerticalScrollIndicator = false self.view.addSubview(collectionView) } func loadData() { Alamofire.request(.GET, homeRecUrl).responseJSON { [unowned self] (response) in if response.result.error == nil { let keyArray = ["block_config", "blocks", "top_block"] for i in 0...2 { let array = (response.result.value as! NSDictionary)[keyArray[i]] as! [AnyObject] var j = -1 let indexArray = [5, 8, 13, 14] xx: for dic in array { j += 1 if i == 0 { let model = HomeBkCgModel() model.setValuesForKeysWithDictionary(dic as! [String : AnyObject]) self.dataArray1.append(model) } else if i == 1 { for i in indexArray { if j == i { continue xx } } let model = HomeBsModel() model.setValuesForKeysWithDictionary(dic as! [String : AnyObject]) self.dataArray2.append(model) } else if i == 2 { let model = HomeScrModel() model.setValuesForKeysWithDictionary(dic as! [String : AnyObject]) self.dataArray3.append(model) self.scrNameArray.append(model.poster) self.subTitleArray.append(model.subtitle) } } } self.collectionView.reloadData() } self.getDataArray() } } //重新排列数据 func getDataArray() { for j in 0..<dataArray1.count { for i in 0..<dataArray1.count { let BsModel = dataArray2[i] if dataArray1[j].block_id == BsModel.block_id { dataArray.append(dataArray2[i]) } } } } } //MARK: UICollectionView代理 extension HomeRecommendViewController: UICollectionViewDataSource, UICollectionViewDelegateFlowLayout { func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int { return dataArray2.count + 1 } func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { if section == 0 { return 0 } else { if dataArray.count == 0 { return 0 } else { return dataArray[section-1].data.count } } } func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCellWithReuseIdentifier("normal", forIndexPath: indexPath) as! NormalCell if indexPath.section == 0 { return cell } else { if dataArray.count != 0 { let model = dataArray[indexPath.section - 1].data[indexPath.row] cell.posterImage.kf_setImageWithURL(NSURL(string: model.poster), placeholderImage: UIImage(named: "default_poster_250_350"), optionsInfo: nil, progressBlock: nil, completionHandler: nil) cell.titleLabel.text = model.title cell.detailLabel.text = model.subtitle cell.descLabel.text = model.kankan_type cell.rankLabel.text = model.rating if model.is_vip != nil { if model.is_vip == "true" { cell.VIPLabel.text = "VIP" cell.VIPLabel.textColor = UIColor.whiteColor() cell.VIPLabel.backgroundColor = UIColor.redColor() } else { cell.VIPLabel.text = "" cell.VIPLabel.backgroundColor = UIColor.clearColor() } } else { cell.VIPLabel.text = "" cell.VIPLabel.backgroundColor = UIColor.clearColor() } } return cell } } func collectionView(collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView { if kind == UICollectionElementKindSectionHeader { if indexPath.section == 0 { let header = collectionView.dequeueReusableSupplementaryViewOfKind(kind, withReuseIdentifier: "header", forIndexPath: indexPath) as! HeaderReusableView header.setImages(scrNameArray, textString: subTitleArray) header.jumpClosure = { currentPage in if self.dataArray3[currentPage].ad_url != "" { print("您当前点击的是第\(currentPage)页,是广告,广告地址为\(self.dataArray3[currentPage].ad_url)") } else { print("您当前点击的是第\(currentPage)页,是视频,视频Id为:\(self.dataArray3[currentPage].movieid)(视频地址已加密)") } } return header } let other = collectionView.dequeueReusableSupplementaryViewOfKind(kind, withReuseIdentifier: "other", forIndexPath: indexPath) as! OtherReusableView if indexPath.section == 0 { return other } let model = dataArray1[indexPath.section-1] other.categoryLabel.text = model.block_title var allWords: String = "" var j = model.hot_words!.count - 1 for i in 0..<model.hot_words!.count { if i == 0 { allWords = allWords + model.hot_words![j].words } else { allWords = allWords + " / " + model.hot_words![j].words } j -= 1 } other.moreLabel.text = allWords return other } else { let footer = collectionView.dequeueReusableSupplementaryViewOfKind(kind, withReuseIdentifier: "footer", forIndexPath: indexPath) return footer } } func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize { if dataArray[indexPath.section-1].data.count % 2 == 1 { if indexPath.row == 0 { return CGSize(width: screenWidth-10, height: (screenHeight-100)/3) } } if indexPath.section == 12 { return CGSize(width: screenWidth-10, height: (screenHeight-150)/3) } return CGSize(width: (screenWidth-10)/2, height: (screenHeight-180)/3) } func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize { if section == 0 { return CGSize(width: screenWidth, height: (screenHeight-100)/3) } return CGSize(width: screenWidth, height: 25) } /*返回第section组collectionView尾部视图的尺寸 */ func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize { if section == 0 { return CGSize() } return CGSize(width: screenWidth, height: 10) } func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAtIndex section: Int) -> UIEdgeInsets { return UIEdgeInsets(top: 0, left: 5, bottom: 0, right: 5) } //跳转页面 func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) { let VC = DetailViewController() VC.URLString = "http://wvideo.spriteapp.cn/video/2016/0328/56f8ec01d9bfe_wpd.mp4" VC.title = "蝙蝠侠大战超人" VC.hidesBottomBarWhenPushed = true navigationController?.pushViewController(VC, animated: true) } }
mit
ce49462a48e3062b17b5a95681f980fc
34.625767
202
0.551834
5.801199
false
false
false
false
jnwagstaff/PutItOnMyTabBar
Example/PutItOnMyTabBar/UIColor+Extras.swift
1
1757
import Foundation import UIKit extension UIColor{ class func fromHex(rgbValue:UInt32, alpha:Double=1.0) -> UIColor{ let red = CGFloat((rgbValue & 0xFF0000) >> 16)/256.0 let green = CGFloat((rgbValue & 0xFF00) >> 8)/256.0 let blue = CGFloat(rgbValue & 0xFF)/256.0 return UIColor(red:red, green:green, blue:blue, alpha:CGFloat(alpha)) } class func rangoonGreen() -> UIColor { return fromHex(rgbValue: 0x1B1B1B) } class func powerPlayBlack() -> UIColor{ return fromHex(rgbValue: 0x222222) } class func stringToHex(s: NSString)->Int{ let numbers = [ "a": 10, "A": 10, "b": 11, "B": 11, "c": 12, "C": 12, "d": 13, "D": 13, "e": 14, "E": 14, "f": 15, "F": 15, "0": 0 ] var number: Int = Int() if(s.intValue > 0){ number = s.integerValue } else{ number = numbers[s as String]! } return number } func rgb() -> (red:CGFloat, green:CGFloat, blue:CGFloat, alpha:CGFloat)? { var fRed : CGFloat = 0 var fGreen : CGFloat = 0 var fBlue : CGFloat = 0 var fAlpha: CGFloat = 0 if self.getRed(&fRed, green: &fGreen, blue: &fBlue, alpha: &fAlpha) { let iRed = CGFloat(fRed * 255.0) let iGreen = CGFloat(fGreen * 255.0) let iBlue = CGFloat(fBlue * 255.0) let iAlpha = CGFloat(fAlpha * 255.0) return (red:iRed, green:iGreen, blue:iBlue, alpha:iAlpha) } else { // Could not extract RGBA components: return nil } } }
mit
e65f4ce04308561addc7013c895c3552
26.888889
78
0.497439
3.706751
false
false
false
false
kyouko-taiga/anzen
Sources/AnzenIR/AIRType.swift
1
2198
import AST import Utils public class AIRType: Equatable { fileprivate init() {} /// The metatype of the type. public lazy var metatype: AIRMetatype = { [unowned self] in return AIRMetatype(of: self) }() public static func == (lhs: AIRType, rhs: AIRType) -> Bool { return lhs === rhs } public static let anything = AIRBuiltinType(name: "Anything") public static let nothing = AIRBuiltinType(name: "Nothing") public static let bool = AIRBuiltinType(name: "Bool") public static let int = AIRBuiltinType(name: "Int") public static let float = AIRBuiltinType(name: "Float") public static let string = AIRBuiltinType(name: "String") public static func builtin(named name: String) -> AIRType? { return AIRType.builtinTypes[name] } /// Built-in AIR types. private static var builtinTypes: [String: AIRType] = [ "Anything": .anything, "Nothing" : .nothing, "Bool" : .bool, "Int" : .int, "Float" : .float, "String" : .string, ] } public final class AIRMetatype: AIRType, CustomStringConvertible { fileprivate init(of type: AIRType) { self.type = type } public let type: AIRType public var description: String { return "\(type).metatype" } } public final class AIRBuiltinType: AIRType, CustomStringConvertible { fileprivate init(name: String) { self.name = name } public let name: String public var description: String { return self.name } } public final class AIRFunctionType: AIRType, CustomStringConvertible { internal init(domain: [AIRType], codomain: AIRType) { self.domain = domain self.codomain = codomain } public let domain: [AIRType] public let codomain: AIRType public var description: String { return "(" + domain.map({ "\($0)" }).joined(separator: ",") + ") -> \(codomain)" } } public final class AIRStructType: AIRType, CustomStringConvertible { internal init(name: String, members: OrderedMap<String, AIRType>) { self.name = name self.members = members } public let name: String public var members: OrderedMap<String, AIRType> public var description: String { return self.name } }
apache-2.0
52a3be1d0771b340900c4163d53ca646
21.428571
84
0.66697
4.047882
false
false
false
false
realm/SwiftLint
Tests/SwiftLintFrameworkTests/ExplicitTypeInterfaceConfigurationTests.swift
1
1998
@testable import SwiftLintFramework import XCTest class ExplicitTypeInterfaceConfigurationTests: XCTestCase { func testDefaultConfiguration() { let config = ExplicitTypeInterfaceConfiguration() XCTAssertEqual(config.severityConfiguration.severity, .warning) XCTAssertEqual(config.allowedKinds, Set([.varInstance, .varClass, .varStatic, .varLocal])) } func testApplyingCustomConfiguration() throws { var config = ExplicitTypeInterfaceConfiguration() try config.apply(configuration: ["severity": "error", "excluded": ["local"], "allow_redundancy": true]) XCTAssertEqual(config.severityConfiguration.severity, .error) XCTAssertEqual(config.allowedKinds, Set([.varInstance, .varClass, .varStatic])) XCTAssertTrue(config.allowRedundancy) } func testInvalidKeyInCustomConfiguration() { var config = ExplicitTypeInterfaceConfiguration() checkError(ConfigurationError.unknownConfiguration) { try config.apply(configuration: ["invalidKey": "error"]) } } func testInvalidTypeOfCustomConfiguration() { var config = ExplicitTypeInterfaceConfiguration() checkError(ConfigurationError.unknownConfiguration) { try config.apply(configuration: "invalidKey") } } func testInvalidTypeOfValueInCustomConfiguration() { var config = ExplicitTypeInterfaceConfiguration() checkError(ConfigurationError.unknownConfiguration) { try config.apply(configuration: ["severity": 1]) } } func testConsoleDescription() throws { var config = ExplicitTypeInterfaceConfiguration() try config.apply(configuration: ["excluded": ["class", "instance"]]) XCTAssertEqual( config.consoleDescription, "warning, excluded: [\"class\", \"instance\"], allow_redundancy: false" ) } }
mit
5d69687b69d56d44eafe2c9ed7253fb4
38.96
98
0.663664
5.859238
false
true
false
false
sonsongithub/testFoldr
testFoldrTests/testFoldrTests.swift
1
4401
// // testFoldrTests.swift // testFoldrTests // // Created by sonson on 2015/08/18. // Copyright © 2015年 sonson. All rights reserved. // import XCTest extension CollectionType { func foldr_recursive<T>(accm:T, f: (Self.Generator.Element, T) -> T) -> T { var g = self.generate() func next() -> T { return g.next().map {x in f(x, next())} ?? accm } return next() } func foldr_loop<T>(accm:T, @noescape f: (Self.Generator.Element, T) -> T) -> T { var result = accm for temp in self.reverse() { result = f(temp, result) } return result } func foldr_forEach<T>(accm:T, @noescape f: (Self.Generator.Element, T) -> T) -> T { var result = accm self.reverse().forEach { (t) -> () in result = f(t, result) } return result } func foldr_reduce<T>(accm:T, @noescape f: (T, Self.Generator.Element) -> T) -> T { return self.reverse().reduce(accm) { f($0, $1) } } func foldl_reduce<T>(accm:T, @noescape f: (T, Self.Generator.Element) -> T) -> T { return self.reduce(accm) { f($0, $1) } } } extension CollectionType where Index : RandomAccessIndexType { func foldr_loop2<T>(accm:T, @noescape f: (Self.Generator.Element, T) -> T) -> T { var result = accm for temp in self.reverse() { result = f(temp, result) } return result } func foldr_reduce2<T>(accm:T, @noescape f: (T, Self.Generator.Element) -> T) -> T { return self.reverse().reduce(accm) { f($0, $1) } } func foldr_forEach2<T>(accm:T, @noescape f: (Self.Generator.Element, T) -> T) -> T { var result = accm self.reverse().forEach { (t) -> () in result = f(t, result) } return result } } class foldrTests: XCTestCase { var data:[Int] = [] let count = 1000 let loop = 1000 override func setUp() { super.setUp() if data.count == 0 { data.removeAll() for var i = 0; i < count; i++ { data.append(Int(arc4random() % 10 + 1)) } } } func test_ref_foldl() { self.measureBlock { for var i = 0; i < self.loop; i++ { self.data.foldl_reduce(1) { (x, accm) -> Int in return accm + x / 2 } } } } func test_foldr_recursive() { if count <= 1000 { self.measureBlock { for var i = 0; i < self.loop; i++ { self.data.foldr_recursive(1) { (x, accm) -> Int in return accm + x / 2 } } } } } func test_foldr_loop() { self.measureBlock { for var i = 0; i < self.loop; i++ { self.data.foldr_loop(1) { (x, accm) -> Int in return accm + x / 2 } } } } func test_foldr_loop2() { self.measureBlock { for var i = 0; i < self.loop; i++ { self.data.foldr_loop2(1) { (x, accm) -> Int in return accm + x / 2 } } } } func test_foldr_forEach() { self.measureBlock { for var i = 0; i < self.loop; i++ { self.data.foldr_forEach(1, f: { (x, accm) -> Int in return accm + x / 2 }) } } } func test_foldr_forEach2() { self.measureBlock { for var i = 0; i < self.loop; i++ { self.data.foldr_forEach2(1, f: { (x, accm) -> Int in return accm + x / 2 }) } } } func test_foldr_reduce() { self.measureBlock { for var i = 0; i < self.loop; i++ { self.data.foldr_reduce(1) { (x, accm) -> Int in return accm + x / 2 } } } } func test_foldr_reduce2() { self.measureBlock { for var i = 0; i < self.loop; i++ { self.data.foldr_reduce2(1) { (x, accm) -> Int in return accm + x / 2 } } } } }
mit
b98c3361c37d77818ced22a8d46df586
26.154321
88
0.437017
3.746167
false
true
false
false
Webtrekk/webtrekk-ios-sdk
Source/Internal/Requests/RequestManager.swift
1
12838
import Foundation #if !os(watchOS) import UIKit #endif // TODO: keep if later import is necessary (once no <Swift 5 support is necessary), // for now we have the code in the Reachability folder //#if !os(watchOS) // import Reachability //#endif internal final class RequestManager: NSObject, URLSessionDelegate { internal typealias Delegate = _RequestManagerDelegate private var currentFailureCount = 0 private var currentRequest: URL? private var pendingTask: URLSessionDataTask? private var sendNextRequestTimer: Timer? private var urlSession: URLSession? private let manualStart: Bool #if !os(watchOS) private let reachability: Reachability? private var sendingInterruptedBecauseUnreachable = false var backgroundTaskIdentifier = UIBackgroundTaskIdentifier.invalid #endif internal fileprivate(set) var queue = RequestQueue() internal fileprivate(set) var started = false private(set) var finishing = false var isPending: Bool {return pendingTask != nil} internal weak var delegate: Delegate? internal init(manualStart: Bool) { checkIsOnMainThread() self.manualStart = manualStart #if !os(watchOS) self.reachability = Reachability.init() #endif super.init() #if !os(watchOS) self.reachability?.whenReachable = { [weak self] reachability in logDebug("Internet is reachable again!") reachability.stopNotifier() self?.sendNextRequest() } #endif } #if !os(watchOS) deinit { reachability?.stopNotifier() } #endif fileprivate func cancelCurrentRequest() { checkIsOnMainThread() guard let pendingTask = self.pendingTask else { return } pendingTask.cancel() self.currentRequest = nil self.currentFailureCount = 0 self.pendingTask = nil } internal func clearPendingRequests() { checkIsOnMainThread() logInfo("Clearing queue of \(self.queue.size) requests.") self.queue.deleteAll() } internal static func createUrlSession(delegate: URLSessionDelegate? = nil) -> URLSession { let configuration = URLSessionConfiguration.ephemeral configuration.httpCookieAcceptPolicy = .never configuration.httpShouldSetCookies = false configuration.urlCache = nil configuration.urlCredentialStorage = nil configuration.requestCachePolicy = .reloadIgnoringLocalAndRemoteCacheData let session = URLSession(configuration: configuration, delegate: delegate, delegateQueue: OperationQueue.main) session.sessionDescription = "Webtrekk Tracking" return session } internal func enqueueRequest(_ request: URL, maximumDelay: TimeInterval) { checkIsOnMainThread() // add senNextRequest to closerue. So it will be called only after adding is done self.queue.addURL(url: request) logDebug("Queued: \(request.absoluteString.replacingOccurrences(of: "&", with: " "))") if !manualStart { sendNextRequest(maximumDelay: maximumDelay) } } func fetch(url: URL, completion: @escaping (Data?, ConnectionError?) -> Void) -> URLSessionDataTask? { checkIsOnMainThread() guard let urlSession = self.urlSession else { WebtrekkTracking.defaultLogger.logError("Error: session is nil during fetch") return nil } let task = urlSession.dataTask(with: url, completionHandler: {data, response, error in if let error = error { let retryable: Bool let isCompletelyOffline: Bool switch (error as NSError).code { case NSURLErrorBadServerResponse, NSURLErrorCallIsActive, NSURLErrorCannotConnectToHost, NSURLErrorCannotFindHost, NSURLErrorDataNotAllowed, NSURLErrorDNSLookupFailed, NSURLErrorInternationalRoamingOff, NSURLErrorNetworkConnectionLost, NSURLErrorNotConnectedToInternet, NSURLErrorTimedOut, NSURLErrorZeroByteResource: retryable = true default: retryable = false } switch (error as NSError).code { case NSURLErrorCallIsActive, NSURLErrorDataNotAllowed, NSURLErrorInternationalRoamingOff, NSURLErrorNotConnectedToInternet: isCompletelyOffline = true default: isCompletelyOffline = false } completion(nil, ConnectionError(message: error.localizedDescription, isTemporary: retryable, isCompletelyOffline: isCompletelyOffline, underlyingError: error)) return } guard let response = response as? HTTPURLResponse else { completion(nil, ConnectionError(message: "No Response", isTemporary: false)) return } guard !(500 ... 599).contains(response.statusCode) else { completion(nil, ConnectionError(message: "HTTP \(response.statusCode)", isTemporary: true)) return } guard (200 ... 299).contains(response.statusCode), let data = data else { completion(nil, ConnectionError(message: "HTTP \(response.statusCode)", isTemporary: false)) return } completion(data, nil) }) task.resume() return task } fileprivate func maximumNumberOfFailures(with error: ConnectionError) -> Int { checkIsOnMainThread() if error.isCompletelyOffline { return 60 } else { return 10 } } internal func prependRequests(_ requests: [URL]) { checkIsOnMainThread() // it can be done only on after application update at first start guard self.queue.isEmpty else { return } self.queue.addArray(urls: requests) } internal func sendAllRequests() { checkIsOnMainThread() sendNextRequest() } fileprivate func sendNextRequest() { checkIsOnMainThread() sendNextRequestTimer?.invalidate() sendNextRequestTimer = nil guard started else { return } guard self.pendingTask == nil else { return } guard !self.queue.isEmpty else { WebtrekkTracking.defaultLogger.logDebug("queue is empty: finish send process") return } #if !os(watchOS) if let reachability = reachability { if reachability.connection == .none { if !sendingInterruptedBecauseUnreachable { sendingInterruptedBecauseUnreachable = true logDebug("Internet is unreachable. Pausing requests.") do { try reachability.startNotifier() } catch let error { logError("Cannot listen for reachability events: \(error)") } } return } sendingInterruptedBecauseUnreachable = false reachability.stopNotifier() } #endif do { try self.queue.getURL { url in if url != self.currentRequest { self.currentFailureCount = 0 self.currentRequest = url } guard let url = url else { return } guard !self.finishing else { WebtrekkTracking.defaultLogger.logDebug("Interrupt get request. process is finishing") return } self.pendingTask = self.fetch(url: url) { data, error in self.pendingTask = nil if let error = error { guard error.isTemporary else { logError("Request \(url) failed and will not be retried: \(error)") self.currentFailureCount = 0 self.currentRequest = nil _ = self.queue.deleteFirst() self.delegate?.requestManager(self, didFailToSendRequest: url, error: error) return } guard self.currentFailureCount < self.maximumNumberOfFailures(with: error) else { logError("Request \(url) failed and will no longer be retried: \(error)") self.currentFailureCount = 0 self.currentRequest = nil _ = self.queue.deleteFirst() self.delegate?.requestManager(self, didFailToSendRequest: url, error: error) return } let retryDelay = Double(self.currentFailureCount * 5) logWarning("Request \(url) failed temporarily and will be retried in \(retryDelay) seconds: \(error)") self.currentFailureCount += 1 self.sendNextRequest(maximumDelay: retryDelay) return } logDebug("Request has been sent successefully") self.currentFailureCount = 0 self.currentRequest = nil _ = self.queue.deleteFirst() if let delegate = self.delegate { delegate.requestManager(self, didSendRequest: url) } self.sendNextRequest() } } } catch let error { if let error = error as? TrackerError { WebtrekkTracking.defaultLogger.logError("catched exception: \(error.message)") } } } fileprivate func sendNextRequest(maximumDelay: TimeInterval) { checkIsOnMainThread() guard !self.queue.isEmpty else { return } if let sendNextRequestTimer = self.sendNextRequestTimer { let fireDate = Date(timeIntervalSinceNow: maximumDelay) if fireDate.compare(sendNextRequestTimer.fireDate) == ComparisonResult.orderedAscending { sendNextRequestTimer.fireDate = fireDate } } else { self.sendNextRequestTimer = Timer.scheduledTimerWithTimeInterval(maximumDelay) { self.sendNextRequestTimer = nil self.sendAllRequests() } } } internal func start() { checkIsOnMainThread() guard !started else { logWarning("Cannot start RequestManager which was already started.") return } self.started = true self.finishing = false if self.urlSession == nil { self.urlSession = RequestManager.createUrlSession(delegate: self) } if !manualStart { sendNextRequest() } } internal func stop() { checkIsOnMainThread() guard started else { logWarning("Cannot stop RequestManager which wasn't started.") return } started = false self.sendNextRequestTimer?.invalidate() self.sendNextRequestTimer = nil #if !os(watchOS) sendingInterruptedBecauseUnreachable = false reachability?.stopNotifier() #endif self.finishing = true WebtrekkTracking.defaultLogger.logDebug("stop. pending task is: \(self.pendingTask.simpleDescription)") self.urlSession?.finishTasksAndInvalidate() self.urlSession = nil } internal struct ConnectionError: Error { internal var isCompletelyOffline: Bool internal var isTemporary: Bool internal var message: String internal var underlyingError: Error? internal init(message: String, isTemporary: Bool, isCompletelyOffline: Bool = false, underlyingError: Error? = nil) { self.isCompletelyOffline = isCompletelyOffline self.isTemporary = isTemporary self.message = message self.underlyingError = underlyingError } } // implement URLSessionDelegate public func urlSession( _ session: URLSession, didBecomeInvalidWithError error: Error?) { logDebug("didBecomeInvalidWithError call") DispatchQueue.global(qos: .background).async { if self.finishing { WebtrekkTracking.defaultLogger.logDebug("URL request has been finished. Save all") if let error = error { WebtrekkTracking.defaultLogger.logError("URL session invalidated with error: \(error)") } self.queue.save() self.finishing = false #if !os(watchOS) if self.backgroundTaskIdentifier != UIBackgroundTaskIdentifier.invalid { UIApplication.shared.endBackgroundTask(convertToUIBackgroundTaskIdentifier(self.backgroundTaskIdentifier.rawValue)) self.backgroundTaskIdentifier = UIBackgroundTaskIdentifier.invalid } #endif } } } } internal protocol _RequestManagerDelegate: class { func requestManager (_ requestManager: RequestManager, didSendRequest request: URL) func requestManager (_ requestManager: RequestManager, didFailToSendRequest request: URL, error: RequestManager.ConnectionError) } // Helper function inserted by Swift 4.2 migrator. #if !os(watchOS) private func convertToUIBackgroundTaskIdentifier(_ input: Int) -> UIBackgroundTaskIdentifier { return UIBackgroundTaskIdentifier(rawValue: input) } #endif
mit
ee2546921ac5eea6fcbf042e99caa144
28.580645
163
0.645506
5.203891
false
false
false
false
asm-products/cakebird
CakeBird/TwitterUser.swift
1
4379
// // TwitterUser.swift // CakeBird // // Created by Rhett Rogers on 8/17/14. // Copyright (c) 2014 Lyokotech. All rights reserved. // import Foundation import Twitter import Accounts import Social import SwifteriOS class TwitterUser : NSObject { var swifter:Swifter var account:ACAccount var userObject:[String:SwifteriOS.JSONValue]? var location: String? var favorites: Int? var bio: String? // var profileImage: UIImage? // var bannerImage: UIImage? var name: String? var handle: String? var timeZone: String? var accountCreatedDate: NSDate? var tweets: Int? var following: Int? var followers: Int? var language: String? init(swifter: Swifter, account: ACAccount, callback:()->Void) { self.swifter = swifter self.account = account super.init() fillUserInfo(callback) } func fillUserInfo(callback:()->Void) { swifter.getUsersShowWithScreenName(account.username, includeEntities: true, success: { (user) -> Void in if let unwrappedUser = user { self.userObject = user self.location = unwrappedUser["location"]!.string self.favorites = unwrappedUser["favourites_count"]!.integer self.bio = unwrappedUser["description"]!.string // self.profileImage = UIImage(data: NSData(contentsOfURL: NSURL(string: unwrappedUser["profile_image_url_https"]!.string!))) // self.bannerImage = UIImage(data: NSData(contentsOfURL: NSURL(string: unwrappedUser["profile_banner_url"]!.string!))) self.name = unwrappedUser["name"]!.string self.handle = unwrappedUser["screen_name"]!.string self.timeZone = unwrappedUser["time_zone"]!.string self.tweets = unwrappedUser["statuses_count"]!.integer self.following = unwrappedUser["friends_count"]!.integer self.followers = unwrappedUser["followers_count"]!.integer self.language = unwrappedUser["lang"]!.string callback() } else { println("EXTREME ERROR") } }) { (error) -> Void in println("ERROR: \(error)") } } func getUserStream(callback:(error: NSError!, jsonTweets: [JSONValue]?)->Void) { swifter.getStatusesHomeTimelineWithCount(20, sinceID: nil, maxID: nil, trimUser: true, contributorDetails: true, includeEntities: true, success: { (statuses: [JSONValue]?) -> Void in callback(error: nil, jsonTweets:statuses) }) { (error) -> Void in callback(error: error, jsonTweets: nil) } } func description() -> String { if let h = handle { if let n = name { return "@\(h) – \(n)" } } return "Incomplete User" } func encodeWithCoder(coder: NSCoder) { coder.encodeObject(account, forKey: "account") coder.encodeObject(location!, forKey: "location") coder.encodeObject(favorites!, forKey: "favorites") coder.encodeObject(bio!, forKey: "bio") // coder.encodeObject(profileImage!, forKey: "profileImage") // coder.encodeObject(bannerImage!, forKey: "bannerImage") coder.encodeObject(name!, forKey: "name") coder.encodeObject(handle!, forKey: "handle") coder.encodeObject(timeZone!, forKey: "timeZone") coder.encodeObject(tweets!, forKey: "tweets") coder.encodeObject(following!, forKey: "following") coder.encodeObject(followers!, forKey: "followers") coder.encodeObject(language!, forKey: "language") } init(coder: NSCoder) { self.account = coder.decodeObjectForKey("account") as ACAccount self.swifter = Swifter(account: self.account) self.location = coder.decodeObjectForKey("location") as? String self.favorites = coder.decodeObjectForKey("favorites") as? Int self.bio = coder.decodeObjectForKey("bio") as? String // self.profileImage = coder.decodeObjectForKey("profileImage") as? UIImage // self.bannerImage = coder.decodeObjectForKey("bannerImage") as? UIImage self.name = coder.decodeObjectForKey("name") as? String self.handle = coder.decodeObjectForKey("handle") as? String self.timeZone = coder.decodeObjectForKey("timeZone") as? String self.tweets = coder.decodeObjectForKey("tweets") as? Int self.following = coder.decodeObjectForKey("following") as? Int self.followers = coder.decodeObjectForKey("followers") as? Int self.language = coder.decodeObjectForKey("language") as? String } }
agpl-3.0
843e6983d8554725e5cc683c23e26155
35.789916
186
0.678318
4.350895
false
false
false
false
mactive/rw-courses-note
advanced-swift-types-and-operations/TypesAndOps.playground/Pages/AccessControl.xcplaygroundpage/Contents.swift
1
565
//: [Previous](@previous) // https://swift.gg/2016/01/11/public-properties-with-private-setters/ // https://docs.swift.org/swift-book/LanguageGuide/AccessControl.html import Foundation public struct TrackedString { // 公开 Getter,隐藏 Setter public private(set) var numberOfEdits = 0 public var value: String = "" { didSet { numberOfEdits += 1 } } public init() {} } var name: TrackedString = TrackedString() name.value = "name" name.numberOfEdits name.value = "name1" name.numberOfEdits //: [Next](@next)
mit
2d2ba544a3121a12b15bb20cd0c76373
21.2
70
0.663063
3.603896
false
false
false
false
fluidsonic/JetPack
Sources/Extensions/CoreGraphics/CGRect.swift
1
6613
import CoreGraphics public extension CGRect { init(size: CGSize) { self.init(x: 0, y: 0, width: size.width, height: size.height) } init(left: CGFloat, top: CGFloat, width: CGFloat, height: CGFloat) { self.init(x: left, y: top, width: width, height: height) } init(width: CGFloat, height: CGFloat) { self.init(x: 0, y: 0, width: width, height: height) } func applying(_ transform: CGAffineTransform, anchorPoint: CGPoint) -> CGRect { if anchorPoint != .zero { let anchorLeft = left + (width * anchorPoint.left) let anchorTop = top + (height * anchorPoint.top) let t1 = CGAffineTransform(horizontalTranslation: anchorLeft, verticalTranslation: anchorTop) let t2 = CGAffineTransform(horizontalTranslation: -anchorLeft, verticalTranslation: -anchorTop) return applying(t2 * transform * t1) } else { return applying(transform) } } var bottom: CGFloat { get { return origin.top + size.height } mutating set { origin.top = newValue - size.height } } var bottomCenter: CGPoint { get { return CGPoint(left: left + (width / 2), top: bottom) } mutating set { left = newValue.left - (width / 2); bottom = newValue.top } } var bottomLeft: CGPoint { get { return CGPoint(left: left, top: bottom) } mutating set { left = newValue.left; bottom = newValue.top } } var bottomRight: CGPoint { get { return CGPoint(left: right, top: bottom) } mutating set { right = newValue.left; bottom = newValue.top } } var center: CGPoint { get { return CGPoint(left: left + (width / 2), top: top + (height / 2)) } mutating set { left = newValue.left - (width / 2); top = newValue.top - (height / 2) } } func centered(at center: CGPoint) -> CGRect { var rect = self rect.center = center return rect } var centerLeft: CGPoint { get { return CGPoint(left: left, top: top + (height / 2)) } mutating set { left = newValue.left; top = newValue.top - (height / 2) } } var centerRight: CGPoint { get { return CGPoint(left: right, top: top + (height / 2)) } mutating set { right = newValue.left; top = newValue.top - (height / 2) } } func contains(_ point: CGPoint, cornerRadius: CGFloat) -> Bool { guard contains(point) else { // full rect misses, so does any rounded rect return false } guard cornerRadius > 0 else { // full rect already hit return true } // we already hit the full rect, so if the point is at least cornerRadius pixels away from both sides in one axis we have a hit let minX = origin.x let minXAfterCorner = minX + cornerRadius let maxX = minX + width let maxXBeforeCorner = maxX - cornerRadius guard point.x < minXAfterCorner || point.x > maxXBeforeCorner else { return true } let minY = origin.y let minYAfterCorner = minY + cornerRadius let maxY = minY + height let maxYBeforeCorner = maxY - cornerRadius guard point.y < minYAfterCorner || point.y > maxYBeforeCorner else { return true } // it must be near one of the corners - figure out which one let midX = minX + (width / 2) let midY = minY + (height / 2) let circleCenter: CGPoint if point.x <= midX { // must be near one of the left corners if point.y <= midY { // must be near the top left corner circleCenter = CGPoint(x: minXAfterCorner, y: minYAfterCorner) } else { // must be near the bottom left corner circleCenter = CGPoint(x: minXAfterCorner, y: maxYBeforeCorner) } } else { // must ne near one of the right corners if point.y <= midY { // must be near the top right corner circleCenter = CGPoint(x: maxXBeforeCorner, y: minYAfterCorner) } else { // must be near the bottom right corner circleCenter = CGPoint(x: maxXBeforeCorner, y: maxYBeforeCorner) } } // just test distance from the matching circle to the point return (circleCenter.distance(to: point) <= cornerRadius) } func displacement(to point: CGPoint) -> CGPoint { return CGPoint( left: point.left.coerced(in: left ... right), top: point.top.coerced(in: top ... bottom) ).displacement(to: point) } func distance(to point: CGPoint) -> CGFloat { let displacement = self.displacement(to: point) return ((displacement.x * displacement.x) + (displacement.y * displacement.y)).squareRoot() } internal var height: CGFloat { // public doesn't work due getter ambigutity get { return size.height } @available(*, deprecated, renamed: "heightFromTop") mutating set { size.height = newValue } } var heightFromBottom: CGFloat { get { return size.height } mutating set { top += height - newValue; heightFromTop = newValue } } var heightFromTop: CGFloat { get { return size.height } mutating set { size.height = newValue } } var horizontalCenter: CGFloat { get { return CGFloat(left + (width / 2)) } mutating set { left = newValue - (width / 2) } } func interpolate(to destination: CGRect, fraction: CGFloat) -> CGRect { return CGRect( left: left + ((destination.left - left) * fraction), top: top + ((destination.top - top) * fraction), width: width + ((destination.width - width) * fraction), height: height + ((destination.height - height) * fraction) ) } var isValid: Bool { return size.isValid } var left: CGFloat { get { return origin.left } mutating set { origin.left = newValue } } func offsetBy(_ offset: CGPoint) -> CGRect { return offsetBy(dx: offset.x, dy: offset.y) } var right: CGFloat { get { return origin.left + size.width } mutating set { origin.left = newValue - size.width } } var top: CGFloat { get { return origin.top } mutating set { origin.top = newValue } } var topCenter: CGPoint { get { return CGPoint(left: left + (width / 2), top: top) } mutating set { left = newValue.left - (width / 2); top = newValue.top } } var topLeft: CGPoint { get { return origin } mutating set { origin = newValue } } var topRight: CGPoint { get { return CGPoint(left: right, top: top) } mutating set { right = newValue.left; top = newValue.top } } var verticalCenter: CGFloat { get { return CGFloat(top + (height / 2)) } mutating set { top = newValue - (height / 2) } } internal var width: CGFloat { // public doesn't work due getter ambigutity get { return size.width } @available(*, deprecated, renamed: "widthFromLeft") mutating set { size.width = newValue } } var widthFromLeft: CGFloat { get { return size.width } mutating set { size.width = newValue } } var widthFromRight: CGFloat { get { return size.width } mutating set { left += width - newValue; widthFromLeft = newValue } } }
mit
3b852205a1bfe810ebcd2d168004154a
24.240458
129
0.666566
3.451461
false
false
false
false
skedgo/tripkit-ios
Sources/TripKitUI/helper/TKUIModePickerLayoutHelper.swift
1
4467
// // TKUIModePickerLayoutHelper.swift // TripKitUI-iOS // // Created by Brian Huang on 12/11/21. // Copyright © 2021 SkedGo Pty Ltd. All rights reserved. // import Foundation import UIKit import TripKit protocol TKUIModePickerLayoutHelperDelegate: AnyObject { func numberOfModesToDisplay(in collectionView: UICollectionView) -> Int func pickerCellToDisplay(at indexPath: IndexPath, in collectionView: UICollectionView) -> TKUIModePickerCell func size(for pickerCell: TKUIModePickerCell, at indexPath: IndexPath) -> CGSize func selectedItem(at indexPath: IndexPath, in collectionView: UICollectionView) func hoverChanged(isActive: Bool, at indexPath: IndexPath?, in collectionView: UICollectionView) } class TKUIModePickerLayoutHelper: NSObject { weak var delegate: TKUIModePickerLayoutHelperDelegate! weak var collectionView: UICollectionView! private let sectionInset: UIEdgeInsets = .init(top: 8, left: 8, bottom: 8, right: 8) private let sizingCell = TKUIModePickerCell.newInstance() init(collectionView: UICollectionView, delegate: TKUIModePickerLayoutHelperDelegate) { self.collectionView = collectionView self.delegate = delegate super.init() collectionView.dataSource = self collectionView.delegate = self collectionView.backgroundColor = .clear collectionView.register(TKUIModePickerCell.nib, forCellWithReuseIdentifier: TKUIModePickerCell.reuseIdentifier) } } // MARK: - Data source extension TKUIModePickerLayoutHelper: UICollectionViewDataSource { #if targetEnvironment(macCatalyst) @objc func tapped(sender: UITapGestureRecognizer) { guard let collectionView = collectionView else { return } let point = sender.location(in: collectionView) if let indexPath = collectionView.indexPathForItem(at: point) { delegate.selectedItem(at: indexPath, in: collectionView) } } @objc func hover(sender: UIHoverGestureRecognizer) { guard let collectionView = collectionView else { return } let point = sender.location(in: collectionView) if let indexPath = collectionView.indexPathForItem(at: point) { switch sender.state { case .began: delegate.hoverChanged(isActive: true, at: indexPath, in: collectionView) case .ended, .cancelled, .failed: delegate.hoverChanged(isActive: false, at: indexPath, in: collectionView) default: break } } else { delegate.hoverChanged(isActive: false, at: nil, in: collectionView) } } #endif func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return delegate.numberOfModesToDisplay(in: collectionView) } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let pickerCell = delegate.pickerCellToDisplay(at: indexPath, in: collectionView) #if targetEnvironment(macCatalyst) if (pickerCell.gestureRecognizers ?? []).isEmpty { // For some reason, the 'did select' delegate callback won't fire on // Mac Catalyst, so we immitate that manually. let tapper = UITapGestureRecognizer(target: self, action: #selector(tapped(sender:))) pickerCell.addGestureRecognizer(tapper) let hover = UIHoverGestureRecognizer(target: self, action: #selector(hover(sender:))) pickerCell.addGestureRecognizer(hover) } #endif return pickerCell } } // MARK: - Delegate extension TKUIModePickerLayoutHelper: UICollectionViewDelegate { func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { delegate.selectedItem(at: indexPath, in: collectionView) } } // MARK: - Layout extension TKUIModePickerLayoutHelper: UICollectionViewDelegateFlowLayout { func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { return delegate.size(for: sizingCell, at: indexPath) } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets { return sectionInset } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat { return sectionInset.left } }
apache-2.0
0ebbba9f6e19fc6d3f2afd89a4e43893
32.578947
168
0.746305
5.316667
false
false
false
false
sammeadley/TopStories
TopStories/ImageCache.swift
1
6422
// // ImageCache.swift // TopStories // // Created by Sam Meadley on 21/04/2016. // Copyright © 2016 Sam Meadley. All rights reserved. // import UIKit final class ImageCache { private let cache: NSCache<NSString, UIImage> private let fileManager: FileManager /** Initializes the ImageCache with dependent objects. ImageCache internally handles a dual cache; one in-memory and one on disk. This allows images to be persisted across launches to save network traffic. Files are stores in Library/Caches; a system provided store which iOS automatically empties if it starts to run out of storage. We should also set a cache policy to routinely clean up old content, but that is out of scope for this project. - parameter cache: The underlying NSCache instance or nil, if not supplied a new instance will be used. - parameter fileManager: The file manager to use to access the disk cache or nil. If not supplied the defaultManager is used. */ init(cache: NSCache<NSString, UIImage> = NSCache(), fileManager: FileManager = FileManager.default) { self.cache = cache self.fileManager = fileManager } /** Gets the cached image for the URL, or nil if not present. First checks for membership of in-memory cache, before hitting the disk cache. It is recommended that imageForURL(_:) be called from a background thread as the disk fetch can be slow. Images fetched from the disk cache are decompressed and added to the in-memory cache for fast future retrieval. - returns: UIImage instance if image is in the cache or nil. */ func imageForURL(_ url: String) -> UIImage? { if let image = cache.object(forKey: url as NSString) { return image } // Attempt to fetch from Library/Caches. guard let path = try? urlForCachedImageForKey(url).path else { return nil } if !fileManager.fileExists(atPath: path) { return nil } guard let data = fileManager.contents(atPath: path) else { return nil } guard let image = UIImage(data: data)?.decompress() else { return nil } setImage(image, forURL: url) return image } /** Adds an image to the cache. Adds UIImage instance to in-memory cache and disk cache. It is recommended that setImage(_:forURL:temporaryFileURL:) is called from a background queue, as disk IO can be slow. Copies the downloaded data to a temporary location (returned from NSURLSessionDownloadTask) to Library/Caches/{filename} - where the filename is the MD5 hash of the URL of the image resource. - parameter image: UIImage instance to add to the cache. - parameter URL: Web URL of the downloaded image- used to calculate the MD5 cache key. - parameter temporaryFileURL: URL on disk of the temporary file download. */ func setImage(_ image: UIImage, forURL url: String, temporaryFileURL: URL? = nil) { cache.setObject(image, forKey: url as NSString) guard let sourceURL = temporaryFileURL else { return } do { let destinationURL = try urlForCachedImageForKey(url) try fileManager.moveItem(at: sourceURL, to: destinationURL) } catch { // TODO: Handle error } } /** The expected URL for the cached image on disk. The path of the cached image on disk- if the image is contained in the cache, then it will exist at this path. If the image is not cached to disk, the path will be empty. We build the cache path by simply taking the MD5 hash of the passed key. - parameter key: The key to use for the cache filename. - throws: ImageCacheError.CachesDirectoryNotFound if iOS is unable to locate Library/Caches. - returns: NSURL instance containing the path of the cached image on disk. */ func urlForCachedImageForKey(_ key: String) throws -> URL { let urls = fileManager.urls(for: .cachesDirectory, in: .userDomainMask) guard let url = urls.last else { throw ImageCacheError.cachesDirectoryNotFound } return url.appendingPathComponent(key.MD5()) } } // MARK:- Error Types enum ImageCacheError: Error { case cachesDirectoryNotFound } // MARK: - String extension methods extension String { /** Transforms the current value of this String instance to an MD5 hash. - returns: A new string containing the MD5 hash. */ func MD5() -> String { let data = self.data(using: String.Encoding.utf8)! var digest = [UInt8](repeating: 0, count: Int(CC_MD5_DIGEST_LENGTH)) CC_MD5((data as NSData).bytes, CC_LONG(data.count), &digest) let hexBytes = digest.map { String(format: "%02x", $0) } return hexBytes.joined(separator: "") } } // MARK: - UIImage extensions methods extension UIImage { /** Decompresses the image data. Decompresses the data on this UIImage instance- the benefit being we can perform this from a background queue and avoid on-the-fly decompression occuring at the point of setting the image value of the imageView. - returns: A new UIImage instance containing the decompressed image. */ func decompress() -> UIImage? { let imageRef = self.cgImage let colorSpace = CGColorSpaceCreateDeviceRGB() let bitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.premultipliedLast.rawValue).rawValue guard let context = CGContext(data: nil, width: (imageRef?.width)!, height: (imageRef?.height)!, bitsPerComponent: 8, bytesPerRow: 0, space: colorSpace, bitmapInfo: bitmapInfo) else { return nil } let rect = CGRect(x: 0, y: 0, width: (imageRef?.width)!, height: (imageRef?.height)!) context.draw(imageRef!, in: rect) let decompressedImageRef = context.makeImage() return UIImage(cgImage: decompressedImageRef!) } }
mit
8b4f684ff4417f0f555049eb9b1d8825
33.336898
191
0.632456
4.897788
false
false
false
false
jasonhenderson/examples-ios
WebServices/Pods/Unbox/Sources/Unboxer.swift
3
12216
/** * Unbox * Copyright (c) 2015-2017 John Sundell * Licensed under the MIT license, see LICENSE file */ import Foundation // MARK: - Public /** * Class used to Unbox (decode) values from a dictionary * * For each supported type, simply call `unbox(key: string)` (where `string` is a key in the dictionary that is being unboxed) * - and the correct type will be returned. If a required (non-optional) value couldn't be unboxed `UnboxError` will be thrown. */ public final class Unboxer { /// The underlying JSON dictionary that is being unboxed public let dictionary: UnboxableDictionary // MARK: - Initializer /// Initialize an instance with a dictionary that can then be decoded using the `unbox()` methods. public init(dictionary: UnboxableDictionary) { self.dictionary = dictionary } /// Initialize an instance with binary data than can then be decoded using the `unbox()` methods. Throws `UnboxError` for invalid data. public init(data: Data) throws { self.dictionary = try JSONSerialization.unbox(data: data) } // MARK: - Custom unboxing API /// Perform custom unboxing using an Unboxer (created from a dictionary) passed to a closure, or throw an UnboxError public static func performCustomUnboxing<T>(dictionary: UnboxableDictionary, closure: (Unboxer) throws -> T?) throws -> T { return try Unboxer(dictionary: dictionary).performCustomUnboxing(closure: closure) } /// Perform custom unboxing on an array of dictionaries, executing a closure with a new Unboxer for each one, or throw an UnboxError public static func performCustomUnboxing<T>(array: [UnboxableDictionary], allowInvalidElements: Bool = false, closure: (Unboxer) throws -> T?) throws -> [T] { return try array.map(allowInvalidElements: allowInvalidElements) { try Unboxer(dictionary: $0).performCustomUnboxing(closure: closure) } } /// Perform custom unboxing using an Unboxer (created from binary data) passed to a closure, or throw an UnboxError public static func performCustomUnboxing<T>(data: Data, closure: @escaping (Unboxer) throws -> T?) throws -> T { return try data.unbox(closure: closure) } // MARK: - Unboxing required values (by key) /// Unbox a required value by key public func unbox<T: UnboxCompatible>(key: String) throws -> T { return try self.unbox(path: .key(key), transform: T.unbox) } /// Unbox a required collection by key public func unbox<T: UnboxableCollection>(key: String, allowInvalidElements: Bool) throws -> T { let transform = T.makeTransform(allowInvalidElements: allowInvalidElements) return try self.unbox(path: .key(key), transform: transform) } /// Unbox a required Unboxable type by key public func unbox<T: Unboxable>(key: String) throws -> T { return try self.unbox(path: .key(key), transform: T.makeTransform()) } /// Unbox a required UnboxableWithContext type by key public func unbox<T: UnboxableWithContext>(key: String, context: T.UnboxContext) throws -> T { return try self.unbox(path: .key(key), transform: T.makeTransform(context: context)) } /// Unbox a required collection of UnboxableWithContext values by key public func unbox<C: UnboxableCollection, V: UnboxableWithContext>(key: String, context: V.UnboxContext, allowInvalidElements: Bool = false) throws -> C where C.UnboxValue == V { return try self.unbox(path: .key(key), transform: V.makeCollectionTransform(context: context, allowInvalidElements: allowInvalidElements)) } /// Unbox a required value using a formatter by key public func unbox<F: UnboxFormatter>(key: String, formatter: F) throws -> F.UnboxFormattedType { return try self.unbox(path: .key(key), transform: formatter.makeTransform()) } /// Unbox a required collection of values using a formatter by key public func unbox<C: UnboxableCollection, F: UnboxFormatter>(key: String, formatter: F, allowInvalidElements: Bool = false) throws -> C where C.UnboxValue == F.UnboxFormattedType { return try self.unbox(path: .key(key), transform: formatter.makeCollectionTransform(allowInvalidElements: allowInvalidElements)) } // MARK: - Unboxing required values (by key path) /// Unbox a required value by key path public func unbox<T: UnboxCompatible>(keyPath: String) throws -> T { return try self.unbox(path: .keyPath(keyPath), transform: T.unbox) } /// Unbox a required collection by key path public func unbox<T: UnboxCompatible>(keyPath: String, allowInvalidElements: Bool) throws -> T where T: Collection { let transform = T.makeTransform(allowInvalidElements: allowInvalidElements) return try self.unbox(path: .keyPath(keyPath), transform: transform) } /// Unbox a required Unboxable by key path public func unbox<T: Unboxable>(keyPath: String) throws -> T { return try self.unbox(path: .keyPath(keyPath), transform: T.makeTransform()) } /// Unbox a required UnboxableWithContext type by key path public func unbox<T: UnboxableWithContext>(keyPath: String, context: T.UnboxContext) throws -> T { return try self.unbox(path: .keyPath(keyPath), transform: T.makeTransform(context: context)) } /// Unbox a required collection of UnboxableWithContext values by key path public func unbox<C: UnboxableCollection, V: UnboxableWithContext>(keyPath: String, context: V.UnboxContext, allowInvalidElements: Bool = false) throws -> C where C.UnboxValue == V { return try self.unbox(path: .keyPath(keyPath), transform: V.makeCollectionTransform(context: context, allowInvalidElements: allowInvalidElements)) } /// Unbox a required value using a formatter by key path public func unbox<F: UnboxFormatter>(keyPath: String, formatter: F) throws -> F.UnboxFormattedType { return try self.unbox(path: .keyPath(keyPath), transform: formatter.makeTransform()) } /// Unbox a required collection of values using a formatter by key path public func unbox<C: UnboxableCollection, F: UnboxFormatter>(keyPath: String, formatter: F, allowInvalidElements: Bool = false) throws -> C where C.UnboxValue == F.UnboxFormattedType { return try self.unbox(path: .keyPath(keyPath), transform: formatter.makeCollectionTransform(allowInvalidElements: allowInvalidElements)) } // MARK: - Unboxing optional values (by key) /// Unbox an optional value by key public func unbox<T: UnboxCompatible>(key: String) -> T? { return try? self.unbox(key: key) } /// Unbox an optional collection by key public func unbox<T: UnboxableCollection>(key: String, allowInvalidElements: Bool) -> T? { return try? self.unbox(key: key, allowInvalidElements: allowInvalidElements) } /// Unbox an optional Unboxable type by key public func unbox<T: Unboxable>(key: String) -> T? { return try? self.unbox(key: key) } /// Unbox an optional UnboxableWithContext type by key public func unbox<T: UnboxableWithContext>(key: String, context: T.UnboxContext) -> T? { return try? self.unbox(key: key, context: context) } /// Unbox an optional collection of UnboxableWithContext values by key public func unbox<C: UnboxableCollection, V: UnboxableWithContext>(key: String, context: V.UnboxContext, allowInvalidElements: Bool = false) -> C? where C.UnboxValue == V { return try? self.unbox(path: .key(key), transform: V.makeCollectionTransform(context: context, allowInvalidElements: allowInvalidElements)) } /// Unbox an optional value using a formatter by key public func unbox<F: UnboxFormatter>(key: String, formatter: F) -> F.UnboxFormattedType? { return try? self.unbox(key: key, formatter: formatter) } /// Unbox an optional collection of values using a formatter by key public func unbox<C: UnboxableCollection, F: UnboxFormatter>(key: String, formatter: F, allowInvalidElements: Bool = false) -> C? where C.UnboxValue == F.UnboxFormattedType { return try? self.unbox(key: key, formatter: formatter, allowInvalidElements: allowInvalidElements) } // MARK: - Unboxing optional values (by key path) /// Unbox an optional value by key path public func unbox<T: UnboxCompatible>(keyPath: String) -> T? { return try? self.unbox(keyPath: keyPath) } /// Unbox an optional collection by key path public func unbox<T: UnboxableCollection>(keyPath: String, allowInvalidElements: Bool) -> T? { return try? self.unbox(keyPath: keyPath, allowInvalidElements: allowInvalidElements) } /// Unbox an optional Unboxable type by key path public func unbox<T: Unboxable>(keyPath: String) -> T? { return try? self.unbox(keyPath: keyPath) } /// Unbox an optional UnboxableWithContext type by key path public func unbox<T: UnboxableWithContext>(keyPath: String, context: T.UnboxContext) -> T? { return try? self.unbox(keyPath: keyPath, context: context) } /// Unbox an optional collection of UnboxableWithContext values by key path public func unbox<C: UnboxableCollection, V: UnboxableWithContext>(keyPath: String, context: V.UnboxContext, allowInvalidElements: Bool = false) -> C? where C.UnboxValue == V { return try? self.unbox(path: .keyPath(keyPath), transform: V.makeCollectionTransform(context: context, allowInvalidElements: allowInvalidElements)) } /// Unbox an optional value using a formatter by key path public func unbox<F: UnboxFormatter>(keyPath: String, formatter: F) -> F.UnboxFormattedType? { return try? self.unbox(keyPath: keyPath, formatter: formatter) } /// Unbox an optional collection of values using a formatter by key path public func unbox<C: UnboxableCollection, F: UnboxFormatter>(keyPath: String, formatter: F, allowInvalidElements: Bool = false) -> C? where C.UnboxValue == F.UnboxFormattedType { return try? self.unbox(keyPath: keyPath, formatter: formatter, allowInvalidElements: allowInvalidElements) } } // MARK: - Internal internal extension Unboxer { func performUnboxing<T: Unboxable>() throws -> T { return try T(unboxer: self) } func performUnboxing<T: UnboxableWithContext>(context: T.UnboxContext) throws -> T { return try T(unboxer: self, context: context) } } // MARK: - Private private extension Unboxer { func unbox<R>(path: UnboxPath, transform: UnboxTransform<R>) throws -> R { do { switch path { case .key(let key): let value = try self.dictionary[key].orThrow(UnboxPathError.missingKey(key)) return try transform(value).orThrow(UnboxPathError.invalidValue(value, key)) case .keyPath(let keyPath): var node: UnboxPathNode = self.dictionary let components = keyPath.components(separatedBy: ".") let lastKey = components.last for key in components { guard let nextValue = node.unboxPathValue(forKey: key) else { throw UnboxPathError.missingKey(key) } if key == lastKey { return try transform(nextValue).orThrow(UnboxPathError.invalidValue(nextValue, key)) } guard let nextNode = nextValue as? UnboxPathNode else { throw UnboxPathError.invalidValue(nextValue, key) } node = nextNode } throw UnboxPathError.emptyKeyPath } } catch { if let publicError = error as? UnboxError { throw publicError } else if let pathError = error as? UnboxPathError { throw UnboxError.pathError(pathError, path.description) } throw error } } func performCustomUnboxing<T>(closure: (Unboxer) throws -> T?) throws -> T { return try closure(self).orThrow(UnboxError.customUnboxingFailed) } }
gpl-3.0
07e9bf6efd329fd4b189457f0eaff8da
45.804598
188
0.683366
4.731216
false
false
false
false
duming91/Hear-You
Hear You/ViewControllers/List/SongListViewController.swift
1
6060
// // ListTableViewController.swift // Hear You // // Created by 董亚珣 on 16/5/3. // Copyright © 2016年 snow. All rights reserved. // import UIKit import RealmSwift class SongListViewController: UITableViewController { private var category = SongCategory() var categoryType : DefaultCategory? var popWindow : Pop? let tableHeaderHeight = screenBounds.width / 2 lazy var tableHeaderView = UIImageView() @IBOutlet weak var headerImageView: UIImageView! override func viewDidLoad() { super.viewDidLoad() tableView.contentInset = UIEdgeInsetsMake(-64, 0, 0, 0) tableView.registerNib(UINib.init(nibName: "MusicCell", bundle: NSBundle.mainBundle()), forCellReuseIdentifier: "ListCell") tableHeaderView.frame = CGRectMake(0, 0, screenBounds.width, tableHeaderHeight) tableHeaderView.backgroundColor = UIColor.defaultRedColor() view.addSubview(tableHeaderView) dispatch_async(realmQueue) { if let categoryType = self.categoryType { switch categoryType { case .DOWNLOADED: self.category = DefaultCategory.DOWNLOADED.category case .LATEST: self.category = DefaultCategory.LATEST.category case .FAVOURITE: self.category = DefaultCategory.FAVOURITE.category case .SEARCH: self.category = DefaultCategory.SEARCH.category default: self.category = DefaultCategory.CURRENT.category } dispatch_async(dispatch_get_main_queue(), { self.tableView.reloadData() }) } } } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) navigationController?.navigationBar.subviews[0].alpha = 0 navigationController?.navigationBar.translucent = true } // MARK: - EventMethods // MARK: - 弹出操作视图 @objc func showPopView(sender: UIButton) { let choices = ["下一首播放","收藏到歌单","删除","分享","歌手","专辑"] popWindow = Pop(choices: choices) popWindow?.tag = sender.tag popWindow?.delegate = self popWindow?.popFromBottomInViewController() } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return category.songs.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("ListCell", forIndexPath: indexPath) as! MusicCell let song = category.songs[indexPath.row] cell.songNameLabel.textColor = UIColor.defaultBlackColor() cell.singerNameLabel.textColor = UIColor.defaultBlackColor() cell.songNameLabel.text = song.songName cell.singerNameLabel.text = song.singerName // 记录歌曲的tag,以便后续的详情操作 cell.detailButton.tag = indexPath.row cell.detailButton.addTarget(self, action: #selector(SongListViewController.showPopView(_:)), forControlEvents: .TouchUpInside) return cell } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { defer { tableView.deselectRowAtIndexPath(indexPath, animated: true) } let song = category.songs[indexPath.row] category.currentSonglist = category.songs switch gStorage.cycleMode { case .RANDOM: category.currentSonglist = PlayerManager.getRandomListWithCategory(category) default: break } (self.tabBarController as! HYTabBarController).showPlayerViewControllerWithSong(song, inCategory: category) } override func scrollViewDidScroll(scrollView: UIScrollView) { let contentOffY = scrollView.contentOffset.y if contentOffY >= 0 { let alpha = contentOffY / tableView.tableHeaderView!.bounds.height navigationController?.navigationBar.subviews[0].alpha = alpha } else { tableView.tableHeaderView?.frame = CGRectMake(0, contentOffY, tableView.tableHeaderView!.bounds.width, tableHeaderHeight - contentOffY) } } /* // 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. } */ } extension SongListViewController : PopViewDelegate { func popView(popView: Pop, didSelectItemAtIndex index: Int) { popView.dismiss() switch index { case 2: let song = category.songs[popView.tag] if let localInfo = song.localInfo { if let realm = try? Realm() { deleteSong(song, inRealm: realm) } NSFileManager.deleteSongFileWithName(String(song.songID), andExtension: localInfo.suffix) Alert.showMiddleHint("删除成功") category.songs.removeAtIndex(popView.tag) tableView.reloadData() } default: break } } }
gpl-3.0
898f2b86327ad6cd935dcb75c06415a5
31.243243
147
0.599329
5.606203
false
false
false
false
Johennes/firefox-ios
XCUITests/ThirdPartySearchTest.swift
1
4937
/* 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 XCTest class ThirdPartySearchTest: BaseTestCase { override func setUp() { super.setUp() } override func tearDown() { super.tearDown() } private func dismissKeyboardAssistant(forApp app: XCUIApplication) { if app.buttons["Done"].exists { // iPhone app.buttons["Done"].tap() } else { // iPad app.buttons["Dismiss"].tap() } } func testCustomSearchEngines() { let app = XCUIApplication() // Visit MDN to add a custom search engine loadWebPage("https://developer.mozilla.org/en-US/search", waitForLoadToFinish: true) app.webViews.searchFields.elementBoundByIndex(0).tap() app.buttons["AddSearch"].tap() app.alerts["Add Search Provider?"].buttons["OK"].tap() XCTAssertFalse(app.buttons["AddSearch"].enabled) dismissKeyboardAssistant(forApp: app) // Perform a search using a custom search engine tabTrayButton(forApp: app).tap() app.buttons["TabTrayController.addTabButton"].tap() app.textFields["url"].tap() app.typeText("window") app.scrollViews.otherElements.buttons["developer.mozilla.org search"].tap() // Ensure that the search is done on MDN let url = app.textFields["url"].value as! String XCTAssert(url.hasPrefix("https://developer.mozilla.org/en-US/search"), "The URL should indicate that the search was performed on MDN and not the default") } func testCustomSearchEngineAsDefault() { let app = XCUIApplication() // Visit MDN to add a custom search engine loadWebPage("https://developer.mozilla.org/en-US/search", waitForLoadToFinish: true) app.webViews.searchFields.elementBoundByIndex(0).tap() app.buttons["AddSearch"].tap() app.alerts["Add Search Provider?"].buttons["OK"].tap() XCTAssertFalse(app.buttons["AddSearch"].enabled) dismissKeyboardAssistant(forApp: app) // Go to settings and set MDN as the default tabTrayButton(forApp: app).tap() app.buttons["TabTrayController.menuButton"].tap() app.collectionViews.cells["Settings"].tap() let tablesQuery = app.tables tablesQuery.cells["Search"].tap() tablesQuery.cells.elementBoundByIndex(0).tap() tablesQuery.staticTexts["developer.mozilla.org"].tap() app.navigationBars["Search"].buttons["Settings"].tap() app.navigationBars["Settings"].buttons["AppSettingsTableViewController.navigationItem.leftBarButtonItem"].tap() // Perform a search to check app.buttons["TabTrayController.addTabButton"].tap() app.textFields["url"].tap() app.typeText("window\r") // Ensure that the default search is MDN let url = app.textFields["url"].value as! String XCTAssert(url.hasPrefix("https://developer.mozilla.org/en-US/search"), "The URL should indicate that the search was performed on MDN and not the default") } func testCustomSearchEngineDeletion() { let app = XCUIApplication() // Visit MDN to add a custom search engine loadWebPage("https://developer.mozilla.org/en-US/search", waitForLoadToFinish: true) app.webViews.searchFields.elementBoundByIndex(0).tap() app.buttons["AddSearch"].tap() app.alerts["Add Search Provider?"].buttons["OK"].tap() XCTAssertFalse(app.buttons["AddSearch"].enabled) dismissKeyboardAssistant(forApp: app) let tabTrayButton = self.tabTrayButton(forApp: app) tabTrayButton.tap() app.buttons["TabTrayController.addTabButton"].tap() app.textFields["url"].tap() app.typeText("window") XCTAssert(app.scrollViews.otherElements.buttons["developer.mozilla.org search"].exists) app.typeText("\r") // Go to settings and set MDN as the default tabTrayButton.tap(force: true) app.buttons["TabTrayController.menuButton"].tap() app.collectionViews.cells["Settings"].tap() let tablesQuery = app.tables tablesQuery.cells["Search"].tap() app.navigationBars["Search"].buttons["Edit"].tap() tablesQuery.buttons["Delete developer.mozilla.org"].tap() tablesQuery.buttons["Delete"].tap() app.navigationBars["Search"].buttons["Settings"].tap() app.navigationBars["Settings"].buttons["AppSettingsTableViewController.navigationItem.leftBarButtonItem"].tap() // Perform a search to check app.textFields["url"].tap() app.typeText("window") XCTAssertFalse(app.scrollViews.otherElements.buttons["developer.mozilla.org search"].exists) } }
mpl-2.0
f4e223a9d0dd5c8b4ff54fccf230ca6b
38.18254
162
0.656877
4.797862
false
false
false
false
3squared/ios-charts
Charts/Classes/Utils/ChartUtils.swift
1
7242
// // Utils.swift // Charts // // Created by Daniel Cohen Gindi on 23/2/15. // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/ios-charts // import Foundation import UIKit import Darwin internal class ChartUtils { internal struct Math { internal static let FDEG2RAD = CGFloat(M_PI / 180.0) internal static let FRAD2DEG = CGFloat(180.0 / M_PI) internal static let DEG2RAD = M_PI / 180.0 internal static let RAD2DEG = 180.0 / M_PI } internal class func roundToNextSignificant(number number: Double) -> Double { if (isinf(number) || isnan(number) || number == 0) { return number } let d = ceil(log10(number < 0.0 ? -number : number)) let pw = 1 - Int(d) let magnitude = pow(Double(10.0), Double(pw)) let shifted = round(number * magnitude) return shifted / magnitude } internal class func decimals(number: Double) -> Int { if (number == 0.0) { return 0 } let i = roundToNextSignificant(number: Double(number)) return Int(ceil(-log10(i))) + 2 } internal class func nextUp(number: Double) -> Double { if (isinf(number) || isnan(number)) { return number } else { return number + DBL_EPSILON } } /// - returns: the index of the DataSet that contains the closest value on the y-axis. This will return -Integer.MAX_VALUE if failure. internal class func closestDataSetIndex(valsAtIndex: [ChartSelectionDetail], value: Double, axis: ChartYAxis.AxisDependency?) -> Int { var index = -Int.max var distance = DBL_MAX for (var i = 0; i < valsAtIndex.count; i++) { let sel = valsAtIndex[i] if (axis == nil || sel.dataSet?.axisDependency == axis) { let cdistance = abs(sel.value - value) if (cdistance < distance) { index = valsAtIndex[i].dataSetIndex distance = cdistance } } } return index } /// - returns: the minimum distance from a touch-y-value (in pixels) to the closest y-value (in pixels) that is displayed in the chart. internal class func getMinimumDistance(valsAtIndex: [ChartSelectionDetail], val: Double, axis: ChartYAxis.AxisDependency) -> Double { var distance = DBL_MAX for (var i = 0, count = valsAtIndex.count; i < count; i++) { let sel = valsAtIndex[i] if (sel.dataSet!.axisDependency == axis) { let cdistance = abs(sel.value - val) if (cdistance < distance) { distance = cdistance } } } return distance } /// Calculates the position around a center point, depending on the distance from the center, and the angle of the position around the center. internal class func getPosition(center center: CGPoint, dist: CGFloat, angle: CGFloat) -> CGPoint { return CGPoint( x: center.x + dist * cos(angle * Math.FDEG2RAD), y: center.y + dist * sin(angle * Math.FDEG2RAD) ) } internal class func drawImage(context context: CGContext?, image: UIImage, point: CGPoint) { UIGraphicsPushContext(context) image.drawAtPoint(point) UIGraphicsPopContext() } internal class func drawText(context context: CGContext?, text: String, var point: CGPoint, align: NSTextAlignment, attributes: [String : AnyObject]?) { if (align == .Center) { point.x -= text.sizeWithAttributes(attributes).width / 2.0 } else if (align == .Right) { point.x -= text.sizeWithAttributes(attributes).width } UIGraphicsPushContext(context) (text as NSString).drawAtPoint(point, withAttributes: attributes) UIGraphicsPopContext() } internal class func drawMultilineText(context context: CGContext?, text: String, knownTextSize: CGSize, point: CGPoint, align: NSTextAlignment, attributes: [String : AnyObject]?, constrainedToSize: CGSize) { var rect = CGRect(origin: CGPoint(), size: knownTextSize) rect.origin.x += point.x rect.origin.y += point.y if (align == .Center) { rect.origin.x -= rect.size.width / 2.0 } else if (align == .Right) { rect.origin.x -= rect.size.width } UIGraphicsPushContext(context) (text as NSString).drawWithRect(rect, options: .UsesLineFragmentOrigin, attributes: attributes, context: nil) UIGraphicsPopContext() } internal class func drawMultilineText(context context: CGContext?, text: String, point: CGPoint, align: NSTextAlignment, attributes: [String : AnyObject]?, constrainedToSize: CGSize) { let rect = text.boundingRectWithSize(constrainedToSize, options: .UsesLineFragmentOrigin, attributes: attributes, context: nil) drawMultilineText(context: context, text: text, knownTextSize: rect.size, point: point, align: align, attributes: attributes, constrainedToSize: constrainedToSize) } /// - returns: an angle between 0.0 < 360.0 (not less than zero, less than 360) internal class func normalizedAngleFromAngle(var angle: CGFloat) -> CGFloat { while (angle < 0.0) { angle += 360.0 } return angle % 360.0 } /// MARK: - Bridging functions internal class func bridgedObjCGetUIColorArray (swift array: [UIColor?]) -> [NSObject] { var newArray = [NSObject]() for val in array { if (val == nil) { newArray.append(NSNull()) } else { newArray.append(val!) } } return newArray } internal class func bridgedObjCGetUIColorArray (objc array: [NSObject]) -> [UIColor?] { var newArray = [UIColor?]() for object in array { newArray.append(object as? UIColor) } return newArray } internal class func bridgedObjCGetStringArray (swift array: [String?]) -> [NSObject] { var newArray = [NSObject]() for val in array { if (val == nil) { newArray.append(NSNull()) } else { newArray.append(val!) } } return newArray } internal class func bridgedObjCGetStringArray (objc array: [NSObject]) -> [String?] { var newArray = [String?]() for object in array { newArray.append(object as? String) } return newArray } }
apache-2.0
540498b125868285772417bab2f1b0ec
29.561181
209
0.558271
4.764474
false
false
false
false
pepaslabs/RxViewLifeCycleDemultiplexer
RxViewLifeCycleDemultiplexer.swift
1
7739
// // RxViewLifeCycleDemultiplexer.swift // See https://github.com/pepaslabs/RxViewLifeCycleDemultiplexer // // Created by Jason Pepas on 11/29/15. // Copyright © 2015 Jason Pepas. All rights reserved. // // Released under the terms of the MIT License. // See https://opensource.org/licenses/MIT import UIKit class RxViewLifeCycleDemultiplexer: ViewLifeCycleDemultiplexer, ModalViewLifeCycleProtocol, NavigationViewLifeCycleProtocol { var rx_viewWillAppear: Observable<Bool> { return _viewWillAppearSubject.asObservable() } var rx_viewDidAppear: Observable<Bool> { return _viewDidAppearSubject.asObservable() } var rx_viewWillDisappear: Observable<Bool> { return _viewWillDisappearSubject.asObservable() } var rx_viewDidDisappear: Observable<Bool> { return _viewDidDisappearSubject.asObservable() } // MARK: - ModalViewLifeCycleProtocol observables var rx_viewWillGetPresented: Observable<Bool> { return _viewWillGetPresentedSubject.asObservable() } var rx_viewDidGetPresented: Observable<Bool> { return _viewDidGetPresentedSubject.asObservable() } var rx_viewWillGetDismissed: Observable<Bool> { return _viewWillGetDismissedSubject.asObservable() } var rx_viewDidGetDismissed: Observable<Bool> { return _viewDidGetDismissedSubject.asObservable() } var rx_viewWillDisappearBeneathModal: Observable<Bool> { return _viewWillDisappearBeneathModalSubject.asObservable() } var rx_viewDidDisappearBeneathModal: Observable<Bool> { return _viewDidDisappearBeneathModalSubject.asObservable() } var rx_viewWillReappearFromBeneathModal: Observable<Bool> { return _viewWillReappearFromBeneathModalSubject.asObservable() } var rx_viewDidReappearFromBeneathModal: Observable<Bool> { return _viewDidReappearFromBeneathModalSubject.asObservable() } // MARK: - NavigationViewLifeCycleProtocol observables var rx_viewWillGetPushed: Observable<Bool> { return _viewWillGetPushedSubject.asObservable() } var rx_viewDidGetPushed: Observable<Bool> { return _viewDidGetPushedSubject.asObservable() } var rx_viewWillGetPopped: Observable<Bool> { return _viewWillGetPoppedSubject.asObservable() } var rx_viewDidGetPopped: Observable<Bool> { return _viewDidGetPoppedSubject.asObservable() } var rx_viewWillDisappearBeneathNavStack: Observable<Bool> { return _viewWillDisappearBeneathNavStackSubject.asObservable() } var rx_viewDidDisappearBeneathNavStack: Observable<Bool> { return _viewDidDisappearBeneathNavStackSubject.asObservable() } var rx_viewWillReappearFromBeneathNavStack: Observable<Bool> { return _viewWillReappearFromBeneathNavStackSubject.asObservable() } var rx_viewDidReappearFromBeneathNavStack: Observable<Bool> { return _viewDidReappearFromBeneathNavStackSubject.asObservable() } init() { super.init(modalDelegate: nil, navDelegate: nil) modalDelegate = self navDelegate = self } private let _viewWillAppearSubject = PublishSubject<Bool>() private let _viewDidAppearSubject = PublishSubject<Bool>() private let _viewWillDisappearSubject = PublishSubject<Bool>() private let _viewDidDisappearSubject = PublishSubject<Bool>() private let _viewWillGetPresentedSubject = PublishSubject<Bool>() private let _viewDidGetPresentedSubject = PublishSubject<Bool>() private let _viewWillGetDismissedSubject = PublishSubject<Bool>() private let _viewDidGetDismissedSubject = PublishSubject<Bool>() private let _viewWillDisappearBeneathModalSubject = PublishSubject<Bool>() private let _viewDidDisappearBeneathModalSubject = PublishSubject<Bool>() private let _viewWillReappearFromBeneathModalSubject = PublishSubject<Bool>() private let _viewDidReappearFromBeneathModalSubject = PublishSubject<Bool>() private let _viewWillGetPushedSubject = PublishSubject<Bool>() private let _viewDidGetPushedSubject = PublishSubject<Bool>() private let _viewWillGetPoppedSubject = PublishSubject<Bool>() private let _viewDidGetPoppedSubject = PublishSubject<Bool>() private let _viewWillDisappearBeneathNavStackSubject = PublishSubject<Bool>() private let _viewDidDisappearBeneathNavStackSubject = PublishSubject<Bool>() private let _viewWillReappearFromBeneathNavStackSubject = PublishSubject<Bool>() private let _viewDidReappearFromBeneathNavStackSubject = PublishSubject<Bool>() override func viewWillAppear(viewController vc: UIViewController, animated: Bool) { super.viewWillAppear(viewController: vc, animated: animated) _viewWillAppearSubject.on(.Next(animated)) } override func viewDidAppear(viewController vc: UIViewController, animated: Bool) { super.viewDidAppear(viewController: vc, animated: animated) _viewDidAppearSubject.on(.Next(animated)) } override func viewWillDisappear(viewController vc: UIViewController, animated: Bool) { super.viewWillDisappear(viewController: vc, animated: animated) _viewWillDisappearSubject.on(.Next(animated)) } override func viewDidDisappear(viewController vc: UIViewController, animated: Bool) { super.viewDidDisappear(viewController: vc, animated: animated) _viewDidDisappearSubject.on(.Next(animated)) } // MARK: - ModalViewLifeCycleProtocol func viewWillGetPresented(animated: Bool) { _viewWillGetPresentedSubject.on(.Next(animated)) } func viewDidGetPresented(animated: Bool) { _viewDidGetPresentedSubject.on(.Next(animated)) } func viewWillGetDismissed(animated: Bool) { _viewWillGetDismissedSubject.on(.Next(animated)) } func viewDidGetDismissed(animated: Bool) { _viewDidGetDismissedSubject.on(.Next(animated)) } func viewWillDisappearBeneathModal(animated: Bool) { _viewWillDisappearBeneathModalSubject.on(.Next(animated)) } func viewDidDisappearBeneathModal(animated: Bool) { _viewDidDisappearBeneathModalSubject.on(.Next(animated)) } func viewWillReappearFromBeneathModal(animated: Bool) { _viewWillReappearFromBeneathModalSubject.on(.Next(animated)) } func viewDidReappearFromBeneathModal(animated: Bool) { _viewDidReappearFromBeneathModalSubject.on(.Next(animated)) } // MARK: - NavigationViewLifeCycleProtocol func viewWillGetPushed(animated: Bool) { _viewWillGetPushedSubject.on(.Next(animated)) } func viewDidGetPushed(animated: Bool) { _viewDidGetPushedSubject.on(.Next(animated)) } func viewWillGetPopped(animated: Bool) { _viewWillGetPoppedSubject.on(.Next(animated)) } func viewDidGetPopped(animated: Bool) { _viewDidGetPoppedSubject.on(.Next(animated)) } func viewWillDisappearBeneathNavStack(animated: Bool) { _viewWillDisappearBeneathNavStackSubject.on(.Next(animated)) } func viewDidDisappearBeneathNavStack(animated: Bool) { _viewDidDisappearBeneathNavStackSubject.on(.Next(animated)) } func viewWillReappearFromBeneathNavStack(animated: Bool) { _viewWillReappearFromBeneathNavStackSubject.on(.Next(animated)) } func viewDidReappearFromBeneathNavStack(animated: Bool) { _viewDidReappearFromBeneathNavStackSubject.on(.Next(animated)) } }
mit
4510e8b347bae783c97baf31ebed2761
32.353448
123
0.716464
5.53505
false
false
false
false
gtranchedone/FlickrParty
FlickrParty/Networking/APIClient.swift
1
1863
// // APIClient.swift // FlickrParty // // Created by Gianluca Tranchedone on 04/05/2015. // Copyright (c) 2015 Gianluca Tranchedone. All rights reserved. // import UIKit import Alamofire import CoreLocation public protocol APIRequest { func responseJSON(options options: NSJSONReadingOptions, completionHandler: Response<AnyObject, NSError> -> Void) -> Self } public protocol APIRequestManager { func makeRequest(method: Alamofire.Method, _ URLString: URLStringConvertible, parameters: [String : AnyObject]?, encoding: ParameterEncoding, headers: [String : String]?) -> APIRequest } public struct APIResponseMetadata: Equatable { public let page: Int public let itemsPerPage: Int public let numberOfPages: Int public init(page: Int, itemsPerPage: Int, numberOfPages: Int) { self.page = page self.itemsPerPage = itemsPerPage self.numberOfPages = numberOfPages } } public func ==(lhs: APIResponseMetadata, rhs: APIResponseMetadata) -> Bool { return (lhs.page == rhs.page && lhs.numberOfPages == rhs.numberOfPages && lhs.itemsPerPage == rhs.itemsPerPage) } public struct APIResponse { public let metadata: APIResponseMetadata? public let responseObject: AnyObject? public init(metadata: APIResponseMetadata?, responseObject: AnyObject?) { self.metadata = metadata self.responseObject = responseObject } } public typealias APIClientCompletionBlock = (response: APIResponse?, error: NSError?) -> () public protocol APIClient { var parser: PhotoParser { get set } func fetchPhotosWithTags(tags: [String], page: Int, completionBlock: APIClientCompletionBlock) func fetchPhotosWithTags(tags: [String], location: CLLocationCoordinate2D?, page: Int, completionBlock: APIClientCompletionBlock) }
mit
e5832b7ad6db68e19c2ad96d9779b6c8
28.109375
188
0.712829
4.789203
false
false
false
false
miguelgutierrez/Curso-iOS-Swift-Programming-Netmind
newsApp 1.9/newsApp/LocalizacionViewController.swift
2
4376
// // LocalizacionViewController.swift // newsApp // // Created by Miguel Gutiérrez Moreno on 2/2/15. // Copyright (c) 2015 MGM. All rights reserved. // // Uso de CoreLocation : http://nevan.net/2014/09/core-location-manager-changes-in-ios-8/ import UIKit import MapKit class LocalizacionViewController: UIViewController, MKMapViewDelegate, CLLocationManagerDelegate { struct MainStoryboard { struct PinIdentifiers { static let pinMapa = "pinMapa" } } // MARK: - properties @IBOutlet weak var mapaMapView: MKMapView! var locationManager = CLLocationManager() // MARK: - ciclo de vida del controller 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() locationManager.delegate = self locationManager.distanceFilter = kCLLocationAccuracyHundredMeters locationManager.desiredAccuracy = kCLLocationAccuracyBest } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) refreshLocation() cargarAnotaciones() } // MARK: - MKMapViewDelegate func mapView(mapView: MKMapView, viewForAnnotation annotation: MKAnnotation) -> MKAnnotationView? { if let annotation = annotation as? Anotacion { var pin : MKPinAnnotationView! if let pinMapa = mapaMapView.dequeueReusableAnnotationViewWithIdentifier(MainStoryboard.PinIdentifiers.pinMapa) { pin = pinMapa as! MKPinAnnotationView pin.annotation = annotation } else { pin = MKPinAnnotationView(annotation: annotation, reuseIdentifier: MainStoryboard.PinIdentifiers.pinMapa) } pin.pinColor = MKPinAnnotationColor.Red pin.canShowCallout = true pin.animatesDrop = false return pin } else { return nil } } // MARK: - CLLocationManagerDelegate func locationManager(manager: CLLocationManager, didUpdateToLocation newLocation: CLLocation, fromLocation oldLocation: CLLocation) { let userLocation = MKCoordinateRegionMakeWithDistance( newLocation.coordinate, 5000.0,5000.0) locationManager.stopUpdatingLocation() mapaMapView.setRegion(userLocation, animated: true) } // el usuario ha dado permiso para poder localizar func locationManager(manager: CLLocationManager, didChangeAuthorizationStatus status: CLAuthorizationStatus) { if (CLLocationManager.authorizationStatus() == CLAuthorizationStatus.AuthorizedAlways || CLLocationManager.authorizationStatus() == CLAuthorizationStatus.AuthorizedWhenInUse ) { showLocation() } } // MARK: - funciones auxiliares private func refreshLocation() { if (CLLocationManager.authorizationStatus() == CLAuthorizationStatus.AuthorizedAlways || CLLocationManager.authorizationStatus() == CLAuthorizationStatus.AuthorizedWhenInUse ) { showLocation() } else { // ** Don't forget to add NSLocationWhenInUseUsageDescription in MyApp-Info.plist and give it a string // Check for iOS 8. Without this guard the code will crash with "unknown selector" on iOS 7. if locationManager.respondsToSelector("requestWhenInUseAuthorization"){ locationManager.requestWhenInUseAuthorization() } } } private func showLocation(){ mapaMapView.showsUserLocation = true locationManager.startUpdatingLocation() } private func cargarAnotaciones(){ mapaMapView.addAnnotation(Anotacion(coordenada: CLLocationCoordinate2D(latitude: 40.40349, longitude: -3.71441))) } }
mit
9fc31683c8ea433a5ab4a8af85ec7904
35.764706
137
0.660571
5.936228
false
false
false
false
runr/BreadMaker
BreadMaker.playground/Pages/14 - Divide.xcplaygroundpage/Contents.swift
2
1928
//: [Previous](@previous) import Interstellar struct Dough { let yield: Double var mixed = false var autolyseCompleted = false init(yield: Double) { self.yield = yield } mutating func mix() { self.mixed = true } mutating func autolyse() { self.autolyseCompleted = true } } //: A loaf of bread. No mutating functions as yet, let's see if we can keep it that way struct Loaf { let weight: Double init(weight: Double) { self.weight = weight } } enum BakeError: ErrorType { case MixingError case AutolyseError case DivideError } struct BreadMaker { //: The signature changes to return an array of loaves func makeBread(completion: Result<[Loaf]> -> Void) -> Void { print("Making bread") let dough = Dough(yield: 1700) Signal(dough) .flatMap(mix) .flatMap(autolyse) .flatMap(divide) .subscribe { result in completion(result) } } private func mix(var dough: Dough) -> Result<Dough> { print("Mix") dough.mix() return dough.mixed ? .Success(dough) : .Error(BakeError.MixingError) } private func autolyse(var dough: Dough) -> Result<Dough> { print("Autolyse") dough.autolyse() return dough.autolyseCompleted ? .Success(dough) : .Error(BakeError.AutolyseError) } private func divide(dough: Dough) -> Result<[Loaf]> { print("Divide") let loaves = [Loaf(weight: dough.yield / 2), Loaf(weight: dough.yield / 2)] //: This cannot possibly go wrong return .Success(loaves) } } BreadMaker().makeBread { result in switch result { case .Success: print("Yeah! Got bread: \(result.value!)") break case .Error: print("Error, no bread!!") } } //: [Next](@next)
mit
df086d5dfbeb4c7f999230dbcb80fe38
21.418605
90
0.575726
3.967078
false
false
false
false
Thongpak21/NongBeer-MVVM-iOS-Demo
NongBeer/Classes/ConfirmDestination/ViewController/ConfirmDestinationViewController.swift
1
2438
// // ConfirmDestinationViewController.swift // NongBeer // // Created by Thongpak on 4/9/2560 BE. // Copyright © 2560 Thongpak. All rights reserved. // import UIKit import GoogleMaps import CoreLocation class ConfirmDestinationViewController: BaseViewController, GMSMapViewDelegate { @IBOutlet weak var markerView: UIImageView! @IBOutlet weak var confirmDesButton: BaseButton! var orderList = [BeerModel]() var position: CLLocationCoordinate2D? weak var delegate: OrderSuccessViewControllerDelegate? var viewModel: ConfirmDestinationViewModel! override func viewDidLoad() { super.viewDidLoad() self.setNavigationButton() self.confirmDesButton.addTarget(self, action: #selector(orderSuccess), for: .touchUpInside) self.confirmDesButton.setButtonNormal() setNavigationBarProperties() viewModel = ConfirmDestinationViewModel(delegate: self) } func orderSuccess() { let mapOrder = self.orderList.map({ ["id": $0.id!, "amount": $0.amount] }) self.viewModel.requestOrderService(order: mapOrder, location: position!) } override func onDataDidLoad() { let storyboard = UIStoryboard(name: "Main", bundle: nil) let vc = storyboard.instantiateVC(OrderSuccessViewController.self) vc?.delegate = delegate self.pushVC(vc!) } func setNavigationBarProperties() { self.navigationBarColor = UIColor(hexString: "FFBC00") } func setNavigationButton() { self.navigationItem.leftBarButtonItem?.target = self self.navigationItem.leftBarButtonItem?.action = #selector(didTabBackNavigation) } func didTabBackNavigation() { dismissVC(completion: nil) } override func loadView() { super.loadView() let camera = GMSCameraPosition.camera(withLatitude: 13.7453729, longitude: 100.5348983, zoom: 15) var frame = self.view.bounds frame.h = frame.h - 60 let mapView = GMSMapView.map(withFrame: frame, camera: camera) mapView.settings.myLocationButton = true mapView.isMyLocationEnabled = true mapView.delegate = self self.view.addSubview(mapView) self.view.addSubview(markerView) } func mapView(_ mapView: GMSMapView, idleAt position: GMSCameraPosition) { print(position.target) self.position = position.target } }
apache-2.0
853be7f75b3f98bd1388b529f980470d
32.847222
105
0.682807
4.686538
false
false
false
false
pennlabs/penn-mobile-ios
PennMobile/Course Alerts/Controllers/CourseAlertCreateController.swift
1
13041
// // CourseAlertCreateController.swift // PennMobile // // Created by Raunaq Singh on 10/25/20. // Copyright © 2020 PennLabs. All rights reserved. // import UIKit import Foundation protocol FetchPCADataProtocol { func fetchAlerts() func fetchSettings() } class CourseAlertCreateController: GenericViewController, IndicatorEnabled { fileprivate var searchBar = UISearchBar() fileprivate var alertTypeView: UIView! fileprivate var alertTypeSeparator: UIView! fileprivate var switchLabel: UILabel! fileprivate var alertSwitcher: UISegmentedControl! fileprivate var navBar: UINavigationBar! fileprivate var searchPromptView: UIView! fileprivate var noResultsView: UIView! fileprivate var searchResults: [CourseSection] = [] fileprivate var resultsTableView = UITableView() fileprivate var mostRecentSearch: String = "" var delegate: FetchPCADataProtocol? override func viewDidLoad() { super.viewDidLoad() setupUI() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) } } // MARK: - Setup UI extension CourseAlertCreateController { fileprivate func setupUI() { setupCustomNavBar() setupSearchBar() setupAlertType() setupResultsTableView() setupAlertTypeSeparator() setupSearchPromptView() setupNoSearchResultsView() } fileprivate func setupCustomNavBar() { navBar = UINavigationBar(frame: CGRect(x: 0, y: 0, width: view.frame.size.width, height: 54)) view.addSubview(navBar) let navItem = UINavigationItem(title: "Create Alert") navItem.leftBarButtonItem = UIBarButtonItem(title: "Cancel", style: .done, target: self, action: #selector(handleCancel)) navBar.setItems([navItem], animated: false) } fileprivate func setupSearchBar() { searchBar.delegate = self searchBar.placeholder = "Ex. ECON 001" searchBar.returnKeyType = .search searchBar.autocapitalizationType = .allCharacters searchBar.autocorrectionType = .no searchBar.keyboardType = .asciiCapable view.addSubview(searchBar) searchBar.translatesAutoresizingMaskIntoConstraints = false searchBar.topAnchor.constraint(equalTo: navBar.bottomAnchor, constant: 0).isActive = true searchBar.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true searchBar.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true searchBar.heightAnchor.constraint(equalToConstant: 60).isActive = true } fileprivate func setupAlertType() { switchLabel = UILabel() switchLabel.text = "Alert me:" switchLabel.font = UIFont.systemFont(ofSize: 16, weight: .regular) switchLabel.textColor = .labelSecondary switchLabel.textAlignment = .left switchLabel.numberOfLines = 0 switchLabel.sizeToFit() alertSwitcher = UISegmentedControl(items: ["Once", "Until I cancel"]) alertSwitcher.tintColor = UIColor.navigation alertSwitcher.selectedSegmentIndex = 0 alertSwitcher.isUserInteractionEnabled = true alertTypeView = UIView() alertTypeView.addSubview(switchLabel) alertTypeView.addSubview(alertSwitcher) switchLabel.translatesAutoresizingMaskIntoConstraints = false switchLabel.leadingAnchor.constraint(equalTo: alertTypeView.leadingAnchor, constant: 0).isActive = true switchLabel.centerYAnchor.constraint(equalTo: alertTypeView.centerYAnchor).isActive = true alertSwitcher.translatesAutoresizingMaskIntoConstraints = false alertSwitcher.leadingAnchor.constraint(equalTo: switchLabel.trailingAnchor, constant: 10).isActive = true alertSwitcher.centerYAnchor.constraint(equalTo: alertTypeView.centerYAnchor).isActive = true view.addSubview(alertTypeView) alertTypeView.translatesAutoresizingMaskIntoConstraints = false alertTypeView.topAnchor.constraint(equalTo: searchBar.bottomAnchor, constant: 0).isActive = true alertTypeView.centerXAnchor.constraint(equalTo: view.centerXAnchor, constant: 0).isActive = true alertTypeView.widthAnchor.constraint(equalToConstant: switchLabel.frame.size.width + alertSwitcher.frame.size.width + 10).isActive = true alertTypeView.heightAnchor.constraint(equalToConstant: alertSwitcher.frame.size.height + 22).isActive = true } fileprivate func setupResultsTableView() { resultsTableView.delegate = self resultsTableView.dataSource = self resultsTableView.keyboardDismissMode = .onDrag resultsTableView.register(SearchResultsCell.self, forCellReuseIdentifier: SearchResultsCell.identifier) view.addSubview(resultsTableView) resultsTableView.translatesAutoresizingMaskIntoConstraints = false resultsTableView.topAnchor.constraint(equalTo: alertTypeView.bottomAnchor, constant: 0).isActive = true resultsTableView.leftAnchor.constraint(equalTo: view.leftAnchor, constant: 0).isActive = true resultsTableView.rightAnchor.constraint(equalTo: view.rightAnchor, constant: 0).isActive = true resultsTableView.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: 0).isActive = true } fileprivate func setupAlertTypeSeparator() { alertTypeSeparator = UIView() alertTypeSeparator.backgroundColor = .grey5 view.addSubview(alertTypeSeparator) alertTypeSeparator.translatesAutoresizingMaskIntoConstraints = false alertTypeSeparator.centerXAnchor.constraint(equalTo: view.centerXAnchor, constant: 0).isActive = true alertTypeSeparator.widthAnchor.constraint(equalToConstant: view.frame.size.width).isActive = true alertTypeSeparator.heightAnchor.constraint(equalToConstant: 1).isActive = true alertTypeSeparator.topAnchor.constraint(equalTo: resultsTableView.topAnchor, constant: 0).isActive = true } fileprivate func setupSearchPromptView() { searchPromptView = UIView() let searchLabel = UILabel() searchLabel.text = "Search courses for the current semester." searchLabel.font = UIFont.avenirMedium searchLabel.textColor = .lightGray searchLabel.textAlignment = .center searchLabel.numberOfLines = 0 searchLabel.sizeToFit() searchPromptView.addSubview(searchLabel) searchLabel.translatesAutoresizingMaskIntoConstraints = false searchLabel.centerXAnchor.constraint(equalTo: searchPromptView.centerXAnchor, constant: 0).isActive = true searchLabel.centerYAnchor.constraint(equalTo: searchPromptView.centerYAnchor, constant: -150).isActive = true searchLabel.widthAnchor.constraint(equalTo: searchPromptView.widthAnchor, multiplier: 0.9).isActive = true view.addSubview(searchPromptView) searchPromptView.translatesAutoresizingMaskIntoConstraints = false searchPromptView.topAnchor.constraint(equalTo: alertTypeView.bottomAnchor, constant: 1).isActive = true searchPromptView.leftAnchor.constraint(equalTo: view.leftAnchor, constant: 0).isActive = true searchPromptView.rightAnchor.constraint(equalTo: view.rightAnchor, constant: 0).isActive = true searchPromptView.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: 0).isActive = true } fileprivate func setupNoSearchResultsView() { noResultsView = UIView() let searchLabel = UILabel() searchLabel.text = "No results found." searchLabel.font = UIFont.avenirMedium searchLabel.textColor = .lightGray searchLabel.textAlignment = .center searchLabel.numberOfLines = 0 searchLabel.sizeToFit() noResultsView.addSubview(searchLabel) searchLabel.translatesAutoresizingMaskIntoConstraints = false searchLabel.centerXAnchor.constraint(equalTo: noResultsView.centerXAnchor, constant: 0).isActive = true searchLabel.centerYAnchor.constraint(equalTo: noResultsView.centerYAnchor, constant: -150).isActive = true searchLabel.widthAnchor.constraint(equalTo: noResultsView.widthAnchor, multiplier: 0.9).isActive = true view.addSubview(noResultsView) noResultsView.translatesAutoresizingMaskIntoConstraints = false noResultsView.topAnchor.constraint(equalTo: alertTypeView.bottomAnchor, constant: 1).isActive = true noResultsView.leftAnchor.constraint(equalTo: view.leftAnchor, constant: 0).isActive = true noResultsView.rightAnchor.constraint(equalTo: view.rightAnchor, constant: 0).isActive = true noResultsView.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: 0).isActive = true noResultsView.isHidden = true } } // MARK: - Event Handlers extension CourseAlertCreateController: ShowsAlert { @objc fileprivate func handleCancel() { dismiss(animated: true, completion: nil) } fileprivate func confirmAlert(section: CourseSection) { var message = "Create a one-time alert for " + section.section + "?" if alertSwitcher.selectedSegmentIndex == 1 { message = "Create a repeated alert for " + section.section + "? This will repeat until the end of the semester." } self.showOption(withMsg: message, title: "Confirm New Alert", onAccept: { CourseAlertNetworkManager.instance.createRegistration(section: section.section, autoResubscribe: (self.alertSwitcher.selectedSegmentIndex == 1), callback: {(success, response, _) in DispatchQueue.main.async { if success { self.showAlert(withMsg: response, title: "Success!", completion: self.handleCancel) self.delegate?.fetchAlerts() } else if !response.isEmpty { self.showAlert(withMsg: response, title: "Uh-Oh!", completion: nil) } } }) }, onCancel: nil) } } // MARK: - TableView Functions extension CourseAlertCreateController: UITableViewDelegate, UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return searchResults.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: SearchResultsCell.identifier, for: indexPath) as! SearchResultsCell cell.selectionStyle = .none cell.section = searchResults[indexPath.row] return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { confirmAlert(section: searchResults[indexPath.row]) } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { if searchResults[indexPath.row].instructors.isEmpty { return SearchResultsCell.noInstructorCellHeight } return SearchResultsCell.cellHeight } } // MARK: - Search Bar Functions extension CourseAlertCreateController: UISearchBarDelegate { func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) { self.searchResults = [] self.resultsTableView.reloadData() handleSearchQuery() } func searchBarTextDidEndEditing(_ searchBar: UISearchBar) { self.searchBar.resignFirstResponder() } func searchBarSearchButtonClicked(_ searchBar: UISearchBar) { handleSearchQuery() } func searchBarShouldEndEditing(_ searchBar: UISearchBar) -> Bool { self.searchBar.resignFirstResponder() } @objc func handleSearchQuery() { let searchText = searchBar.text ?? "" mostRecentSearch = searchText if searchText == "" { hideActivity() searchPromptView.isHidden = false noResultsView.isHidden = true } else { searchPromptView.isHidden = true noResultsView.isHidden = true showActivity(isUserInteractionEnabled: true) CourseAlertNetworkManager.instance.getSearchedCourses(searchText: searchText) { (results) in self.hideActivity() if searchText == self.mostRecentSearch { if let results = results { DispatchQueue.main.async { self.searchResults = results if results.isEmpty { self.noResultsView.isHidden = false } } } else { self.searchResults = [] self.noResultsView.isHidden = false } DispatchQueue.main.async { self.resultsTableView.reloadData() } } } } } }
mit
6f63cad231ff5b6e9635785e89ef8bc8
39.371517
193
0.692101
5.800712
false
false
false
false
practicalswift/swift
stdlib/public/Darwin/Foundation/NSSet.swift
2
6582
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// @_exported import Foundation // Clang module extension Set { /// Private initializer used for bridging. /// /// The provided `NSSet` will be copied to ensure that the copy can /// not be mutated by other code. fileprivate init(_cocoaSet: __shared NSSet) { assert(_isBridgedVerbatimToObjectiveC(Element.self), "Set can be backed by NSSet _variantStorage only when the member type can be bridged verbatim to Objective-C") // FIXME: We would like to call CFSetCreateCopy() to avoid doing an // objc_msgSend() for instances of CoreFoundation types. We can't do that // today because CFSetCreateCopy() copies dictionary contents // unconditionally, resulting in O(n) copies even for immutable dictionaries. // // <rdar://problem/20697680> CFSetCreateCopy() does not call copyWithZone: // // The bug is fixed in: OS X 10.11.0, iOS 9.0, all versions of tvOS // and watchOS. self = Set(_immutableCocoaSet: _cocoaSet.copy(with: nil) as AnyObject) } } extension NSSet : Sequence { /// Return an *iterator* over the elements of this *sequence*. /// /// - Complexity: O(1). public func makeIterator() -> NSFastEnumerationIterator { return NSFastEnumerationIterator(self) } } extension NSOrderedSet : Sequence { /// Return an *iterator* over the elements of this *sequence*. /// /// - Complexity: O(1). public func makeIterator() -> NSFastEnumerationIterator { return NSFastEnumerationIterator(self) } } // Set<Element> is conditionally bridged to NSSet extension Set : _ObjectiveCBridgeable { @_semantics("convertToObjectiveC") public func _bridgeToObjectiveC() -> NSSet { return unsafeBitCast(_bridgeToObjectiveCImpl() as AnyObject, to: NSSet.self) } public static func _forceBridgeFromObjectiveC(_ s: NSSet, result: inout Set?) { if let native = Set<Element>._bridgeFromObjectiveCAdoptingNativeStorageOf(s as AnyObject) { result = native return } if _isBridgedVerbatimToObjectiveC(Element.self) { result = Set<Element>(_cocoaSet: s) return } if Element.self == String.self { // String and NSString have different concepts of equality, so // string-keyed NSSets may generate key collisions when bridged over to // Swift. See rdar://problem/35995647 var set = Set(minimumCapacity: s.count) s.enumerateObjects({ (anyMember: Any, _) in let member = Swift._forceBridgeFromObjectiveC( anyMember as AnyObject, Element.self) // FIXME: Log a warning if `member` is already in the set. set.insert(member) }) result = set return } // `Set<Element>` where `Element` is a value type may not be backed by // an NSSet. var builder = _SetBuilder<Element>(count: s.count) s.enumerateObjects({ (anyMember: Any, _) in builder.add(member: Swift._forceBridgeFromObjectiveC( anyMember as AnyObject, Element.self)) }) result = builder.take() } public static func _conditionallyBridgeFromObjectiveC( _ x: NSSet, result: inout Set? ) -> Bool { let anySet = x as Set<NSObject> if _isBridgedVerbatimToObjectiveC(Element.self) { result = Swift._setDownCastConditional(anySet) return result != nil } result = anySet as? Set return result != nil } @_effects(readonly) public static func _unconditionallyBridgeFromObjectiveC(_ s: NSSet?) -> Set { // `nil` has historically been used as a stand-in for an empty // set; map it to an empty set. if _slowPath(s == nil) { return Set() } var result: Set? = nil Set<Element>._forceBridgeFromObjectiveC(s!, result: &result) return result! } } extension NSSet : _HasCustomAnyHashableRepresentation { // Must be @nonobjc to avoid infinite recursion during bridging @nonobjc public func _toCustomAnyHashable() -> AnyHashable? { return AnyHashable(self as! Set<AnyHashable>) } } extension NSOrderedSet { // - (instancetype)initWithObjects:(id)firstObj, ... public convenience init(objects elements: Any...) { self.init(array: elements) } } extension NSSet { // - (instancetype)initWithObjects:(id)firstObj, ... public convenience init(objects elements: Any...) { self.init(array: elements) } } extension NSSet : ExpressibleByArrayLiteral { public required convenience init(arrayLiteral elements: Any...) { self.init(array: elements) } } extension NSOrderedSet : ExpressibleByArrayLiteral { public required convenience init(arrayLiteral elements: Any...) { self.init(array: elements) } } extension NSSet { /// Initializes a newly allocated set and adds to it objects from /// another given set. /// /// - Returns: An initialized objects set containing the objects from /// `set`. The returned set might be different than the original /// receiver. @nonobjc public convenience init(set anSet: __shared NSSet) { // FIXME(performance)(compiler limitation): we actually want to do just // `self = anSet.copy()`, but Swift does not have factory // initializers right now. let numElems = anSet.count let stride = MemoryLayout<Optional<UnsafeRawPointer>>.stride let alignment = MemoryLayout<Optional<UnsafeRawPointer>>.alignment let bufferSize = stride * numElems assert(stride == MemoryLayout<AnyObject>.stride) assert(alignment == MemoryLayout<AnyObject>.alignment) let rawBuffer = UnsafeMutableRawPointer.allocate( byteCount: bufferSize, alignment: alignment) defer { rawBuffer.deallocate() _fixLifetime(anSet) } let valueBuffer = rawBuffer.bindMemory( to: Optional<UnsafeRawPointer>.self, capacity: numElems) CFSetGetValues(anSet, valueBuffer) let valueBufferForInit = rawBuffer.assumingMemoryBound(to: AnyObject.self) self.init(objects: valueBufferForInit, count: numElems) } } extension NSSet : CustomReflectable { public var customMirror: Mirror { return Mirror(reflecting: self as Set<NSObject>) } } extension Set: CVarArg {}
apache-2.0
96ca2a105cbf309d64d34c0e23709609
32.242424
116
0.677302
4.593161
false
false
false
false
jopamer/swift
benchmark/single-source/SetTests.swift
2
5420
//===--- SetTests.swift ---------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// import TestsUtils public let SetTests = [ BenchmarkInfo(name: "SetExclusiveOr", runFunction: run_SetExclusiveOr, tags: [.validation, .api, .Set]), BenchmarkInfo(name: "SetExclusiveOr_OfObjects", runFunction: run_SetExclusiveOr_OfObjects, tags: [.validation, .api, .Set]), BenchmarkInfo(name: "SetIntersect", runFunction: run_SetIntersect, tags: [.validation, .api, .Set]), BenchmarkInfo(name: "SetIntersect_OfObjects", runFunction: run_SetIntersect_OfObjects, tags: [.validation, .api, .Set]), BenchmarkInfo(name: "SetIsSubsetOf", runFunction: run_SetIsSubsetOf, tags: [.validation, .api, .Set]), BenchmarkInfo(name: "SetIsSubsetOf_OfObjects", runFunction: run_SetIsSubsetOf_OfObjects, tags: [.validation, .api, .Set]), BenchmarkInfo(name: "SetUnion", runFunction: run_SetUnion, tags: [.validation, .api, .Set]), BenchmarkInfo(name: "SetUnion_OfObjects", runFunction: run_SetUnion_OfObjects, tags: [.validation, .api, .Set]), ] @inline(never) public func run_SetIsSubsetOf(_ N: Int) { let size = 200 SRand() var set = Set<Int>(minimumCapacity: size) var otherSet = Set<Int>(minimumCapacity: size) for _ in 0 ..< size { set.insert(Int(truncatingIfNeeded: Random())) otherSet.insert(Int(truncatingIfNeeded: Random())) } var isSubset = false for _ in 0 ..< N * 5000 { isSubset = set.isSubset(of: otherSet) if isSubset { break } } CheckResults(!isSubset) } @inline(never) func sink(_ s: inout Set<Int>) { } @inline(never) public func run_SetExclusiveOr(_ N: Int) { let size = 400 SRand() var set = Set<Int>(minimumCapacity: size) var otherSet = Set<Int>(minimumCapacity: size) for _ in 0 ..< size { set.insert(Int(truncatingIfNeeded: Random())) otherSet.insert(Int(truncatingIfNeeded: Random())) } var xor = Set<Int>() for _ in 0 ..< N * 100 { xor = set.symmetricDifference(otherSet) } sink(&xor) } @inline(never) public func run_SetUnion(_ N: Int) { let size = 400 SRand() var set = Set<Int>(minimumCapacity: size) var otherSet = Set<Int>(minimumCapacity: size) for _ in 0 ..< size { set.insert(Int(truncatingIfNeeded: Random())) otherSet.insert(Int(truncatingIfNeeded: Random())) } var or = Set<Int>() for _ in 0 ..< N * 100 { or = set.union(otherSet) } sink(&or) } @inline(never) public func run_SetIntersect(_ N: Int) { let size = 400 SRand() var set = Set<Int>(minimumCapacity: size) var otherSet = Set<Int>(minimumCapacity: size) for _ in 0 ..< size { set.insert(Int(truncatingIfNeeded: Random())) otherSet.insert(Int(truncatingIfNeeded: Random())) } var and = Set<Int>() for _ in 0 ..< N * 100 { and = set.intersection(otherSet) } sink(&and) } class Box<T : Hashable> : Hashable { var value: T init(_ v: T) { value = v } func hash(into hasher: inout Hasher) { hasher.combine(value) } static func ==(lhs: Box, rhs: Box) -> Bool { return lhs.value == rhs.value } } @inline(never) public func run_SetIsSubsetOf_OfObjects(_ N: Int) { let size = 200 SRand() var set = Set<Box<Int>>(minimumCapacity: size) var otherSet = Set<Box<Int>>(minimumCapacity: size) for _ in 0 ..< size { set.insert(Box(Int(truncatingIfNeeded: Random()))) otherSet.insert(Box(Int(truncatingIfNeeded: Random()))) } var isSubset = false for _ in 0 ..< N * 5000 { isSubset = set.isSubset(of: otherSet) if isSubset { break } } CheckResults(!isSubset) } @inline(never) func sink(_ s: inout Set<Box<Int>>) { } @inline(never) public func run_SetExclusiveOr_OfObjects(_ N: Int) { let size = 400 SRand() var set = Set<Box<Int>>(minimumCapacity: size) var otherSet = Set<Box<Int>>(minimumCapacity: size) for _ in 0 ..< size { set.insert(Box(Int(truncatingIfNeeded: Random()))) otherSet.insert(Box(Int(truncatingIfNeeded: Random()))) } var xor = Set<Box<Int>>() for _ in 0 ..< N * 100 { xor = set.symmetricDifference(otherSet) } sink(&xor) } @inline(never) public func run_SetUnion_OfObjects(_ N: Int) { let size = 400 SRand() var set = Set<Box<Int>>(minimumCapacity: size) var otherSet = Set<Box<Int>>(minimumCapacity: size) for _ in 0 ..< size { set.insert(Box(Int(truncatingIfNeeded: Random()))) otherSet.insert(Box(Int(truncatingIfNeeded: Random()))) } var or = Set<Box<Int>>() for _ in 0 ..< N * 100 { or = set.union(otherSet) } sink(&or) } @inline(never) public func run_SetIntersect_OfObjects(_ N: Int) { let size = 400 SRand() var set = Set<Box<Int>>(minimumCapacity: size) var otherSet = Set<Box<Int>>(minimumCapacity: size) for _ in 0 ..< size { set.insert(Box(Int(truncatingIfNeeded: Random()))) otherSet.insert(Box(Int(truncatingIfNeeded: Random()))) } var and = Set<Box<Int>>() for _ in 0 ..< N * 100 { and = set.intersection(otherSet) } sink(&and) }
apache-2.0
220af11105840968b7e24df4ca5f9f59
23.196429
126
0.637454
3.712329
false
false
false
false
markedwardmurray/Precipitate
Precipitate/SummaryViewController.swift
1
2774
// // SummaryViewController.swift // Precipitate // // Created by Mark Murray on 12/14/15. // Copyright © 2015 markedwardmurray. All rights reserved. // import UIKit import FontAwesome_swift import MarqueeLabel_Swift import SwiftyUserDefaults class SummaryViewController: UIViewController { let lineChartDataManager = LineChartDataManager.sharedInstance @IBOutlet weak var iconButton: UIButton! @IBOutlet weak var summaryLabel: MarqueeLabel! @IBOutlet weak var settingsButton: UIButton! var shouldShowSettings: Bool = false override func viewDidLoad() { super.viewDidLoad() self.setUpSubviews() } func setUpSubviews() { if let currentlyIcon = lineChartDataManager.chartDataSetManager.dataEntryCollator?.currentlyIcon { let weatherIconName = WeatherIconName(rawValue: currentlyIcon) let (icon, size) = weatherIconForName(weatherIconName) iconButton.titleLabel?.font = UIFont(name: "Weather Icons", size: size) iconButton.setTitle(icon, forState: UIControlState.Normal) iconButton.setTitleColor(UIColor.s3Chambray(), forState:UIControlState.Normal) iconButton.setTitle(icon, forState: UIControlState.Highlighted) iconButton.setTitleColor(UIColor.s1FadedBlue(), forState:UIControlState.Highlighted) } // disable until it does something iconButton.userInteractionEnabled = false if let summary = lineChartDataManager.chartDataSetManager.dataEntryCollator?.summary { self.summaryLabel.text = summary + " " self.summaryLabel.triggerScrollStart() self.summaryLabel.animationDelay = 2.0; } settingsButton.titleLabel?.font = UIFont.fontAwesomeOfSize(25) settingsButton.setTitle(String.fontAwesomeIconWithName(FontAwesome.Gear), forState:UIControlState.Normal) settingsButton.setTitleColor(UIColor.s3Chambray(), forState:UIControlState.Normal) settingsButton.setTitle(String.fontAwesomeIconWithName(FontAwesome.Gear), forState:UIControlState.Highlighted) settingsButton.setTitleColor(UIColor.s1FadedBlue(), forState:UIControlState.Highlighted) } @IBAction func iconTapped(sender: AnyObject) { } @IBAction func SettingsTapped(sender: AnyObject) { self.shouldShowSettings = !self.shouldShowSettings if self.shouldShowSettings { NSNotificationCenter.defaultCenter().postNotificationName("showSettings", object: nil) } else { NSNotificationCenter.defaultCenter().postNotificationName("showWeather", object: nil) } } }
mit
2c99991b24418fb406154c56e6142d11
38.614286
118
0.689506
5.447937
false
false
false
false
PomTTcat/YYModelGuideRead_JEFF
RxSwiftGuideRead/RxSwift-master/RxExample/RxExample/Services/ImageService.swift
5
3614
// // ImageService.swift // RxExample // // Created by Krunoslav Zaher on 3/28/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // import RxSwift import RxCocoa #if os(iOS) import UIKit #elseif os(macOS) import Cocoa #endif protocol ImageService { func imageFromURL(_ url: URL, reachabilityService: ReachabilityService) -> Observable<DownloadableImage> } class DefaultImageService: ImageService { static let sharedImageService = DefaultImageService() // Singleton let `$`: Dependencies = Dependencies.sharedDependencies // 1st level cache private let _imageCache = NSCache<AnyObject, AnyObject>() // 2nd level cache private let _imageDataCache = NSCache<AnyObject, AnyObject>() let loadingImage = ActivityIndicator() private init() { // cost is approx memory usage _imageDataCache.totalCostLimit = 10 * MB _imageCache.countLimit = 20 } private func decodeImage(_ imageData: Data) -> Observable<Image> { return Observable.just(imageData) .observeOn(`$`.backgroundWorkScheduler) .map { data in guard let image = Image(data: data) else { // some error throw apiError("Decoding image error") } return image.forceLazyImageDecompression() } } private func _imageFromURL(_ url: URL) -> Observable<Image> { return Observable.deferred { let maybeImage = self._imageCache.object(forKey: url as AnyObject) as? Image let decodedImage: Observable<Image> // best case scenario, it's already decoded an in memory if let image = maybeImage { decodedImage = Observable.just(image) } else { let cachedData = self._imageDataCache.object(forKey: url as AnyObject) as? Data // does image data cache contain anything if let cachedData = cachedData { decodedImage = self.decodeImage(cachedData) } else { // fetch from network decodedImage = self.`$`.URLSession.rx.data(request: URLRequest(url: url)) .do(onNext: { data in self._imageDataCache.setObject(data as AnyObject, forKey: url as AnyObject) }) .flatMap(self.decodeImage) .trackActivity(self.loadingImage) } } return decodedImage.do(onNext: { image in self._imageCache.setObject(image, forKey: url as AnyObject) }) } } /** Service that tries to download image from URL. In case there were some problems with network connectivity and image wasn't downloaded, automatic retry will be fired when networks becomes available. After image is successfully downloaded, sequence is completed. */ func imageFromURL(_ url: URL, reachabilityService: ReachabilityService) -> Observable<DownloadableImage> { return _imageFromURL(url) .map { DownloadableImage.content(image: $0) } .retryOnBecomesReachable(DownloadableImage.offlinePlaceholder, reachabilityService: reachabilityService) .startWith(.content(image: Image())) } }
mit
22f42b025142830cc104a53707cc8af9
34.07767
143
0.57044
5.618974
false
false
false
false
coach-plus/ios
CoachPlus/app/shared/events/EventTableViewCell.swift
1
1356
// // EventTableViewCell.swift // CoachPlus // // Created by Maurice Breit on 13.04.17. // Copyright © 2017 Mathandoro GbR. All rights reserved. // import UIKit import SwiftDate class EventTableViewCell: UITableViewCell { @IBOutlet weak var leftContainer: UIView! @IBOutlet weak var monthLbl: UILabel! @IBOutlet weak var dayLbl: UILabel! @IBOutlet weak var nameLbl: UILabel! @IBOutlet weak var dateTimeLbl: UILabel! @IBOutlet weak var locationLbl: UILabel! func setup(event:Event) { //self.heroID = "event\(event.id)" let name = event.name self.nameLbl.text = name //self.nameLbl.heroID = "\(self.heroID!)/name" self.dateTimeLbl.text = event.fromToString() self.locationLbl.text = event.getLocationString() self.leftContainer.backgroundColor = UIColor.coachPlusLightBlue self.monthLbl.text = event.start.monthName() self.dayLbl.text = event.start.dayOfMonth() self.monthLbl.textColor = UIColor.coachPlusBlue self.dayLbl.textColor = UIColor.coachPlusBlue self.leftContainer.layer.cornerRadius = 5 self.leftContainer.clipsToBounds = true self.backgroundColor = UIColor.defaultBackground } }
mit
8e572e8785d19a7643b7c552eb09ba03
25.568627
71
0.632472
4.672414
false
false
false
false
swordmanboy/KeychainGroupBySMB
_Main/DMPKeyChain-For-Master_Main_swift/DMPKeyChain-For-Master_Main_swift/CustomView/SMBUIView.swift
2
727
// // SMBUIView.swift // CustomNormalViewForSwift3_0 // // Created by Apinun Wongintawang on 8/31/17. // Copyright © 2017 Apinun Wongintawang. All rights reserved. // import UIKit @IBDesignable class SMBUIView : UIView{ //cornor radius @IBInspectable var cornorRadius : CGFloat = 0.0 { didSet{ self.layer.cornerRadius = cornorRadius } } //width border @IBInspectable var borderWidth : CGFloat = 0.0 { didSet{ self.layer.borderWidth = borderWidth } } //color of Boder @IBInspectable var colorBorder : UIColor = UIColor.clear { didSet{ self.layer.borderColor = colorBorder.cgColor } } }
mit
199b9c8d2f3afac7592f9e626ec5984c
20.352941
62
0.604683
3.989011
false
false
false
false
Antondomashnev/Sourcery
SourceryTests/Stub/Performance-Code/Kiosk/App/Networking/Networking.swift
2
6963
import Foundation import Moya import RxSwift import Alamofire class OnlineProvider<Target>: RxMoyaProvider<Target> where Target: TargetType { fileprivate let online: Observable<Bool> init(endpointClosure: @escaping EndpointClosure = MoyaProvider.DefaultEndpointMapping, requestClosure: @escaping RequestClosure = MoyaProvider.DefaultRequestMapping, stubClosure: @escaping StubClosure = MoyaProvider.NeverStub, manager: Manager = RxMoyaProvider<Target>.DefaultAlamofireManager(), plugins: [PluginType] = [], trackInflights: Bool = false, online: Observable<Bool> = connectedToInternetOrStubbing()) { self.online = online super.init(endpointClosure: endpointClosure, requestClosure: requestClosure, stubClosure: stubClosure, manager: manager, plugins: plugins, trackInflights: trackInflights) } override func request(_ token: Target) -> Observable<Moya.Response> { let actualRequest = super.request(token) return online .ignore(value: false) // Wait until we're online .take(1) // Take 1 to make sure we only invoke the API once. .flatMap { _ in // Turn the online state into a network request return actualRequest } } } protocol NetworkingType { associatedtype T: TargetType, ArtsyAPIType var provider: OnlineProvider<T> { get } } struct Networking: NetworkingType { typealias T = ArtsyAPI let provider: OnlineProvider<ArtsyAPI> } struct AuthorizedNetworking: NetworkingType { typealias T = ArtsyAuthenticatedAPI let provider: OnlineProvider<ArtsyAuthenticatedAPI> } private extension Networking { /// Request to fetch and store new XApp token if the current token is missing or expired. func XAppTokenRequest(_ defaults: UserDefaults) -> Observable<String?> { var appToken = XAppToken(defaults: defaults) // If we have a valid token, return it and forgo a request for a fresh one. if appToken.isValid { return Observable.just(appToken.token) } let newTokenRequest = self.provider.request(ArtsyAPI.xApp) .filterSuccessfulStatusCodes() .mapJSON() .map { element -> (token: String?, expiry: String?) in guard let dictionary = element as? NSDictionary else { return (token: nil, expiry: nil) } return (token: dictionary["xapp_token"] as? String, expiry: dictionary["expires_in"] as? String) } .do(onNext: { element in // These two lines set the defaults values injected into appToken appToken.token = element.0 appToken.expiry = KioskDateFormatter.fromString(element.1 ?? "") }) .map { (token, expiry) -> String? in return token } .logError() return newTokenRequest } } // "Public" interfaces extension Networking { /// Request to fetch a given target. Ensures that valid XApp tokens exist before making request func request(_ token: ArtsyAPI, defaults: UserDefaults = UserDefaults.standard) -> Observable<Moya.Response> { let actualRequest = self.provider.request(token) return self.XAppTokenRequest(defaults).flatMap { _ in actualRequest } } } extension AuthorizedNetworking { func request(_ token: ArtsyAuthenticatedAPI, defaults: UserDefaults = UserDefaults.standard) -> Observable<Moya.Response> { return self.provider.request(token) } } // Static methods extension NetworkingType { static func newDefaultNetworking() -> Networking { return Networking(provider: newProvider(plugins)) } static func newAuthorizedNetworking(_ xAccessToken: String) -> AuthorizedNetworking { return AuthorizedNetworking(provider: newProvider(authenticatedPlugins, xAccessToken: xAccessToken)) } static func newStubbingNetworking() -> Networking { return Networking(provider: OnlineProvider(endpointClosure: endpointsClosure(), requestClosure: Networking.endpointResolver(), stubClosure: MoyaProvider.ImmediatelyStub, online: .just(true))) } static func newAuthorizedStubbingNetworking() -> AuthorizedNetworking { return AuthorizedNetworking(provider: OnlineProvider(endpointClosure: endpointsClosure(), requestClosure: Networking.endpointResolver(), stubClosure: MoyaProvider.ImmediatelyStub, online: .just(true))) } static func endpointsClosure<T>(_ xAccessToken: String? = nil) -> (T) -> Endpoint<T> where T: TargetType, T: ArtsyAPIType { return { target in var endpoint: Endpoint<T> = Endpoint<T>(URL: url(target), sampleResponseClosure: {.networkResponse(200, target.sampleData)}, method: target.method, parameters: target.parameters) // If we were given an xAccessToken, add it if let xAccessToken = xAccessToken { endpoint = endpoint.adding(httpHeaderFields: ["X-Access-Token": xAccessToken]) } // Sign all non-XApp, non-XAuth token requests if target.addXAuth { return endpoint.adding(httpHeaderFields:["X-Xapp-Token": XAppToken().token ?? ""]) } else { return endpoint } } } static func APIKeysBasedStubBehaviour<T>(_: T) -> Moya.StubBehavior { return APIKeys.sharedKeys.stubResponses ? .immediate : .never } static var plugins: [PluginType] { return [ NetworkLogger(blacklist: { target -> Bool in guard let target = target as? ArtsyAPI else { return false } switch target { case .ping: return true default: return false } }) ] } static var authenticatedPlugins: [PluginType] { return [NetworkLogger(whitelist: { target -> Bool in guard let target = target as? ArtsyAuthenticatedAPI else { return false } switch target { case .myBidPosition: return true case .findMyBidderRegistration: return true default: return false } }) ] } // (Endpoint<Target>, NSURLRequest -> Void) -> Void static func endpointResolver<T>() -> MoyaProvider<T>.RequestClosure where T: TargetType { return { (endpoint, closure) in var request = endpoint.urlRequest! request.httpShouldHandleCookies = false closure(.success(request)) } } } private func newProvider<T>(_ plugins: [PluginType], xAccessToken: String? = nil) -> OnlineProvider<T> where T: TargetType, T: ArtsyAPIType { return OnlineProvider(endpointClosure: Networking.endpointsClosure(xAccessToken), requestClosure: Networking.endpointResolver(), stubClosure: Networking.APIKeysBasedStubBehaviour, plugins: plugins) }
mit
af193112094882f7eb239b003f12d279
37.683333
209
0.65647
5.161601
false
false
false
false
trujillo138/MyExpenses
MyExpenses/Shared/HelperFunctions/DateFunctions.swift
1
2775
// // DateFunctions.swift // MyExpenses // // Created by Tomas Trujillo on 5/29/17. // Copyright © 2017 TOMApps. All rights reserved. // import Foundation extension Date { var shortFormat: String { let formatter = DateFormatter() formatter.dateStyle = .short return formatter.string(from: self) } var mediumFormat: String { let formatter = DateFormatter() formatter.dateStyle = .medium return formatter.string(from: self) } var longFormat: String { let formatter = DateFormatter() formatter.dateStyle = .long return formatter.string(from: self) } func year() -> Int { let calendar = Calendar.current let components = calendar.dateComponents([.year], from: self) return components.year ?? 0 } func month() -> Int { let calendar = Calendar.current let components = calendar.dateComponents([.month], from: self) return components.month ?? 0 } func day() -> Int { let calendar = Calendar.current let components = calendar.dateComponents([.day], from: self) return components.day ?? 0 } func hour() -> Int { let calendar = Calendar.current let components = calendar.dateComponents([.hour], from: self) return components.hour ?? 0 } func minute() -> Int { let calendar = Calendar.current let components = calendar.dateComponents([.minute], from: self) return components.minute ?? 0 } func second() -> Int { let calendar = Calendar.current let components = calendar.dateComponents([.second], from: self) return components.second ?? 0 } func dateByAdding(years: Int, months: Int, days: Int) -> Date { var dateComponents = DateComponents() dateComponents.year = years dateComponents.month = months dateComponents.day = days return Calendar.current.date(byAdding: dateComponents, to: self)! } func dateForFirstDayOfMonth() -> Date { var dateComponents = DateComponents() dateComponents.year = self.year() dateComponents.month = self.month() //Doing this so that the change in time zone does not affect the periods dateComponents.day = 2 return Calendar.current.date(from: dateComponents)! } static func dateWithComponents(years: Int, months: Int, days: Int) -> Date { var dateComponents = DateComponents() dateComponents.year = years dateComponents.month = months dateComponents.day = days return Calendar.current.date(from: dateComponents)! } }
apache-2.0
f7f1a96bc16d08e71fb9f5b14d0f53c2
28.2
80
0.607426
4.927176
false
false
false
false
joemasilotti/Quick
Quick/Quick/World.swift
1
3192
// // World.swift // Quick // // Created by Brian Ivan Gesiak on 6/5/14. // Copyright (c) 2014 Brian Ivan Gesiak. All rights reserved. // import Foundation public typealias SharedExampleContext = () -> (NSDictionary) public typealias SharedExampleClosure = (SharedExampleContext) -> () public class World: NSObject { typealias BeforeSuiteClosure = () -> () typealias AfterSuiteClosure = BeforeSuiteClosure var _specs: Dictionary<String, ExampleGroup> = [:] var _beforeSuites = [BeforeSuiteClosure]() var _beforeSuitesNotRunYet = true var _afterSuites = [AfterSuiteClosure]() var _afterSuitesNotRunYet = true var _sharedExamples: [String: SharedExampleClosure] = [:] public var currentExampleGroup: ExampleGroup? struct _Shared { static let instance = World() } public class func sharedWorld() -> World { return _Shared.instance } public func rootExampleGroupForSpecClass(cls: AnyClass) -> ExampleGroup { let name = NSStringFromClass(cls) if let group = _specs[name] { return group } else { let group = ExampleGroup("root example group") _specs[name] = group return group } } func runBeforeSpec() { assert(_beforeSuitesNotRunYet, "runBeforeSuite was called twice") for beforeSuite in _beforeSuites { beforeSuite() } _beforeSuitesNotRunYet = false } func runAfterSpec() { assert(_afterSuitesNotRunYet, "runAfterSuite was called twice") for afterSuite in _afterSuites { afterSuite() } _afterSuitesNotRunYet = false } func appendBeforeSuite(closure: BeforeSuiteClosure) { _beforeSuites.append(closure) } func appendAfterSuite(closure: AfterSuiteClosure) { _afterSuites.append(closure) } var exampleCount: Int { get { var count = 0 for (_, group) in _specs { group.walkDownExamples { (example: Example) -> () in _ = ++count } } return count } } func registerSharedExample(name: String, closure: SharedExampleClosure) { _raiseIfSharedExampleAlreadyRegistered(name) _sharedExamples[name] = closure } func _raiseIfSharedExampleAlreadyRegistered(name: String) { if _sharedExamples[name] != nil { NSException(name: NSInternalInconsistencyException, reason: "A shared example named '\(name)' has already been registered.", userInfo: nil).raise() } } func sharedExample(name: String) -> SharedExampleClosure { _raiseIfSharedExampleNotRegistered(name) return _sharedExamples[name]! } func _raiseIfSharedExampleNotRegistered(name: String) { if _sharedExamples[name] == nil { NSException(name: NSInternalInconsistencyException, reason: "No shared example named '\(name)' has been registered. Registered shared examples: '\(Array(_sharedExamples.keys))'", userInfo: nil).raise() } } }
mit
984629a0fb5e36e02243c652d3f75dab
28.284404
142
0.616228
5.042654
false
false
false
false
iCodeForever/ifanr
ifanr/ifanr/Views/MindStoreView/MindStoreTableViewCell.swift
1
9462
// // MindStoreTableViewCell.swift // ifanr // // Created by sys on 16/7/8. // Copyright © 2016年 ifanrOrg. All rights reserved. // import UIKit class MindStoreTableViewCell: UITableViewCell, Reusable { //MARK:-----Init----- override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) self.isUserInteractionEnabled = true self.contentView.isUserInteractionEnabled = true self.contentView.addSubview(self.voteBtn) self.contentView.addSubview(self.voteNumberLabel) self.contentView.addSubview(self.tagLineLabel) self.contentView.addSubview(self.titleLabel) self.contentView.addSubview(self.relatedImg1) self.contentView.addSubview(self.relatedImg2) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } //MARK:-----Variables----- var model : MindStoreModel! { didSet { self.titleLabel.attributedText = UILabel.setAttributText(model.title, lineSpcae: 5.0) self.tagLineLabel.attributedText = UILabel.setAttributText(model.tagline, lineSpcae: 5.0); // if model.relatedImageModelArr.count == 1 { // self.relatedImg1.if_setImage(NSURL(string: model.relatedImageModelArr[0].link!)) // self.relatedImg2.image = UIImage(named: "ic_mind_store_like") // } else if model.relatedImageModelArr.count == 2 { // self.relatedImg1.if_setImage(NSURL(string: model.relatedImageModelArr[0].link!)) // self.relatedImg2.if_setImage(NSURL(string: model.relatedImageModelArr[1].link!)) // } else { // self.relatedImg1.image = UIImage(named: "ic_mind_store_comment") // self.relatedImg2.image = UIImage(named: "ic_mind_store_like") // } self.relatedImg1.if_setAvatarImage(URL(string: model.createdByModel.avatar_url)) self.relatedImg2.image = UIImage(named: "mind_store_comment_background") self.voteBtn.imageView?.image = UIImage(named: "mind_store_vote_background_voted_false") self.voteNumberLabel.text = "\(model.vote_user_count)" self.setupLayout() } } //MARK:-----Action----- @objc fileprivate func toVote(_ btn: UIButton) { if btn.isSelected { btn.isSelected = false let num: Int = Int(self.voteNumberLabel.text!)! - 1; self.voteNumberLabel.text = "\(num)" self.voteNumberLabel.textColor = UIColor(colorLiteralRed: 41/255.0, green: 173/255.0, blue: 169/255.0, alpha: 1) } else { btn.isSelected = true let num: Int = Int(self.voteNumberLabel.text!)! + 1; self.voteNumberLabel.text = "\(num)" self.voteNumberLabel.textColor = UIColor.white } } //MARK:-----Private Function----- fileprivate func setupLayout() -> Void { // // voteBtn - - - - - - - // - - - - titlelabel - // - - - - tagLineLabel - // - - - - rImg1-rImg2 - - // self.voteBtn.snp.makeConstraints { (make) in make.top.equalTo(self.contentView).offset(UIConstant.UI_MARGIN_20) make.left.equalTo(self.contentView).offset(UIConstant.UI_MARGIN_15) make.width.equalTo(35) make.height.equalTo(45) } self.voteNumberLabel.snp.makeConstraints { (make) in make.top.equalTo(self.voteBtn.snp.top).offset(20) make.left.equalTo(self.voteBtn.snp.left).offset(3) make.right.equalTo(self.voteBtn.snp.right).offset(-3) make.bottom.equalTo(self.voteBtn.snp.bottom).offset(-3) } self.relatedImg1.snp.makeConstraints { (make) in make.bottom.equalTo(self.contentView).offset(-UIConstant.UI_MARGIN_20) make.left.equalTo(self.voteBtn.snp.right).offset(UIConstant.UI_MARGIN_15) make.width.equalTo(20) make.height.equalTo(20) } self.relatedImg2.snp.makeConstraints { (make) in make.bottom.equalTo(relatedImg1) make.left.equalTo(self.relatedImg1.snp.right).offset(UIConstant.UI_MARGIN_5) make.size.equalTo(relatedImg1) } self.titleLabel.snp.makeConstraints { (make) in make.left.equalTo(self.voteBtn.snp.right).offset(UIConstant.UI_MARGIN_15) make.right.equalTo(self.contentView).offset(-UIConstant.UI_MARGIN_15) make.top.equalTo(self.contentView).offset(UIConstant.UI_MARGIN_20) make.bottom.equalTo(self.tagLineLabel.snp.top).offset(-UIConstant.UI_MARGIN_10) } self.tagLineLabel.snp.makeConstraints { (make) in make.left.equalTo(self.voteBtn.snp.right).offset(UIConstant.UI_MARGIN_15) make.right.equalTo(self.contentView).offset(-UIConstant.UI_MARGIN_15) make.bottom.equalTo(self.relatedImg1.snp.top).offset(-UIConstant.UI_MARGIN_10) } // 设置拉伸的优先级,titleLabel默认不拉伸 self.titleLabel.setContentHuggingPriority(UILayoutPriorityDefaultHigh, for: .vertical) self.tagLineLabel.setContentHuggingPriority(UILayoutPriorityDefaultLow, for: .vertical) self.relatedImg1.contentMode = .scaleAspectFill self.relatedImg1.layer.cornerRadius = 10 self.relatedImg1.layer.masksToBounds = true self.relatedImg1.clipsToBounds = true self.relatedImg2.contentMode = .scaleAspectFit // self.relatedImg2.clipsToBounds = true // self.relatedImg2.layer.cornerRadius = 10 // self.relatedImg2.layer.masksToBounds = true } class func cellWithTableView(_ tableView : UITableView) -> MindStoreTableViewCell { var cell: MindStoreTableViewCell? = tableView.dequeueReusableCell() as MindStoreTableViewCell? if cell == nil { cell = MindStoreTableViewCell(style: .default, reuseIdentifier: self.reuseIdentifier) cell?.selectionStyle = .none } return cell! } // 动态label的高度 class func estimateLabelHeight (_ content: String, font: UIFont) -> CGFloat { let size = CGSize(width: UIConstant.SCREEN_WIDTH - 80 ,height: 2000) let paragphStyle = NSMutableParagraphStyle() paragphStyle.lineSpacing = 5.0; paragphStyle.firstLineHeadIndent = 0.0; paragphStyle.hyphenationFactor = 0.0; paragphStyle.paragraphSpacingBefore = 0.0; let dic = [NSFontAttributeName : font, NSParagraphStyleAttributeName: paragphStyle, NSKernAttributeName : 1.0] as [String : Any] let labelRect : CGRect = content.boundingRect(with: size, options: .usesLineFragmentOrigin, attributes: dic as [String : AnyObject], context: nil) return labelRect.height } // 动态计算 titleLabel/tagLineLabel 的高度 class func estimateCellHeight(_ title : String, tagline: String) -> CGFloat { return estimateLabelHeight(title, font: UIFont.customFont_FZLTXIHJW(fontSize: 16)) + estimateLabelHeight(tagline, font: UIFont.customFont_FZLTZCHJW(fontSize: 12)) + 80 } //MARK:-----Setter Getter----- // vote button fileprivate lazy var voteBtn: UIButton = { let voteBtn = UIButton() voteBtn.setImage(UIImage(named: "mind_store_vote_background_voted_false"), for: UIControlState()) voteBtn.setImage(UIImage(named: "mind_store_vote_background_voted_true"), for: .selected) voteBtn.addTarget(self, action: #selector(toVote), for: .touchUpInside) return voteBtn }() // vote label fileprivate lazy var voteNumberLabel: UILabel = { let voteNumberLabel = UILabel() voteNumberLabel.font = UIFont.customFont_FZLTZCHJW(fontSize: 13) voteNumberLabel.textAlignment = .center voteNumberLabel.textColor = UIColor(colorLiteralRed: 41/255.0, green: 173/255.0, blue: 169/255.0, alpha: 1) return voteNumberLabel }() // 标题,需动态计算高度 fileprivate lazy var titleLabel: UILabel = { let titleLabel = UILabel() titleLabel.font = UIFont.customFont_FZLTXIHJW(fontSize: 16) titleLabel.numberOfLines = 0 titleLabel.lineBreakMode = .byWordWrapping return titleLabel }() // 粗略信息,动态计算高度 fileprivate lazy var tagLineLabel: UILabel = { let tagLineLabel = UILabel() tagLineLabel.numberOfLines = 0 tagLineLabel.lineBreakMode = .byCharWrapping tagLineLabel.font = UIFont.customFont_FZLTXIHJW(fontSize: 12) tagLineLabel.textColor = UIColor.lightGray return tagLineLabel }() // related imageview fileprivate lazy var relatedImg1: UIImageView = { let relatedImg1 = UIImageView() return relatedImg1 }() fileprivate lazy var relatedImg2: UIImageView = { let relatedImg2 = UIImageView() return relatedImg2 }() }
mit
4a7b64bad36a5a481656c3af1d79e240
41.568182
154
0.621143
4.599705
false
false
false
false
austinzheng/swift-compiler-crashes
crashes-duplicates/05753-swift-sourcemanager-getmessage.swift
11
2340
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing struct B<Int> protocol a struct S<j struct S<T.Generator.Generator.Generator.E == a struct B<T where g: a { var e: S<f : d where S<T { var e: j { func g<T>(v: S<T where T.Generator.e = ") enum S.e : a { if true { struct B<T where g<f : T class c : NSObject { case c, [k<T where g: d where S().E == a() { protocol a(").e : d = ").Generator.E == B<Int>(Any) { func g<j func g: AnyObject) { var e: T> struct B<T.f.f.e = a { protocol a(h:as b) struct B<T case c, func j>(Any) { { { protocol e = a() var e(v: AnyObject) { var d = B<j> var e: j { func j var e: a { { struct d<T { protocol A : d = B<b) if true { { struct B<D> Void> protocol e : C { case c, protocol a func j { class c : a { protocol h : a { case c, if true { struct B<b) protocol h : T: d = ").E == ") [k<Int>(") class c : a { protocol e = ") if true { var e() { var d where g: T struct d<Int> struct B<j protocol h : AnyObject) { func a() { func a protocol a struct Q<T: AnyObject) { func a struct d<h : T protocol h : j { func a() { protocol A : AnyObject) { class c : T where S(Any) { func j struct S<T where g: a { func j>(").E == ") struct B<f : T: A? { case c, { for () { class c : j { func a(v: NSObject { protocol a func a(v: S.h() { for ().e = a struct B<T where g: S<b) protocol h : a { struct B<T var d where g<T where g: NSObject { class c : C { { var e: T if true { { func g: d = B<h : a { func a() class struct d<D> Void> protocol e = compose() case c, func a struct Q<D> Void>(v: T> protocol a struct d<j func a(v: a { case c, case c, protocol A : S<b) func a(") var e: d = B<T where g: j { func g: T { struct B<f : NSObject { var e(h:as b) [k<Int>(Any) { case c, case c, var e().h:as b: A? { { case c, func a struct B<T where S<Int> class struct B<T where S<T>(Any) { case c, case c, protocol h : d = a if true { struct S<f : T where g<b: AnyObject) { var e() var d = B<h : T where g: d = ").f() var e: S<b: T: T where g: C { class case c, struct S<j protocol h : AnyObject) { func a if true { var d = B<T where g<T>() { [k<T where g: S() { protocol e : S(") case c, protocol e : T where S<D> Void>(") protocol A : S().Generator.f.e : C { struct d<T where S.E == B<b) case c, { protocol A : T>
mit
30d01816df8de6d8e9d7a00e08b5131e
15.478873
87
0.6
2.392638
false
false
false
false
brave/browser-ios
brave/src/data/CRUDProtocols.swift
1
4398
// 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 CoreData import Shared import XCGLogger private let log = Logger.browserLogger // TODO: Creatable, Updateable. Those are not needed at the moment. typealias CRUD = Readable & Deletable public protocol Deletable where Self: NSManagedObject { func delete() static func deleteAll(predicate: NSPredicate?, context: NSManagedObjectContext, includesPropertyValues: Bool, save: Bool) } public protocol Readable where Self: NSManagedObject { static func count(predicate: NSPredicate?) -> Int? static func first(where predicate: NSPredicate?, context: NSManagedObjectContext) -> Self? static func all(where predicate: NSPredicate?, sortDescriptors: [NSSortDescriptor]?, fetchLimit: Int, context: NSManagedObjectContext) -> [Self]? } // MARK: - Implementations public extension Deletable where Self: NSManagedObject { func delete() { let context = DataController.newBackgroundContext() do { let objectOnContext = try context.existingObject(with: self.objectID) context.delete(objectOnContext) DataController.save(context: context) } catch { log.warning("Could not find object: \(self) on a background context.") } } static func deleteAll(predicate: NSPredicate? = nil, context: NSManagedObjectContext = DataController.newBackgroundContext(), includesPropertyValues: Bool = true, save: Bool = true) { guard let request = getFetchRequest() as? NSFetchRequest<NSFetchRequestResult> else { return } request.predicate = predicate request.includesPropertyValues = includesPropertyValues do { // NSBatchDeleteRequest can't be used for in-memory store we use in tests. // Have to delete objects one by one. if AppConstants.IsRunningTest { let results = try context.fetch(request) as? [NSManagedObject] results?.forEach { context.delete($0) } } else { let deleteRequest = NSBatchDeleteRequest(fetchRequest: request) try context.execute(deleteRequest) } } catch { log.error("Delete all error: \(error)") } if save { DataController.save(context: context) } } } public extension Readable where Self: NSManagedObject { static func count(predicate: NSPredicate? = nil) -> Int? { let context = DataController.viewContext let request = getFetchRequest() request.predicate = predicate do { return try context.count(for: request) } catch { log.error("Count error: \(error)") } return nil } static func first(where predicate: NSPredicate?, context: NSManagedObjectContext = DataController.viewContext) -> Self? { return all(where: predicate, fetchLimit: 1, context: context)?.first } static func all(where predicate: NSPredicate? = nil, sortDescriptors: [NSSortDescriptor]? = nil, fetchLimit: Int = 0, context: NSManagedObjectContext = DataController.viewContext) -> [Self]? { let request = getFetchRequest() request.predicate = predicate request.sortDescriptors = sortDescriptors request.fetchLimit = fetchLimit do { return try context.fetch(request) } catch { log.error("Fetch error: \(error)") } return nil } } // Getting a fetch request for each NSManagedObject protocol Fetchable: NSFetchRequestResult {} extension Fetchable { static func getFetchRequest() -> NSFetchRequest<Self> { var selfName = String(describing: self) // This is a hack until FaviconMO won't be renamed to Favicon. if selfName.contains("FaviconMO") { selfName = "Favicon" } return NSFetchRequest<Self>(entityName: selfName) } } extension NSManagedObject: Fetchable {}
mpl-2.0
2b0b280e85ad600452b771e698a1d57f
35.04918
125
0.625284
5.350365
false
false
false
false
jsslai/Action
Carthage/Checkouts/RxSwift/Tests/RxSwiftTests/Tests/SchedulerTests.swift
3
3522
// // SchedulerTests.swift // Rx // // Created by Krunoslav Zaher on 7/22/16. // Copyright © 2016 Krunoslav Zaher. All rights reserved. // import Foundation import RxSwift import XCTest #if os(Linux) import Glibc #endif class ConcurrentDispatchQueueSchedulerTests: RxTest { func createScheduler() -> SchedulerType { return ConcurrentDispatchQueueScheduler(globalConcurrentQueueQOS: .userInitiated) } } class SerialDispatchQueueSchedulerTests: RxTest { func createScheduler() -> SchedulerType { return SerialDispatchQueueScheduler(globalConcurrentQueueQOS: .userInitiated) } } extension ConcurrentDispatchQueueSchedulerTests { func test_scheduleRelative() { let expectScheduling = expectation(description: "wait") let start = Date() var interval = 0.0 let scheduler = self.createScheduler() _ = scheduler.scheduleRelative(1, dueTime: 0.5) { (_) -> Disposable in interval = Date().timeIntervalSince(start) expectScheduling.fulfill() return Disposables.create() } waitForExpectations(timeout: 1.0) { error in XCTAssertNil(error) } XCTAssertEqualWithAccuracy(interval, 0.5, accuracy: 0.1) } func test_scheduleRelativeCancel() { let expectScheduling = expectation(description: "wait") let start = Date() var interval = 0.0 let scheduler = self.createScheduler() let disposable = scheduler.scheduleRelative(1, dueTime: 0.1) { (_) -> Disposable in interval = Date().timeIntervalSince(start) expectScheduling.fulfill() return Disposables.create() } disposable.dispose() DispatchQueue.main.asyncAfter (deadline: .now() + .milliseconds(200)) { expectScheduling.fulfill() } waitForExpectations(timeout: 0.5) { error in XCTAssertNil(error) } XCTAssertEqualWithAccuracy(interval, 0.0, accuracy: 0.1) } func test_schedulePeriodic() { let expectScheduling = expectation(description: "wait") let start = Date() var times = [Date]() let scheduler = self.createScheduler() let disposable = scheduler.schedulePeriodic(0, startAfter: 0.2, period: 0.3) { (state) -> Int in times.append(Date()) if state == 1 { expectScheduling.fulfill() } return state + 1 } waitForExpectations(timeout: 1.0) { error in XCTAssertNil(error) } disposable.dispose() XCTAssertEqual(times.count, 2) XCTAssertEqualWithAccuracy(times[0].timeIntervalSince(start), 0.2, accuracy: 0.1) XCTAssertEqualWithAccuracy(times[1].timeIntervalSince(start), 0.5, accuracy: 0.1) } func test_schedulePeriodicCancel() { let expectScheduling = expectation(description: "wait") var times = [Date]() let scheduler = self.createScheduler() let disposable = scheduler.schedulePeriodic(0, startAfter: 0.2, period: 0.3) { (state) -> Int in times.append(Date()) return state + 1 } disposable.dispose() DispatchQueue.main.asyncAfter (deadline: .now() + .milliseconds(300)) { expectScheduling.fulfill() } waitForExpectations(timeout: 1.0) { error in XCTAssertNil(error) } XCTAssertEqual(times.count, 0) } }
mit
05c81b18dc6aef948330aab13ff1433f
27.168
104
0.61971
4.931373
false
true
false
false
apple/swift
test/Reflection/typeref_decoding_objc.swift
2
2440
// RUN: %empty-directory(%t) // RUN: %target-build-swift %S/Inputs/ObjectiveCTypes.swift -parse-as-library -emit-module -emit-library -module-name TypesToReflect -o %t/%target-library-name(TypesToReflect) // RUN: %target-swift-reflection-dump %t/%target-library-name(TypesToReflect) | %FileCheck %s --check-prefix=CHECK-%target-ptrsize --check-prefix=CHECK // REQUIRES: objc_interop // Disable asan builds until we build swift-reflection-dump and the reflection library with the same compile: rdar://problem/30406870 // REQUIRES: no_asan // rdar://100558042 // UNSUPPORTED: CPU=arm64e // CHECK: FIELDS: // CHECK: ======= // CHECK: TypesToReflect.OC // CHECK: ----------------- // CHECK: nsObject: __C.NSObject // CHECK: (objective_c_class name=NSObject) // CHECK: nsString: __C.NSString // CHECK: (objective_c_class name=NSString) // CHECK: cfString: __C.CFStringRef // CHECK: (alias __C.CFStringRef) // CHECK: aBlock: @convention(block) () -> () // CHECK: (function convention=block // CHECK: (tuple)) // CHECK: ocnss: TypesToReflect.GenericOC<__C.NSString> // CHECK: (bound_generic_class TypesToReflect.GenericOC // CHECK: (objective_c_class name=NSString)) // CHECK: occfs: TypesToReflect.GenericOC<__C.CFStringRef> // CHECK: (bound_generic_class TypesToReflect.GenericOC // CHECK: (alias __C.CFStringRef)) // CHECK: TypesToReflect.GenericOC // CHECK: ------------------------ // CHECK: TypesToReflect.HasObjCClasses // CHECK: ----------------------------- // CHECK: url: __C.NSURL // CHECK: (objective_c_class name=NSURL) // CHECK: integer: Swift.Int // CHECK: (struct Swift.Int) // CHECK: rect: __C.CGRect // CHECK: (struct __C.CGRect) // CHECK: TypesToReflect.OP // CHECK: ----------------- // CHECK: ASSOCIATED TYPES: // CHECK: ================= // CHECK: BUILTIN TYPES: // CHECK: ============== // CHECK-32: - __C.CGRect: // CHECK-32: Size: 16 // CHECK-32: Alignment: 4 // CHECK-32: Stride: 16 // CHECK-32: NumExtraInhabitants: 0 // CHECK-32: BitwiseTakable: 1 // CHECK-64: - __C.CGRect: // CHECK-64: Size: 32 // CHECK-64: Alignment: 8 // CHECK-64: Stride: 32 // CHECK-64: NumExtraInhabitants: 0 // CHECK-64: BitwiseTakable: 1 // CHECK: CAPTURE DESCRIPTORS: // CHECK-NEXT: ==================== // CHECK: - Capture types: // CHECK-NEXT: (objective_c_class name=NSBundle) // CHECK-NEXT: (protocol_composition // CHECK-NEXT: (objective_c_protocol name=NSCoding)) // CHECK-NEXT: - Metadata sources:
apache-2.0
fb3096f743ba8998a5bb334945ddbcda
29.123457
175
0.65123
3.388889
false
false
false
false
avaidyam/Parrot
Parrot/LinkPreviewParser.swift
1
8886
import Foundation /* TODO: Support meta[name="theme-color"] tags for background color tint. */ public enum LinkPreviewError: Error { case invalidUrl(String) case unsafeUrl(URL) case invalidHeaders(URL, Int) case documentTooLarge(URL, Double) case unhandleableUrl(URL, String) case invalidDocument(URL) } public struct LinkMeta { /// og:title, twitter:title, <title /> let title: [String] /// `favicon.ico` let icon: [String] /// og:image, twitter:image let image: [String] /// og:description, twitter:description, <meta name="description" ... /> let description: [String] /// og:type, twitter:card let type: [String] /// og:site (!), twitter:creator let source: [String] /// og:audio let audio: [String] /// og:video, twitter:player let video: [String] } public enum LinkPreviewType { /// MIME: audio/* case audio /// MIME: video/* case video /// MIME: image/* case image(URL) /// MIME: text/plain case snippet(String) /// URL: youtu.be or youtube.com case youtube(String) /// MIME: text/html case link(LinkMeta) /// Special: long text messages case summary(String) } public struct LinkPreviewParser { private init() {} private static let SBKEY = "AIzaSyCE0A8INTc8KQLIaotaHiWvqUkit5-_sTE" private static let SBURL = "https://sb-ssl.google.com/safebrowsing/api/lookup?client=parrot&key=\(SBKEY)&appver=1.0.0&pver=3.1&url=" private static let _validIcons = ["icon", "apple-touch-icon", "apple-touch-icon-precomposed"] private static let _YTDomains = ["youtu.be", "www.youtube.com", "youtube.com"] // Precompile all the regex so we save on time a little. private static let TITLE_REGEX = try! NSRegularExpression(pattern: "(?<=<title>)(?:[\\s\\S]*?)(?=<\\/title>)", options: .caseInsensitive) private static let META_REGEX = try! NSRegularExpression(pattern: "(?:\\<meta)([\\s\\S]*?)(?:>)", options: .caseInsensitive) private static let LINK_REGEX = try! NSRegularExpression(pattern: "(?:\\<link)([\\s\\S]*?)(?:>)", options: .caseInsensitive) private static let NAME_REGEX = try! NSRegularExpression(pattern: "(?<=name=\\\")[\\s\\S]+?(?=\\\")", options: .caseInsensitive) private static let PROP_REGEX = try! NSRegularExpression(pattern: "(?<=property=\\\")[\\s\\S]+?(?=\\\")", options: .caseInsensitive) private static let CONT_REGEX = try! NSRegularExpression(pattern: "(?<=content=\\\")[\\s\\S]+?(?=\\\")", options: .caseInsensitive) private static let REL_REGEX = try! NSRegularExpression(pattern: "(?<=rel=\\\")[\\s\\S]+?(?=\\\")", options: .caseInsensitive) private static let HREF_REGEX = try! NSRegularExpression(pattern: "(?<=href=\\\")[\\s\\S]+?(?=\\\")", options: .caseInsensitive) private static func _get(_ url: URL, method: String = "GET") -> (Data?, URLResponse?, Error?) { return URLSession.shared.synchronousRequest(url, method: method) } private static func _extractTitle(from str: String) -> String { let o = str.find(matching: TITLE_REGEX) let q = CFXMLCreateStringByUnescapingEntities(nil, o.first! as CFString, nil) as String return q.trimmingCharacters(in: .whitespacesAndNewlines) } private static func _extractMetadata(from str: String) -> [String: String] { var tags: [String: String] = [:] for s in str.find(matching: META_REGEX) { var keys = s.find(matching: NAME_REGEX) + s.find(matching: PROP_REGEX) var vals = s.find(matching: CONT_REGEX) keys = keys.flatMap { $0.components(separatedBy: " ") } vals = vals.map { $0.trimmingCharacters(in: .whitespacesAndNewlines) } vals = vals.map { CFXMLCreateStringByUnescapingEntities(nil, $0 as CFString, nil) as String } keys.forEach { tags[$0] = (vals.first ?? "") } } return tags } private static func _extractIcon(from str: String) -> [String] { var icons: [String] = [] for s in str.find(matching: LINK_REGEX) { var keys = s.find(matching: REL_REGEX) let vals = s.find(matching: HREF_REGEX) keys = keys.flatMap { $0.components(separatedBy: " ") } //vals = vals.map { $0.trimmingCharacters(in: .whitespacesAndNewlines()) } //vals = vals.map { CFXMLCreateStringByUnescapingEntities(nil, $0, nil) as String } if keys.contains("icon") || keys.contains("apple-touch-icon") || keys.contains("apple-touch-icon-precomposed") { icons.append(vals.first! ) } } return icons } private static func _verifyLink(_ url: URL) -> (safe: Bool, error: Bool) { let url2 = URL(string: SBURL + url.absoluteString)! let out = _get(url2, method: "HEAD") let resp = (out.1 as? HTTPURLResponse)?.statusCode ?? 0 return (safe: (resp == 204), error: !(resp == 200 || resp == 204)) } private static func _parseMeta(from str: String) -> LinkPreviewType { let m = _extractMetadata(from: str) var title: [String] = [] if let x = m["og:title"] { title.append(x) } if let x = m["twitter:title"] { title.append(x) } title.append(_extractTitle(from: str)) var icon: [String] = [] icon.append(contentsOf: _extractIcon(from: str)) var image: [String] = [] if let x = m["og:image"] { image.append(x) } if let x = m["twitter:image"] { image.append(x) } var description: [String] = [] if let x = m["og:description"] { description.append(x) } if let x = m["twitter:description"] { description.append(x) } if let x = m["description"] { description.append(x) } var type: [String] = [] if let x = m["og:type"] { type.append(x) } if let x = m["twitter:card"] { type.append(x) } var source: [String] = [] if let x = m["og:site"] { source.append(x) } if let x = m["twitter:creator"] { source.append(x) } var audio: [String] = [] if let x = m["og:audio"] { audio.append(x) } var video: [String] = [] if let x = m["og:video"] { video.append(x) } if let x = m["twitter:player"] { video.append(x) } return .link(LinkMeta(title: title, icon: icon, image: image, description: description, type: type, source: source, audio: audio, video: video)) } public static func parse(_ link: String) throws -> LinkPreviewType { // Step 1: Verify valid URL guard let url = URL(string: link) else { throw LinkPreviewError.invalidUrl(link) } // Step 2: Verify safe URL let browse = _verifyLink(url) guard browse.safe && !browse.error else { throw LinkPreviewError.unsafeUrl(url) } // Step 3: Verify URL headers let _headers = _get(url, method: "HEAD") guard let headers = _headers.1 as? HTTPURLResponse else { throw LinkPreviewError.invalidHeaders(url, 0) } guard headers.statusCode == 200 else { throw LinkPreviewError.invalidHeaders(url, headers.statusCode) } // Step 4: Verify URL content type let type = headers.mimeType ?? "" if _YTDomains.contains(url.host ?? "") { var id = "" if let loc = url.absoluteString.range(of: "youtu.be/") { id = String(url.absoluteString[loc.upperBound...]) } else if let loc = url.absoluteString.range(of: "youtube.com/watch?v=") { id = String(url.absoluteString[loc.upperBound...]) } else { throw LinkPreviewError.unhandleableUrl(url, id) } // domain-specialized case (not MIME type) return .youtube(id) } else if type.hasPrefix("image/") { let size = Double(headers.expectedContentLength) / (1024.0 * 1024.0) guard size < 4 else { throw LinkPreviewError.documentTooLarge(url, size) } return .image(url) } else if type.hasPrefix("audio/") { return .audio } else if type.hasPrefix("video/") { return .video } else if type.hasPrefix("text/html") { guard let dl = _get(url).0, let content = NSString(data: dl, encoding: String.Encoding.utf8.rawValue) else { throw LinkPreviewError.invalidDocument(url) } // higher priority than text/* return _parseMeta(from: content as String) } else if type.hasPrefix("text/") { guard let _sz = headers.allHeaderFields["Content-Length"] as? String, let _dz = Double(_sz) else { throw LinkPreviewError.documentTooLarge(url, -1) } let size = _dz / (1024.0 * 1024.0) guard size < 4 else { throw LinkPreviewError.documentTooLarge(url, size) } guard let dl = _get(url).0, let content = NSString(data: dl, encoding: String.Encoding.utf8.rawValue) else { throw LinkPreviewError.invalidDocument(url) } // only use the first 1024 characters. return .snippet(content.substring(to: 512)) } // If we've reached here, none of our code paths can handle the URL. throw LinkPreviewError.unhandleableUrl(url, type) } }
mpl-2.0
06ed8842be0acfdc4112589d2c19217a
38.145374
133
0.628517
3.436195
false
false
false
false
yankodimitrov/SignalKit
SignalKit/Extensions/UIKit/UIControlExtensions.swift
1
1293
// // UIControlExtensions.swift // SignalKit // // Created by Yanko Dimitrov on 3/6/16. // Copyright © 2016 Yanko Dimitrov. All rights reserved. // import UIKit public extension SignalEventType where Sender: UIControl { /// Observe for control events public func events(events: UIControlEvents) -> Signal<Sender> { let signal = Signal<Sender>() let observer = ControlEventObserver(control: sender, events: events) observer.eventCallback = { [weak signal] control in if let control = control as? Sender { signal?.sendNext(control) } } signal.disposableSource = observer return signal } /// Observe the confrol for TouchUpInside events public var tapEvent: Signal<Sender> { return events(.TouchUpInside) } } public extension SignalType where ObservationValue == Bool { /// Bind the boolean value of the signal to the enabled property of UIControl public func bindTo(enabledStateIn control: UIControl) -> Self { addObserver { [weak control] in control?.enabled = $0 } return self } }
mit
cae81121252dafeaa155636978604ee6
22.925926
81
0.578173
5.273469
false
false
false
false
alirsamar/BiOS
beginning-ios-alien-adventure-alien-adventure-2/Alien Adventure/OldestItemFromPlanet.swift
1
1161
// // OldestItemFromPlanet.swift // Alien Adventure // // Created by Jarrod Parkes on 10/3/15. // Copyright © 2015 Udacity. All rights reserved. // extension Hero { func oldestItemFromPlanet(inventory: [UDItem], planet: String) -> UDItem? { var oldestItem: UDItem? = nil var oldestItemCarbonAge = 0 for item in inventory { if var histData = item.historicalData as? [String:AnyObject] { if let planetName = histData["PlanetOfOrigin"] as? String { if let carbonAge = histData["CarbonAge"] as? Int { if planetName == planet && carbonAge > oldestItemCarbonAge { oldestItem = item oldestItemCarbonAge = carbonAge } } } } } return oldestItem } } // If you have completed this function and it is working correctly, feel free to skip this part of the adventure by opening the "Under the Hood" folder, and making the following change in Settings.swift: "static var RequestsToSkip = 2"
mit
c506c56efe0663feb34662ad20049c1e
35.28125
235
0.564655
4.87395
false
false
false
false
xuech/OMS-WH
OMS-WH/Classes/DeliveryGoods/ViewModel/DeliveryGoodsViewModel.swift
1
7015
// // StockInWHSearchViewModel.swift // OMS-WH // // Created by ___Gwy on 2017/9/19. // Copyright © 2017年 medlog. All rights reserved. // import UIKit import SVProgressHUD import ObjectMapper class DeliveryGoodsViewModel: NSObject { func requstDefaultMinuteDeliveryInfo(_ sONo:String, _ api:String, _ finished: @escaping (_ info:DefaultDeliveryInfoModel?,_ error: NSError?)->()){ moyaNetWork.request(.commonRequst(paramters: ["sONo" : sONo], api: api)) { result in switch result { case let .success(moyaResponse): do { let moyaJSON = try moyaResponse.filterSuccessfulStatusCodes() let data = try moyaJSON.mapJSON() as! [String:AnyObject] guard data["code"] as! Int == 0 else { SVProgressHUD.showError(data["msg"] as? String ?? "") return } if let info = data["info"] as? [String:AnyObject]{ let childrenCategory = Mapper<DefaultDeliveryInfoModel>().map(JSONObject: info) finished(childrenCategory, nil) } } catch { } case .failure(_): SVProgressHUD.showError("网络请求错误") break } } } func requstDict(_ param:[String:String],_ finished: @escaping (_ info: [[String : AnyObject]],_ error: NSError?)->()){ XCHRefershUI.show() moyaNetWork.request(.dictoryList(paramters: param)) { result in XCHRefershUI.dismiss() switch result { case let .success(moyaResponse): do { let moyaJSON = try moyaResponse.filterSuccessfulStatusCodes() let data = try moyaJSON.mapJSON() as! [String:AnyObject] guard data["code"] as! Int == 0 else { SVProgressHUD.showError(data["msg"]! as! String) return } if let info = data["info"] as? [[String:AnyObject]]{ finished(info, nil) } } catch { } case .failure(_): SVProgressHUD.showError("网络请求错误") break } } } func requstOutBoundList(_ sONo:String,_ finished: @escaping (_ info: [DGOutBoundListModel],_ error: NSError?)->()){ XCHRefershUI.show() moyaNetWork.request(.commonRequst(paramters: ["sONo":sONo], api: "oms-api-v3/order/waitingDeliveryOutBoundList")) { result in XCHRefershUI.dismiss() switch result { case let .success(moyaResponse): do { let moyaJSON = try moyaResponse.filterSuccessfulStatusCodes() let data = try moyaJSON.mapJSON() as! [String:AnyObject] guard data["code"] as! Int == 0 else { SVProgressHUD.showError(data["msg"]! as! String) return } if let info = data ["info"] as? [[String:AnyObject]]{ var child = [DGOutBoundListModel]() for item in info{ child.append(DGOutBoundListModel.init(dict: item)) } finished(child, nil) } } catch { } case .failure(_): SVProgressHUD.showError("网络请求错误") break } } } func submit(_ param:[String:Any], _ api:String, _ finished: @escaping (_ info:String?,_ error: NSError?)->()){ moyaNetWork.request(.commonRequst(paramters: param, api: api)) { result in switch result { case let .success(moyaResponse): do { let moyaJSON = try moyaResponse.filterSuccessfulStatusCodes() let data = try moyaJSON.mapJSON() as! [String:AnyObject] print(data) guard data["code"] as! Int == 0 else { SVProgressHUD.showError(data["msg"] as? String ?? "") return } finished(data ["info"] as? String, nil) } catch { } case .failure(_): SVProgressHUD.showError("网络请求错误") break } } } func requstdefaultDirectDeliveryInfo(_ sONo:String, _ api:String, _ finished: @escaping (_ info:[String:AnyObject]?,_ error: NSError?)->()){ moyaNetWork.request(.commonRequst(paramters: ["sONo" : sONo], api: api)) { result in switch result { case let .success(moyaResponse): do { let moyaJSON = try moyaResponse.filterSuccessfulStatusCodes() let data = try moyaJSON.mapJSON() as! [String:AnyObject] guard data["code"] as! Int == 0 else { SVProgressHUD.showError(data["msg"]! as! String) return } let info = data["info"] as? [String:AnyObject] finished(info, nil) } catch { } case .failure(_): SVProgressHUD.showError("网络请求错误") break } } } func requstProvince(_ parentDivCode:String, _ api:String, _ finished: @escaping (_ info:[[String:AnyObject]],_ error: NSError?)->()){ moyaNetWork.request(.commonRequst(paramters: ["parentDivCode" : parentDivCode], api: api)) { result in switch result { case let .success(moyaResponse): do { let moyaJSON = try moyaResponse.filterSuccessfulStatusCodes() let data = try moyaJSON.mapJSON() as! [String:AnyObject] print(data) guard data["code"] as! Int == 0 else { SVProgressHUD.showError(data["msg"]! as! String) return } if let info = data["info"] as? [[String:AnyObject]]{ finished(info, nil) } } catch { } case .failure(_): SVProgressHUD.showError("网络请求错误") break } } } }
mit
0e1ceb80253a474f44b71055eaa07872
37.342541
150
0.452161
5.778518
false
false
false
false
interstateone/Pipeline
Pipeline/PipelineOperation.swift
2
4713
// // PipelineOperation.swift // Pipeline // // Created by Brandon Evans on 2015-07-16. // Copyright © 2015 Brandon Evans. All rights reserved. // import Foundation import Result public protocol Pipelinable: class { typealias Value var output: Result<Value, NSError>? { get set } } private enum OperationState { case Ready case Executing case Finished case Cancelled } public class Handlers { var cancelled: () -> () = {} } public class PipelineOperation<T>: NSOperation, Pipelinable { public typealias Fulfill = T -> Void public typealias Reject = NSError -> Void public var output: Result<T, NSError>? private var task: ((Fulfill, Reject, Handlers) -> Void)? private var handlers: Handlers = Handlers() public let internalQueue: PipelineQueue = { let q = PipelineQueue() q.suspended = true return q }() // MARK: State Management class func keyPathsForValuesAffectingIsReady() -> Set<NSObject> { return ["state"] } class func keyPathsForValuesAffectingIsExecuting() -> Set<NSObject> { return ["state"] } class func keyPathsForValuesAffectingIsFinished() -> Set<NSObject> { return ["state"] } class func keyPathsForValuesAffectingIsCancelled() -> Set<NSObject> { return ["state"] } private var _state = OperationState.Ready private var state: OperationState { get { return _state } set(newState) { willChangeValueForKey("state") switch (_state, newState) { case (.Cancelled, _): break // cannot leave the cancelled state case (.Finished, _): break // cannot leave the finished state default: assert(_state != newState, "Performing invalid cyclic state transition.") _state = newState } didChangeValueForKey("state") } } public override var ready: Bool { switch state { case .Ready: return super.ready default: return false } } public override var executing: Bool { return state == .Executing } public override var finished: Bool { return state == .Finished || state == .Cancelled } public override var cancelled: Bool { return state == .Cancelled } // MARK: Initializers public init(task: (Fulfill, Reject, Handlers) -> Void) { self.task = task super.init() } public init(value: T) { self.output = .Success(value) super.init() } // MARK: Execution public override final func start() { state = .Executing main() } public override final func main() { internalQueue.suspended = false if let task = self.task { task(fulfill, reject, handlers) } } public override final func cancel() { if state == .Finished { return } state = .Cancelled internalQueue.cancelAllOperations() handlers.cancelled() super.cancel() } private func fulfill(output: T) { self.output = .Success(output) state = .Finished } private func reject(error: NSError) { self.output = .Failure(error) state = .Finished } // map public func success<U>(successHandler handler: T -> U) -> PipelineOperation<U> { let next = PipelineOperation<U> { fulfill, reject, handlers in if let output = self.output { switch output { case .Failure(let error): reject(error) case .Success(let output): fulfill(handler(output)) } } } next.addDependency(self) internalQueue.addOperation(next) return next } // flatMap public func success<U>(successHandler handler: T -> PipelineOperation<U>) -> PipelineOperation<U> { var next: PipelineOperation<U>! next = PipelineOperation<U> { fulfill, reject, cancelled in if let output = self.output { switch output { case .Failure(let error): reject(error) case .Success(let output): let innerOp = handler(output) innerOp.success { output in fulfill(output) } next.internalQueue.addOperation(innerOp) } } } next.addDependency(self) internalQueue.addOperation(next) return next } }
mit
4e4ab8f73f9479470d1f0a5fb42e194a
24.47027
103
0.560272
5.034188
false
false
false
false
bluesnap/bluesnap-ios
BluesnapSDK/BluesnapSDK/BSApiCaller.swift
1
31941
// // BSApiCaller.swift // BluesnapSDK // // Holds all the messy code for executing http calls // // Created by Shevie Chen on 13/09/2017. // Copyright © 2017 Bluesnap. All rights reserved. // import Foundation class BSApiCaller: NSObject { internal static let PAYPAL_SERVICE = "services/2/tokenized-services/paypal-token?amount=" internal static let PAYPAL_SHIPPING = "&req-confirm-shipping=0&no-shipping=2" internal static let TOKENIZED_SERVICE = "services/2/payment-fields-tokens/" internal static let UPDATE_SHOPPER = "services/2/tokenized-services/shopper" internal static let BLUESNAP_VERSION_HEADER = "BLUESNAP_VERSION_HEADER" internal static let BLUESNAP_VERSION_HEADER_VAL = "2.0" internal static let SDK_VERSION_HEADER = "BLUESNAP_ORIGIN_HEADER" internal static let SDK_VERSION_HEADER_VAL = "IOS SDK " + (BSViewsManager.getBundle().object(forInfoDictionaryKey: "CFBundleShortVersionString") as! String); private static func createRequest(_ urlStr: String, bsToken: BSToken!) -> NSMutableURLRequest { let url = NSURL(string: urlStr)! let request = NSMutableURLRequest(url: url as URL) request.setValue("application/json", forHTTPHeaderField: "Content-Type") request.setValue(bsToken!.tokenStr, forHTTPHeaderField: "Token-Authentication") request.setValue(BLUESNAP_VERSION_HEADER_VAL, forHTTPHeaderField: BLUESNAP_VERSION_HEADER) request.setValue(SDK_VERSION_HEADER_VAL, forHTTPHeaderField: SDK_VERSION_HEADER) return request } /** Fetch all the initial data required for the SDK from BlueSnap server: - BlueSnap Kount MID - Exchange rates - Returning shopper data - Supported Payment methods - parameters: - bsToken: a token for BlueSnap tokenized services - baseCurrency: optional base currency for currency rates; default = USD - completion: a callback function to be called once the data is fetched; receives optional data and optional error */ static func getSdkData(bsToken: BSToken!, baseCurrency: String?, completion: @escaping (BSSdkConfiguration?, BSErrors?) -> Void) { let urlStr = bsToken.serverUrl + "services/2/tokenized-services/sdk-init?base-currency=" + (baseCurrency ?? "USD") let request = createRequest(urlStr, bsToken: bsToken) // fire request var sdkConfig : BSSdkConfiguration? var resultError: BSErrors? let task = URLSession.shared.dataTask(with: request as URLRequest) { (data: Data?, response, error) in if let error = error { let errorType = type(of: error) NSLog("error getting supportedPaymentMethods - \(errorType). Error: \(error.localizedDescription)") resultError = .unknown } else { let httpStatusCode:Int? = (response as? HTTPURLResponse)?.statusCode if (httpStatusCode != nil && httpStatusCode! >= 200 && httpStatusCode! <= 299) { (sdkConfig, resultError) = parseSdkDataJSON(data: data) } else { resultError = parseHttpError(data: data, httpStatusCode: httpStatusCode) } } defer { completion(sdkConfig, resultError) } } task.resume() } private static func parseSdkDataJSON(data: Data?) -> (BSSdkConfiguration?, BSErrors?) { var resultData: BSSdkConfiguration? var resultError: BSErrors? if let data = data { do { // Parse the result JSOn object if let json = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [String: AnyObject] { resultData = BSSdkConfiguration() if let kountMID = json["kountMerchantId"] as? Int { resultData?.kountMID = kountMID } if let rates = json["rates"] as? [String: AnyObject] { let currencies = parseCurrenciesJSON(json: rates) resultData?.currencies = currencies } else { resultError = .unknown NSLog("Error parsing BS currency rates") } if let shopper = json["shopper"] as? [String: AnyObject] { let shopper = parseShopperJSON(json: shopper) resultData?.shopper = shopper } if let supportedPaymentMethods = json["supportedPaymentMethods"] as? [String: AnyObject] { let methods = parseSupportedPaymentMethodsJSON(json: supportedPaymentMethods) resultData?.supportedPaymentMethods = methods } else { resultError = .unknown NSLog("Error parsing supported payment methods") } } else { resultError = .unknown NSLog("Error parsing BS currency rates") } } catch let error as NSError { resultError = .unknown NSLog("Error parsing BS currency rates: \(error.localizedDescription)") } } else { resultError = .unknown NSLog("No BS currency data exists") } return (resultData, resultError) } /** Calls BlueSnap server to create a PayPal token - parameters: - bsToken: a token for BlueSnap tokenized services - purchaseDetails: details of the purchase: specifically amount and currency are used - withShipping: setting for the PayPal flow - do we want to request shipping details from the shopper - completion: a callback function to be called once the PayPal token is fetched; receives optional PayPal Token string data and optional error */ static func createPayPalToken(bsToken: BSToken!, purchaseDetails: BSPayPalSdkResult, withShipping: Bool, completion: @escaping (String?, BSErrors?) -> Void) { var urlStr = bsToken.serverUrl + PAYPAL_SERVICE + "\(purchaseDetails.getAmount() ?? 0)" + "&currency=" + purchaseDetails.getCurrency() if withShipping { urlStr += PAYPAL_SHIPPING } let request = createRequest(urlStr, bsToken: bsToken) // fire request var resultToken: String? var resultError: BSErrors? let task = URLSession.shared.dataTask(with: request as URLRequest) { (data, response, error) in if let error = error { let errorType = type(of: error) NSLog("error creating PayPal token - \(errorType). Error: \(error.localizedDescription)") } else { let httpStatusCode:Int? = (response as? HTTPURLResponse)?.statusCode if (httpStatusCode != nil && httpStatusCode! >= 200 && httpStatusCode! <= 299) { (resultToken, resultError) = parsePayPalTokenJSON(data: data) } else { resultError = parseHttpError(data: data, httpStatusCode: httpStatusCode) } } defer { completion(resultToken, resultError) } } task.resume() } /** Fetch a list of merchant-supported payment methods from BlueSnap server - parameters: - bsToken: a token for BlueSnap tokenized services - completion: a callback function to be called once the data is fetched; receives optional payment method list and optional error */ static func getSupportedPaymentMethods(bsToken: BSToken!, completion: @escaping ([String]?, BSErrors?) -> Void) { let urlStr = bsToken.serverUrl + "services/2/tokenized-services/supported-payment-methods" let request = createRequest(urlStr, bsToken: bsToken) // fire request var supportedPaymentMethods: [String]? var resultError: BSErrors? let task = URLSession.shared.dataTask(with: request as URLRequest) { (data: Data?, response, error) in if let error = error { let errorType = type(of: error) NSLog("error getting supportedPaymentMethods - \(errorType). Error: \(error.localizedDescription)") resultError = .unknown } else { let httpStatusCode:Int? = (response as? HTTPURLResponse)?.statusCode if (httpStatusCode != nil && httpStatusCode! >= 200 && httpStatusCode! <= 299) { (supportedPaymentMethods, resultError) = parsePaymentMethodsData(data: data) } else { resultError = parseHttpError(data: data, httpStatusCode: httpStatusCode) } } defer { completion(supportedPaymentMethods, resultError) } } task.resume() } /** Submit payment fields to BlueSnap */ static func submitPaymentDetails(bsToken: BSToken!, requestBody: [String: String], parseFunction: @escaping (Int, Data?) -> ([String:String],BSErrors?), completion: @escaping ([String:String], BSErrors?) -> Void) { createHttpRequest(bsToken: bsToken, requestBody: requestBody, parseFunction: parseFunction, urlStringWithoutDomain: TOKENIZED_SERVICE, httpMethod: "PUT", completion: completion) } /** Update Shopper */ static func updateShopper(bsToken: BSToken!, requestBody: [String: Any], parseFunction: @escaping (Int, Data?) -> ([String: String], BSErrors?), completion: @escaping ([String: String], BSErrors?) -> Void) { createHttpRequest(bsToken: bsToken, requestBody: requestBody, parseFunction: parseFunction, urlStringWithoutDomain: UPDATE_SHOPPER, httpMethod: "PUT", completion: completion) } /** Create Http Request */ static func createHttpRequest(bsToken: BSToken!, requestBody: [String: Any], parseFunction: @escaping (Int, Data?) -> ([String:String],BSErrors?), urlStringWithoutDomain: String, httpMethod: String, completion: @escaping ([String:String], BSErrors?) -> Void) { let domain: String! = bsToken!.serverUrl let urlStr = (TOKENIZED_SERVICE == urlStringWithoutDomain) ? domain + urlStringWithoutDomain + bsToken!.getTokenStr() : domain + urlStringWithoutDomain var request = createRequest(urlStr, bsToken: bsToken) request.httpMethod = httpMethod do { request.httpBody = try JSONSerialization.data(withJSONObject: requestBody, options: .prettyPrinted) } catch let error { NSLog("Error update shopper: \(error.localizedDescription)") } // fire request var resultError: BSErrors? let task = URLSession.shared.dataTask(with: request as URLRequest) { (data, response, error) in var resultData: [String: String] = [:] if let error = error { let errorType = type(of: error) NSLog("error createHttpRequest - \(errorType) for URL \(urlStr). Error: \(error.localizedDescription)") completion(resultData, .unknown) return } let httpResponse = response as? HTTPURLResponse if let httpStatusCode: Int = (httpResponse?.statusCode) { (resultData, resultError) = parseFunction(httpStatusCode, data) } else { NSLog("Error getting response from BS on createHttpRequest") } defer { completion(resultData, resultError) } } task.resume() } static func parseCCResponse(httpStatusCode: Int, data: Data?) -> ([String: String], BSErrors?) { var resultData: [String: String] = [:] var resultError: BSErrors? if (httpStatusCode >= 200 && httpStatusCode <= 299) { (resultData, resultError) = parseResultCCDetailsFromResponse(data: data) } else if (httpStatusCode >= 400 && httpStatusCode <= 499) { resultError = parseHttpError(data: data, httpStatusCode: httpStatusCode) } else { NSLog("Http error submitting CC details to BS; HTTP status = \(httpStatusCode)") resultError = .unknown } return (resultData, resultError) } static func parseGenericResponse(httpStatusCode: Int, data: Data?) -> ([String:String], BSErrors?) { let resultData: [String:String] = [:] var resultError: BSErrors? if (httpStatusCode >= 200 && httpStatusCode <= 299) { } else if (httpStatusCode >= 400 && httpStatusCode <= 499) { resultError = parseHttpError(data: data, httpStatusCode: httpStatusCode) } else { NSLog("Http error submitting CC details to BS; HTTP status = \(httpStatusCode)") resultError = .unknown } return (resultData, resultError) } static func parseResultCCDetailsFromResponse(data: Data?) -> ([String:String], BSErrors?) { var resultData: [String:String] = [:] var resultError: BSErrors? = nil if let data = data { if !data.isEmpty { do { // Parse the result JSOn object if let json = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [String: AnyObject] { resultData[BSTokenizeBaseCCDetails.CARD_TYPE_KEY] = json[BSTokenizeBaseCCDetails.CARD_TYPE_KEY] as? String resultData[BSTokenizeBaseCCDetails.LAST_4_DIGITS_KEY] = json[BSTokenizeBaseCCDetails.LAST_4_DIGITS_KEY] as? String resultData[BSTokenizeBaseCCDetails.ISSUING_COUNTRY_KEY] = (json[BSTokenizeBaseCCDetails.ISSUING_COUNTRY_KEY] as? String ?? "").uppercased() } else { NSLog("Error parsing BS result on CC details submit") resultError = .unknown } } catch let error as NSError { NSLog("Error parsing BS result on CC details submit: \(error.localizedDescription)") resultError = .unknown } } } return (resultData, resultError) } internal static func parseApplePayResponse(httpStatusCode: Int, data: Data?) -> ([String:String], BSErrors?) { let resultData: [String:String] = [:] var resultError: BSErrors? if (httpStatusCode >= 200 && httpStatusCode <= 299) { NSLog("ApplePay data submitted successfully") } else if (httpStatusCode >= 400 && httpStatusCode <= 499) { resultError = parseHttpError(data: data, httpStatusCode: httpStatusCode) } else { NSLog("Http error submitting ApplePay details to BS; HTTP status = \(httpStatusCode)") resultError = .unknown } return (resultData, resultError) } /** This function checks if a token is expired by trying to submit payment fields, then checking the response. */ static func isTokenExpired(bsToken: BSToken?, completion: @escaping (Bool) -> Void) { if let bsToken = bsToken { // create request let urlStr = bsToken.serverUrl + TOKENIZED_SERVICE + bsToken.getTokenStr() var request = createRequest(urlStr, bsToken: bsToken) request.httpMethod = "PUT" do { let requestBody = ["dummy":"check:"] request.httpBody = try JSONSerialization.data(withJSONObject: requestBody, options: .prettyPrinted) } catch let error { NSLog("Error serializing CC details: \(error.localizedDescription)") } // fire request var result: Bool = false let task = URLSession.shared.dataTask(with: request as URLRequest) { (data, response, error) in var resultData: [String:String] = [:] if let error = error { let errorType = type(of: error) NSLog("error submitting to check if token is expired - \(errorType). Error: \(error.localizedDescription)") return } let httpResponse = response as? HTTPURLResponse if let httpStatusCode: Int = (httpResponse?.statusCode) { if httpStatusCode == 400 { let errStr = extractError(data: data) result = errStr == "EXPIRED_TOKEN" || errStr == "TOKEN_NOT_FOUND" } } else { NSLog("Error getting response from BS on check if token is expired") } defer { completion(result) } } task.resume() } else { completion(true) } } // MARK: private functions private static func parseHttpError(data: Data?, httpStatusCode: Int?) -> BSErrors { var resultError : BSErrors = .invalidInput let errStr : String? = extractError(data: data) if (httpStatusCode != nil && httpStatusCode! >= 400 && httpStatusCode! <= 499) { if (errStr == "EXPIRED_TOKEN") { resultError = .expiredToken } else if (errStr == "INVALID_CC_NUMBER") { resultError = .invalidCcNumber } else if (errStr == "INVALID_CVV") { resultError = .invalidCvv } else if (errStr == "INVALID_EXP_DATE") { resultError = .invalidExpDate } else if (errStr == "CARD_TYPE_NOT_SUPPORTED") { resultError = .cardTypeNotSupported } else if (BSStringUtils.startsWith(theString: errStr ?? "", subString: "TOKEN_WAS_ALREADY_USED_FOR_")) { resultError = .tokenAlreadyUsed } else if httpStatusCode == 403 && errStr == "Unauthorized" { resultError = .tokenAlreadyUsed // PayPal } else if (errStr == "PAYPAL_UNSUPPORTED_CURRENCY") { resultError = .paypalUnsupportedCurrency } else if (errStr == "PAYPAL_TOKEN_ALREADY_USED") { resultError = .paypalUTokenAlreadyUsed } else if (errStr == "TOKEN_NOT_FOUND") { resultError = .tokenNotFound } else if httpStatusCode == 401 { resultError = .unAuthorised } } else { resultError = .unknown NSLog("Http error; HTTP status = \(String(describing: httpStatusCode))") } return resultError } private static func extractError(data: Data?) -> String { var errStr : String? if let data = data { do { // sometimes the data is not JSON :( let str : String = String(data: data, encoding: .utf8) ?? "" let p = str.firstIndex(of: "{") if p == nil { errStr = str.replacingOccurrences(of: "\"", with: "") } else { let json = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as! [String: AnyObject] if let messages = json["message"] as? [[String: AnyObject]] { if let message = messages[0] as? [String: String] { errStr = message["errorName"] } else { NSLog("Error - result messages does not contain message") } } else { NSLog("Error - result data does not contain messages") } } } catch let error { NSLog("Error parsing result data; error: \(error.localizedDescription)") } } else { NSLog("Error - result data is empty") } return errStr ?? "" } private static func parseCurrenciesJSON(json: [String: AnyObject]) -> BSCurrencies { var currencies: [BSCurrency] = [] var baseCurrency = "USD" if let currencyName = json["baseCurrencyName"] as? String , let currencyCode = json["baseCurrency"] as? String { let bsCurrency = BSCurrency(name: currencyName, code: currencyCode, rate: 1.0) currencies.append(bsCurrency) baseCurrency = currencyCode } if let exchangeRatesArr = json["exchangeRate"] as? [[String: Any]] { for exchangeRateItem in exchangeRatesArr { if let currencyName = exchangeRateItem["quoteCurrencyName"] as? String , let currencyCode = exchangeRateItem["quoteCurrency"] as? String , let currencyRate = exchangeRateItem["conversionRate"] as? Double { let bsCurrency = BSCurrency(name: currencyName, code: currencyCode, rate: currencyRate) currencies.append(bsCurrency) } } } currencies = currencies.sorted { $0.name < $1.name } return BSCurrencies(baseCurrency: baseCurrency, currencies: currencies) } private static func parseShopperJSON(json: [String: AnyObject]) -> BSShopper { let shopper = BSShopper() if let firstName = json["firstName"] as? String , let lastName = json["lastName"] as? String { shopper.name = firstName + " " + lastName } if let email = json["email"] as? String { shopper.email = email } if let country = json["country"] as? String { shopper.country = country } if let state = json["state"] as? String { shopper.state = state } if let address = json["address"] as? String { shopper.address = address } if let address2 = json["address2"] as? String { if (shopper.address == nil) { shopper.address = address2 } else { shopper.address2 = address2 } } if let city = json["city"] as? String { shopper.city = city } if let zip = json["zip"] as? String { shopper.zip = zip } if let phone = json["phone"] as? String { shopper.phone = phone } if let shipping = json["shippingContactInfo"] as? [String: AnyObject] { let shippingDetails = BSShippingAddressDetails() shopper.shippingDetails = shippingDetails if let firstName = shipping["firstName"] as? String , let lastName = shipping["lastName"] as? String { shippingDetails.name = firstName + " " + lastName } if let country = shipping["country"] as? String { shippingDetails.country = country } if let state = shipping["state"] as? String { shippingDetails.state = state } if let address = shipping["address1"] as? String { shippingDetails.address = address } if let address2 = shipping["address2"] as? String { if (shopper.address == nil) { shippingDetails.address = address2 } else { shippingDetails.address = shopper.address! + " " + address2 } } if let city = shipping["city"] as? String { shippingDetails.city = city } if let zip = shipping["zip"] as? String { shippingDetails.zip = zip } } if let paymentSources = json["paymentSources"] as? [String: AnyObject] { if let creditCardInfo = paymentSources["creditCardInfo"] as? [[String: AnyObject]] { for ccDetailsJson in creditCardInfo { var billingDetails : BSBillingAddressDetails? if let billingContactInfo = ccDetailsJson["billingContactInfo"] as? [String: AnyObject] { billingDetails = BSBillingAddressDetails() if let firstName = billingContactInfo["firstName"] as? String , let lastName = billingContactInfo["lastName"] as? String { billingDetails?.name = firstName + " " + lastName } if let country = billingContactInfo["country"] as? String { billingDetails?.country = country } if let state = billingContactInfo["state"] as? String { billingDetails?.state = state } if let address = billingContactInfo["address1"] as? String { billingDetails?.address = address } if let address2 = billingContactInfo["address2"] as? String { if (shopper.address == nil) { billingDetails?.address = address2 } else { billingDetails?.address = shopper.address! + " " + address2 } } if let city = billingContactInfo["city"] as? String { billingDetails?.city = city } if let zip = billingContactInfo["zip"] as? String { billingDetails?.zip = zip } } if let creditCardJson = ccDetailsJson["creditCard"] as? [String: AnyObject] { let cc = parseCreditCardJSON(creditCardJson: creditCardJson) // add the CC only if it's not expired let validCc: (Bool, String) = BSValidator.isCcValidExpiration(mm: cc.expirationMonth ?? "", yy: cc.expirationYear ?? "") if validCc.0 { let ccInfo = BSCreditCardInfo(creditCard: cc, billingDetails: billingDetails) shopper.existingCreditCards.append(ccInfo) } } } } } if let chosenPaymentMethod = json["chosenPaymentMethod"] as? [String: AnyObject] { let methods = parseChosenPaymentMethodsJSON(json: chosenPaymentMethod) shopper.chosenPaymentMethod = methods } if let vaultedShopperId = json["vaultedShopperId"] as? Int { shopper.vaultedShopperId = vaultedShopperId } return shopper } private static func parseCreditCardJSON(creditCardJson: [String: AnyObject]) -> (BSCreditCard) { let cc = BSCreditCard() if let cardLastFourDigits = creditCardJson["cardLastFourDigits"] as? String { cc.last4Digits = cardLastFourDigits } if let cardType = creditCardJson["cardType"] as? String { cc.ccType = cardType } if let expirationMonth = creditCardJson["expirationMonth"] as? String, let expirationYear = creditCardJson["expirationYear"] as? String { cc.expirationMonth = expirationMonth cc.expirationYear = expirationYear } return cc } private static func parsePayPalTokenJSON(data: Data?) -> (String?, BSErrors?) { var resultToken: String? var resultError: BSErrors? if let data = data { do { // Parse the result JSOn object if let json = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [String: AnyObject] { resultToken = json["paypalUrl"] as? String } else { resultError = .unknown NSLog("Error parsing BS result on getting PayPal Token") } } catch let error as NSError { resultError = .unknown NSLog("Error parsing BS result on getting PayPal Token: \(error.localizedDescription)") } } else { resultError = .unknown NSLog("No data in BS result on getting PayPal Token") } return (resultToken, resultError) } private static func parsePaymentMethodsData(data: Data?) -> ([String]?, BSErrors?) { var resultArr: [String]? var resultError: BSErrors? if let data = data { do { // Parse the result JSOn object if let json = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [String: AnyObject] { resultArr = parseSupportedPaymentMethodsJSON(json: json) } else { resultError = .unknown NSLog("Error parsing BS Supported Payment Methods") } } catch let error as NSError { resultError = .unknown NSLog("Error parsing Bs Supported Payment Methods: \(error.localizedDescription)") } } else { resultError = .unknown NSLog("No BS Supported Payment Methods data exists") } return (resultArr, resultError) } private static func parseSupportedPaymentMethodsJSON(json: [String: AnyObject]) -> [String]? { // insert SDKInit Regex data to the cardTypeRegex Validator while maintaining order if let cardTypesRegex = json["creditCardRegex"] as? [String: String] { var index: Int = 0 for (k,v) in cardTypesRegex { BSValidator.cardTypesRegex[index] = (cardType: k, regexp: v) index += 1 } } var resultArr: [String]? if let arr = json["paymentMethods"] as? [String] { resultArr = arr } return resultArr } private static func parseChosenPaymentMethodsJSON(json: [String: AnyObject]) -> BSChosenPaymentMethod? { let chosenPaymentMethod = BSChosenPaymentMethod() if let chosenPaymentMethodType = json["chosenPaymentMethodType"] as? String { chosenPaymentMethod.chosenPaymentMethodType = chosenPaymentMethodType } if let creditCard = json["creditCard"] as? [String: AnyObject] { let cc = parseCreditCardJSON(creditCardJson: creditCard) chosenPaymentMethod.creditCard = cc } return chosenPaymentMethod } /** Build the basic authentication header from username/password - parameters: - user: username - password: password */ private static func getBasicAuth(user: String!, password: String!) -> String { let loginStr = String(format: "%@:%@", user, password) let loginData = loginStr.data(using: String.Encoding.utf8)! let base64LoginStr = loginData.base64EncodedString() return "Basic \(base64LoginStr)" } }
mit
8f8c70983809b215d1e0dca1060900c4
42.99449
185
0.557013
5.503101
false
false
false
false
DRybochkin/Spika.swift
Spika/ViewController/UsersViewController/CSUsersViewController.swift
1
4120
// // UsersViewController.h // Prototype // // Created by Dmitry Rybochkin on 25.02.17. // Copyright (c) 2015 Clover Studio. All rights reserved. // import UIKit class CSUsersViewController: CSBaseViewController, UITableViewDelegate, UITableViewDataSource { var roomID: String = "" var token: String = "" var users: [CSUserModel]! @IBOutlet weak var tableView: UITableView! @IBOutlet var parentView: UIView! convenience init() { self.init(roomID: "", token: "") } init(roomID: String, token: String) { self.roomID = roomID self.token = token super.init(nibName: "CSUsersViewController", bundle: Bundle.main) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view from its nib. parentView.backgroundColor = kAppGrayLight(1) tableView.backgroundColor = kAppGrayLight(1) tableView.register(UINib(nibName: "CSUsersTableViewCell", bundle: nil), forCellReuseIdentifier: KAppCellType.Users.rawValue) getUsers() } override func viewWillAppear(_ animated: Bool) { title = String(format: "Users in %@", roomID) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func viewDidLayoutSubviews() { tableView.separatorInset = UIEdgeInsets.zero tableView.layoutMargins = UIEdgeInsets.zero tableView.allowsSelection = false } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let user: CSUserModel! = users[indexPath.row] let cell: CSUsersTableViewCell! = tableView.dequeueReusableCell(withIdentifier: KAppCellType.Users.rawValue, for: indexPath) as! CSUsersTableViewCell cell?.user = user return cell! } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 108 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if (users != nil) { return users.count } return 0 } func getUsers() { let url = String(format: "%@%@/%@", CSCustomConfig.sharedInstance.server_url, KAppAPIMethod.GetUsersInRoom.rawValue, roomID) CSApiManager.shared.apiGETCall(url: url, vc: self, finish: {(_ responseModel: CSResponseModel?, _ error: Error?) -> Void in self.users = [] if (responseModel != nil) { let respModel = responseModel! if (respModel.code.intValue > 1) { let alert: UIAlertController = UIAlertController.init(title: "Error", message: CSChatErrorCodes.error(forCode: respModel.code), preferredStyle: .alert) let actionOk: UIAlertAction = UIAlertAction.init(title: "OK", style: .default, handler: nil) alert.addAction(actionOk) self.present(alert, animated: true, completion: nil) return } else if (responseModel?.data != nil) { let values: [Any] = Array(respModel.data.values.first as! [Any]) for item in values { let itemUser = (try? CSUserModel(dictionary: item as! [AnyHashable: Any])) self.users.append(itemUser!) } } self.tableView.reloadData() } else { let alert: UIAlertController = UIAlertController.init(title: "Error", message: error?.localizedDescription, preferredStyle: .alert) let actionOk: UIAlertAction = UIAlertAction.init(title: "OK", style: .default, handler: nil) alert.addAction(actionOk) self.present(alert, animated: true, completion: nil) } }) } deinit { print("dealloc: UsersViewController") } }
mit
e8f2a9f44572148ab2e5eca8667f1cda
37.148148
171
0.617718
4.847059
false
false
false
false
carabina/ActionSwift3
ActionSwift3/SKMultilineLabel.swift
1
6368
// // SKMultilineLabel.swift // GrabbleWords // // Created by Craig on 10/04/2015. // Copyright (c) 2015 Interactive Coconut. All rights reserved. // /* USE: (most component parameters have defaults) ``` let multiLabel = SKMultilineLabel(text: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.", labelWidth: 250, pos: CGPoint(x: size.width / 2, y: size.height / 2)) self.addChild(multiLabel) ``` */ import SpriteKit class SKMultilineLabel: SKNode { //props var labelWidth:CGFloat {didSet {update()}} var labelHeight:CGFloat = 0 var text:String {didSet {update()}} var fontName:String {didSet {update()}} var fontSize:CGFloat {didSet {update()}} /**refers to the centre(x) top(y) of the label*/ var pos:CGPoint {didSet {update()}} var fontColor:UIColor {didSet {update()}} var leading:CGFloat {didSet {update()}} var alignment:SKLabelHorizontalAlignmentMode {didSet {update()}} var dontUpdate = false var shouldShowBorder:Bool = false {didSet {update()}} var shouldShowBackground:Bool = false {didSet {update()}} var borderColor:UIColor = UIColor.whiteColor() var backgroundColor:UIColor = UIColor.whiteColor() //display objects var rect:SKShapeNode? var labels:[SKLabelNode] = [] var lineCount = 0 init(text:String, labelWidth:CGFloat, pos:CGPoint, fontName:String="ChalkboardSE-Regular",fontSize:CGFloat=10,fontColor:UIColor=UIColor.blackColor(),leading:CGFloat=10, alignment:SKLabelHorizontalAlignmentMode = .Center, shouldShowBorder:Bool = false,shouldShowBackground:Bool = false,borderColor:UIColor = UIColor.whiteColor(),backgroundColor:UIColor = UIColor.whiteColor()) { self.text = text self.labelWidth = labelWidth self.pos = pos self.fontName = fontName self.fontSize = fontSize self.fontColor = fontColor self.leading = leading self.shouldShowBorder = shouldShowBorder self.shouldShowBackground = shouldShowBackground self.borderColor = borderColor self.backgroundColor = backgroundColor self.alignment = alignment super.init() self.update(forceUpdate: true) } //if you want to change properties without updating the text field, // set dontUpdate to true and call the update method manually, passing forceUpdate as true. func update(forceUpdate:Bool = false) { if (dontUpdate && !forceUpdate) {return} if (labels.count>0) { for label in labels { label.removeFromParent() } labels = [] } let separators = NSCharacterSet.whitespaceAndNewlineCharacterSet() let words = text.componentsSeparatedByCharactersInSet(separators) let len = count(text) var finalLine = false var wordCount = -1 lineCount = 0 while (!finalLine) { lineCount++ var lineLength = CGFloat(0) var lineString = "" var lineStringBeforeAddingWord = "" // creation of the SKLabelNode itself var label = SKLabelNode(fontNamed: fontName) // name each label node so you can animate it if u wish label.name = "line\(lineCount)" label.horizontalAlignmentMode = alignment label.fontSize = fontSize label.fontColor = fontColor while lineLength < CGFloat(labelWidth) { wordCount++ if wordCount > words.count-1 { //label.text = "\(lineString) \(words[wordCount])" finalLine = true break } else { lineStringBeforeAddingWord = lineString lineString = "\(lineString) \(words[wordCount])" label.text = lineString lineLength = label.frame.width } } if lineLength > 0 { wordCount-- if (!finalLine) { lineString = lineStringBeforeAddingWord } label.text = lineString var linePos = pos if (alignment == .Left) { linePos.x -= CGFloat(labelWidth / 2) } else if (alignment == .Right) { linePos.x += CGFloat(labelWidth / 2) } linePos.y += -leading * CGFloat(lineCount) label.position = CGPointMake( linePos.x , linePos.y ) self.addChild(label) labels.append(label) } } labelHeight = CGFloat(lineCount) * leading showBorder() } func showBorder() { if (!shouldShowBorder && !shouldShowBackground) {return} if let rect = self.rect { self.removeChildrenInArray([rect]) } self.rect = SKShapeNode(rectOfSize: CGSize(width: labelWidth, height: labelHeight)) if let rect = self.rect { if (shouldShowBackground) { rect.fillColor = backgroundColor } if (shouldShowBorder) { rect.strokeColor = borderColor rect.lineWidth = 1 } rect.position = CGPoint(x: pos.x, y: pos.y - (CGFloat(labelHeight) / 2.0)) self.insertChild(rect, atIndex: 0) rect.zPosition = -1 } } var width:CGFloat { return CGFloat(labelWidth) } var height:CGFloat { get { if labels.count==0 { return 0 } else { return (CGFloat(labels.count * Int(leading))) } } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
mit
d2548651c09116fbaaa63f958d81628a
36.458824
558
0.581972
5.118971
false
false
false
false
antonio081014/LeeCode-CodeBase
Swift/longest-palindromic-subsequence.swift
2
2390
/** * https://leetcode.com/problems/longest-palindromic-subsequence/ * * */ // Date: Thu May 14 11:22:30 PDT 2020 class Solution { /// Dynamic Programming. /// isPalindromic[start][end] indicates the max length of valid palindromic substring from start to end, inclusive. /// - Complexity: /// - Time: O(n^2), n is the length of string /// - Space: O(n^2), n is the length of string /// func longestPalindromeSubseq(_ s: String) -> Int { let s = Array(s) var isPalindromic: [[Int]] = Array(repeating: Array(repeating: 0, count: s.count), count: s.count) for len in 1 ... s.count { for start in 0 ... (s.count - len) { let end = start + len - 1 if len == 1 { isPalindromic[start][end] = 1 } else { isPalindromic[start][end] = max(isPalindromic[start][end], isPalindromic[start + 1][end]) isPalindromic[start][end] = max(isPalindromic[start][end], isPalindromic[start][end - 1]) if s[start] == s[end] { isPalindromic[start][end] = max(isPalindromic[start][end], isPalindromic[start + 1][end - 1] + 2) } } } } return isPalindromic[0][s.count - 1] } } /** * https://leetcode.com/problems/longest-palindromic-subsequence/ * * */ // Date: Thu May 14 11:31:15 PDT 2020 class Solution { /// Faster with less comparison function `max` used. func longestPalindromeSubseq(_ s: String) -> Int { let s = Array(s) var isPalindromic: [[Int]] = Array(repeating: Array(repeating: 0, count: s.count), count: s.count) for len in 1 ... s.count { for start in 0 ... (s.count - len) { let end = start + len - 1 if len == 1 { isPalindromic[start][end] = 1 } else { if s[start] == s[end] { isPalindromic[start][end] = max(isPalindromic[start][end], isPalindromic[start + 1][end - 1] + 2) } else { isPalindromic[start][end] = max(isPalindromic[start][end - 1], isPalindromic[start + 1][end]) } } } } return isPalindromic[0][s.count - 1] } }
mit
286a967ead3b8ca40840be8d50e01c13
38.180328
121
0.508787
4.057725
false
false
false
false
zats/Tribute
TributeTests/TributeTests.swift
1
68645
// // TributeTests.swift // TributeTests // // Created by Sash Zats on 11/26/15. // Copyright © 2015 Sash Zats. All rights reserved. // import Quick import Nimble @testable import Tribute class TributeSpec: QuickSpec { override func spec() { var string: NSMutableAttributedString! beforeEach{ string = NSMutableAttributedString() } context("internals") { // we are testing implementation details only to use internal methods as a part of the test flow describe("runningAttributes") { it("should report nil if string is empty") { expect(string.runningAttributes).to(beNil()) } it("should report last attributes if string is not empty") { let attributes: [String: NSObject] = [ NSFontAttributeName: UIFont.boldSystemFontOfSize(12), NSForegroundColorAttributeName: UIColor.redColor() ] string.appendAttributedString(NSAttributedString(string: "persimmon", attributes: attributes)) expect(string.runningAttributes).to(haveCount(attributes.count)) for (key, value) in attributes { expect(string.runningAttributes?[key] as? NSObject).to(equal(value)) } } } } context("sanity") { describe("empty string") { it("produces no attributes") { string.add("картошка") expect(string.attributesAtIndex(0, effectiveRange: nil)).to(haveCount(0)) } it("keeps existent attributes") { string.appendAttributedString(NSAttributedString(string: "תפוח", attributes: [ NSForegroundColorAttributeName: UIColor.redColor() ])) string.add(" אדמה") guard let attributes = string.runningAttributes else { fail("No attributes found") return } expect(attributes).to(haveCount(1)) expect(attributes[NSForegroundColorAttributeName] as? UIColor).to(equal(UIColor.redColor())) } it("resets attributes") { string.appendAttributedString(NSAttributedString(string: "apple", attributes: [ NSForegroundColorAttributeName: UIColor.redColor() ])) string.add("pineapple") { (inout a: Attributes) in a.reset() } expect(string.runningAttributes!).to(haveCount(0)) } } describe("simple manipulations") { it("should keep running attributes") { string.add("Hello ") { (inout a: Attributes) in a.color = .redColor() } string.add("world") { _ in } let attributes = string.runningAttributes expect(attributes).to(haveCount(1)) expect(attributes![NSForegroundColorAttributeName] as? UIColor).to(equal(UIColor.redColor())) } } } context("properties") { describe("alignment") { it("sets new value") { string.add("potato") { (inout a: Attributes) in a.alignment = .Center } expect(string.runningAttributes).to(haveCount(1)) let paragraph = string.runningAttributes![NSParagraphStyleAttributeName] as? NSParagraphStyle expect(paragraph?.alignment).to(equal(NSTextAlignment.Center)) } it("sets new value equal to default") { string.add("potato") { (inout a: Attributes) in a.alignment = NSParagraphStyle.defaultParagraphStyle().alignment } expect(string.runningAttributes).to(haveCount(1)) let paragraph = string.runningAttributes![NSParagraphStyleAttributeName] as? NSParagraphStyle expect(paragraph?.alignment).to(equal(NSParagraphStyle.defaultParagraphStyle().alignment)) } it("overrides existent value with a new one") { string.add("tomato") { (inout a: Attributes) in a.alignment = .Center } string.add("potato") { (inout a: Attributes) in expect(string.runningAttributes).to(haveCount(1)) let paragraph = string.runningAttributes![NSParagraphStyleAttributeName] as? NSParagraphStyle expect(paragraph?.alignment).to(equal(NSTextAlignment.Center)) a.alignment = .Justified } expect(string.runningAttributes).to(haveCount(1)) let paragraph = string.runningAttributes![NSParagraphStyleAttributeName] as? NSParagraphStyle expect(paragraph?.alignment).to(equal(NSTextAlignment.Justified)) } it("overrides existent value equal to the default with a new one") { string.add("tomato") { (inout a: Attributes) in a.alignment = NSParagraphStyle.defaultParagraphStyle().alignment } string.add("potato") { (inout a: Attributes) in a.alignment = .Justified } expect(string.runningAttributes).to(haveCount(1)) let paragraph = string.runningAttributes![NSParagraphStyleAttributeName] as? NSParagraphStyle expect(paragraph?.alignment).to(equal(NSTextAlignment.Justified)) } it("overrides existent value with a new one equal to the default") { string.add("tomato") { (inout a: Attributes) in a.alignment = .Center } string.add("potato") { (inout a: Attributes) in a.alignment = NSParagraphStyle.defaultParagraphStyle().alignment } expect(string.runningAttributes).to(haveCount(1)) let paragraph = string.runningAttributes![NSParagraphStyleAttributeName] as? NSParagraphStyle expect(paragraph?.alignment).to(equal(NSParagraphStyle.defaultParagraphStyle().alignment)) } it("removes existent value when set to nil") { string.add("tomato") { (inout a: Attributes) in a.alignment = .Center } string.add("potato") { (inout a: Attributes) in a.alignment = nil } expect(string.runningAttributes).to(haveCount(0)) } } describe("backgroundColor") { it("sets new value") { string.add("potato") { (inout a: Attributes) in a.backgroundColor = .redColor() } expect(string.runningAttributes).to(haveCount(1)) expect(string.runningAttributes![NSBackgroundColorAttributeName] as? UIColor).to(equal(UIColor.redColor())) } it("overrides existent value with a new one") { string.add("tomato") { (inout a: Attributes) in a.backgroundColor = .redColor() } string.add("potato") { (inout a: Attributes) in expect(string.runningAttributes).to(haveCount(1)) expect(string.runningAttributes![NSBackgroundColorAttributeName] as? UIColor).to(equal(UIColor.redColor())) a.backgroundColor = .blueColor() } expect(string.runningAttributes).to(haveCount(1)) expect(string.runningAttributes?[NSBackgroundColorAttributeName] as? UIColor).to(equal(UIColor.blueColor())) } it("removes existent value when set to nil") { string.add("tomato") { (inout a: Attributes) in a.backgroundColor = .redColor() } string.add("potato") { (inout a: Attributes) in a.backgroundColor = nil } expect(string.runningAttributes).to(haveCount(0)) } } describe("baseline") { it("sets new value") { string.add("potato") { (inout a: Attributes) in a.baseline = 13 } expect(string.runningAttributes).to(haveCount(1)) expect(string.runningAttributes![NSBaselineOffsetAttributeName] as? Float).to(equal(13)) } it("overrides existent value with a new one") { string.add("tomato") { (inout a: Attributes) in a.baseline = 13 } string.add("potato") { (inout a: Attributes) in expect(string.runningAttributes).to(haveCount(1)) expect(string.runningAttributes![NSBaselineOffsetAttributeName] as? Float).to(equal(13)) a.baseline = -7 } expect(string.runningAttributes).to(haveCount(1)) expect(string.runningAttributes?[NSBaselineOffsetAttributeName] as? Float).to(equal(-7)) } it("removes existent value when set to nil") { string.add("tomato") { (inout a: Attributes) in a.baseline = 7 } string.add("potato") { (inout a: Attributes) in a.baseline = nil } expect(string.runningAttributes).to(haveCount(0)) } } describe("bold") { it("sets new value") { string.add("potato") { (inout a: Attributes) in a.bold = true } expect(string.runningAttributes!).to(haveCount(1)) expect(string.runningAttributes![NSFontAttributeName] as? UIFont).to(equal(UIFont.boldSystemFontOfSize(12))) } it("overrides existent value with a new one") { string.add("tomato") { (inout a: Attributes) in a.bold = true } string.add("potato") { (inout a: Attributes) in expect(string.runningAttributes!).to(haveCount(1)) expect(string.runningAttributes![NSFontAttributeName] as? UIFont).to(equal(UIFont.boldSystemFontOfSize(12))) a.bold = false } expect(string.runningAttributes!).to(haveCount(1)) expect(string.runningAttributes![NSFontAttributeName] as? UIFont).to(equal(UIFont.systemFontOfSize(12))) } } describe("color") { it("sets new value") { string.add("potato") { (inout a: Attributes) in a.color = .redColor() } expect(string.runningAttributes).to(haveCount(1)) expect(string.runningAttributes![NSForegroundColorAttributeName] as? UIColor).to(equal(UIColor.redColor())) } it("overrides existent value with a new one") { string.add("tomato") { (inout a: Attributes) in a.color = .redColor() } string.add("potato") { (inout a: Attributes) in expect(string.runningAttributes).to(haveCount(1)) expect(string.runningAttributes![NSForegroundColorAttributeName] as? UIColor).to(equal(UIColor.redColor())) a.color = .blueColor() } expect(string.runningAttributes).to(haveCount(1)) expect(string.runningAttributes?[NSForegroundColorAttributeName] as? UIColor).to(equal(UIColor.blueColor())) } it("removes existent value when set to nil") { string.add("tomato") { (inout a: Attributes) in a.color = .redColor() } string.add("potato") { (inout a: Attributes) in a.color = nil } expect(string.runningAttributes).to(haveCount(0)) } } describe("direction") { it("sets new value") { string.add("potato") { (inout a: Attributes) in a.direction = .Vertical } expect(string.runningAttributes!).to(haveCount(1)) expect(string.runningAttributes![NSVerticalGlyphFormAttributeName] as? Int).to(equal(1)) } it("ignores incorrect values") { string.appendAttributedString(NSAttributedString(string: "invalid direciton", attributes: [ NSVerticalGlyphFormAttributeName: 13 ])) string.add("potato") { (inout a: Attributes) in expect(a.direction).to(beNil()) } } it("overrides existent value with a new one") { string.add("tomato") { (inout a: Attributes) in a.direction = .Vertical } string.add("potato") { (inout a: Attributes) in expect(string.runningAttributes!).to(haveCount(1)) expect(string.runningAttributes![NSVerticalGlyphFormAttributeName] as? Int).to(equal(1)) a.direction = .Horizontal } expect(string.runningAttributes!).to(haveCount(1)) expect(string.runningAttributes![NSVerticalGlyphFormAttributeName] as? Int).to(equal(0)) } it("removes existent value when set to nil") { string.add("tomato") { (inout a: Attributes) in a.direction = .Horizontal } string.add("potato") { (inout a: Attributes) in a.direction = nil } expect(string.runningAttributes).to(haveCount(0)) } it("unknown glyph direction won't affect direction") { string.add("tomato") { (inout a: Attributes) in a.direction = .Horizontal } string.add("potato") { (inout a: Attributes) in a.direction = nil } expect(string.runningAttributes).to(haveCount(0)) } } describe("expansion") { it("sets new value") { string.add("potato") { (inout a: Attributes) in a.expansion = 3 } expect(string.runningAttributes!).to(haveCount(1)) expect(string.runningAttributes![NSExpansionAttributeName] as? Float).to(equal(3)) } it("overrides existent value with a new one") { string.add("tomato") { (inout a: Attributes) in a.expansion = 3 } string.add("potato") { (inout a: Attributes) in expect(string.runningAttributes!).to(haveCount(1)) expect(string.runningAttributes![NSExpansionAttributeName] as? Float).to(equal(3)) a.expansion = 5 } expect(string.runningAttributes!).to(haveCount(1)) expect(string.runningAttributes![NSExpansionAttributeName] as? Float).to(equal(5)) } it("removes existent value when set to nil") { string.add("tomato") { (inout a: Attributes) in a.expansion = 10 } string.add("potato") { (inout a: Attributes) in a.expansion = nil } expect(string.runningAttributes).to(haveCount(0)) } } describe("font") { it("sets new value") { string.add("potato") { (inout a: Attributes) in a.font = .boldSystemFontOfSize(20) } expect(string.runningAttributes!).to(haveCount(1)) expect(string.runningAttributes![NSFontAttributeName] as? UIFont).to(equal(UIFont.boldSystemFontOfSize(20))) } it("overrides existent value with a new one") { string.add("tomato") { (inout a: Attributes) in a.font = .boldSystemFontOfSize(20) } string.add("potato") { (inout a: Attributes) in expect(string.runningAttributes!).to(haveCount(1)) expect(string.runningAttributes![NSFontAttributeName] as? UIFont).to(equal(UIFont.boldSystemFontOfSize(20))) a.font = .italicSystemFontOfSize(20) } expect(string.runningAttributes!).to(haveCount(1)) expect(string.runningAttributes![NSFontAttributeName] as? UIFont).to(equal(UIFont.italicSystemFontOfSize(20))) } it("removes existent value when set to nil") { string.add("tomato") { (inout a: Attributes) in a.font = .boldSystemFontOfSize(20) } string.add("potato") { (inout a: Attributes) in a.font = nil } expect(string.runningAttributes).to(haveCount(0)) } } describe("italics") { it("sets new value") { string.add("potato") { (inout a: Attributes) in a.italic = true } expect(string.runningAttributes!).to(haveCount(1)) expect(string.runningAttributes![NSFontAttributeName] as? UIFont).to(equal(UIFont.italicSystemFontOfSize(12))) } it("overrides existent value with a new one") { string.add("tomato") { (inout a: Attributes) in a.italic = true } string.add("potato") { (inout a: Attributes) in expect(string.runningAttributes!).to(haveCount(1)) expect(string.runningAttributes![NSFontAttributeName] as? UIFont).to(equal(UIFont.italicSystemFontOfSize(12))) a.italic = false } expect(string.runningAttributes!).to(haveCount(1)) expect(string.runningAttributes![NSFontAttributeName] as? UIFont).to(equal(UIFont.systemFontOfSize(12))) } } describe("leading") { it("sets new value") { string.add("potato") { (inout a: Attributes) in a.leading = 20 } expect(string.runningAttributes).to(haveCount(1)) let paragraph = string.runningAttributes![NSParagraphStyleAttributeName] as? NSParagraphStyle expect(paragraph?.lineSpacing).to(equal(20)) } it("sets new value equal to default") { string.add("potato") { (inout a: Attributes) in a.leading = Float(NSParagraphStyle.defaultParagraphStyle().lineSpacing) } expect(string.runningAttributes).to(haveCount(1)) let paragraph = string.runningAttributes![NSParagraphStyleAttributeName] as? NSParagraphStyle expect(paragraph?.lineSpacing).to(equal(NSParagraphStyle.defaultParagraphStyle().lineSpacing)) } it("overrides existent value with a new one") { string.add("tomato") { (inout a: Attributes) in a.leading = 20 } string.add("potato") { (inout a: Attributes) in expect(string.runningAttributes).to(haveCount(1)) let paragraph = string.runningAttributes![NSParagraphStyleAttributeName] as? NSParagraphStyle expect(paragraph?.lineSpacing).to(equal(20)) a.leading = 30 } expect(string.runningAttributes).to(haveCount(1)) let paragraph = string.runningAttributes![NSParagraphStyleAttributeName] as? NSParagraphStyle expect(paragraph?.lineSpacing).to(equal(30)) } it("overrides existent value equal to the default with a new one") { string.add("tomato") { (inout a: Attributes) in a.leading = Float(NSParagraphStyle.defaultParagraphStyle().lineSpacing) } string.add("potato") { (inout a: Attributes) in a.leading = 30 } expect(string.runningAttributes).to(haveCount(1)) let paragraph = string.runningAttributes![NSParagraphStyleAttributeName] as? NSParagraphStyle expect(paragraph?.lineSpacing).to(equal(30)) } it("overrides existent value with a new one equal to the default") { string.add("tomato") { (inout a: Attributes) in a.leading = 30 } string.add("potato") { (inout a: Attributes) in a.leading = Float(NSParagraphStyle.defaultParagraphStyle().lineSpacing) } expect(string.runningAttributes).to(haveCount(1)) let paragraph = string.runningAttributes![NSParagraphStyleAttributeName] as? NSParagraphStyle expect(paragraph?.lineSpacing).to(equal(NSParagraphStyle.defaultParagraphStyle().lineSpacing)) } it("removes existent value when set to nil") { string.add("tomato") { (inout a: Attributes) in a.leading = 30 } string.add("potato") { (inout a: Attributes) in a.leading = nil } expect(string.runningAttributes).to(haveCount(0)) } } describe("ligature") { it("sets new value") { string.add("potato") { (inout a: Attributes) in a.ligature = true } expect(string.runningAttributes!).to(haveCount(1)) expect(string.runningAttributes![NSLigatureAttributeName] as? Int).to(equal(1)) } it("overrides existent value with a new one") { string.add("tomato") { (inout a: Attributes) in a.ligature = true } string.add("potato") { (inout a: Attributes) in expect(string.runningAttributes!).to(haveCount(1)) expect(string.runningAttributes![NSLigatureAttributeName] as? Int).to(equal(1)) a.ligature = false } expect(string.runningAttributes!).to(haveCount(1)) expect(string.runningAttributes![NSLigatureAttributeName] as? Int).to(equal(0)) } it("removes existent value when set to nil") { string.add("tomato") { (inout a: Attributes) in a.ligature = true } string.add("potato") { (inout a: Attributes) in a.ligature = nil } expect(string.runningAttributes).to(haveCount(0)) } } describe("lineBreakMode") { it("sets new value") { string.add("potato") { (inout a: Attributes) in a.lineBreakMode = .ByWordWrapping } expect(string.runningAttributes).to(haveCount(1)) let paragraph = string.runningAttributes![NSParagraphStyleAttributeName] as? NSParagraphStyle expect(paragraph?.lineBreakMode).to(equal(NSLineBreakMode.ByWordWrapping)) } it("overrides existent value with a new one") { string.add("tomato") { (inout a: Attributes) in a.lineBreakMode = .ByClipping } string.add("potato") { (inout a: Attributes) in expect(string.runningAttributes).to(haveCount(1)) let paragraph = string.runningAttributes![NSParagraphStyleAttributeName] as? NSParagraphStyle expect(paragraph?.lineBreakMode).to(equal(NSLineBreakMode.ByClipping)) a.lineBreakMode = .ByTruncatingHead } expect(string.runningAttributes).to(haveCount(1)) let paragraph = string.runningAttributes![NSParagraphStyleAttributeName] as? NSParagraphStyle expect(paragraph?.lineBreakMode).to(equal(NSLineBreakMode.ByTruncatingHead)) } it("removes existent value when set to nil") { string.add("tomato") { (inout a: Attributes) in a.lineBreakMode = .ByTruncatingHead } string.add("potato") { (inout a: Attributes) in a.lineBreakMode = nil } expect(string.runningAttributes).to(haveCount(0)) } } describe("paragraphSpacingAfter") { it("sets new value") { string.add("potato") { (inout a: Attributes) in a.paragraphSpacingAfter = 10 } expect(string.runningAttributes).to(haveCount(1)) let paragraph = string.runningAttributes![NSParagraphStyleAttributeName] as? NSParagraphStyle expect(paragraph?.paragraphSpacing).to(equal(10)) } it("overrides existent value with a new one") { string.add("tomato") { (inout a: Attributes) in a.paragraphSpacingAfter = 7 } string.add("potato") { (inout a: Attributes) in expect(string.runningAttributes).to(haveCount(1)) let paragraph = string.runningAttributes![NSParagraphStyleAttributeName] as? NSParagraphStyle expect(paragraph?.paragraphSpacing).to(equal(7)) a.paragraphSpacingAfter = 5 } expect(string.runningAttributes).to(haveCount(1)) let paragraph = string.runningAttributes![NSParagraphStyleAttributeName] as? NSParagraphStyle expect(paragraph?.paragraphSpacing).to(equal(5)) } it("removes existent value when set to nil") { string.add("tomato") { (inout a: Attributes) in a.paragraphSpacingAfter = 13 } string.add("potato") { (inout a: Attributes) in a.paragraphSpacingAfter = nil } expect(string.runningAttributes).to(haveCount(0)) } } describe("paragraphSpacingBefore") { it("sets new value") { string.add("potato") { (inout a: Attributes) in a.paragraphSpacingBefore = 10 } expect(string.runningAttributes).to(haveCount(1)) let paragraph = string.runningAttributes![NSParagraphStyleAttributeName] as? NSParagraphStyle expect(paragraph?.paragraphSpacingBefore).to(equal(10)) } it("overrides existent value with a new one") { string.add("tomato") { (inout a: Attributes) in a.paragraphSpacingBefore = 7 } string.add("potato") { (inout a: Attributes) in expect(string.runningAttributes).to(haveCount(1)) let paragraph = string.runningAttributes![NSParagraphStyleAttributeName] as? NSParagraphStyle expect(paragraph?.paragraphSpacingBefore).to(equal(7)) a.paragraphSpacingBefore = 5 } expect(string.runningAttributes).to(haveCount(1)) let paragraph = string.runningAttributes![NSParagraphStyleAttributeName] as? NSParagraphStyle expect(paragraph?.paragraphSpacingBefore).to(equal(5)) } it("removes existent value when set to nil") { string.add("tomato") { (inout a: Attributes) in a.paragraphSpacingBefore = 13 } string.add("potato") { (inout a: Attributes) in a.paragraphSpacingBefore = nil } expect(string.runningAttributes).to(haveCount(0)) } } describe("firstLineHeadIndent") { it("sets new value") { string.add("potato") { (inout a: Attributes) in a.firstLineHeadIndent = 10 } expect(string.runningAttributes).to(haveCount(1)) let paragraph = string.runningAttributes![NSParagraphStyleAttributeName] as? NSParagraphStyle expect(paragraph?.firstLineHeadIndent).to(equal(10)) } it("overrides existent value with a new one") { string.add("tomato") { (inout a: Attributes) in a.firstLineHeadIndent = 7 } string.add("potato") { (inout a: Attributes) in expect(string.runningAttributes).to(haveCount(1)) let paragraph = string.runningAttributes![NSParagraphStyleAttributeName] as? NSParagraphStyle expect(paragraph?.firstLineHeadIndent).to(equal(7)) a.firstLineHeadIndent = 5 } expect(string.runningAttributes).to(haveCount(1)) let paragraph = string.runningAttributes![NSParagraphStyleAttributeName] as? NSParagraphStyle expect(paragraph?.firstLineHeadIndent).to(equal(5)) } it("removes existent value when set to nil") { string.add("tomato") { (inout a: Attributes) in a.firstLineHeadIndent = 13 } string.add("potato") { (inout a: Attributes) in a.firstLineHeadIndent = nil } expect(string.runningAttributes).to(haveCount(0)) } } describe("minimumLineHeight") { it("sets new value") { string.add("potato") { (inout a: Attributes) in a.minimumLineHeight = 10 } expect(string.runningAttributes).to(haveCount(1)) let paragraph = string.runningAttributes![NSParagraphStyleAttributeName] as? NSParagraphStyle expect(paragraph?.minimumLineHeight).to(equal(10)) } it("overrides existent value with a new one") { string.add("tomato") { (inout a: Attributes) in a.minimumLineHeight = 7 } string.add("potato") { (inout a: Attributes) in expect(string.runningAttributes).to(haveCount(1)) let paragraph = string.runningAttributes![NSParagraphStyleAttributeName] as? NSParagraphStyle expect(paragraph?.minimumLineHeight).to(equal(7)) a.minimumLineHeight = 5 } expect(string.runningAttributes).to(haveCount(1)) let paragraph = string.runningAttributes![NSParagraphStyleAttributeName] as? NSParagraphStyle expect(paragraph?.minimumLineHeight).to(equal(5)) } it("removes existent value when set to nil") { string.add("tomato") { (inout a: Attributes) in a.minimumLineHeight = 13 } string.add("potato") { (inout a: Attributes) in a.minimumLineHeight = nil } expect(string.runningAttributes).to(haveCount(0)) } } describe("maximumLineHeight") { it("sets new value") { string.add("potato") { (inout a: Attributes) in a.maximumLineHeight = 10 } expect(string.runningAttributes).to(haveCount(1)) let paragraph = string.runningAttributes![NSParagraphStyleAttributeName] as? NSParagraphStyle expect(paragraph?.maximumLineHeight).to(equal(10)) } it("overrides existent value with a new one") { string.add("tomato") { (inout a: Attributes) in a.maximumLineHeight = 7 } string.add("potato") { (inout a: Attributes) in expect(string.runningAttributes).to(haveCount(1)) let paragraph = string.runningAttributes![NSParagraphStyleAttributeName] as? NSParagraphStyle expect(paragraph?.maximumLineHeight).to(equal(7)) a.maximumLineHeight = 5 } expect(string.runningAttributes).to(haveCount(1)) let paragraph = string.runningAttributes![NSParagraphStyleAttributeName] as? NSParagraphStyle expect(paragraph?.maximumLineHeight).to(equal(5)) } it("removes existent value when set to nil") { string.add("tomato") { (inout a: Attributes) in a.maximumLineHeight = 13 } string.add("potato") { (inout a: Attributes) in a.maximumLineHeight = nil } expect(string.runningAttributes).to(haveCount(0)) } } describe("hyphenationFactor") { it("sets new value") { string.add("potato") { (inout a: Attributes) in a.hyphenationFactor = 10 } expect(string.runningAttributes).to(haveCount(1)) let paragraph = string.runningAttributes![NSParagraphStyleAttributeName] as? NSParagraphStyle expect(paragraph?.hyphenationFactor).to(equal(10)) } it("overrides existent value with a new one") { string.add("tomato") { (inout a: Attributes) in a.hyphenationFactor = 7 } string.add("potato") { (inout a: Attributes) in expect(string.runningAttributes).to(haveCount(1)) let paragraph = string.runningAttributes![NSParagraphStyleAttributeName] as? NSParagraphStyle expect(paragraph?.hyphenationFactor).to(equal(7)) a.hyphenationFactor = 5 } expect(string.runningAttributes).to(haveCount(1)) let paragraph = string.runningAttributes![NSParagraphStyleAttributeName] as? NSParagraphStyle expect(paragraph?.hyphenationFactor).to(equal(5)) } it("removes existent value when set to nil") { string.add("tomato") { (inout a: Attributes) in a.hyphenationFactor = 13 } string.add("potato") { (inout a: Attributes) in a.hyphenationFactor = nil } expect(string.runningAttributes).to(haveCount(0)) } } if #available(iOS 9.0, *) { describe("allowsTighteningForTruncation") { it("sets new value") { string.add("potato") { (inout a: Attributes) in a.allowsTighteningForTruncation = true } expect(string.runningAttributes).to(haveCount(1)) let paragraph = string.runningAttributes![NSParagraphStyleAttributeName] as? NSParagraphStyle expect(paragraph?.allowsDefaultTighteningForTruncation).to(equal(true)) } it("overrides existent value with a new one") { string.add("tomato") { (inout a: Attributes) in a.allowsTighteningForTruncation = true } string.add("potato") { (inout a: Attributes) in expect(string.runningAttributes).to(haveCount(1)) let paragraph = string.runningAttributes![NSParagraphStyleAttributeName] as? NSParagraphStyle expect(paragraph?.allowsDefaultTighteningForTruncation).to(equal(true)) a.allowsTighteningForTruncation = false } expect(string.runningAttributes).to(haveCount(1)) let paragraph = string.runningAttributes![NSParagraphStyleAttributeName] as? NSParagraphStyle expect(paragraph?.allowsDefaultTighteningForTruncation).to(equal(false)) } it("removes existent value when set to nil") { string.add("tomato") { (inout a: Attributes) in a.allowsTighteningForTruncation = true } string.add("potato") { (inout a: Attributes) in a.allowsTighteningForTruncation = nil } expect(string.runningAttributes).to(haveCount(0)) } } } describe("headIndent") { it("sets new value") { string.add("potato") { (inout a: Attributes) in a.headIndent = 10 } expect(string.runningAttributes).to(haveCount(1)) let paragraph = string.runningAttributes![NSParagraphStyleAttributeName] as? NSParagraphStyle expect(paragraph?.headIndent).to(equal(10)) } it("overrides existent value with a new one") { string.add("tomato") { (inout a: Attributes) in a.headIndent = 7 } string.add("potato") { (inout a: Attributes) in expect(string.runningAttributes).to(haveCount(1)) let paragraph = string.runningAttributes![NSParagraphStyleAttributeName] as? NSParagraphStyle expect(paragraph?.headIndent).to(equal(7)) a.headIndent = 5 } expect(string.runningAttributes).to(haveCount(1)) let paragraph = string.runningAttributes![NSParagraphStyleAttributeName] as? NSParagraphStyle expect(paragraph?.headIndent).to(equal(5)) } it("removes existent value when set to nil") { string.add("tomato") { (inout a: Attributes) in a.headIndent = 13 } string.add("potato") { (inout a: Attributes) in a.headIndent = nil } expect(string.runningAttributes).to(haveCount(0)) } } describe("tailIndent") { it("sets new value") { string.add("potato") { (inout a: Attributes) in a.tailIndent = 10 } expect(string.runningAttributes).to(haveCount(1)) let paragraph = string.runningAttributes![NSParagraphStyleAttributeName] as? NSParagraphStyle expect(paragraph?.tailIndent).to(equal(10)) } it("overrides existent value with a new one") { string.add("tomato") { (inout a: Attributes) in a.tailIndent = 7 } string.add("potato") { (inout a: Attributes) in expect(string.runningAttributes).to(haveCount(1)) let paragraph = string.runningAttributes![NSParagraphStyleAttributeName] as? NSParagraphStyle expect(paragraph?.tailIndent).to(equal(7)) a.tailIndent = 5 } expect(string.runningAttributes).to(haveCount(1)) let paragraph = string.runningAttributes![NSParagraphStyleAttributeName] as? NSParagraphStyle expect(paragraph?.tailIndent).to(equal(5)) } it("removes existent value when set to nil") { string.add("tomato") { (inout a: Attributes) in a.tailIndent = 13 } string.add("potato") { (inout a: Attributes) in a.tailIndent = nil } expect(string.runningAttributes).to(haveCount(0)) } } describe("lineHeightMultiplier") { it("sets new value") { string.add("potato") { (inout a: Attributes) in a.lineHeightMultiplier = 10 } expect(string.runningAttributes).to(haveCount(1)) let paragraph = string.runningAttributes![NSParagraphStyleAttributeName] as? NSParagraphStyle expect(paragraph?.lineHeightMultiple).to(equal(10)) } it("overrides existent value with a new one") { string.add("tomato") { (inout a: Attributes) in a.lineHeightMultiplier = 7 } string.add("potato") { (inout a: Attributes) in expect(string.runningAttributes).to(haveCount(1)) let paragraph = string.runningAttributes![NSParagraphStyleAttributeName] as? NSParagraphStyle expect(paragraph?.lineHeightMultiple).to(equal(7)) a.lineHeightMultiplier = 5 } expect(string.runningAttributes).to(haveCount(1)) let paragraph = string.runningAttributes![NSParagraphStyleAttributeName] as? NSParagraphStyle expect(paragraph?.lineHeightMultiple).to(equal(5)) } it("removes existent value when set to nil") { string.add("tomato") { (inout a: Attributes) in a.lineHeightMultiplier = 13 } string.add("potato") { (inout a: Attributes) in a.lineHeightMultiplier = nil } expect(string.runningAttributes).to(haveCount(0)) } } describe("kern") { it("sets new value") { string.add("potato") { (inout a: Attributes) in a.kern = 5 } expect(string.runningAttributes!).to(haveCount(1)) expect(string.runningAttributes![NSKernAttributeName] as? Float).to(equal(5)) } it("overrides existent value with a new one") { string.add("tomato") { (inout a: Attributes) in a.kern = 5 } string.add("potato") { (inout a: Attributes) in expect(string.runningAttributes!).to(haveCount(1)) expect(string.runningAttributes![NSKernAttributeName] as? Float).to(equal(5)) a.kern = 3 } expect(string.runningAttributes!).to(haveCount(1)) expect(string.runningAttributes![NSKernAttributeName] as? Float).to(equal(3)) } it("removes existent value when set to nil") { string.add("tomato") { (inout a: Attributes) in a.kern = 5 } string.add("potato") { (inout a: Attributes) in a.kern = nil } expect(string.runningAttributes).to(haveCount(0)) } } describe("obliqueness") { it("sets new value") { string.add("potato") { (inout a: Attributes) in a.obliqueness = 3 } expect(string.runningAttributes!).to(haveCount(1)) expect(string.runningAttributes![NSObliquenessAttributeName] as? Float).to(equal(3)) } it("overrides existent value with a new one") { string.add("tomato") { (inout a: Attributes) in a.obliqueness = 3 } string.add("potato") { (inout a: Attributes) in expect(string.runningAttributes!).to(haveCount(1)) expect(string.runningAttributes![NSObliquenessAttributeName] as? Float).to(equal(3)) a.obliqueness = 5 } expect(string.runningAttributes!).to(haveCount(1)) expect(string.runningAttributes![NSObliquenessAttributeName] as? Float).to(equal(5)) } it("removes existent value when set to nil") { string.add("tomato") { (inout a: Attributes) in a.obliqueness = 10 } string.add("potato") { (inout a: Attributes) in a.obliqueness = nil } expect(string.runningAttributes).to(haveCount(0)) } } describe("strikethrough") { it("sets new value") { string.add("potato") { (inout a: Attributes) in a.strikethrough = .StyleSingle } expect(string.runningAttributes!).to(haveCount(1)) expect(NSUnderlineStyle(rawValue: string.runningAttributes![NSStrikethroughStyleAttributeName] as! Int)).to(equal(NSUnderlineStyle.StyleSingle)) } it("overrides existent value with a new one") { string.add("tomato") { (inout a: Attributes) in a.strikethrough = .StyleSingle } string.add("potato") { (inout a: Attributes) in expect(string.runningAttributes!).to(haveCount(1)) expect(NSUnderlineStyle(rawValue: string.runningAttributes![NSStrikethroughStyleAttributeName] as! Int)).to(equal(NSUnderlineStyle.StyleSingle)) a.strikethrough = .StyleThick } expect(string.runningAttributes!).to(haveCount(1)) expect(NSUnderlineStyle(rawValue: string.runningAttributes![NSStrikethroughStyleAttributeName] as! Int)).to(equal(NSUnderlineStyle.StyleThick)) } it("removes existent value when set to nil") { string.add("tomato") { (inout a: Attributes) in a.strikethrough = .StyleThick } string.add("potato") { (inout a: Attributes) in a.strikethrough = nil } expect(string.runningAttributes).to(haveCount(0)) } } describe("strikethroughColor") { it("sets new value") { string.add("potato") { (inout a: Attributes) in a.strikethroughColor = .redColor() } expect(string.runningAttributes!).to(haveCount(1)) expect(string.runningAttributes![NSStrikethroughColorAttributeName] as? UIColor).to(equal(UIColor.redColor())) } it("overrides existent value with a new one") { string.add("tomato") { (inout a: Attributes) in a.strikethroughColor = .redColor() } string.add("potato") { (inout a: Attributes) in expect(string.runningAttributes!).to(haveCount(1)) expect(string.runningAttributes![NSStrikethroughColorAttributeName] as? UIColor).to(equal(UIColor.redColor())) a.strikethroughColor = .blueColor() } expect(string.runningAttributes!).to(haveCount(1)) expect(string.runningAttributes![NSStrikethroughColorAttributeName] as? UIColor).to(equal(UIColor.blueColor())) } it("removes existent value when set to nil") { string.add("tomato") { (inout a: Attributes) in a.strikethroughColor = .redColor() } string.add("potato") { (inout a: Attributes) in a.strikethroughColor = nil } expect(string.runningAttributes).to(haveCount(0)) } } describe("stroke") { it("sets new value") { string.add("potato") { (inout a: Attributes) in a.stroke = .Filled(width: 10) } expect(string.runningAttributes).to(haveCount(1)) expect(string.runningAttributes![NSStrokeWidthAttributeName] as? Float).to(equal(-10)) } it("overrides existent value with a new one") { string.add("tomato") { (inout a: Attributes) in a.stroke = .Filled(width: 10) } string.add("potato") { (inout a: Attributes) in expect(string.runningAttributes).to(haveCount(1)) expect(string.runningAttributes![NSStrokeWidthAttributeName] as? Float).to(equal(-10)) a.stroke = .NotFilled(width: 10) } expect(string.runningAttributes).to(haveCount(1)) expect(string.runningAttributes?[NSStrokeWidthAttributeName] as? Float).to(equal(10)) } it("removes existent value when set to nil") { string.add("tomato") { (inout a: Attributes) in a.stroke = .NotFilled(width: 10) } string.add("potato") { (inout a: Attributes) in a.stroke = nil } expect(string.runningAttributes).to(haveCount(0)) } } describe("strokeColor") { it("sets new value") { string.add("potato") { (inout a: Attributes) in a.strokeColor = .redColor() } expect(string.runningAttributes).to(haveCount(1)) expect(string.runningAttributes![NSStrokeColorAttributeName] as? UIColor).to(equal(UIColor.redColor())) } it("overrides existent value with a new one") { string.add("tomato") { (inout a: Attributes) in a.strokeColor = .redColor() } string.add("potato") { (inout a: Attributes) in expect(string.runningAttributes).to(haveCount(1)) expect(string.runningAttributes![NSStrokeColorAttributeName] as? UIColor).to(equal(UIColor.redColor())) a.strokeColor = .blueColor() } expect(string.runningAttributes).to(haveCount(1)) expect(string.runningAttributes?[NSStrokeColorAttributeName] as? UIColor).to(equal(UIColor.blueColor())) } it("removes existent value when set to nil") { string.add("tomato") { (inout a: Attributes) in a.strokeColor = UIColor.redColor() } string.add("potato") { (inout a: Attributes) in a.strokeColor = nil } expect(string.runningAttributes).to(haveCount(0)) } } describe("textEffect") { it("sets new value") { string.add("potato") { (inout a: Attributes) in a.textEffect = .Letterpress } expect(string.runningAttributes).to(haveCount(1)) expect(string.runningAttributes![NSTextEffectAttributeName] as? String).to(equal(NSTextEffectLetterpressStyle)) } it("ignores invalid values") { string.appendAttributedString(NSAttributedString(string: "invalid text effect", attributes: [ NSTextEffectAttributeName: "shazooo" ])) string.add("potato") { (inout a: Attributes) in expect(a.textEffect).to(beNil()) } } // TODO: change the test when Cocoa supports more effects it("overrides existent value with the same one") { string.add("tomato") { (inout a: Attributes) in a.textEffect = .Letterpress } string.add("potato") { (inout a: Attributes) in expect(string.runningAttributes).to(haveCount(1)) expect(string.runningAttributes?[NSTextEffectAttributeName] as? String).to(equal(NSTextEffectLetterpressStyle)) a.textEffect = .Letterpress } expect(string.runningAttributes).to(haveCount(1)) expect(string.runningAttributes?[NSTextEffectAttributeName] as? String).to(equal(NSTextEffectLetterpressStyle)) } it("removes existent value when set to nil") { string.add("tomato") { (inout a: Attributes) in a.textEffect = .Letterpress } string.add("potato") { (inout a: Attributes) in a.textEffect = nil } expect(string.runningAttributes).to(haveCount(0)) } } describe("underline") { it("sets new value") { string.add("potato") { (inout a: Attributes) in a.underline = .StyleSingle } expect(string.runningAttributes!).to(haveCount(1)) expect(NSUnderlineStyle(rawValue: string.runningAttributes![NSUnderlineStyleAttributeName] as! Int)).to(equal(NSUnderlineStyle.StyleSingle)) } it("overrides existent value with a new one") { string.add("tomato") { (inout a: Attributes) in a.underline = .StyleSingle } string.add("potato") { (inout a: Attributes) in expect(string.runningAttributes!).to(haveCount(1)) expect(NSUnderlineStyle(rawValue: string.runningAttributes![NSUnderlineStyleAttributeName] as! Int)).to(equal(NSUnderlineStyle.StyleSingle)) a.underline = .StyleThick } expect(string.runningAttributes!).to(haveCount(1)) expect(NSUnderlineStyle(rawValue: string.runningAttributes![NSUnderlineStyleAttributeName] as! Int)).to(equal(NSUnderlineStyle.StyleThick)) } it("removes existent value when set to nil") { string.add("tomato") { (inout a: Attributes) in a.underline = .StyleThick } string.add("potato") { (inout a: Attributes) in a.underline = nil } expect(string.runningAttributes).to(haveCount(0)) } } describe("underlineColor") { it("sets new value") { string.add("potato") { (inout a: Attributes) in a.underlineColor = .redColor() } expect(string.runningAttributes!).to(haveCount(1)) expect(string.runningAttributes![NSUnderlineColorAttributeName] as? UIColor).to(equal(UIColor.redColor())) } it("overrides existent value with a new one") { string.add("tomato") { (inout a: Attributes) in a.underlineColor = .redColor() } string.add("potato") { (inout a: Attributes) in expect(string.runningAttributes!).to(haveCount(1)) expect(string.runningAttributes![NSUnderlineColorAttributeName] as? UIColor).to(equal(UIColor.redColor())) a.underlineColor = .blueColor() } expect(string.runningAttributes!).to(haveCount(1)) expect(string.runningAttributes![NSUnderlineColorAttributeName] as? UIColor).to(equal(UIColor.blueColor())) } it("removes existent value when set to nil") { string.add("tomato") { (inout a: Attributes) in a.underlineColor = .redColor() } string.add("potato") { (inout a: Attributes) in a.underlineColor = nil } expect(string.runningAttributes).to(haveCount(0)) } } describe("URL") { var url1: NSURL!, url2: NSURL! beforeEach { url1 = NSURL(string: "https://swift.org")! url2 = NSURL(string: "https://apple.com")! } it("sets new value") { string.add("potato") { (inout a: Attributes) in a.URL = url1 } expect(string.runningAttributes!).to(haveCount(1)) expect(string.runningAttributes![NSLinkAttributeName] as? NSURL).to(equal(url1)) } it("overrides existent value with a new one") { string.add("tomato") { (inout a: Attributes) in a.URL = url1 } string.add("potato") { (inout a: Attributes) in expect(string.runningAttributes!).to(haveCount(1)) expect(string.runningAttributes![NSLinkAttributeName] as? NSURL).to(equal(url1)) a.URL = url2 } expect(string.runningAttributes!).to(haveCount(1)) expect(string.runningAttributes![NSLinkAttributeName] as? NSURL).to(equal(url2)) } it("removes existent value when set to nil") { string.add("tomato") { (inout a: Attributes) in a.URL = url1 } string.add("potato") { (inout a: Attributes) in a.URL = nil } expect(string.runningAttributes).to(haveCount(0)) } } } context("image") { var image: UIImage! beforeSuite { let bundle = NSBundle(forClass: self.dynamicType) image = UIImage(named: "swift", inBundle: bundle, compatibleWithTraitCollection: nil)! } describe("adding image") { it("just works") { string.add(image) expect(string.runningAttributes).to(haveCount(1)) expect((string.runningAttributes?[NSAttachmentAttributeName] as? NSTextAttachment)?.image).to(equal(image)) } it("keeps existent attributes") { string.add("banana") { $0.color = .redColor() $0.font = .systemFontOfSize(20) }.add(image) expect(string.runningAttributes?[NSFontAttributeName] as? UIFont).to(equal(UIFont.systemFontOfSize(20))) expect(string.runningAttributes?[NSForegroundColorAttributeName] as? UIColor).to(equal(UIColor.redColor())) } it("applies new attributes") { string.add(image) { $0.color = .redColor() $0.font = .boldSystemFontOfSize(12) } expect(string.runningAttributes?[NSFontAttributeName] as? UIFont).to(equal(UIFont.boldSystemFontOfSize(12))) expect(string.runningAttributes?[NSForegroundColorAttributeName] as? UIColor).to(equal(UIColor.redColor())) } } describe("setting bounds") { it("changes bounds of attachment") { let imageBounds = CGRect(x: 1, y: 2, width: 3, height: 4) string.add(image, bounds: imageBounds) expect(string.runningAttributes).to(haveCount(1)) let attachment = string.runningAttributes?[NSAttachmentAttributeName] as? NSTextAttachment expect(attachment?.bounds).to(equal(imageBounds)) } } } context("helpers") { describe("fontSize") { it("sets new value") { string.add("potato") { (inout a: Attributes) in a.fontSize = 20 } expect(string.runningAttributes).to(haveCount(1)) expect((string.runningAttributes![NSFontAttributeName] as? UIFont)?.pointSize).to(equal(20)) } it("overrides existent value with a new one") { string.add("tomato") { (inout a: Attributes) in a.fontSize = 20 } string.add("potato") { (inout a: Attributes) in expect(string.runningAttributes).to(haveCount(1)) expect((string.runningAttributes![NSFontAttributeName] as? UIFont)?.pointSize).to(equal(20)) a.fontSize = 30 } expect(string.runningAttributes).to(haveCount(1)) expect((string.runningAttributes?[NSFontAttributeName] as? UIFont)?.pointSize).to(equal(30)) } it("removes existent value when set to nil") { string.add("tomato") { (inout a: Attributes) in a.fontSize = 30 } string.add("potato") { (inout a: Attributes) in a.fontSize = nil } expect(string.runningAttributes).to(haveCount(0)) } } } } }
mit
435c9ea6808bba34b28b69112cf6e45b
48.301724
168
0.474821
6.135169
false
false
false
false
automationWisdri/WISData.JunZheng
WISData.JunZheng/View/LeftView/LeftUserHeadCell.swift
1
2158
// // LeftUserHeadCell.swift // V2ex-Swift // // Created by huangfeng on 1/23/16. // Copyright © 2016 Fin. All rights reserved. // import UIKit class LeftUserHeadCell: UITableViewCell { /// 头像 var avatarImageView: UIImageView = { let imageView = UIImageView() imageView.backgroundColor = UIColor(white: 0.9, alpha: 0.3) imageView.layer.borderWidth = 1.5 imageView.layer.borderColor = UIColor(white: 1, alpha: 0.6).CGColor imageView.layer.masksToBounds = true imageView.layer.cornerRadius = 25 return imageView }() /// 用户名 var userNameLabel: UILabel = { let label = UILabel() label.font = wisFont(15) return label }() override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) self.setup() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } func setup() -> Void { self.backgroundColor = UIColor.clearColor() self.selectionStyle = .None self.contentView.addSubview(self.avatarImageView) self.contentView.addSubview(self.userNameLabel) self.avatarImageView.snp_makeConstraints{ (make) -> Void in // make.centerX.equalTo(self.contentView) // make.centerY.equalTo(self.contentView).offset(-8) // make.width.height.equalTo(self.avatarImageView.layer.cornerRadius * 2) make.left.equalTo(self.contentView).offset(10) make.top.equalTo(self.contentView).offset(20) make.width.height.equalTo(self.avatarImageView.layer.cornerRadius * 2) } self.userNameLabel.snp_makeConstraints{ (make) -> Void in // make.top.equalTo(self.avatarImageView.snp_bottom).offset(10) // make.centerX.equalTo(self.avatarImageView) make.left.equalTo(self.avatarImageView.snp_right).offset(10) make.centerY.equalTo(self.avatarImageView) } self.userNameLabel.textColor = UIColor.lightTextColor() } }
mit
006f27df57c4c50f1932a9b695770f1d
31.530303
84
0.634839
4.372709
false
false
false
false
Spriter/SwiftyHue
Sources/Base/BridgeResourceModels/Sensors/SensorState.swift
1
4628
// // SensorState.swift // Pods // // Created by Jerome Schmitz on 01.05.16. // // import Foundation import Gloss public enum ButtonEvent: Int { /** Tap Button 1 */ case button_1 = 34 /** Tap Button 2 */ case button_2 = 16 /** Tap Button 3 */ case button_3 = 17 /** Tap Button 4 */ case button_4 = 18 /** INITIAL_PRESS Button 1 (ON) */ case initial_PRESS_BUTTON_1 = 1000 /** HOLD Button 1 (ON) */ case hold_BUTTON_1 = 1001 /** SHORT_RELEASED Button 1 */ case short_RELEASED_BUTTON_1 = 1002 /** LONG_RELEASED Button 1 */ case long_RELEASED_BUTTON_1 = 1003 /** INITIAL_PRESS Button 2 (ON) */ case initial_PRESS_BUTTON_2 = 2000 /** HOLD Button 2 (ON) */ case hold_BUTTON_2 = 2001 /** SHORT_RELEASED Button 2 */ case short_RELEASED_BUTTON_2 = 2002 /** LONG_RELEASED Button 2 */ case long_RELEASED_BUTTON_2 = 2003 /** INITIAL_PRESS Button 3 (ON) */ case initial_PRESS_BUTTON_3 = 3000 /** HOLD Button 3 (ON) */ case hold_BUTTON_3 = 3001 /** SHORT_RELEASED Button 3 */ case short_RELEASED_BUTTON_3 = 3002 /** LONG_RELEASED Button 3 */ case long_RELEASED_BUTTON_3 = 3003 /** INITIAL_PRESS Button 4 (ON) */ case initial_PRESS_BUTTON_4 = 4000 /** HOLD Button 4 (ON) */ case hold_BUTTON_4 = 4001 /** SHORT_RELEASED Button 4 */ case short_RELEASED_BUTTON_4 = 4002 /** LONG_RELEASED Button 4 */ case long_RELEASED_BUTTON_4 = 4003 } public func ==(lhs: PartialSensorState, rhs: PartialSensorState) -> Bool { return lhs.lastUpdated == rhs.lastUpdated } public class PartialSensorState: JSONDecodable, Equatable { public let lastUpdated: Date? init(lastUpdated: Date?) { self.lastUpdated = lastUpdated } required public init?(json: JSON) { let dateFormatter = DateFormatter.hueApiDateFormatter lastUpdated = Decoder.decode(dateForKey: "lastupdated", dateFormatter: dateFormatter)(json) } public func toJSON() -> JSON? { let dateFormatter = DateFormatter.hueApiDateFormatter let json = jsonify([ Encoder.encode(dateForKey: "lastupdated", dateFormatter: dateFormatter)(lastUpdated) ]) return json } } public class SensorState: PartialSensorState { // Daylight public let daylight: Bool? // GenericFlagSensor public let flag: Bool? // GenericStatusState public let status: Int? // HumiditySensorState public let humidity: Int? // OpenCloseSensorState public let open: Bool? // PresenceSensorState public let presence: Bool? // SwitchSensorState public let buttonEvent: ButtonEvent? // TemperatureSensorState public let temperature: Int? // LightlevelSensorState public let lightlevel: Int? public let dark: Bool? required public init?(json: JSON) { daylight = "daylight" <~~ json flag = "flag" <~~ json status = "status" <~~ json humidity = "humidity" <~~ json open = "open" <~~ json presence = "presence" <~~ json buttonEvent = "buttonevent" <~~ json temperature = "temperature" <~~ json lightlevel = "lightlevel" <~~ json dark = "dark" <~~ json super.init(json: json) } public override func toJSON() -> JSON? { let json = jsonify([ "daylight" ~~> daylight, "flag" ~~> flag, "status" ~~> status, "humidity" ~~> humidity, "open" ~~> open, "presence" ~~> presence, "buttonevent" ~~> buttonEvent, "temperature" ~~> temperature, "lightlevel" ~~> lightlevel, "dark" ~~> dark ]) return json } } public func ==(lhs: SensorState, rhs: SensorState) -> Bool { return lhs.lastUpdated == rhs.lastUpdated && lhs.daylight == rhs.daylight && lhs.flag == rhs.flag && lhs.status == rhs.status && lhs.open == rhs.open && lhs.presence == rhs.presence && lhs.buttonEvent == rhs.buttonEvent && lhs.temperature == rhs.temperature && lhs.lightlevel == rhs.lightlevel && lhs.dark == rhs.dark }
mit
f1f9a2cf0eb1b376e02323963b183847
21.686275
99
0.542783
4.349624
false
false
false
false
AlexRamey/mbird-iOS
Pods/Nuke/Sources/Manager.swift
1
8050
// The MIT License (MIT) // // Copyright (c) 2015-2018 Alexander Grebenyuk (github.com/kean). import Foundation /// Loads images into the given targets. public final class Manager: Loading { public let loader: Loading public let cache: Caching? /// Shared `Manager` instance. /// /// Shared manager is created with `Loader.shared` and `Cache.shared`. public static let shared = Manager(loader: Loader.shared, cache: Cache.shared) /// Initializes the `Manager` with the image loader and the memory cache. /// - parameter cache: `nil` by default. public init(loader: Loading, cache: Caching? = nil) { self.loader = loader self.cache = cache } // MARK: Loading Images into Targets /// Loads an image into the given target. Cancels previous outstanding request /// associated with the target. /// /// If the image is stored in the memory cache, the image is displayed /// immediately. The image is loaded using the `loader` object otherwise. /// /// `Manager` keeps a weak reference to the target. If the target deallocates /// the associated request automatically gets cancelled. public func loadImage(with request: Request, into target: Target) { loadImage(with: request, into: target) { [weak target] in target?.handle(response: $0, isFromMemoryCache: $1) } } public typealias Handler = (Result<Image>, _ isFromMemoryCache: Bool) -> Void /// Loads an image and calls the given `handler`. The method itself /// **doesn't do** anything when the image is loaded - you have full /// control over how to display it, etc. /// /// The handler only gets called if the request is still associated with the /// `target` by the time it's completed. The handler gets called immediately /// if the image was stored in the memory cache. /// /// See `loadImage(with:into:)` method for more info. public func loadImage(with request: Request, into target: AnyObject, handler: @escaping Handler) { assert(Thread.isMainThread) let context = getContext(for: target) context.cts?.cancel() // cancel outstanding request if any context.cts = nil // Quick synchronous memory cache lookup if let image = cachedImage(for: request) { handler(.success(image), true) return } // Create CTS and associate it with a context let cts = CancellationTokenSource() context.cts = cts // Start the request _loadImage(with: request, token: cts.token) { [weak context] in guard let context = context, context.cts === cts else { return } // check if still registered handler($0, false) context.cts = nil // avoid redundant cancellations on deinit } } /// Cancels an outstanding request associated with the target. public func cancelRequest(for target: AnyObject) { assert(Thread.isMainThread) let context = getContext(for: target) context.cts?.cancel() // cancel outstanding request if any context.cts = nil // unregister request } // MARK: Loading Images w/o Targets /// Loads an image with a given request by using manager's cache and loader. /// /// - parameter completion: Gets called asynchronously on the main thread. /// If the request is cancelled the completion closure isn't guaranteed to /// be called. public func loadImage(with request: Request, token: CancellationToken?, completion: @escaping (Result<Image>) -> Void) { // Check if image is in memory cache if let image = cachedImage(for: request) { DispatchQueue.main.async { completion(.success(image)) } } else { _loadImage(with: request, token: token, completion: completion) } } private func _loadImage(with request: Request, token: CancellationToken? = nil, completion: @escaping (Result<Image>) -> Void) { // Use underlying loader to load an image and then store it in cache loader.loadImage(with: request, token: token) { [weak self] result in if let image = result.value { // save in cache self?.store(image: image, for: request) } DispatchQueue.main.async { completion(result) } } } // MARK: Memory Cache Helpers private func cachedImage(for request: Request) -> Image? { guard request.memoryCacheOptions.readAllowed else { return nil } return cache?[request] } private func store(image: Image, for request: Request) { guard request.memoryCacheOptions.writeAllowed else { return } cache?[request] = image } // MARK: Managing Context private static var contextAK = "Manager.Context.AssociatedKey" // Lazily create context for a given target and associate it with a target. private func getContext(for target: AnyObject) -> Context { // Associated objects is a simplest way to bind Context and Target lifetimes // The implementation might change in the future. if let ctx = objc_getAssociatedObject(target, &Manager.contextAK) as? Context { return ctx } let ctx = Context() objc_setAssociatedObject(target, &Manager.contextAK, ctx, .OBJC_ASSOCIATION_RETAIN) return ctx } // Context is reused for multiple requests which makes sense, because in // most cases image views are also going to be reused (e.g. in a table view) private final class Context { var cts: CancellationTokenSource? // also used to identify requests // Automatically cancel the request when target deallocates. deinit { cts?.cancel() } } } public extension Manager { /// Loads an image into the given target. See the corresponding /// `loadImage(with:into)` method that takes `Request` for more info. public func loadImage(with url: URL, into target: Target) { loadImage(with: Request(url: url), into: target) } /// Loads an image and calls the given `handler`. The method itself /// **doesn't do** anything when the image is loaded - you have full /// control over how to display it, etc. /// /// The handler only gets called if the request is still associated with the /// `target` by the time it's completed. The handler gets called immediately /// if the image was stored in the memory cache. /// /// See `loadImage(with:into:)` method for more info. public func loadImage(with url: URL, into target: AnyObject, handler: @escaping Handler) { loadImage(with: Request(url: url), into: target, handler: handler) } } /// Represents a target for image loading. public protocol Target: class { /// Callback that gets called when the request is completed. func handle(response: Result<Image>, isFromMemoryCache: Bool) } #if os(macOS) import Cocoa /// Alias for `NSImageView` public typealias ImageView = NSImageView #elseif os(iOS) || os(tvOS) import UIKit /// Alias for `UIImageView` public typealias ImageView = UIImageView #endif #if os(macOS) || os(iOS) || os(tvOS) /// Default implementation of `Target` protocol for `ImageView`. extension ImageView: Target { /// Displays an image on success. Runs `opacity` transition if /// the response was not from the memory cache. public func handle(response: Result<Image>, isFromMemoryCache: Bool) { guard let image = response.value else { return } self.image = image if !isFromMemoryCache { let animation = CABasicAnimation(keyPath: "opacity") animation.duration = 0.25 animation.fromValue = 0 animation.toValue = 1 let layer: CALayer? = self.layer // Make compiler happy on macOS layer?.add(animation, forKey: "imageTransition") } } } #endif
mit
67a0c9f78f26055d55574f0ad8620a1c
38.655172
132
0.647826
4.680233
false
false
false
false
primetimer/PrimeFactors
PrimeFactors/Classes/TrialDivision.swift
1
2738
// // TrialDivision.swift // PFactors // // Created by Stephan Jancar on 18.10.17. // import Foundation import BigInt public class TrialDivision : PFactor { public func GetFactor(n: BigUInt, cancel: CalcCancelProt?) -> BigUInt { let factor = BigTrialDivision(n: n, cancel: cancel) return factor } private let pfirst : [UInt64] = [2,3,5,7,11,13,17,19,23,29,31,37,41,43] private var mk : UInt64 = 1 //Primorial up to limit2 private var wk : [UInt16] = [] private var lastp : UInt64 = 2 //Last prime number used in wheel private var sieve : PrimeSieve! public init() { sieve = PSieve.shared InitWheel() } public init(sieve : PrimeSieve) { self.sieve = sieve InitWheel() } private func IsCancelled(cancel: CalcCancelProt?) -> Bool { return cancel?.IsCancelled() ?? false } public func TrialDivision(n: UInt64, upto: UInt64 = 0, cancel: CalcCancelProt?) -> UInt64 { let limit = (upto > 0) ? upto : n.squareRoot() let limitsieve = sieve.limit if n < 2 { return 1 } for p in pfirst { if n % p == 0 { return p } } var q = pfirst[pfirst.count-1] while !IsCancelled(cancel: cancel) { let offset = Int(wk[Int(q % mk)]) q = q + UInt64(offset) if q > limit { break } if q < limitsieve { if sieve.IsPrime(n: q) { if n % q == 0 { return q } } } else { if n % q == 0 { return q } } } return 0 } public func BigTrialDivision(n: BigUInt, upto: BigUInt = 0, startwith : BigUInt = 0, cancel : CalcCancelProt?) -> BigUInt { if n < BigUInt(UINT64_MAX) { let divisor64 = TrialDivision(n: UInt64(n), upto: UInt64(upto), cancel: cancel) return BigUInt(divisor64) } let limit = (upto > 0) ? upto : n.squareRoot() let limitsieve = sieve.limit if n < 2 { return 1 } for p in pfirst { if n % BigUInt(p) == 0 { return BigUInt(p) } } var q = UInt64(startwith) if q == 0 { q = pfirst[pfirst.count-1] } while !IsCancelled(cancel: cancel) { let offset = Int(wk[Int(q % mk)]) q = q + UInt64(offset) if q > limit { break } if q < limitsieve { if sieve.IsPrime(n: q) { if n % BigUInt(q) == 0 { return BigUInt(q) } } } else { if n % BigUInt(q) == 0 { return BigUInt(q) } } } return 0 } private func InitPrimorial() { mk = 1 let limit2 = sieve.limit.squareRoot() for k in 0..<pfirst.count { if mk * pfirst[k] > limit2 { break } mk = mk * pfirst[k] lastp = pfirst[k] } } private func InitWheel() { InitPrimorial() wk = [UInt16] (repeating: 0, count: Int(mk)) wk[Int(mk)-1] = 2 var y = Int(mk-1) for x in stride(from: Int(mk)-2, to: 0, by: -1) { if mk.greatestCommonDivisor(with: UInt64(x)) == 1 { wk[Int(x)] = UInt16(y - x) y = x } } } }
mit
3d8ee00b3efc481ed47b338a582a9628
22.603448
124
0.601169
2.776876
false
false
false
false
andrea-prearo/SwiftExamples
AtomicVariables/AtomicVariables/AtomicVariables/AtomicVariables/Atomic.swift
1
694
// // Atomic.swift // AtomicVariables // // Created by Andrea Prearo on 1/4/19. // Copyright © 2019 Andrea Prearo. All rights reserved. // import Foundation class Atomic<A> { private let queue = DispatchQueue(label: "com.aprearo.SynchronizedAtomic.queue") private var _value: A private(set) var getCount = 0 private(set) var setCount = 0 init(_ value: A) { self._value = value } var value: A { get { getCount += 1 return queue.sync { _value } } } func mutate(_ transform: (inout A) -> ()) { queue.sync { transform(&_value) setCount += 1 } } }
mit
d6f36fc044aa4d46ab62094ed5e13afb
18.8
84
0.535354
3.915254
false
false
false
false
BranchMetrics/iOS-Deferred-Deep-Linking-SDK
Branch-TestBed-Swift/TestBed-Swift/IntegratedSDKsData.swift
1
32505
// // IntegratedSDKsData.swift // TestBed-Swift // // Created by David Westgate on 9/18/17. // Copyright © 2017 Branch Metrics. All rights reserved. // import Foundation struct IntegratedSDKsData { static let userDefaults = UserDefaults.standard // MARK - Adjust static func activeAdjustAppToken() -> String? { if let value = userDefaults.string(forKey: "activeAppToken") { if value.count > 0 { return value } } if let value = Bundle.main.object(forInfoDictionaryKey: "adjust_app_token") as? String { userDefaults.setValue(value, forKey: "activeAppToken") return value } return nil } static func setActiveAdjustAppToken(_ value: String) { userDefaults.setValue(value, forKey: "activeAppToken") } static func pendingAdjustAppToken() -> String? { if let value = userDefaults.string(forKey: "pendingAdjustAppToken") { if value.count > 0 { return value } } if let value = Bundle.main.object(forInfoDictionaryKey: "adjust_app_token") as? String { userDefaults.setValue(value, forKey: "pendingAdjustAppToken") return value } return nil } static func setPendingAdjustAppToken(_ value: String) { userDefaults.setValue(value, forKey: "pendingAdjustAppToken") } static func activeAdjustEnabled() -> Bool? { return userDefaults.bool(forKey: "activeAdjustEnabled") } static func setActiveAdjustEnabled(_ value: Bool) { userDefaults.setValue(value, forKey: "activeAdjustEnabled") } static func pendingAdjustEnabled() -> Bool? { return userDefaults.bool(forKey: "pendingAdjustEnabled") } static func setPendingAdjustEnabled(_ value: Bool) { userDefaults.setValue(value, forKey: "pendingAdjustEnabled") } // MARK - Adobe static func activeAdobeKey() -> String? { if let value = userDefaults.string(forKey: "activeAdobeKey") { if value.count > 0 { return value } } if let value = Bundle.main.object(forInfoDictionaryKey: "adobe_api_key") as? String { userDefaults.setValue(value, forKey: "activeAdobeKey") return value } return nil } static func setActiveAdobeKey(_ value: String) { userDefaults.setValue(value, forKey: "activeAdobeKey") } static func pendingAdobeKey() -> String? { if let value = userDefaults.string(forKey: "pendingAdobeKey") { if value.count > 0 { return value } } if let value = Bundle.main.object(forInfoDictionaryKey: "adobe_api_key") as? String { userDefaults.setValue(value, forKey: "pendingAdobeKey") return value } return nil } static func setPendingAdobeKey(_ value: String) { userDefaults.setValue(value, forKey: "pendingAdobeKey") } static func activeAdobeEnabled() -> Bool? { return userDefaults.bool(forKey: "activeAdobeEnabled") } static func setActiveAdobeEnabled(_ value: Bool) { userDefaults.setValue(value, forKey: "activeAdobeEnabled") } static func pendingAdobeEnabled() -> Bool? { return userDefaults.bool(forKey: "pendingAdobeEnabled") } static func setPendingAdobeEnabled(_ value: Bool) { userDefaults.setValue(value, forKey: "pendingAdobeEnabled") } // Amplitude static func activeAmplitudeKey() -> String? { if let value = userDefaults.string(forKey: "activeAmplitudeKey") { if value.count > 0 { return value } } if let value = Bundle.main.object(forInfoDictionaryKey: "amplitude_api_key") as? String{ userDefaults.setValue(value, forKey: "activeAmplitudeKey") return value } return nil } static func setActiveAmplitudeKey(_ value: String) { userDefaults.setValue(value, forKey: "activeAmplitudeKey") } static func pendingAmplitudeKey() -> String? { if let value = userDefaults.string(forKey: "pendingAmplitudeKey") { if value.count > 0 { return value } } if let value = Bundle.main.object(forInfoDictionaryKey: "amplitude_api_key") as? String { userDefaults.setValue(value, forKey: "pendingAmplitudeKey") return value } return nil } static func setPendingAmplitudeKey(_ value: String) { userDefaults.setValue(value, forKey: "pendingAmplitudeKey") } static func activeAmplitudeEnabled() -> Bool? { return userDefaults.bool(forKey: "activeAmplitudeEnabled") } static func setActiveAmplitudeEnabled(_ value: Bool) { userDefaults.setValue(value, forKey: "activeAmplitudeEnabled") } static func pendingAmplitudeEnabled() -> Bool? { return userDefaults.bool(forKey: "pendingAmplitudeEnabled") } static func setPendingAmplitudeEnabled(_ value: Bool) { userDefaults.setValue(value, forKey: "pendingAmplitudeEnabled") } // Mark - Appsflyer static func activeAppsflyerKey() -> String? { if let value = userDefaults.string(forKey: "activeAppsflyerKey") { if value.count > 0 { return value } } if let value = Bundle.main.object(forInfoDictionaryKey: "appsflyer_api_key") as? String { userDefaults.setValue(value, forKey: "activeAppsflyerKey") return value } return nil } static func setActiveAppsflyerKey(_ value: String) { userDefaults.setValue(value, forKey: "activeAppsflyerKey") } static func pendingAppsflyerKey() -> String? { if let value = userDefaults.string(forKey: "pendingAppsflyerKey") { if value.count > 0 { return value } } if let value = Bundle.main.object(forInfoDictionaryKey: "appsflyer_api_key") as? String { userDefaults.setValue(value, forKey: "pendingAppsflyerKey") return value } return nil } static func setPendingAppsflyerKey(_ value: String) { userDefaults.setValue(value, forKey: "pendingAppsflyerKey") } static func activeAppsflyerEnabled() -> Bool? { return userDefaults.bool(forKey: "activeAppsflyerEnabled") } static func setActiveAppsflyerEnabled(_ value: Bool) { userDefaults.setValue(value, forKey: "activeAppsflyerEnabled") } static func pendingAppsflyerEnabled() -> Bool? { return userDefaults.bool(forKey: "pendingAppsflyerEnabled") } static func setPendingAppsflyerEnabled(_ value: Bool) { userDefaults.setValue(value, forKey: "pendingAppsflyerEnabled") } // Mark - Google Analytics static func activeGoogleAnalyticsTrackingID() -> String? { if let value = userDefaults.string(forKey: "activeGoogleAnalyticsTrackingID") { if value.count > 0 { return value } } if let value = Bundle.main.object(forInfoDictionaryKey: "google_analytics_tracking_id") as? String { userDefaults.setValue(value, forKey: "activeGoogleAnalyticsTrackingID") return value } return nil } static func setActiveGoogleAnalyticsTrackingID(_ value: String) { userDefaults.setValue(value, forKey: "activeGoogleAnalyticsTrackingID") } static func pendingGoogleAnalyticsTrackingID() -> String? { if let value = userDefaults.string(forKey: "pendingGoogleAnalyticsTrackingID") { if value.count > 0 { return value } } if let value = Bundle.main.object(forInfoDictionaryKey: "google_analytics_tracking_id") as? String { userDefaults.setValue(value, forKey: "pendingGoogleAnalyticsTrackingID") return value } return nil } static func setPendingGoogleAnalyticsTrackingID(_ value: String) { userDefaults.setValue(value, forKey: "pendingGoogleAnalyticsTrackingID") } static func activeGoogleAnalyticsEnabled() -> Bool? { return userDefaults.bool(forKey: "activeGoogleAnalyticsEnabled") } static func setActiveGoogleAnalyticsEnabled(_ value: Bool) { userDefaults.setValue(value, forKey: "activeGoogleAnalyticsEnabled") } static func pendingGoogleAnalyticsEnabled() -> Bool? { return userDefaults.bool(forKey: "pendingGoogleAnalyticsEnabled") } static func setPendingGoogleAnalyticsEnabled(_ value: Bool) { userDefaults.setValue(value, forKey: "pendingGoogleAnalyticsEnabled") } // Mark - Mixpanel static func activeMixpanelKey() -> String? { if let value = userDefaults.string(forKey: "activeMixpanelKey") { if value.count > 0 { return value } } if let value = Bundle.main.object(forInfoDictionaryKey: "mixpanel_api_key") as? String { userDefaults.setValue(value, forKey: "activeMixpanelKey") return value } return nil } static func setActiveMixpanelKey(_ value: String) { userDefaults.setValue(value, forKey: "activeMixpanelKey") } static func pendingMixpanelKey() -> String? { if let value = userDefaults.string(forKey: "pendingMixpanelKey") { if value.count > 0 { return value } } if let value = Bundle.main.object(forInfoDictionaryKey: "mixpanel_api_key") as? String { userDefaults.setValue(value, forKey: "pendingMixpanelKey") return value } return nil } static func setPendingMixpanelKey(_ value: String) { userDefaults.setValue(value, forKey: "pendingMixpanelKey") } static func activeMixpanelEnabled() -> Bool? { return userDefaults.bool(forKey: "activeMixpanelEnabled") } static func setActiveMixpanelEnabled(_ value: Bool) { userDefaults.setValue(value, forKey: "activeMixpanelEnabled") } static func pendingMixpanelEnabled() -> Bool? { return userDefaults.bool(forKey: "pendingMixpanelEnabled") } static func setPendingMixpanelEnabled(_ value: Bool) { userDefaults.setValue(value, forKey: "pendingMixpanelEnabled") } // Mark - Tune // AdvertisingID static func activeTuneAdvertisingID() -> String? { if let value = userDefaults.string(forKey: "activeTuneAdvertisingID") { if value.count > 0 { return value } } if let value = Bundle.main.object(forInfoDictionaryKey: "tune_advertising_id") as? String { userDefaults.setValue(value, forKey: "activeTuneAdvertisingID") return value } return nil } static func setActiveTuneAdvertisingID(_ value: String) { userDefaults.setValue(value, forKey: "activeTuneAdvertisingID") } static func pendingTuneAdvertisingID() -> String? { if let value = userDefaults.string(forKey: "pendingTuneAdvertisingID") { if value.count > 0 { return value } } if let value = Bundle.main.object(forInfoDictionaryKey: "tune_advertising_id") as? String { userDefaults.setValue(value, forKey: "pendingTuneAdvertisingID") return value } return nil } static func setPendingTuneAdvertisingID(_ value: String) { userDefaults.setValue(value, forKey: "pendingTuneAdvertisingID") } // ConversionKey static func activeTuneConversionKey() -> String? { if let value = userDefaults.string(forKey: "activeTuneConversionKey") { if value.count > 0 { return value } } if let value = Bundle.main.object(forInfoDictionaryKey: "tune_conversion_key") as? String { userDefaults.setValue(value, forKey: "activeTuneConversionKey") return value } return nil } static func setActiveTuneConversionKey(_ value: String) { userDefaults.setValue(value, forKey: "activeTuneConversionKey") } static func pendingTuneConversionKey() -> String? { if let value = userDefaults.string(forKey: "pendingTuneConversionKey") { if value.count > 0 { return value } } if let value = Bundle.main.object(forInfoDictionaryKey: "tune_conversion_key") as? String { userDefaults.setValue(value, forKey: "pendingTuneConversionKey") return value } return nil } static func setPendingTuneConversionKey(_ value: String) { userDefaults.setValue(value, forKey: "pendingTuneConversionKey") } static func activeTuneEnabled() -> Bool? { return userDefaults.bool(forKey: "activeTuneEnabled") } static func setActiveTuneEnabled(_ value: Bool) { userDefaults.setValue(value, forKey: "activeTuneEnabled") } static func pendingTuneEnabled() -> Bool? { return userDefaults.bool(forKey: "pendingTuneEnabled") } static func setPendingTuneEnabled(_ value: Bool) { userDefaults.setValue(value, forKey: "pendingTuneEnabled") } // Mark - Appboy static func activeAppboyAPIKey() -> String? { if let value = userDefaults.string(forKey: "activeAppboyAPIKey") { if value.count > 0 { return value } } if let value = Bundle.main.object(forInfoDictionaryKey: "appboy_api_key") as? String { userDefaults.setValue(value, forKey: "activeAppboyAPIKey") return value } return nil } static func setActiveAppboyAPIKey(_ value: String) { userDefaults.setValue(value, forKey: "activeAppboyAPIKey") } static func pendingAppboyAPIKey() -> String? { if let value = userDefaults.string(forKey: "pendingAppboyAPIKey") { if value.count > 0 { return value } } if let value = Bundle.main.object(forInfoDictionaryKey: "appboy_api_key") as? String { userDefaults.setValue(value, forKey: "pendingAppboyAPIKey") return value } return nil } static func setPendingAppboyAPIKey(_ value: String) { userDefaults.setValue(value, forKey: "pendingAppboyAPIKey") } static func activeAppboyEnabled() -> Bool? { return userDefaults.bool(forKey: "activeAppboyEnabled") } static func setActiveAppboyEnabled(_ value: Bool) { userDefaults.setValue(value, forKey: "activeAppboyEnabled") } static func pendingAppboyEnabled() -> Bool? { return userDefaults.bool(forKey: "pendingAppboyEnabled") } static func setPendingAppboyEnabled(_ value: Bool) { userDefaults.setValue(value, forKey: "pendingAppboyEnabled") } // Mark - AppMetrica static func activeAppMetricaAPIKey() -> String? { if let value = userDefaults.string(forKey: "activeAppMetricaAPIKey") { if value.count > 0 { return value } } if let value = Bundle.main.object(forInfoDictionaryKey: "appmetrica_api_key") as? String { userDefaults.setValue(value, forKey: "activeAppMetricaAPIKey") return value } return nil } static func setActiveAppMetricaAPIKey(_ value: String) { userDefaults.setValue(value, forKey: "activeAppMetricaAPIKey") } static func pendingAppMetricaAPIKey() -> String? { if let value = userDefaults.string(forKey: "pendingAppMetricaAPIKey") { if value.count > 0 { return value } } if let value = Bundle.main.object(forInfoDictionaryKey: "appmetrica_api_key") as? String { userDefaults.setValue(value, forKey: "pendingAppMetricaAPIKey") return value } return nil } static func setPendingAppMetricaAPIKey(_ value: String) { userDefaults.setValue(value, forKey: "pendingAppMetricaAPIKey") } static func activeAppMetricaEnabled() -> Bool? { return userDefaults.bool(forKey: "activeAppMetricaEnabled") } static func setActiveAppMetricaEnabled(_ value: Bool) { userDefaults.setValue(value, forKey: "activeAppMetricaEnabled") } static func pendingAppMetricaEnabled() -> Bool? { return userDefaults.bool(forKey: "pendingAppMetricaEnabled") } static func setPendingAppMetricaEnabled(_ value: Bool) { userDefaults.setValue(value, forKey: "pendingAppMetricaEnabled") } // Mark - ClearTap static func activeClearTapAPIKey() -> String? { if let value = userDefaults.string(forKey: "activeClearTapAPIKey") { if value.count > 0 { return value } } if let value = Bundle.main.object(forInfoDictionaryKey: "clevertap_api_key") as? String { userDefaults.setValue(value, forKey: "activeClearTapAPIKey") return value } return nil } static func setActiveClearTapAPIKey(_ value: String) { userDefaults.setValue(value, forKey: "activeClearTapAPIKey") } static func pendingClearTapAPIKey() -> String? { if let value = userDefaults.string(forKey: "pendingClearTapAPIKey") { if value.count > 0 { return value } } if let value = Bundle.main.object(forInfoDictionaryKey: "clevertap_api_key") as? String { userDefaults.setValue(value, forKey: "pendingClearTapAPIKey") return value } return nil } static func setPendingClearTapAPIKey(_ value: String) { userDefaults.setValue(value, forKey: "pendingClearTapAPIKey") } static func activeClearTapEnabled() -> Bool? { return userDefaults.bool(forKey: "activeClearTapEnabled") } static func setActiveClearTapEnabled(_ value: Bool) { userDefaults.setValue(value, forKey: "activeClearTapEnabled") } static func pendingClearTapEnabled() -> Bool? { return userDefaults.bool(forKey: "pendingClearTapEnabled") } static func setPendingClearTapEnabled(_ value: Bool) { userDefaults.setValue(value, forKey: "pendingClearTapEnabled") } // Mark - Convertro static func activeConvertroAPIKey() -> String? { if let value = userDefaults.string(forKey: "activeConvertroAPIKey") { if value.count > 0 { return value } } if let value = Bundle.main.object(forInfoDictionaryKey: "convertro_api_key") as? String { userDefaults.setValue(value, forKey: "activeConvertroAPIKey") return value } return nil } static func setActiveConvertroAPIKey(_ value: String) { userDefaults.setValue(value, forKey: "activeConvertroAPIKey") } static func pendingConvertroAPIKey() -> String? { if let value = userDefaults.string(forKey: "pendingConvertroAPIKey") { if value.count > 0 { return value } } if let value = Bundle.main.object(forInfoDictionaryKey: "convertro_api_key") as? String { userDefaults.setValue(value, forKey: "pendingConvertroAPIKey") return value } return nil } static func setPendingConvertroAPIKey(_ value: String) { userDefaults.setValue(value, forKey: "pendingConvertroAPIKey") } static func activeConvertroEnabled() -> Bool? { return userDefaults.bool(forKey: "activeConvertroEnabled") } static func setActiveConvertroEnabled(_ value: Bool) { userDefaults.setValue(value, forKey: "activeConvertroEnabled") } static func pendingConvertroEnabled() -> Bool? { return userDefaults.bool(forKey: "pendingConvertroEnabled") } static func setPendingConvertroEnabled(_ value: Bool) { userDefaults.setValue(value, forKey: "pendingConvertroEnabled") } // Mark - Kochava static func activeKochavaAPIKey() -> String? { if let value = userDefaults.string(forKey: "activeKochavaAPIKey") { if value.count > 0 { return value } } if let value = Bundle.main.object(forInfoDictionaryKey: "kochava_api_key") as? String { userDefaults.setValue(value, forKey: "activeKochavaAPIKey") return value } return nil } static func setActiveKochavaAPIKey(_ value: String) { userDefaults.setValue(value, forKey: "activeKochavaAPIKey") } static func pendingKochavaAPIKey() -> String? { if let value = userDefaults.string(forKey: "pendingKochavaAPIKey") { if value.count > 0 { return value } } if let value = Bundle.main.object(forInfoDictionaryKey: "kochava_api_key") as? String { userDefaults.setValue(value, forKey: "pendingKochavaAPIKey") return value } return nil } static func setPendingKochavaAPIKey(_ value: String) { userDefaults.setValue(value, forKey: "pendingKochavaAPIKey") } static func activeKochavaEnabled() -> Bool? { return userDefaults.bool(forKey: "activeKochavaEnabled") } static func setActiveKochavaEnabled(_ value: Bool) { userDefaults.setValue(value, forKey: "activeKochavaEnabled") } static func pendingKochavaEnabled() -> Bool? { return userDefaults.bool(forKey: "pendingKochavaEnabled") } static func setPendingKochavaEnabled(_ value: Bool) { userDefaults.setValue(value, forKey: "pendingKochavaEnabled") } // Mark - Localytics static func activeLocalyticsAppKey() -> String? { if let value = userDefaults.string(forKey: "activeLocalyticsAppKey") { if value.count > 0 { return value } } if let value = Bundle.main.object(forInfoDictionaryKey: "localytics_app_key") as? String { userDefaults.setValue(value, forKey: "activeLocalyticsAppKey") return value } return nil } static func setActiveLocalyticsAppKey(_ value: String) { userDefaults.setValue(value, forKey: "activeLocalyticsAppKey") } static func pendingLocalyticsAppKey() -> String? { if let value = userDefaults.string(forKey: "pendingLocalyticsAppKey") { if value.count > 0 { return value } } if let value = Bundle.main.object(forInfoDictionaryKey: "localytics_app_key") as? String { userDefaults.setValue(value, forKey: "pendingLocalyticsAppKey") return value } return nil } static func setPendingLocalyticsAppKey(_ value: String) { userDefaults.setValue(value, forKey: "pendingLocalyticsAppKey") } static func activeLocalyticsEnabled() -> Bool? { return userDefaults.bool(forKey: "activeLocalyticsEnabled") } static func setActiveLocalyticsEnabled(_ value: Bool) { userDefaults.setValue(value, forKey: "activeLocalyticsEnabled") } static func pendingLocalyticsEnabled() -> Bool? { return userDefaults.bool(forKey: "pendingLocalyticsEnabled") } static func setPendingLocalyticsEnabled(_ value: Bool) { userDefaults.setValue(value, forKey: "pendingLocalyticsEnabled") } // Mark - mParticle static func activemParticleAppKey() -> String? { if let value = userDefaults.string(forKey: "activemParticleAppKey") { if value.count > 0 { return value } } if let value = Bundle.main.object(forInfoDictionaryKey: "mparticle_app_key") as? String { userDefaults.setValue(value, forKey: "activemParticleAppKey") return value } return nil } static func setActivemParticleAppKey(_ value: String) { userDefaults.setValue(value, forKey: "activemParticleAppKey") } static func pendingmParticleAppKey() -> String? { if let value = userDefaults.string(forKey: "pendingmParticleAppKey") { if value.count > 0 { return value } } if let value = Bundle.main.object(forInfoDictionaryKey: "mparticle_app_key") as? String { userDefaults.setValue(value, forKey: "pendingmParticleAppKey") return value } return nil } static func setPendingmParticleAppKey(_ value: String) { userDefaults.setValue(value, forKey: "pendingmParticleAppKey") } static func activemParticleAppSecret() -> String? { if let value = userDefaults.string(forKey: "activemParticleAppSecret") { if value.count > 0 { return value } } if let value = Bundle.main.object(forInfoDictionaryKey: "mparticle_app_secret") as? String { userDefaults.setValue(value, forKey: "activemParticleAppSecret") return value } return nil } static func setActivemParticleAppSecret(_ value: String) { userDefaults.setValue(value, forKey: "activemParticleAppSecret") } static func pendingmParticleAppSecret() -> String? { if let value = userDefaults.string(forKey: "pendingmParticleAppSecret") { if value.count > 0 { return value } } if let value = Bundle.main.object(forInfoDictionaryKey: "mparticle_app_secret") as? String { userDefaults.setValue(value, forKey: "pendingmParticleAppSecret") return value } return nil } static func setPendingmParticleAppSecret(_ value: String) { userDefaults.setValue(value, forKey: "pendingmParticleAppSecret") } static func activemParticleEnabled() -> Bool? { return userDefaults.bool(forKey: "activemParticleEnabled") } static func setActivemParticleEnabled(_ value: Bool) { userDefaults.setValue(value, forKey: "activemParticleEnabled") } static func pendingmParticleEnabled() -> Bool? { return userDefaults.bool(forKey: "pendingmParticleEnabled") } static func setPendingmParticleEnabled(_ value: Bool) { userDefaults.setValue(value, forKey: "pendingmParticleEnabled") } // Mark - Segment static func activeSegmentAPIKey() -> String? { if let value = userDefaults.string(forKey: "activeSegmentAPIKey") { if value.count > 0 { return value } } if let value = Bundle.main.object(forInfoDictionaryKey: "segment_api_key") as? String { userDefaults.setValue(value, forKey: "activeSegmentAPIKey") return value } return nil } static func setActiveSegmentAPIKey(_ value: String) { userDefaults.setValue(value, forKey: "activeSegmentAPIKey") } static func pendingSegmentAPIKey() -> String? { if let value = userDefaults.string(forKey: "pendingSegmentAPIKey") { if value.count > 0 { return value } } if let value = Bundle.main.object(forInfoDictionaryKey: "segment_api_key") as? String { userDefaults.setValue(value, forKey: "pendingSegmentAPIKey") return value } return nil } static func setPendingSegmentAPIKey(_ value: String) { userDefaults.setValue(value, forKey: "pendingSegmentAPIKey") } static func activeSegmentEnabled() -> Bool? { return userDefaults.bool(forKey: "activeSegmentEnabled") } static func setActiveSegmentEnabled(_ value: Bool) { userDefaults.setValue(value, forKey: "activeSegmentEnabled") } static func pendingSegmentEnabled() -> Bool? { return userDefaults.bool(forKey: "pendingSegmentEnabled") } static func setPendingSegmentEnabled(_ value: Bool) { userDefaults.setValue(value, forKey: "pendingSegmentEnabled") } // Mark - Singular static func activeSingularAPIKey() -> String? { if let value = userDefaults.string(forKey: "activeSingularAPIKey") { if value.count > 0 { return value } } if let value = Bundle.main.object(forInfoDictionaryKey: "singular_api_key") as? String { userDefaults.setValue(value, forKey: "activeSingularAPIKey") return value } return nil } static func setActiveSingularAPIKey(_ value: String) { userDefaults.setValue(value, forKey: "activeSingularAPIKey") } static func pendingSingularAPIKey() -> String? { if let value = userDefaults.string(forKey: "pendingSingularAPIKey") { if value.count > 0 { return value } } if let value = Bundle.main.object(forInfoDictionaryKey: "singular_api_key") as? String { userDefaults.setValue(value, forKey: "pendingSingularAPIKey") return value } return nil } static func setPendingSingularAPIKey(_ value: String) { userDefaults.setValue(value, forKey: "pendingSingularAPIKey") } static func activeSingularEnabled() -> Bool? { return userDefaults.bool(forKey: "activeSingularEnabled") } static func setActiveSingularEnabled(_ value: Bool) { userDefaults.setValue(value, forKey: "activeSingularEnabled") } static func pendingSingularEnabled() -> Bool? { return userDefaults.bool(forKey: "pendingSingularEnabled") } static func setPendingSingularEnabled(_ value: Bool) { userDefaults.setValue(value, forKey: "pendingSingularEnabled") } // Mark - Stitch static func activeStitchAPIKey() -> String? { if let value = userDefaults.string(forKey: "activeStitchAPIKey") { if value.count > 0 { return value } } if let value = Bundle.main.object(forInfoDictionaryKey: "stitch_api_key") as? String { userDefaults.setValue(value, forKey: "activeStitchAPIKey") return value } return nil } static func setActiveStitchAPIKey(_ value: String) { userDefaults.setValue(value, forKey: "activeStitchAPIKey") } static func pendingStitchAPIKey() -> String? { if let value = userDefaults.string(forKey: "pendingStitchAPIKey") { if value.count > 0 { return value } } if let value = Bundle.main.object(forInfoDictionaryKey: "stitch_api_key") as? String { userDefaults.setValue(value, forKey: "pendingStitchAPIKey") return value } return nil } static func setPendingStitchAPIKey(_ value: String) { userDefaults.setValue(value, forKey: "pendingStitchAPIKey") } static func activeStitchEnabled() -> Bool? { return userDefaults.bool(forKey: "activeStitchEnabled") } static func setActiveStitchEnabled(_ value: Bool) { userDefaults.setValue(value, forKey: "activeStitchEnabled") } static func pendingStitchEnabled() -> Bool? { return userDefaults.bool(forKey: "pendingStitchEnabled") } static func setPendingStitchEnabled(_ value: Bool) { userDefaults.setValue(value, forKey: "pendingStitchEnabled") } }
mit
fdad802a2e3280b07e285c03f48b62b9
32.54386
108
0.615032
5.224044
false
false
false
false
mchaffee1/AppModules
Example/Tests/ModuleConnectorTests.swift
1
1944
import Foundation import Quick import Nimble @testable import AppModules class ModuleConnectorTests: QuickSpec { override func spec() { it("mounts a module") { let moduleConnector = ModuleConnector() moduleConnector.mount(module: MockModule(connector: moduleConnector)) let mockModule = moduleConnector.routes.values.first { $0 is MockModule } expect(mockModule).notTo(beNil()) } it("returns nil on get when no module is mounted") { let moduleConnector = ModuleConnector() guard let url = URL(string: "notmock://whatever") else { XCTFail(); return } let result = moduleConnector.get(url: url) expect(result).to(beNil()) } it("routes get requests to the appropriate module") { let moduleConnector = ModuleConnector() let mockModule = MockModule(connector: moduleConnector) let mockModule2 = MockModule(connector: moduleConnector) mockModule2.urlSchemes = ["mock2"] moduleConnector.mount(module: mockModule) moduleConnector.mount(module: mockModule2) guard let url = URL(string: "\(mockModule.urlSchemes[0])://whatever") else { XCTFail(); return } let result = moduleConnector.get(url: url) expect(mockModule.getCount).to(equal(1)) expect(mockModule2.getCount).to(equal(0)) expect(result as? String).to(equal(mockModule.moduleResource as? String)) } it("correctly reports valid url schemes") { let moduleConnector = ModuleConnector() let mockModule = MockModule(connector: moduleConnector) moduleConnector.mount(module: mockModule) let result = moduleConnector.respondsTo(urlScheme: mockModule.urlSchemes[0]) expect(result).to(beTrue()) } } }
apache-2.0
eefc91f5da816c5e9815412402db708c
33.105263
108
0.619342
5.170213
false
false
false
false
ricohapi/media-storage-swift
Source/MediaStorageRequest.swift
2
4621
// // Copyright (c) 2016 Ricoh Company, Ltd. All Rights Reserved. // See LICENSE for more information // import Foundation class MediaStorageRequest { static func get(url url: String, queryParams: Dictionary<String, AnyObject>, header: Dictionary<String, String>, completionHandler: (NSData?, NSURLResponse?, NSError?) -> Void) { var requestUrl = url if queryParams.count > 0 { requestUrl += "?" + joinParameters(params: queryParams) } sendRequest( url: requestUrl, method: "GET", header: header, completionHandler: completionHandler ) } static func post(url url: String, header: Dictionary<String, String>, body: NSData? = nil, completionHandler: (NSData?, NSURLResponse?, NSError?) -> Void) { sendRequest( url: url, method: "POST", header: header, body: body, completionHandler: completionHandler ) } static func put(url url: String, header: Dictionary<String, String>, data: String, completionHandler: (NSData?, NSURLResponse?, NSError?) -> Void){ sendRequest( url: url, method: "PUT", header: header, body: data.dataUsingEncoding(NSUTF8StringEncoding), completionHandler: completionHandler ) } static func upload(url url: String, header: Dictionary<String, String>, data: NSData, completionHandler: (NSData?, NSURLResponse?, NSError?) -> Void) { sendRequestToUpload( url: url, method: "POST", header: header, data: data, completionHandler: completionHandler ) } static func download(url url: String, header: Dictionary<String, String>, completionHandler: (NSURL?, NSURLResponse?, NSError?) -> Void) { sendRequestToDownload( url: url, method: "GET", header: header, completionHandler: completionHandler ) } static func delete(url url: String, header: Dictionary<String, String>, completionHandler: (NSData?, NSURLResponse?, NSError?) -> Void) { sendRequest( url: url, method: "DELETE", header: header, completionHandler: completionHandler ) } static func sendRequest(url url: String, method: String, header: Dictionary<String, String>, body: NSData? = nil, completionHandler: (NSData?, NSURLResponse?, NSError?) -> Void) { let request = generateRequest(url: url, method: method, header: header, body: body) let config = NSURLSessionConfiguration.defaultSessionConfiguration() let session = NSURLSession(configuration: config) let task = session.dataTaskWithRequest(request, completionHandler: completionHandler) task.resume() } static func sendRequestToUpload(url url: String, method: String, header: Dictionary<String, String>, data: NSData, completionHandler: (NSData?, NSURLResponse?, NSError?) -> Void) { let request = generateRequest(url: url, method: method, header: header) let config = NSURLSessionConfiguration.defaultSessionConfiguration() let session = NSURLSession(configuration: config) let task = session.uploadTaskWithRequest(request, fromData: data, completionHandler: completionHandler) task.resume() } static func sendRequestToDownload(url url: String, method: String, header: Dictionary<String, String>, completionHandler: (NSURL?, NSURLResponse?, NSError?) -> Void) { let request = generateRequest(url: url, method: method, header: header) let config = NSURLSessionConfiguration.defaultSessionConfiguration() let session = NSURLSession(configuration: config) let task = session.downloadTaskWithRequest(request, completionHandler: completionHandler) task.resume() } static func generateRequest(url url: String, method: String, header: Dictionary<String, String>, body: NSData? = nil) -> NSMutableURLRequest { let request = NSMutableURLRequest(URL: NSURL(string: url)!) request.HTTPMethod = method for (key, value) in header { request.setValue(value, forHTTPHeaderField: key) } request.HTTPBody = body return request } static func joinParameters(params params: Dictionary<String, AnyObject>) -> String { return params.map({(key, value) in return "\(key)=\(value)" }).joinWithSeparator("&") } }
mit
91cb455453eb368f3ed38845987694c5
41.394495
184
0.635144
5.197975
false
true
false
false
insidegui/WWDC
Packages/ConfCore/ConfCore/UserDataSyncEngine.swift
1
29348
// // UserDataSyncEngine.swift // ConfCore // // Created by Guilherme Rambo on 20/05/18. // Copyright © 2018 Guilherme Rambo. All rights reserved. // import Foundation import CloudKit import CloudKitCodable import RealmSwift import RxCocoa import RxSwift import os.log public final class UserDataSyncEngine { public init(storage: Storage, defaults: UserDefaults = .standard, container: CKContainer = .default()) { self.storage = storage self.defaults = defaults self.container = container self.privateDatabase = container.privateCloudDatabase checkAccountAvailability() NotificationCenter.default.addObserver(self, selector: #selector(checkAccountAvailability), name: .CKAccountChanged, object: nil) } private struct Constants { static let zoneName = "WWDCV6" static let privateSubscriptionId = "wwdcv6-private-changes" } private let storage: Storage private let defaults: UserDefaults private let container: CKContainer private let privateDatabase: CKDatabase private let log = OSLog(subsystem: "ConfCore", category: "UserDataSyncEngine") private lazy var cloudOperationQueue: OperationQueue = { let q = OperationQueue() q.name = "CloudKit" return q }() private let workQueue = DispatchQueue(label: "UserDataSyncEngine") private var createdCustomZone: Bool { get { return defaults.bool(forKey: #function) } set { defaults.set(newValue, forKey: #function) } } private var createdPrivateSubscription: Bool { get { return defaults.bool(forKey: #function) } set { defaults.set(newValue, forKey: #function) } } private lazy var customZoneID: CKRecordZone.ID = { return CKRecordZone.ID(zoneName: Constants.zoneName, ownerName: CKCurrentUserDefaultName) }() // MARK: - State management public private(set) var isRunning = false private var isWaitingForAccountAvailabilityToStart = false public var isEnabled = false { didSet { guard oldValue != isEnabled else { return } if isEnabled { os_log("Starting because isEnabled has changed to true", log: log, type: .debug) start() } else { isWaitingForAccountAvailabilityToStart = false os_log("Stopping because isEnabled has changed to false", log: log, type: .debug) stop() } } } private let disposeBag = DisposeBag() public func start() { guard ConfCoreCapabilities.isCloudKitEnabled else { return } guard !isWaitingForAccountAvailabilityToStart else { return } guard isEnabled else { return } guard !isRunning else { return } os_log("Start!", log: log, type: .debug) // Only start the sync engine if there's an iCloud account available, if availability is not // determined yet, start the sync engine after the account availability is known and == available guard isAccountAvailable.value else { os_log("iCloud account is not available yet, waiting for availability to start", log: log, type: .info) isWaitingForAccountAvailabilityToStart = true isAccountAvailable.asObservable().observe(on: MainScheduler.instance).subscribe(onNext: { [unowned self] available in guard self.isWaitingForAccountAvailabilityToStart else { return } os_log("iCloud account available = %{public}@", log: self.log, type: .info, String(describing: available)) if available { self.isWaitingForAccountAvailabilityToStart = false self.start() } }).disposed(by: disposeBag) return } isRunning = true startObservingSyncOperations() prepareCloudEnvironment { [unowned self] in self.incinerateSoftDeletedObjects() self.uploadLocalDataNotUploadedYet() self.observeLocalChanges() self.fetchChanges() } } public private(set) var isStopping = BehaviorRelay<Bool>(value: false) public private(set) var isPerformingSyncOperation = BehaviorRelay<Bool>(value: false) public private(set) var isAccountAvailable = BehaviorRelay<Bool>(value: false) public func stop(harsh: Bool = false) { guard isRunning, !isStopping.value else { return } isStopping.accept(true) workQueue.async { [unowned self] in defer { DispatchQueue.main.async { self.isStopping.accept(false) self.isRunning = false } } self.cloudOperationQueue.waitUntilAllOperationsAreFinished() DispatchQueue.main.async { self.stopObservingSyncOperations() self.realmNotificationTokens.forEach { $0.invalidate() } self.realmNotificationTokens.removeAll() guard harsh else { return } self.clearSyncMetadata() } } } private var cloudQueueObservation: NSKeyValueObservation? private func startObservingSyncOperations() { cloudQueueObservation = cloudOperationQueue.observe(\.operationCount) { [unowned self] queue, _ in self.isPerformingSyncOperation.accept(queue.operationCount > 0) } } private func stopObservingSyncOperations() { cloudQueueObservation?.invalidate() cloudQueueObservation = nil } // MARK: Account availability private var isWaitingForAccountAvailabilityReply = false @objc private func checkAccountAvailability() { guard !isWaitingForAccountAvailabilityReply else { return } isWaitingForAccountAvailabilityReply = true os_log("checkAccountAvailability()", log: log, type: .debug) container.accountStatus { [unowned self] status, error in defer { self.isWaitingForAccountAvailabilityReply = false } if let error = error { os_log("Failed to determine iCloud account status: %{public}@", log: self.log, type: .error, String(describing: error)) return } os_log("iCloud availability status is %{public}d", log: self.log, type: .debug, status.rawValue) switch status { case .available: self.isAccountAvailable.accept(true) default: self.isAccountAvailable.accept(false) } } } // MARK: - Cloud environment management private func prepareCloudEnvironment(then block: @escaping () -> Void) { workQueue.async { [unowned self] in self.createCustomZoneIfNeeded() self.cloudOperationQueue.waitUntilAllOperationsAreFinished() guard self.createdCustomZone else { return } self.createPrivateSubscriptionsIfNeeded() self.cloudOperationQueue.waitUntilAllOperationsAreFinished() guard self.createdPrivateSubscription else { return } DispatchQueue.main.async { block() } } } private func createCustomZoneIfNeeded(then completion: (() -> Void)? = nil) { guard !createdCustomZone else { os_log("Already have custom zone, skipping creation", log: log, type: .debug) return } os_log("Creating CloudKit zone %@", log: log, type: .info, Constants.zoneName) let zone = CKRecordZone(zoneID: customZoneID) let operation = CKModifyRecordZonesOperation(recordZonesToSave: [zone], recordZoneIDsToDelete: nil) operation.modifyRecordZonesCompletionBlock = { [unowned self] _, _, error in if let error = error { os_log("Failed to create custom CloudKit zone: %{public}@", log: self.log, type: .error, String(describing: error)) error.retryCloudKitOperationIfPossible(self.log) { self.createCustomZoneIfNeeded() } } else { os_log("Zone created successfully", log: self.log, type: .info) self.createdCustomZone = true DispatchQueue.main.async { completion?() } } } operation.qualityOfService = .userInitiated operation.database = privateDatabase cloudOperationQueue.addOperation(operation) } private func createPrivateSubscriptionsIfNeeded() { guard !createdPrivateSubscription else { os_log("Already subscribed to private database changes, skipping subscription", log: log, type: .debug) return } let subscription = CKDatabaseSubscription(subscriptionID: Constants.privateSubscriptionId) let notificationInfo = CKSubscription.NotificationInfo() notificationInfo.shouldSendContentAvailable = true subscription.notificationInfo = notificationInfo let operation = CKModifySubscriptionsOperation(subscriptionsToSave: [subscription], subscriptionIDsToDelete: nil) operation.modifySubscriptionsCompletionBlock = { [unowned self] _, _, error in if let error = error { os_log("Failed to create private CloudKit subscription: %{public}@", log: self.log, type: .error, String(describing: error)) error.retryCloudKitOperationIfPossible(self.log) { self.createPrivateSubscriptionsIfNeeded() } } else { os_log("Private subscription created successfully", log: self.log, type: .info) self.createdPrivateSubscription = true } } operation.database = privateDatabase operation.qualityOfService = .utility cloudOperationQueue.addOperation(operation) } private func clearSyncMetadata() { privateChangeToken = nil createdPrivateSubscription = false createdCustomZone = false clearCloudKitFields() } private func clearCloudKitFields() { clearCloudKitFields(for: Favorite.self) clearCloudKitFields(for: SessionProgress.self) clearCloudKitFields(for: Bookmark.self) } private func clearCloudKitFields<T: SynchronizableObject>(for objectType: T.Type) { performRealmOperations { realm in realm.objects(objectType).forEach { model in var mutableModel = model mutableModel.ckFields = Data() } } } // MARK: - Silent notifications public func processSubscriptionNotification(with userInfo: [String: Any]) -> Bool { guard isEnabled, isRunning else { return false } let notification = CKNotification(fromRemoteNotificationDictionary: userInfo) guard notification?.subscriptionID == Constants.privateSubscriptionId else { return false } os_log("Received remote CloudKit notification for user data", log: log, type: .debug) fetchChanges() return true } // MARK: - Data syncing private var privateChangeToken: CKServerChangeToken? { get { guard let data = defaults.data(forKey: #function) else { return nil } do { guard let token = try NSKeyedUnarchiver.unarchivedObject(ofClass: CKServerChangeToken.self, from: data) else { os_log("Failed to decode CKServerChangeToken from defaults key privateChangeToken", log: log, type: .error) return nil } return token } catch { os_log("Failed to decode CKServerChangeToken from defaults key privateChangeToken: %{public}@", log: self.log, type: .fault, String(describing: error)) return nil } } set { guard let newValue = newValue else { defaults.removeObject(forKey: #function) return } let data = NSKeyedArchiver.archiveData(with: newValue, secure: true) defaults.set(data, forKey: #function) } } private func fetchChanges() { var changedRecords: [CKRecord] = [] let operation = CKFetchRecordZoneChangesOperation() let config = CKFetchRecordZoneChangesOperation.ZoneConfiguration( previousServerChangeToken: privateChangeToken, resultsLimit: nil, desiredKeys: nil ) operation.recordZoneIDs = [customZoneID] operation.fetchAllChanges = privateChangeToken == nil operation.configurationsByRecordZoneID = [customZoneID: config] operation.recordZoneFetchCompletionBlock = { [unowned self] _, token, _, _, error in if let error = error { os_log("Failed to fetch record zone changes: %{public}@", log: self.log, type: .error, String(describing: error)) if error.isCKTokenExpired { os_log("Change token expired, clearing token and retrying", log: self.log, type: .error) DispatchQueue.main.async { self.privateChangeToken = nil self.fetchChanges() } return } else if error.isCKZoneDeleted { os_log("User deleted CK zone, recreating", log: self.log, type: .error) DispatchQueue.main.async { self.privateChangeToken = nil self.createdCustomZone = false self.createCustomZoneIfNeeded { self.clearCloudKitFields() self.uploadLocalDataNotUploadedYet() self.fetchChanges() } } return } else { error.retryCloudKitOperationIfPossible(self.log) { self.fetchChanges() } } } else { self.privateChangeToken = token } } operation.recordChangedBlock = { changedRecords.append($0) } operation.fetchRecordZoneChangesCompletionBlock = { [unowned self] error in guard error == nil else { return } os_log("Finished fetching record zone changes", log: self.log, type: .info) self.databaseQueue.async { self.commitServerChangesToDatabase(with: changedRecords) } } operation.qualityOfService = .userInitiated operation.database = privateDatabase cloudOperationQueue.addOperation(operation) } // MARK: - CloudKit to Realm private struct RecordTypes { static let favorite = "FavoriteSyncObject" static let bookmark = "BookmarkSyncObject" static let sessionProgress = "SessionProgressSyncObject" } private var recordTypesToRealmModels: [String: SoftDeletableSynchronizableObject.Type] = [ RecordTypes.favorite: Favorite.self, RecordTypes.bookmark: Bookmark.self, RecordTypes.sessionProgress: SessionProgress.self ] private var recordTypesToLastSyncDates: [String: Date] = [:] private func realmModel(for recordType: String) -> SoftDeletableSynchronizableObject.Type? { return recordTypesToRealmModels[recordType] } private func performRealmOperations(with block: @escaping (Realm) -> Void) { databaseQueue.async { self.onQueuePerformRealmOperations(with: block) } } private func onQueuePerformRealmOperations(with block: @escaping (Realm) -> Void) { guard let realm = backgroundRealm else { fatalError("Missing background Realm") } do { realm.beginWrite() block(realm) try realm.commitWrite(withoutNotifying: realmNotificationTokens) } catch { os_log("Failed to perform Realm transaction: %{public}@", log: self.log, type: .error, String(describing: error)) } } private func commitServerChangesToDatabase(with records: [CKRecord]) { guard records.count > 0 else { os_log("Finished record zone changes fetch with no changes", log: log, type: .info) return } os_log("Will commit %{public}d changed record(s) to the database", log: log, type: .info, records.count) performRealmOperations { [weak self] queueRealm in guard let self = self else { return } records.forEach { record in switch record.recordType { case RecordTypes.favorite: self.commit(objectType: Favorite.self, with: record, in: queueRealm) case RecordTypes.bookmark: self.commit(objectType: Bookmark.self, with: record, in: queueRealm) case RecordTypes.sessionProgress: self.commit(objectType: SessionProgress.self, with: record, in: queueRealm) default: os_log("Unknown record type %{public}@", log: self.log, type: .fault, record.recordType) } } } } private func commit<T: SynchronizableObject>(objectType: T.Type, with record: CKRecord, in realm: Realm) { do { let obj = try CloudKitRecordDecoder().decode(objectType.SyncObject.self, from: record) let model = objectType.from(syncObject: obj) realm.add(model, update: .all) guard let sessionId = obj.sessionId else { os_log("Sync object didn't have a sessionId!", log: self.log, type: .fault) return } guard let session = realm.object(ofType: Session.self, forPrimaryKey: sessionId) else { os_log("Failed to find session with identifier: %{public}@ for synced object", log: self.log, type: .error, sessionId) return } session.addChild(object: model) } catch { os_log("Failed to decode sync object from cloud record: %{public}@", log: self.log, type: .error, String(describing: error)) } } // MARK: - Realm to CloudKit private var realmNotificationTokens: [NotificationToken] = [] private func observeLocalChanges() { openBackgroundRealm { self.registerRealmObserver(for: Favorite.self) self.registerRealmObserver(for: Bookmark.self) self.registerRealmObserver(for: SessionProgress.self) } } private let databaseQueue = DispatchQueue(label: "Database", qos: .background) private var backgroundRealm: Realm? private func openBackgroundRealm(completion: @escaping () -> Void) { Realm.asyncOpen(configuration: storage.realm.configuration, callbackQueue: databaseQueue) { result in switch result { case .failure(let error): os_log("Failed to open background Realm for sync operations: %{public}@", log: self.log, type: .fault, String(describing: error)) case .success(let realm): self.backgroundRealm = realm DispatchQueue.main.async { completion() } } } } private func registerRealmObserver<T: SynchronizableObject>(for objectType: T.Type) { databaseQueue.async { do { try self.onQueueRegisterRealmObserver(for: objectType) } catch { os_log("Failed to register notification: %{public}@", log: self.log, type: .error, String(describing: error)) } } } private func onQueueRegisterRealmObserver<T: SynchronizableObject>(for objectType: T.Type) throws { guard let realm = backgroundRealm else { return } let token = realm.objects(objectType).observe { [unowned self] change in switch change { case .error(let error): os_log("Realm observer error: %{public}@", log: self.log, type: .error, String(describing: error)) case .update(let objects, _, let inserted, let modified): let objectsToUpload = inserted.map { objects[$0] } + modified.map { objects[$0] } self.upload(models: objectsToUpload) default: break } } realmNotificationTokens.append(token) } private func upload<T: SynchronizableObject>(models: [T]) { guard models.count > 0 else { return } os_log("Upload models. Count = %{public}d", log: log, type: .info, models.count) let syncObjects = models.compactMap { $0.syncObject } let records = syncObjects.compactMap { try? CloudKitRecordEncoder(zoneID: customZoneID).encode($0) } os_log("Produced %{public}d record(s) for %{public}d model(s)", log: log, type: .info, records.count, models.count) upload(records) } private func upload(_ records: [CKRecord]) { guard let firstRecord = records.first else { return } guard let objectType = realmModel(for: firstRecord.recordType) else { os_log("Refusing to upload record of unknown type: %{public}@", log: self.log, type: .error, firstRecord.recordType) return } if let lastSyncDate = recordTypesToLastSyncDates[firstRecord.recordType] { guard Date().timeIntervalSince(lastSyncDate) > objectType.syncThrottlingInterval else { return } } recordTypesToLastSyncDates[firstRecord.recordType] = Date() let operation = CKModifyRecordsOperation(recordsToSave: records, recordIDsToDelete: nil) operation.perRecordCompletionBlock = { [unowned self] record, error in // We're only interested in conflict errors here guard let error = error, error.isCloudKitConflict else { return } os_log("CloudKit conflict with record of type %{public}@", log: self.log, type: .error, record.recordType) guard let objectType = self.realmModel(for: record.recordType) else { os_log( "No object type registered for record type: %{public}@. This should never happen!", log: self.log, type: .fault, record.recordType ) return } guard let resolvedRecord = error.resolveConflict(with: objectType.resolveConflict) else { os_log( "Resolving conflict with record of type %{public}@ returned a nil record. Giving up.", log: self.log, type: .error, record.recordType ) return } os_log("Conflict resolved, will retry upload", log: self.log, type: .info) self.upload([resolvedRecord]) } operation.modifyRecordsCompletionBlock = { [unowned self] serverRecords, _, error in if let error = error { os_log("Failed to upload records: %{public}@", log: self.log, type: .error, String(describing: error)) error.retryCloudKitOperationIfPossible(self.log) { self.upload(records) } } else { os_log("Successfully uploaded %{public}d record(s)", log: self.log, type: .info, records.count) self.databaseQueue.async { guard let serverRecords = serverRecords else { return } self.updateDatabaseModelsSystemFieldsAfterUpload(with: serverRecords) } } } operation.savePolicy = .changedKeys operation.qualityOfService = .userInitiated operation.database = privateDatabase cloudOperationQueue.addOperation(operation) } private func updateDatabaseModelsSystemFieldsAfterUpload(with records: [CKRecord]) { performRealmOperations { [weak self] realm in guard let self = self else { return } records.forEach { record in guard let modelType = self.realmModel(for: record.recordType) else { os_log("There's no corresponding Realm model type for record type %{public}@", log: self.log, type: .error, record.recordType) return } guard var object = realm.object(ofType: modelType, forPrimaryKey: record.recordID.recordName) as? HasCloudKitFields else { os_log("Unable to find record type %{public}@ with primary key %{public}@ for update after sync upload", log: self.log, type: .error, record.recordType, record.recordID.recordName) return } object.ckFields = record.encodedSystemFields os_log("Updated ckFields in record of type %{public}@", log: self.log, type: .debug, record.recordType) } } } // MARK: Initial data upload private func uploadLocalDataNotUploadedYet() { os_log("%{public}@", log: log, type: .debug, #function) uploadLocalModelsNotUploadedYet(of: Favorite.self) uploadLocalModelsNotUploadedYet(of: Bookmark.self) uploadLocalModelsNotUploadedYet(of: SessionProgress.self) } private func uploadLocalModelsNotUploadedYet<T: SynchronizableObject>(of objectType: T.Type) { databaseQueue.async { guard let objects = self.backgroundRealm?.objects(objectType).toArray() else { return } self.upload(models: objects.filter({ $0.ckFields.count == 0 && !$0.isDeleted })) } } // MARK: - Deletion private func incinerateSoftDeletedObjects() { databaseQueue.async { self.onQueueIncinerateSoftDeletedObjects() } } private func onQueueIncinerateSoftDeletedObjects() { guard let realm = backgroundRealm else { return } let predicate = NSPredicate(format: "isDeleted == true") let deletedFavorites = realm.objects(Favorite.self).filter(predicate) let deletedBookmarks = realm.objects(Bookmark.self).filter(predicate) let deletedFavoriteObjIDs = deletedFavorites.toArray().map(\.identifier) let deletedBookmarkObjIDs = deletedBookmarks.toArray().map(\.identifier) os_log("Will incinerate %{public}d deleted object(s)", log: log, type: .info, deletedFavorites.count + deletedBookmarks.count) let favoriteIDs: [CKRecord.ID] = deletedFavorites.compactMap { $0.ckRecordID } let bookmarkIDs: [CKRecord.ID] = deletedBookmarks.compactMap { $0.ckRecordID } let recordsToIncinerate = favoriteIDs + bookmarkIDs let operation = CKModifyRecordsOperation(recordsToSave: nil, recordIDsToDelete: recordsToIncinerate) operation.modifyRecordsCompletionBlock = { [unowned self] _, _, error in if let error = error { os_log("Failed to incinerate records: %{public}@", log: self.log, type: .error, String(describing: error)) error.retryCloudKitOperationIfPossible(self.log, in: self.databaseQueue) { self.incinerateSoftDeletedObjects() } } else { os_log("Successfully incinerated %{public}d record(s)", log: self.log, type: .info, recordsToIncinerate.count) DispatchQueue.main.async { // Actually delete previously soft-deleted items from the database self.performRealmOperations { queueRealm in let favoriteObjs = deletedFavoriteObjIDs.compactMap { queueRealm.object(ofType: Favorite.self, forPrimaryKey: $0) } let bookmarkObjs = deletedBookmarkObjIDs.compactMap { queueRealm.object(ofType: Bookmark.self, forPrimaryKey: $0) } favoriteObjs.forEach(queueRealm.delete) bookmarkObjs.forEach(queueRealm.delete) } } } } operation.database = privateDatabase operation.qualityOfService = .userInitiated cloudOperationQueue.addOperation(operation) } } extension Error { var isCKTokenExpired: Bool { (self as? CKError)?.code == .changeTokenExpired } var isCKZoneDeleted: Bool { (self as? CKError)?.code == .userDeletedZone } }
bsd-2-clause
48bb1a09d33dd19d8d521b5fa55f0fe7
36.432398
167
0.599141
5.362141
false
false
false
false
eeschimosu/ios-charts
Charts/Classes/Renderers/ChartYAxisRenderer.swift
2
14259
// // ChartYAxisRenderer.swift // Charts // // Created by Daniel Cohen Gindi on 3/3/15. // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/ios-charts // import Foundation import CoreGraphics import UIKit public class ChartYAxisRenderer: ChartAxisRendererBase { internal var _yAxis: ChartYAxis! public init(viewPortHandler: ChartViewPortHandler, yAxis: ChartYAxis, transformer: ChartTransformer!) { super.init(viewPortHandler: viewPortHandler, transformer: transformer) _yAxis = yAxis } /// Computes the axis values. public func computeAxis(var #yMin: Double, var yMax: Double) { // calculate the starting and entry point of the y-labels (depending on // zoom / contentrect bounds) if (viewPortHandler.contentWidth > 10.0 && !viewPortHandler.isFullyZoomedOutY) { var p1 = transformer.getValueByTouchPoint(CGPoint(x: viewPortHandler.contentLeft, y: viewPortHandler.contentTop)) var p2 = transformer.getValueByTouchPoint(CGPoint(x: viewPortHandler.contentLeft, y: viewPortHandler.contentBottom)) if (!_yAxis.isInverted) { yMin = Double(p2.y) yMax = Double(p1.y) } else { yMin = Double(p1.y) yMax = Double(p2.y) } } computeAxisValues(min: yMin, max: yMax) } /// Sets up the y-axis labels. Computes the desired number of labels between /// the two given extremes. Unlike the papareXLabels() method, this method /// needs to be called upon every refresh of the view. internal func computeAxisValues(#min: Double, max: Double) { var yMin = min var yMax = max var labelCount = _yAxis.labelCount var range = abs(yMax - yMin) if (labelCount == 0 || range <= 0) { _yAxis.entries = [Double]() return } var rawInterval = range / Double(labelCount) var interval = ChartUtils.roundToNextSignificant(number: Double(rawInterval)) var intervalMagnitude = pow(10.0, round(log10(interval))) var intervalSigDigit = (interval / intervalMagnitude) if (intervalSigDigit > 5) { // Use one order of magnitude higher, to avoid intervals like 0.9 or 90 interval = floor(10.0 * intervalMagnitude) } // force label count if _yAxis.isForceLabelsEnabled { let step = Double(range) / Double(labelCount - 1) if _yAxis.entries.count < labelCount { // Ensure stops contains at least numStops elements. _yAxis.entries.removeAll(keepCapacity: true) } else { _yAxis.entries = [Double]() _yAxis.entries.reserveCapacity(labelCount) } var v = yMin for (var i = 0; i < labelCount; i++) { _yAxis.entries.append(v) v += step } } else { // no forced count // if the labels should only show min and max if (_yAxis.isShowOnlyMinMaxEnabled) { _yAxis.entries = [yMin, yMax] } else { var first = ceil(Double(yMin) / interval) * interval var last = ChartUtils.nextUp(floor(Double(yMax) / interval) * interval) var f: Double var i: Int var n = 0 for (f = first; f <= last; f += interval) { ++n } if (_yAxis.entries.count < n) { // Ensure stops contains at least numStops elements. _yAxis.entries = [Double](count: n, repeatedValue: 0.0) } else if (_yAxis.entries.count > n) { _yAxis.entries.removeRange(n..<_yAxis.entries.count) } for (f = first, i = 0; i < n; f += interval, ++i) { _yAxis.entries[i] = Double(f) } } } } /// draws the y-axis labels to the screen public override func renderAxisLabels(#context: CGContext) { if (!_yAxis.isEnabled || !_yAxis.isDrawLabelsEnabled) { return } var xoffset = _yAxis.xOffset var yoffset = _yAxis.labelFont.lineHeight / 2.5 + _yAxis.yOffset var dependency = _yAxis.axisDependency var labelPosition = _yAxis.labelPosition var xPos = CGFloat(0.0) var textAlign: NSTextAlignment if (dependency == .Left) { if (labelPosition == .OutsideChart) { textAlign = .Right xPos = viewPortHandler.offsetLeft - xoffset } else { textAlign = .Left xPos = viewPortHandler.offsetLeft + xoffset } } else { if (labelPosition == .OutsideChart) { textAlign = .Left xPos = viewPortHandler.contentRight + xoffset } else { textAlign = .Right xPos = viewPortHandler.contentRight - xoffset } } drawYLabels(context: context, fixedPosition: xPos, offset: yoffset - _yAxis.labelFont.lineHeight, textAlign: textAlign) } private var _axisLineSegmentsBuffer = [CGPoint](count: 2, repeatedValue: CGPoint()) public override func renderAxisLine(#context: CGContext) { if (!_yAxis.isEnabled || !_yAxis.drawAxisLineEnabled) { return } CGContextSaveGState(context) CGContextSetStrokeColorWithColor(context, _yAxis.axisLineColor.CGColor) CGContextSetLineWidth(context, _yAxis.axisLineWidth) if (_yAxis.axisLineDashLengths != nil) { CGContextSetLineDash(context, _yAxis.axisLineDashPhase, _yAxis.axisLineDashLengths, _yAxis.axisLineDashLengths.count) } else { CGContextSetLineDash(context, 0.0, nil, 0) } if (_yAxis.axisDependency == .Left) { _axisLineSegmentsBuffer[0].x = viewPortHandler.contentLeft _axisLineSegmentsBuffer[0].y = viewPortHandler.contentTop _axisLineSegmentsBuffer[1].x = viewPortHandler.contentLeft _axisLineSegmentsBuffer[1].y = viewPortHandler.contentBottom CGContextStrokeLineSegments(context, _axisLineSegmentsBuffer, 2) } else { _axisLineSegmentsBuffer[0].x = viewPortHandler.contentRight _axisLineSegmentsBuffer[0].y = viewPortHandler.contentTop _axisLineSegmentsBuffer[1].x = viewPortHandler.contentRight _axisLineSegmentsBuffer[1].y = viewPortHandler.contentBottom CGContextStrokeLineSegments(context, _axisLineSegmentsBuffer, 2) } CGContextRestoreGState(context) } /// draws the y-labels on the specified x-position internal func drawYLabels(#context: CGContext, fixedPosition: CGFloat, offset: CGFloat, textAlign: NSTextAlignment) { var labelFont = _yAxis.labelFont var labelTextColor = _yAxis.labelTextColor var valueToPixelMatrix = transformer.valueToPixelMatrix var pt = CGPoint() for (var i = 0; i < _yAxis.entryCount; i++) { var text = _yAxis.getFormattedLabel(i) if (!_yAxis.isDrawTopYLabelEntryEnabled && i >= _yAxis.entryCount - 1) { break } pt.x = 0 pt.y = CGFloat(_yAxis.entries[i]) pt = CGPointApplyAffineTransform(pt, valueToPixelMatrix) pt.x = fixedPosition pt.y += offset ChartUtils.drawText(context: context, text: text, point: pt, align: textAlign, attributes: [NSFontAttributeName: labelFont, NSForegroundColorAttributeName: labelTextColor]) } } private var _gridLineBuffer = [CGPoint](count: 2, repeatedValue: CGPoint()) public override func renderGridLines(#context: CGContext) { if (!_yAxis.isDrawGridLinesEnabled || !_yAxis.isEnabled) { return } CGContextSaveGState(context) CGContextSetStrokeColorWithColor(context, _yAxis.gridColor.CGColor) CGContextSetLineWidth(context, _yAxis.gridLineWidth) if (_yAxis.gridLineDashLengths != nil) { CGContextSetLineDash(context, _yAxis.gridLineDashPhase, _yAxis.gridLineDashLengths, _yAxis.gridLineDashLengths.count) } else { CGContextSetLineDash(context, 0.0, nil, 0) } var valueToPixelMatrix = transformer.valueToPixelMatrix var position = CGPoint(x: 0.0, y: 0.0) // draw the horizontal grid for (var i = 0, count = _yAxis.entryCount; i < count; i++) { position.x = 0.0 position.y = CGFloat(_yAxis.entries[i]) position = CGPointApplyAffineTransform(position, valueToPixelMatrix) _gridLineBuffer[0].x = viewPortHandler.contentLeft _gridLineBuffer[0].y = position.y _gridLineBuffer[1].x = viewPortHandler.contentRight _gridLineBuffer[1].y = position.y CGContextStrokeLineSegments(context, _gridLineBuffer, 2) } CGContextRestoreGState(context) } private var _limitLineSegmentsBuffer = [CGPoint](count: 2, repeatedValue: CGPoint()) public override func renderLimitLines(#context: CGContext) { var limitLines = _yAxis.limitLines if (limitLines.count == 0) { return } CGContextSaveGState(context) var trans = transformer.valueToPixelMatrix var position = CGPoint(x: 0.0, y: 0.0) for (var i = 0; i < limitLines.count; i++) { var l = limitLines[i] position.x = 0.0 position.y = CGFloat(l.limit) position = CGPointApplyAffineTransform(position, trans) _limitLineSegmentsBuffer[0].x = viewPortHandler.contentLeft _limitLineSegmentsBuffer[0].y = position.y _limitLineSegmentsBuffer[1].x = viewPortHandler.contentRight _limitLineSegmentsBuffer[1].y = position.y CGContextSetStrokeColorWithColor(context, l.lineColor.CGColor) CGContextSetLineWidth(context, l.lineWidth) if (l.lineDashLengths != nil) { CGContextSetLineDash(context, l.lineDashPhase, l.lineDashLengths!, l.lineDashLengths!.count) } else { CGContextSetLineDash(context, 0.0, nil, 0) } CGContextStrokeLineSegments(context, _limitLineSegmentsBuffer, 2) var label = l.label // if drawing the limit-value label is enabled if (count(label) > 0) { var labelLineHeight = l.valueFont.lineHeight let add = CGFloat(4.0) var xOffset: CGFloat = add var yOffset: CGFloat = l.lineWidth + labelLineHeight if (l.labelPosition == .RightTop) { ChartUtils.drawText(context: context, text: label, point: CGPoint( x: viewPortHandler.contentRight - xOffset, y: position.y - yOffset), align: .Right, attributes: [NSFontAttributeName: l.valueFont, NSForegroundColorAttributeName: l.valueTextColor]) } else if (l.labelPosition == .RightBottom) { ChartUtils.drawText(context: context, text: label, point: CGPoint( x: viewPortHandler.contentRight - xOffset, y: position.y + yOffset - labelLineHeight), align: .Right, attributes: [NSFontAttributeName: l.valueFont, NSForegroundColorAttributeName: l.valueTextColor]) } else if (l.labelPosition == .LeftTop) { ChartUtils.drawText(context: context, text: label, point: CGPoint( x: viewPortHandler.contentLeft + xOffset, y: position.y - yOffset), align: .Left, attributes: [NSFontAttributeName: l.valueFont, NSForegroundColorAttributeName: l.valueTextColor]) } else { ChartUtils.drawText(context: context, text: label, point: CGPoint( x: viewPortHandler.contentLeft + xOffset, y: position.y + yOffset - labelLineHeight), align: .Left, attributes: [NSFontAttributeName: l.valueFont, NSForegroundColorAttributeName: l.valueTextColor]) } } } CGContextRestoreGState(context) } }
apache-2.0
e9657151df22b47ac9aa872e1c872a6f
34.036855
184
0.527456
5.685407
false
false
false
false
alskipp/Monoid
Monoid/Monoids/MaxMonoid.swift
1
884
// Copyright © 2016 Al Skipp. All rights reserved. public struct Max<Element: Comparable> { public let value: Element? public init(_ v: Element?) { value = v } } extension Max: Monoid { public static var mempty: Max { return Max(.none) } public static func combine(_ a: Max, _ b: Max) -> Max { return max(a, b) } } extension Max: CustomStringConvertible { public var description: String { return "Max(\(value))" } } extension Max: Equatable, Comparable, Orderable { public static func == <T: Equatable>(x: Max<T>, y: Max<T>) -> Bool { return x.value == y.value } public static func < <T: Comparable>(x: Max<T>, y: Max<T>) -> Bool { switch (x.value, y.value) { case (.none, .none): return false case (.none, .some): return true case (.some, .none): return false case let (.some(a), .some(b)): return a < b } } }
mit
4b8630255d9f3c98da4b8b81f63eead9
22.236842
70
0.610419
3.344697
false
false
false
false
halo/LinkLiar
LinkTools/Configuration/Prefixes.swift
1
3730
/* * Copyright (C) 2012-2021 halo https://io.github.com/halo/LinkLiar * * 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. */ extension Configuration { struct Prefixes { // MARK: Public Instance Properties var dictionary: [String: Any] // MARK: Initialization init(dictionary: [String: Any]) { self.dictionary = dictionary } // MARK: Public Instance Methods /** * Looks up which vendors are specified. * If there are absolutely no prefixes defined (neither vendors nor custom) * then the fallback Vendor (Apple) is returned. * * Because we need always some prefix to use for randomization. * Also, this makes upgrading LinkLiar simpler (i.e. no vendors and no prefixes * defined in settings file means use some default and persist that as new setting) * * - returns: An Array of valid `Vendor`s or an empty Array if there are none. */ var vendors: [Vendor] { guard let vendorIDs = dictionary["vendors"] as? [String] else { return defaultVendors } let vendors = Set(vendorIDs).compactMap { string -> Vendor? in return Vendors.find(string) } // If there are vendors defined directly, return them. guard vendors.isEmpty else { return Array(vendors).sorted() } Log.debug("Currently no vendors active") // We always need *some* prefix. If there are custom prefixes, // we can rely on them and don't need to fall back here to anything. guard prefixes.isEmpty else { return [] } return defaultVendors } private var defaultVendors: [Vendor] { // We assume that this vendor is always defined. It's a sensible default. return [Vendors.find("apple")!] } /** * Looks up which custom prefixes are specified. * * - returns: An Array of valid `MACPrefix`es or an empty Array if there are none. */ var prefixes: [MACPrefix] { guard let rawPrefixes = dictionary["prefixes"] as? [String] else { return [] } let prefixes = rawPrefixes.compactMap { string -> MACPrefix? in let prefix = MACPrefix(string) return prefix.isValid ? prefix : nil } if (prefixes.isEmpty) { Log.debug("Currently no prefixes active")} return prefixes } /** * Gathers all default prefixes that can be used for randomization. * * - parameter hardMAC: The hardware MAC address of an Interface. * * - returns: An Array of valid `MacPrefix`es that is never empty. */ var calculatedPrefixes: [MACPrefix] { let customPrefixes = prefixes let vendorPrefixes = vendors.flatMap { $0.prefixes } return customPrefixes + vendorPrefixes } } }
mit
2f12bf2c8044c8bc2c014e98dba924a7
36.676768
133
0.685523
4.499397
false
false
false
false
rossharper/raspberrysauce-ios
raspberrysauce-ios/Settings/SettingsView.swift
1
2614
// // SettingsView.swift // raspberrysauce-ios // // Created by Ross Harper on 20/03/2021. // Copyright © 2021 rossharper.net. All rights reserved. // import SwiftUI import Combine struct SettingsView: View { @ObservedObject private var viewModel: SettingsViewModel init(_ settingsViewModel: SettingsViewModel) { self.viewModel = settingsViewModel } var body: some View { createView() .onAppear() { viewModel.load() } } func createView() -> some View { let viewState = viewModel.viewState switch viewState { case .Loading: return AnyView(LoadingView()) case .Error: return AnyView(ErrorView(retry: { viewModel.load() })) case let .Loaded(data): return AnyView(VStack() { TemperatureValueStepper( value: data.defaultComfortTemperature, onChanged: { temperature in viewModel.onDefaultComfortTemperatureChanged( temperature) } ) Divider() Toggle(isOn: .init(get: { data.isNewHomeEnabled }, set: { viewModel.enableNewHome($0)} )) { Text("New Home").label() } .padding() Spacer() Button("Sign Out"){ viewModel.signOut() } }.padding()) } } } fileprivate class FakeRepo : SettingsRepository { func loadSettings() -> AnyPublisher<SettingsViewData, SettingsError> { return Just(SettingsViewData(defaultComfortTemperature: Temperature(value: 20.0), isNewHomeEnabled: false)) .setFailureType(to: SettingsError.self) .eraseToAnyPublisher() } func updateDefaultComfortTemperature(_ temperature: Temperature) -> AnyPublisher<Temperature, SettingsError> { return Empty().setFailureType(to: SettingsError.self).eraseToAnyPublisher() } func updateIsNewHomeEnabled(_ enabled: Bool) { } } struct SettingsView_Previews: PreviewProvider { static var previews: some View { let viewModel = SettingsViewModel(settingsRepository: FakeRepo()) viewModel.viewState = SettingsViewModel.ViewState.Loaded(SettingsViewData(defaultComfortTemperature: Temperature(value: 20.0), isNewHomeEnabled: false)) let settingsView = SettingsView(viewModel) return settingsView.accentColor(.raspberry) } }
apache-2.0
0e456892fa16549e068d7d96b9bd272a
31.6625
160
0.587065
5.343558
false
false
false
false
natecook1000/swift
test/IRGen/objc_subclass.swift
2
20078
// RUN: %empty-directory(%t) // RUN: %build-irgen-test-overlays // RUN: %target-swift-frontend(mock-sdk: -sdk %S/Inputs -I %t) -primary-file %s -emit-ir | %FileCheck --check-prefix=CHECK --check-prefix=CHECK-%target-ptrsize %s // REQUIRES: objc_interop // CHECK: [[SGIZMO:T13objc_subclass10SwiftGizmoC]] = type // CHECK: [[OBJC_CLASS:%objc_class]] = type // CHECK: [[OPAQUE:%swift.opaque]] = type // CHECK: [[INT:%TSi]] = type <{ [[LLVM_PTRSIZE_INT:i(32|64)]] }> // CHECK: [[TYPE:%swift.type]] = type // CHECK-DAG: [[GIZMO:%TSo5GizmoC]] = type opaque // CHECK-DAG: [[OBJC:%objc_object]] = type opaque // CHECK-32: @"$S13objc_subclass10SwiftGizmoC1xSivpWvd" = hidden global i32 4, align [[WORD_SIZE_IN_BYTES:4]] // CHECK-64: @"$S13objc_subclass10SwiftGizmoC1xSivpWvd" = hidden global i64 8, align [[WORD_SIZE_IN_BYTES:8]] // CHECK: @"OBJC_METACLASS_$__TtC13objc_subclass10SwiftGizmo" = hidden global [[OBJC_CLASS]] { [[OBJC_CLASS]]* @"OBJC_METACLASS_$_NSObject", [[OBJC_CLASS]]* @"OBJC_METACLASS_$_Gizmo", [[OPAQUE]]* @_objc_empty_cache, [[OPAQUE]]* null, [[LLVM_PTRSIZE_INT]] ptrtoint ({{.*}} @_METACLASS_DATA__TtC13objc_subclass10SwiftGizmo to [[LLVM_PTRSIZE_INT]]) } // CHECK: [[STRING_SWIFTGIZMO:@.*]] = private unnamed_addr constant [32 x i8] c"_TtC13objc_subclass10SwiftGizmo\00" // CHECK-32: @_METACLASS_DATA__TtC13objc_subclass10SwiftGizmo = private constant { {{.*}}* } { // CHECK-32: i32 129, // CHECK-32: i32 20, // CHECK-32: i32 20, // CHECK-32: i8* null, // CHECK-32: i8* getelementptr inbounds ([{{[0-9]+}} x i8], [{{[0-9]+}} x i8]* [[STRING_SWIFTGIZMO]], i32 0, i32 0), // CHECK-32: i8* null, // CHECK-32: i8* null, // CHECK-32: i8* null, // CHECK-32: i8* null, // CHECK-32: i8* null // CHECK-32: }, section "__DATA, __objc_const", align 4 // CHECK-64: @_METACLASS_DATA__TtC13objc_subclass10SwiftGizmo = private constant { {{.*}}* } { // CHECK-64: i32 129, // CHECK-64: i32 40, // CHECK-64: i32 40, // CHECK-64: i32 0, // CHECK-64: i8* null, // CHECK-64: i8* getelementptr inbounds ([{{[0-9]+}} x i8], [{{[0-9]+}} x i8]* [[STRING_SWIFTGIZMO]], i64 0, i64 0), // CHECK-64: i8* null, // CHECK-64: i8* null, // CHECK-64: i8* null, // CHECK-64: i8* null, // CHECK-64: i8* null // CHECK-64: }, section "__DATA, __objc_const", align 8 // CHECK-32: [[METHOD_TYPE_ENCODING1:@.*]] = private unnamed_addr constant [7 x i8] c"l8@0:4\00" // CHECK-64: [[METHOD_TYPE_ENCODING1:@.*]] = private unnamed_addr constant [8 x i8] c"q16@0:8\00" // CHECK-32: [[METHOD_TYPE_ENCODING2:@.*]] = private unnamed_addr constant [10 x i8] c"v12@0:4l8\00" // CHECK-64: [[METHOD_TYPE_ENCODING2:@.*]] = private unnamed_addr constant [11 x i8] c"v24@0:8q16\00" // CHECK-32: [[GETTER_ENCODING:@.*]] = private unnamed_addr constant [7 x i8] c"@8@0:4\00" // CHECK-64: [[GETTER_ENCODING:@.*]] = private unnamed_addr constant [8 x i8] c"@16@0:8\00" // CHECK-32: [[INIT_ENCODING:@.*]] = private unnamed_addr constant [13 x i8] c"@16@0:4l8@12\00" // CHECK-64: [[INIT_ENCODING:@.*]] = private unnamed_addr constant [14 x i8] c"@32@0:8q16@24\00" // CHECK-32: [[DEALLOC_ENCODING:@.*]] = private unnamed_addr constant [7 x i8] c"v8@0:4\00" // CHECK-64: [[DEALLOC_ENCODING:@.*]] = private unnamed_addr constant [8 x i8] c"v16@0:8\00" // CHECK-32: @_INSTANCE_METHODS__TtC13objc_subclass10SwiftGizmo = private constant { {{.*}}] } { // CHECK-32: i32 12, // CHECK-32: i32 11, // CHECK-32: [11 x { i8*, i8*, i8* }] [{ i8*, i8*, i8* } { // CHECK-32: i8* getelementptr inbounds ([2 x i8], [2 x i8]* @"\01L_selector_data(x)", i32 0, i32 0), // CHECK-32: i8* getelementptr inbounds ([7 x i8], [7 x i8]* [[METHOD_TYPE_ENCODING1]], i32 0, i32 0), // CHECK-32: i8* bitcast (i32 (%0*, i8*)* @"$S13objc_subclass10SwiftGizmoC1xSivgTo" to i8*) // CHECK-32: }, { i8*, i8*, i8* } { // CHECK-32: i8* getelementptr inbounds ([6 x i8], [6 x i8]* @"\01L_selector_data(setX:)", i32 0, i32 0), // CHECK-32: i8* getelementptr inbounds ([10 x i8], [10 x i8]* [[METHOD_TYPE_ENCODING2]], i32 0, i32 0), // CHECK-32: i8* bitcast (void (%0*, i8*, i32)* @"$S13objc_subclass10SwiftGizmoC1xSivsTo" to i8*) // CHECK-32: }, { i8*, i8*, i8* } { // CHECK-32: i8* getelementptr inbounds ([5 x i8], [5 x i8]* @"\01L_selector_data(getX)", i32 0, i32 0), // CHECK-32: i8* getelementptr inbounds ([7 x i8], [7 x i8]* [[METHOD_TYPE_ENCODING1]], i32 0, i32 0), // CHECK-32: i8* bitcast (i32 (%0*, i8*)* @"$S13objc_subclass10SwiftGizmoC4getXSiyFTo" to i8*) // CHECK-32: }, { i8*, i8*, i8* } { // CHECK-32: i8* getelementptr inbounds ([10 x i8], [10 x i8]* @"\01L_selector_data(duplicate)", i32 0, i32 0), // CHECK-32: i8* getelementptr inbounds ([7 x i8], [7 x i8]* [[GETTER_ENCODING]], i32 0, i32 0), // CHECK-32: i8* bitcast (%1* (%0*, i8*)* @"$S13objc_subclass10SwiftGizmoC9duplicateSo0D0CyFTo" to i8*) // CHECK-32: }, { i8*, i8*, i8* } { // CHECK-32: i8* getelementptr inbounds ([5 x i8], [5 x i8]* @"\01L_selector_data(init)", i32 0, i32 0), // CHECK-32: i8* getelementptr inbounds ([7 x i8], [7 x i8]* [[GETTER_ENCODING]], i32 0, i32 0), // CHECK-32: i8* bitcast (%0* (%0*, i8*)* @"$S13objc_subclass10SwiftGizmoCACycfcTo" to i8*) // CHECK-32: }, { i8*, i8*, i8* } { // CHECK-32: i8* getelementptr inbounds ([20 x i8], [20 x i8]* @"\01L_selector_data(initWithInt:string:)", i32 0, i32 0), // CHECK-32: i8* getelementptr inbounds ([13 x i8], [13 x i8]* [[INIT_ENCODING]], i32 0, i32 0), // CHECK-32: i8* bitcast (%0* (%0*, i8*, i32, %2*)* @"$S13objc_subclass10SwiftGizmoC3int6stringACSi_SStcfcTo" to i8*) // CHECK-32: }, { i8*, i8*, i8* } { // CHECK-32: i8* getelementptr inbounds ([8 x i8], [8 x i8]* @"\01L_selector_data(dealloc)", i32 0, i32 0), // CHECK-32: i8* getelementptr inbounds ([7 x i8], [7 x i8]* [[DEALLOC_ENCODING]], i32 0, i32 0), // CHECK-32: i8* bitcast (void (%0*, i8*)* @"$S13objc_subclass10SwiftGizmoCfDTo" to i8*) // CHECK-32: }, { i8*, i8*, i8* } { // CHECK-32: i8* getelementptr inbounds ([10 x i8], [10 x i8]* @"\01L_selector_data(isEnabled)", i32 0, i32 0), // CHECK-32: i8* getelementptr inbounds ([7 x i8], [7 x i8]* {{@[0-9]+}}, i32 0, i32 0), // CHECK-32: i8* bitcast ({{(i8|i1)}} (%0*, i8*)* @"$S13objc_subclass10SwiftGizmoC7enabledSbvgTo" to i8*) // CHECK-32: }, { i8*, i8*, i8* } { // CHECK-32: i8* getelementptr inbounds ([14 x i8], [14 x i8]* @"\01L_selector_data(setIsEnabled:)", i32 0, i32 0), // CHECK-32: i8* getelementptr inbounds ([10 x i8], [10 x i8]* {{@[0-9]+}}, i32 0, i32 0), // CHECK-32: i8* bitcast (void (%0*, i8*, {{(i8|i1)}})* @"$S13objc_subclass10SwiftGizmoC7enabledSbvsTo" to i8*) // CHECK-32: }, { i8*, i8*, i8* } { // CHECK-32: i8* getelementptr inbounds ([17 x i8], [17 x i8]* @"\01L_selector_data(initWithBellsOn:)", i32 0, i32 0), // CHECK-32: i8* getelementptr inbounds ([10 x i8], [10 x i8]* {{@[0-9]+}}, i32 0, i32 0), // CHECK-32: i8* bitcast (%0* (%0*, i8*, i32)* @"$S13objc_subclass10SwiftGizmoC7bellsOnACSgSi_tcfcTo" to i8*) // CHECK-32: }, { i8*, i8*, i8* } { // CHECK-32: i8* getelementptr inbounds ([15 x i8], [15 x i8]* @"\01L_selector_data(.cxx_construct)", i32 0, i32 0), // CHECK-32: i8* getelementptr inbounds ([{{[0-9]+}} x i8], [{{[0-9]+}} x i8]* {{@[0-9]+}}, i32 0, i32 0), // CHECK-32: i8* bitcast (%0* (%0*, i8*)* @"$S13objc_subclass10SwiftGizmoCfeTo" to i8*) // CHECK-32: }] // CHECK-32: }, section "__DATA, __objc_const", align 4 // CHECK-64: @_INSTANCE_METHODS__TtC13objc_subclass10SwiftGizmo = private constant { {{.*}}] } { // CHECK-64: i32 24, // CHECK-64: i32 11, // CHECK-64: [11 x { i8*, i8*, i8* }] [{ // CHECK-64: i8* getelementptr inbounds ([2 x i8], [2 x i8]* @"\01L_selector_data(x)", i64 0, i64 0), // CHECK-64: i8* getelementptr inbounds ([8 x i8], [8 x i8]* [[METHOD_TYPE_ENCODING1]], i64 0, i64 0) // CHECK-64: i8* bitcast (i64 ([[OPAQUE2:%.*]]*, i8*)* @"$S13objc_subclass10SwiftGizmoC1xSivgTo" to i8*) // CHECK-64: }, { // CHECK-64: i8* getelementptr inbounds ([6 x i8], [6 x i8]* @"\01L_selector_data(setX:)", i64 0, i64 0), // CHECK-64: i8* getelementptr inbounds ([11 x i8], [11 x i8]* [[METHOD_TYPE_ENCODING2]], i64 0, i64 0) // CHECK-64: i8* bitcast (void ([[OPAQUE3:%.*]]*, i8*, i64)* @"$S13objc_subclass10SwiftGizmoC1xSivsTo" to i8*) // CHECK-64: }, { // CHECK-64: i8* getelementptr inbounds ([5 x i8], [5 x i8]* @"\01L_selector_data(getX)", i64 0, i64 0), // CHECK-64: i8* getelementptr inbounds ([8 x i8], [8 x i8]* [[METHOD_TYPE_ENCODING1]], i64 0, i64 0) // CHECK-64: i8* bitcast (i64 ([[OPAQUE2]]*, i8*)* @"$S13objc_subclass10SwiftGizmoC4getXSiyFTo" to i8*) // CHECK-64: }, { // CHECK-64: i8* getelementptr inbounds ([10 x i8], [10 x i8]* @"\01L_selector_data(duplicate)", i64 0, i64 0), // CHECK-64: i8* getelementptr inbounds ([8 x i8], [8 x i8]* [[GETTER_ENCODING]], i64 0, i64 0), // CHECK-64: i8* bitcast ([[OPAQUE1:.*]]* ([[OPAQUE0:%.*]]*, i8*)* @"$S13objc_subclass10SwiftGizmoC9duplicateSo0D0CyFTo" to i8*) // CHECK-64: }, { // CHECK-64: i8* getelementptr inbounds ([5 x i8], [5 x i8]* @"\01L_selector_data(init)", i64 0, i64 0), // CHECK-64: i8* getelementptr inbounds ([8 x i8], [8 x i8]* [[GETTER_ENCODING]], i64 0, i64 0), // CHECK-64: i8* bitcast ([[OPAQUE5:.*]]* ([[OPAQUE6:.*]]*, i8*)* @"$S13objc_subclass10SwiftGizmoCACycfcTo" to i8*) // CHECK-64: }, { // CHECK-64: i8* getelementptr inbounds ([20 x i8], [20 x i8]* @"\01L_selector_data(initWithInt:string:)", i64 0, i64 0), // CHECK-64: i8* getelementptr inbounds ([14 x i8], [14 x i8]* [[INIT_ENCODING]], i64 0, i64 0), // CHECK-64: i8* bitcast ([[OPAQUE7:%.*]]* ([[OPAQUE8:%.*]]*, i8*, i64, [[OPAQUEONE:.*]]*)* @"$S13objc_subclass10SwiftGizmoC3int6stringACSi_SStcfcTo" to i8*) // CHECK-64: }, { // CHECK-64: i8* getelementptr inbounds ([8 x i8], [8 x i8]* @"\01L_selector_data(dealloc)", i64 0, i64 0), // CHECK-64: i8* getelementptr inbounds ([8 x i8], [8 x i8]* [[DEALLOC_ENCODING]], i64 0, i64 0), // CHECK-64: i8* bitcast (void ([[OPAQUE10:%.*]]*, i8*)* @"$S13objc_subclass10SwiftGizmoCfDTo" to i8*) // CHECK-64: }, { // CHECK-64: i8* getelementptr inbounds ([10 x i8], [10 x i8]* @"\01L_selector_data(isEnabled)", i64 0, i64 0), // CHECK-64: i8* getelementptr inbounds ([8 x i8], [8 x i8]* {{@[0-9]+}}, i64 0, i64 0), // CHECK-64: i8* bitcast ({{(i8|i1)}} ([[OPAQUE11:%.*]]*, i8*)* @"$S13objc_subclass10SwiftGizmoC7enabledSbvgTo" to i8*) // CHECK-64: }, { // CHECK-64: i8* getelementptr inbounds ([14 x i8], [14 x i8]* @"\01L_selector_data(setIsEnabled:)", i64 0, i64 0), // CHECK-64: i8* getelementptr inbounds ([11 x i8], [11 x i8]* {{@[0-9]+}}, i64 0, i64 0), // CHECK-64: i8* bitcast (void ([[OPAQUE12:%.*]]*, i8*, {{(i8|i1)}})* @"$S13objc_subclass10SwiftGizmoC7enabledSbvsTo" to i8*) // CHECK-64: }, { // CHECK-64: i8* getelementptr inbounds ([17 x i8], [17 x i8]* @"\01L_selector_data(initWithBellsOn:)", i64 0, i64 0), // CHECK-64: i8* getelementptr inbounds ([11 x i8], [11 x i8]* {{@[0-9]+}}, i64 0, i64 0), // CHECK-64: i8* bitcast ([[OPAQUE11:%.*]]* ([[OPAQUE12:%.*]]*, i8*, i64)* @"$S13objc_subclass10SwiftGizmoC7bellsOnACSgSi_tcfcTo" to i8*) // CHECK-64: }, { // CHECK-64: i8* getelementptr inbounds ([15 x i8], [15 x i8]* @"\01L_selector_data(.cxx_construct)", i64 0, i64 0), // CHECK-64: i8* getelementptr inbounds ([{{[0-9]+}} x i8], [{{[0-9]+}} x i8]* {{@[0-9]+}}, i64 0, i64 0), // CHECK-64: i8* bitcast ([[OPAQUE5]]* ([[OPAQUE6]]*, i8*)* @"$S13objc_subclass10SwiftGizmoCfeTo" to i8*) // CHECK-64: }] // CHECK-64: }, section "__DATA, __objc_const", align 8 // CHECK: [[STRING_X:@.*]] = private unnamed_addr constant [2 x i8] c"x\00" // CHECK: [[STRING_EMPTY:@.*]] = private unnamed_addr constant [1 x i8] zeroinitializer // CHECK-32: @_IVARS__TtC13objc_subclass10SwiftGizmo = private constant { {{.*}}] } { // CHECK-32: i32 20, // CHECK-32: i32 1, // CHECK-32: [1 x { i32*, i8*, i8*, i32, i32 }] [{ i32*, i8*, i8*, i32, i32 } { // CHECK-32: i32* @"$S13objc_subclass10SwiftGizmoC1xSivpWvd", // CHECK-32: i8* getelementptr inbounds ([2 x i8], [2 x i8]* [[STRING_X]], i32 0, i32 0), // CHECK-32: i8* getelementptr inbounds ([1 x i8], [1 x i8]* [[STRING_EMPTY]], i32 0, i32 0), // CHECK-32: i32 2, // CHECK-32: i32 4 }] // CHECK-32: }, section "__DATA, __objc_const", align 4 // CHECK-64: @_IVARS__TtC13objc_subclass10SwiftGizmo = private constant { {{.*}}] } { // CHECK-64: i32 32, // CHECK-64: i32 1, // CHECK-64: [1 x { i64*, i8*, i8*, i32, i32 }] [{ i64*, i8*, i8*, i32, i32 } { // CHECK-64: i64* @"$S13objc_subclass10SwiftGizmoC1xSivpWvd", // CHECK-64: i8* getelementptr inbounds ([2 x i8], [2 x i8]* [[STRING_X]], i64 0, i64 0), // CHECK-64: i8* getelementptr inbounds ([1 x i8], [1 x i8]* [[STRING_EMPTY]], i64 0, i64 0), // CHECK-64: i32 3, // CHECK-64: i32 8 }] // CHECK-64: }, section "__DATA, __objc_const", align 8 // CHECK-32: @_DATA__TtC13objc_subclass10SwiftGizmo = private constant { {{.*}}* } { // CHECK-32: i32 132, // CHECK-32: i32 4, // CHECK-32: i32 8, // CHECK-32: i8* null, // CHECK-32: i8* getelementptr inbounds ([{{[0-9]+}} x i8], [{{[0-9]+}} x i8]* [[STRING_SWIFTGIZMO]], i32 0, i32 0), // CHECK-32: @_INSTANCE_METHODS__TtC13objc_subclass10SwiftGizmo, // CHECK-32: i8* null, // CHECK-32: @_IVARS__TtC13objc_subclass10SwiftGizmo, // CHECK-32: i8* null, // CHECK-32: @_PROPERTIES__TtC13objc_subclass10SwiftGizmo // CHECK-32: }, section "__DATA, __objc_const", align 4 // CHECK-64: @_DATA__TtC13objc_subclass10SwiftGizmo = private constant { {{.*}}* } { // CHECK-64: i32 132, // CHECK-64: i32 8, // CHECK-64: i32 16, // CHECK-64: i32 0, // CHECK-64: i8* null, // CHECK-64: i8* getelementptr inbounds ([{{[0-9]+}} x i8], [{{[0-9]+}} x i8]* [[STRING_SWIFTGIZMO]], i64 0, i64 0), // CHECK-64: @_INSTANCE_METHODS__TtC13objc_subclass10SwiftGizmo, // CHECK-64: i8* null, // CHECK-64: @_IVARS__TtC13objc_subclass10SwiftGizmo, // CHECK-64: i8* null, // CHECK-64: @_PROPERTIES__TtC13objc_subclass10SwiftGizmo // CHECK-64: }, section "__DATA, __objc_const", align 8 // CHECK-NOT: @_TMCSo13SwiftGizmo = {{.*NSObject}} // CHECK: @_INSTANCE_METHODS__TtC13objc_subclass12GenericGizmo // CHECK-32: [[SETTER_ENCODING:@.*]] = private unnamed_addr constant [10 x i8] c"v12@0:4@8\00" // CHECK-64: [[SETTER_ENCODING:@.*]] = private unnamed_addr constant [11 x i8] c"v24@0:8@16\00" // CHECK-32: @_INSTANCE_METHODS__TtC13objc_subclass11SwiftGizmo2 = private constant { i32, i32, [5 x { i8*, i8*, i8* }] } { // CHECK-32: i32 12, // CHECK-32: i32 5, // CHECK-32: [5 x { i8*, i8*, i8* }] [ // CHECK-32: { // CHECK-32: i8* getelementptr inbounds ([3 x i8], [3 x i8]* @"\01L_selector_data(sg)", i32 0, i32 0), // CHECK-32: i8* getelementptr inbounds ([7 x i8], [7 x i8]* [[GETTER_ENCODING]], i32 0, i32 0), // CHECK-32: i8* bitcast (%0* (%3*, i8*)* @"$S13objc_subclass11SwiftGizmo2C2sgAA0C5GizmoCvgTo" to i8*) // CHECK-32: }, { // CHECK-32: i8* getelementptr inbounds ([7 x i8], [7 x i8]* @"\01L_selector_data(setSg:)", i32 0, i32 0), // CHECK-32: i8* getelementptr inbounds ([10 x i8], [10 x i8]* [[SETTER_ENCODING]], i32 0, i32 0), // CHECK-32: i8* bitcast (void (%3*, i8*, %0*)* @"$S13objc_subclass11SwiftGizmo2C2sgAA0C5GizmoCvsTo" to i8*) // CHECK-32: }, { // CHECK-32: i8* getelementptr inbounds ([5 x i8], [5 x i8]* @"\01L_selector_data(init)", i32 0, i32 0), // CHECK-32: i8* getelementptr inbounds ([7 x i8], [7 x i8]* [[GETTER_ENCODING]], i32 0, i32 0), // CHECK-32: i8* bitcast (%3* (%3*, i8*)* @"$S13objc_subclass11SwiftGizmo2CACycfcTo" to i8*) // CHECK-32: }, { // CHECK-32: i8* getelementptr inbounds ([17 x i8], [17 x i8]* @"\01L_selector_data(initWithBellsOn:)", i32 0, i32 0), // CHECK-32: i8* getelementptr inbounds ([10 x i8], [10 x i8]* {{@[0-9]+}}, i32 0, i32 0), // CHECK-32: i8* bitcast (%3* (%3*, i8*, i32)* @"$S13objc_subclass11SwiftGizmo2C7bellsOnACSgSi_tcfcTo" to i8*) // CHECK-32: }, { // CHECK-32: i8* getelementptr inbounds ([14 x i8], [14 x i8]* @"\01L_selector_data(.cxx_destruct)", i32 0, i32 0), // CHECK-32: i8* getelementptr inbounds ([{{[0-9]+}} x i8], [{{[0-9]+}} x i8]* {{@[0-9]+}}, i32 0, i32 0), // CHECK-32: i8* bitcast (void (%3*, i8*)* @"$S13objc_subclass11SwiftGizmo2CfETo" to i8*) // CHECK-32: } // CHECK-32: ] // CHECK-32: }, section "__DATA, __objc_const", align 4 // CHECK-64: @_INSTANCE_METHODS__TtC13objc_subclass11SwiftGizmo2 = private constant { i32, {{.*}}] } { // CHECK-64: i32 24, // CHECK-64: i32 5, // CHECK-64: [5 x { i8*, i8*, i8* }] [ // CHECK-64: { // CHECK-64: i8* getelementptr inbounds ([3 x i8], [3 x i8]* @"\01L_selector_data(sg)", i64 0, i64 0), // CHECK-64: i8* getelementptr inbounds ([8 x i8], [8 x i8]* [[GETTER_ENCODING]], i64 0, i64 0), // CHECK-64: i8* bitcast ([[OPAQUE13:%.*]]* ([[OPAQUE14:%.*]]*, i8*)* @"$S13objc_subclass11SwiftGizmo2C2sgAA0C5GizmoCvgTo" to i8*) // CHECK-64: }, { // CHECK-64: i8* getelementptr inbounds ([7 x i8], [7 x i8]* @"\01L_selector_data(setSg:)", i64 0, i64 0), // CHECK-64: i8* getelementptr inbounds ([11 x i8], [11 x i8]* [[SETTER_ENCODING]], i64 0, i64 0), // CHECK-64: i8* bitcast (void ([[OPAQUE15:%.*]]*, i8*, [[OPAQUE16:%.*]]*)* @"$S13objc_subclass11SwiftGizmo2C2sgAA0C5GizmoCvsTo" to i8*) // CHECK-64: }, { // CHECK-64: i8* getelementptr inbounds ([5 x i8], [5 x i8]* @"\01L_selector_data(init)", i64 0, i64 0), // CHECK-64: i8* getelementptr inbounds ([8 x i8], [8 x i8]* [[GETTER_ENCODING]], i64 0, i64 0), // CHECK-64: i8* bitcast ([[OPAQUE18:%.*]]* ([[OPAQUE19:%.*]]*, i8*)* @"$S13objc_subclass11SwiftGizmo2CACycfcTo" to i8*) // CHECK-64: }, { // CHECK-64: i8* getelementptr inbounds ([17 x i8], [17 x i8]* @"\01L_selector_data(initWithBellsOn:)", i64 0, i64 0), // CHECK-64: i8* getelementptr inbounds ([11 x i8], [11 x i8]* {{@[0-9]+}}, i64 0, i64 0), // CHECK-64: i8* bitcast ([[OPAQUE21:%.*]]* ([[OPAQUE22:%.*]]*, i8*, i64)* @"$S13objc_subclass11SwiftGizmo2C7bellsOnACSgSi_tcfcTo" to i8*) // CHECK-64: }, { // CHECK-64: i8* getelementptr inbounds ([14 x i8], [14 x i8]* @"\01L_selector_data(.cxx_destruct)", i64 0, i64 0), // CHECK-64: i8* getelementptr inbounds ([{{[0-9]+}} x i8], [{{[0-9]+}} x i8]* {{@[0-9]+}}, i64 0, i64 0) // CHECK-64: i8* bitcast (void ([[OPAQUE20:%.*]]*, i8*)* @"$S13objc_subclass11SwiftGizmo2CfETo" to i8*) // CHECK-64: } // CHECK-64: ] } // CHECK: @objc_classes = internal global [2 x i8*] [i8* bitcast (%swift.type* @"$S13objc_subclass10SwiftGizmoCN" to i8*), i8* bitcast (%swift.type* @"$S13objc_subclass11SwiftGizmo2CN" to i8*)], section "__DATA,__objc_classlist,regular,no_dead_strip", align [[WORD_SIZE_IN_BYTES]] // CHECK: @objc_non_lazy_classes = internal global [1 x i8*] [i8* bitcast (%swift.type* @"$S13objc_subclass11SwiftGizmo2CN" to i8*)], section "__DATA,__objc_nlclslist,regular,no_dead_strip", align [[WORD_SIZE_IN_BYTES]] import Foundation import gizmo @requires_stored_property_inits class SwiftGizmo : Gizmo { @objc var x = Int() @objc func getX() -> Int { return x } override func duplicate() -> Gizmo { return SwiftGizmo() } override init() { super.init(bellsOn:0) } @objc init(int i: Int, string str : String) { super.init(bellsOn:i) } deinit { var x = 10 } @objc var enabled: Bool { @objc(isEnabled) get { return true } @objc(setIsEnabled:) set { } } } class GenericGizmo<T> : Gizmo { @objc func foo() {} @objc var x : Int { return 0 } var array : [T] = [] } // CHECK: define hidden swiftcc [[LLVM_PTRSIZE_INT]] @"$S13objc_subclass12GenericGizmoC1xSivg"( var sg = SwiftGizmo() sg.duplicate() @_objc_non_lazy_realization class SwiftGizmo2 : Gizmo { @objc var sg : SwiftGizmo override init() { sg = SwiftGizmo() super.init() } deinit { } }
apache-2.0
5235552fe326e1930dab6b9fe9a893e1
58.402367
347
0.59498
2.750788
false
false
false
false
Armax/iSpectate
lolSwift.swift
1
6981
// // riotApi.swift // lolSpec // // Created by Arm4x on 26/07/15. // Copyright (c) 2015 Arm4x. All rights reserved. // import Foundation class riotApi { // Wait time after every call to the API (Set 0 in case of no limit) private func rateLimit() {sleep(1)} var riot_key: String // Spectator Grids & Platform IDS // Region, PlatformId, Domain, Port var na = ["NA","NA1","spectator.na.lol.riotgames.com",80] var euw = ["EUW","EUW1","spectator.euw1.lol.riotgames.com",80] var eune = ["EUNE","EUN1","spectator.eu.lol.riotgames.com",8088] var kr = ["KR","KR","spectator.kr.lol.riotgames.com",80] var oce = ["OCE","OC1","spectator.oc1.lol.riotgames.com",80] var br = ["BR","BR1","spectator.br.lol.riotgames.com",80] var lan = ["LAN","LA1","spectator.la1.lol.riotgames.com",80] var las = ["LAS","LA2","spectator.la2.lol.riotgames.com",80] var ru = ["RU","RU","spectator.ru.lol.riotgames.com",80] var tr = ["TR","TR1","spectator.tr.lol.riotgames.com",80] func getPlatformId(region: String) -> String { var platformId:String! = ""; if(region=="NA"){platformId = na[1] as String;} if(region=="EUW"){platformId = euw[1] as String;} if(region=="EUNE"){platformId = eune[1] as String;} if(region=="KR"){platformId = kr[1] as String;} if(region=="OCE"){platformId = oce[1] as String;} if(region=="BR"){platformId = br[1] as String;} if(region=="LAN"){platformId = lan[1] as String;} if(region=="LAS"){platformId = las[1] as String;} if(region=="RU"){platformId = ru[1] as String;} if(region=="TR"){platformId = tr[1] as String;} return platformId } func getGameIpPort(region: String) -> String { var gameIpPort:String! = ""; if(region=="NA"){gameIpPort = "\(na[2]):\(na[3])";} if(region=="EUW"){gameIpPort = "\(euw[2]):\(euw[3])";} if(region=="EUNE"){gameIpPort = "\(eune[2]):\(eune[3])";} if(region=="KR"){gameIpPort = "\(kr[2]):\(kr[3])";} if(region=="OCE"){gameIpPort = "\(oce[2]):\(oce[3])";} if(region=="BR"){gameIpPort = "\(br[2]):\(br[3])";} if(region=="LAN"){gameIpPort = "\(lan[2]):\(lan[3])";} if(region=="LAS"){gameIpPort = "\(las[2]):\(las[3])";} if(region=="RU"){gameIpPort = "\(ru[2]):\(ru[3])";} if(region=="TR"){gameIpPort = "\(tr[2]):\(tr[3])";} return gameIpPort } init(_ riot_key: String) { self.riot_key = riot_key } func getLolGameClientVer() -> String { let filemgr = NSFileManager.defaultManager() let arrDirContent:[AnyObject]! = filemgr.contentsOfDirectoryAtPath("/Applications/League of Legends.app/Contents/LoL/RADS/solutions/lol_game_client_sln/releases/", error: nil)! return String(arrDirContent.last! as NSString) } func getLolGameClientSlnVer() -> String { let filemgr = NSFileManager.defaultManager() let arrDirContent:[AnyObject]! = filemgr.contentsOfDirectoryAtPath("/Applications/League of Legends.app/Contents/LoL/RADS/projects/lol_air_client/releases/", error: nil)! return String(arrDirContent.last! as NSString) } func getSummonerId(name: String, region: String) -> Int { // Escaped name trasforma il nome in formato url var escapedName:String! = name.stringByAddingPercentEncodingWithAllowedCharacters(.URLHostAllowedCharacterSet()) // Il trimmedname è semplicemente il nome tutto minuscolo e senza spazi var trimmedName:String! = name.stringByReplacingOccurrencesOfString(" ", withString: "").lowercaseString // Alcune scritte di log println("[i] Calling Riot API: summoner-v1.4") println("[Parameter] Summoner: \(name)") println("[Parameter] Region: \(region)") // Creo l'url a cui mandare la richiesta utilizzando la regione, il nome in formato url e la riot key con cui è stato creato l'oggetto let url = NSURL(string: "https://\(region.lowercaseString).api.pvp.net/api/lol/\(region)/v1.4/summoner/by-name/\(escapedName)?api_key=\(self.riot_key)") var request = NSURLRequest(URL: url!) var data = NSURLConnection.sendSynchronousRequest(request, returningResponse: nil, error: nil) // rateLimit() if data != nil { var json = JSON(data: data!) let id:Int = json[trimmedName]["id"].intValue println("[Response] ID: \(id)") return id } return 0 } func getGameIdForCurrentGame(id: Int, region: String) -> Int { println("[i] Calling Riot API: current-game-v1.0") println("[Parameter] ID: \(id)") println("[Parameter] Region: \(region)") let platformId:String! = getPlatformId(region) let url:NSURL! = NSURL(string: "https://\(region.lowercaseString).api.pvp.net/observer-mode/rest/consumer/getSpectatorGameInfo/\(platformId)/\(id)?api_key=\(self.riot_key)"); var request = NSURLRequest(URL: url!) var data = NSURLConnection.sendSynchronousRequest(request, returningResponse: nil, error: nil) rateLimit() if data != nil { var json = JSON(data: data!) let gameId:Int = json["gameId"].intValue println("[Response] Game Id: \(gameId)") return gameId } return 0 } func getEncryptionKeyForCurrentGame(id: Int, region: String) -> String { println("[i] Calling Riot API: current-game-v1.0") println("[Parameter] ID: \(id)") println("[Parameter] Region: \(region)") var platformId:String! = ""; if(region=="NA"){platformId = na[1] as String;} if(region=="EUW"){platformId = euw[1] as String;} if(region=="EUNE"){platformId = eune[1] as String;} if(region=="KR"){platformId = kr[1] as String;} if(region=="OCE"){platformId = oce[1] as String;} if(region=="BR"){platformId = br[1] as String;} if(region=="LAN"){platformId = lan[1] as String;} if(region=="LAS"){platformId = las[1] as String;} if(region=="RU"){platformId = ru[1] as String;} if(region=="TR"){platformId = tr[1] as String;} let url:NSURL! = NSURL(string: "https://\(region.lowercaseString).api.pvp.net/observer-mode/rest/consumer/getSpectatorGameInfo/\(platformId)/\(id)?api_key=\(self.riot_key)"); var request = NSURLRequest(URL: url!) var data = NSURLConnection.sendSynchronousRequest(request, returningResponse: nil, error: nil) rateLimit() if data != nil { var json = JSON(data: data!) let encryptionKey:String = json["observers"]["encryptionKey"].stringValue println("[Response] Encryption Key: \(encryptionKey)") return encryptionKey } return "" } }
gpl-2.0
992d358f15cb8132649b84c03f7d7641
42.899371
184
0.597364
3.843062
false
false
false
false
johndpope/Coiffeur
Coiffeur/src/Document.swift
1
3712
// // Document.swift // Coiffeur // // Created by Anton Leuski on 4/7/15. // Copyright (c) 2015 Anton Leuski. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // import Cocoa @objc(Document) class Document : NSDocument { var model : CoiffeurController? override init() { super.init() } convenience init?(type typeName: String, error outError: NSErrorPointer) { self.init() self.fileType = typeName let result = CoiffeurController.coiffeurWithType(typeName) switch result { case .Failure(let error): error.assignTo(outError) return nil case .Success(let controller): self.model = controller } } override var undoManager : NSUndoManager? { get { if let model = self.model { return model.managedObjectContext.undoManager } else { return super.undoManager } } set (um) { super.undoManager = um } } private func _ensureWeHaveModelOfType(typeName:String, errorFormatKey:String) -> NSError? { if let model = self.model { let documentType = model.dynamicType.documentType if typeName == documentType { return nil } return Error(errorFormatKey, typeName, documentType) } else { let result = CoiffeurController.coiffeurWithType(typeName) switch result { case .Failure(let error): return error case .Success(let controller): self.model = controller return nil } } } override func readFromURL(absoluteURL: NSURL, ofType typeName: String, error outError: NSErrorPointer) -> Bool { if let error = self._ensureWeHaveModelOfType(typeName, errorFormatKey:"Cannot read content of document “%@” into document “%@”") { error.assignTo(outError) return false } if let error = self.model!.readValuesFromURL(absoluteURL) { error.assignTo(outError) return false } return true } override func writeToURL(absoluteURL: NSURL, ofType typeName: String, error outError: NSErrorPointer) -> Bool { if let error = self._ensureWeHaveModelOfType(typeName, errorFormatKey:"Cannot write content of document “%2$@” as “%1$@”") { error.assignTo(outError) return false } if let error = self.model!.writeValuesToURL(absoluteURL) { error.assignTo(outError) return false } return true } override class func autosavesInPlace() -> Bool { return true } override func makeWindowControllers() { self.addWindowController(MainWindowController()) } // override func canCloseDocumentWithDelegate(delegate: AnyObject, // shouldCloseSelector: Selector, contextInfo: UnsafeMutablePointer<Void>) // { // self.model?.managedObjectContext.commitEditing() // super.canCloseDocumentWithDelegate(delegate, // shouldCloseSelector:shouldCloseSelector, contextInfo:contextInfo) // } override func writableTypesForSaveOperation(_: NSSaveOperationType) -> [AnyObject] { if let m = self.model { return [m.dynamicType.documentType] } else { return [] } } }
apache-2.0
4ce6ffdf1aac5c53f6f503396c22f134
24.142857
76
0.668019
4.297674
false
false
false
false
hsoi/RxSwift
RxSwift/Disposables/ScopedDisposable.swift
2
1516
// // ScopedDisposable.swift // RxSwift // // Created by Krunoslav Zaher on 5/2/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // import Foundation extension Disposable { /** Returns `ScopedDispose` that will dispose `self` when execution exits current block. **If the reference to returned instance isn't named, it will be deallocated immediately and subscription will be immediately disposed.** Example usage: let disposeOnExit = disposable.scopedDispose() - returns: `ScopedDisposable` that will dispose `self` on `deinit`. */ @available(*, deprecated=2.0.0, message="Please use `DisposeBag` and `addDisposableTo`") public func scopedDispose() -> ScopedDisposable { return ScopedDisposable(disposable: self) } } /** `ScopedDisposable` will dispose `disposable` on `deinit`. This returns ARC (RAII) like resource management to `RxSwift`. */ @available(*, deprecated=2.0.0, message="Please use `DisposeBag` and `addDisposableTo`") public class ScopedDisposable : DisposeBase { private var _disposable: Disposable? /** Initializes new instance with a single disposable. - parameter disposable: `Disposable` that will be disposed on scope exit. */ public init(disposable: Disposable) { _disposable = disposable } /** This is intentionally private. */ func dispose() { _disposable?.dispose() } deinit { dispose() } }
mit
96dc324fb6cded56e332c5a391384bc9
24.694915
92
0.662706
4.661538
false
false
false
false
atrick/swift
test/SILOptimizer/reverse-array.swift
7
2173
// RUN: %target-swift-frontend -primary-file %s -O -module-name=test -emit-sil | %FileCheck %s // RUN: %target-swift-frontend -primary-file %s -O -module-name=test -emit-ir | %FileCheck %s -check-prefix=CHECK-LLVM // Also do an end-to-end test to check all components, including IRGen. // RUN: %empty-directory(%t) // RUN: %target-build-swift -O -module-name=test %s -o %t/a.out // RUN: %target-run %t/a.out | %FileCheck %s -check-prefix=CHECK-OUTPUT // REQUIRES: swift_in_compiler,executable_test,swift_stdlib_no_asserts,optimized_stdlib // Check that we create reasonable optimized code for this function. @inline(never) public func reverseArray(_ a: [Int]) -> [Int] { var new: [Int] = [] new.reserveCapacity(a.count) var fromIndex = a.count &- 1 while fromIndex >= 0 { new.append(a[fromIndex]) fromIndex &-= 1 } return new } // CHECK-LABEL: sil [noinline] {{.*}}@$s4test12reverseArrayySaySiGACF // There must not be more than two begin_cow_mutation - end_cow_mutation pairs: // * the first one for the initial reserveCapacity // * the second for the append. // CHECK-NOT: {{.*(_cow_mutation|cond_fail)}} // CHECK: begin_cow_mutation // CHECK-NOT: {{.*(_cow_mutation|cond_fail)}} // CHECK: end_cow_mutation // CHECK-NOT: {{.*(_cow_mutation|cond_fail)}} // In SIL we fail to eliminate the bounds check of the input array. // But that's okay, because LLVM can do that. // So we accept one cond_fail in the SIL output. // CHECK: cond_fail {{.*}} "Index out of range" // The second begin_cow_mutation - end_cow_mutation pair: // CHECK-NOT: {{.*(_cow_mutation|cond_fail)}} // CHECK: begin_cow_mutation // CHECK-NOT: {{.*(_cow_mutation|cond_fail)}} // CHECK: end_cow_mutation // CHECK-NOT: {{.*(_cow_mutation|cond_fail)}} // CHECK: } // end sil function '$s4test12reverseArrayySaySiGACF' // Check that there are no cond_fails left in the LLVM output. // LLVM should be able to optimize away the bounds check of the input array. // CHECK-LLVM-LABEL: define {{.*}} @"$s4test12reverseArrayySaySiGACF" // CHECK-LLVM-NOT: llvm.trap // CHECK-LLVM: } // CHECK-OUTPUT: [3, 2, 1] print(reverseArray([1, 2, 3]))
apache-2.0
48fe5317acb694fb8bf093f7e0095e65
30.955882
119
0.669581
3.228826
false
true
false
false
society2012/PGDBK
PGDBK/PGDBK/Code/Left/Controller/LeftViewController.swift
1
5725
// // LeftViewController.swift // PGDBK // // Created by hupeng on 2017/7/5. // Copyright © 2017年 m.zintao. All rights reserved. // import UIKit import Kingfisher let kLeftCell:String = "kLeftCell" let kSelectFun:String = "kSelectFun" class LeftViewController: BaseViewController { @IBOutlet var leftTable: UITableView! var headView:LeftHeadView? var dataSource:[[String:String]] = { let array = [["startMe.png":"好评"],["aboutMe.png":"关于作者"],["collect.png":"收藏"],["setting.png":"设置"]] return array }() override func viewDidLoad() { super.viewDidLoad() // self.leftTable.backgroundColor = UIColor.red NotificationCenter.default.addObserver(self, selector: #selector(infoChange(note:)), name: NSNotification.Name("changeInfo"), object: nil) NotificationCenter.default.addObserver(self, selector: #selector(loginSuccess(note:)), name: NSNotification.Name("loginSuccess"), object: nil) NotificationCenter.default.addObserver(self, selector: #selector(loginOut), name: NSNotification.Name("logoutSuccess"), object: nil) setupHeadView() } func loginOut() -> Void { self.headView?.nickLabel.text = "点击登录" self.headView?.logoView.image = UIImage(named: "[email protected]") } func loginSuccess(note:Notification) -> Void { let id = note.object as?String self.setupUserInfo(id: id) } func infoChange(note:Notification) -> Void { let obj = note.object if(obj is String){ self.headView?.nickLabel.text = obj as?String }else{ self.headView?.logoView.image = obj as?UIImage } } func setupHeadView() -> Void { self.leftTable.rowHeight = 45 let nib = UINib(nibName: "LeftTableViewCell", bundle: nil) self.leftTable.register(nib, forCellReuseIdentifier: kLeftCell) self.perform(#selector(delayAdd), with: nib, afterDelay: 0.3) } func delayAdd() -> Void { let headView = Bundle.main.loadNibNamed("LeftHeadView", owner: self, options: nil)?.first as?LeftHeadView headView?.frame = CGRect(x: 0, y: 0, width: self.leftTable.frame.width, height: 120) self.headView = headView self.leftTable.tableHeaderView = headView self.leftTable.tableFooterView = UIView() let tap = UITapGestureRecognizer(target: self, action: #selector(tapLogo)) self.headView?.isUserInteractionEnabled = true self.headView?.addGestureRecognizer(tap) let id = UserDefaults.standard.object(forKey: "userId") as?String self.setupUserInfo(id: id) } func tapLogo() -> Void { closeLeftView() let id = UserDefaults.standard.object(forKey: "userId") as?String if(id == nil){ NotificationCenter.default.post(name: NSNotification.Name("goLogin"), object: "1") }else{ NotificationCenter.default.post(name: NSNotification.Name("goLogin"), object: "2") } } func closeLeftView() -> Void { let navi = kDelegate?.drawerController?.centerViewController as? MainNaviController self.evo_drawerController?.setCenter(navi!, withFullCloseAnimation: true, completion: nil) } } extension LeftViewController{ func setupUserInfo(id:String?) -> Void { if(id == nil){ return } let url = SERVER_IP + "/index.php/api/AppInterface/getInfo" let parmertas = ["id":id!] NetWorkTools.requestData(URLString: url, type: .post, parmertas: parmertas) { (response) in guard let dic = response as? [String:Any] else{return} guard let data = dic["data"] as?[String:Any] else{return} let code = dic["code"] as?Int if(code == 200){ let nick = data["nickname"] as?String self.headView?.nickLabel.text = nick guard let logo = data["icon"]as?String else{return} if(logo.hasPrefix("http")){ let url = URL(string: logo) self.headView?.logoView.kf.setImage(with: url) }else{ let urlStr = SERVER_IP + logo let url = URL(string: urlStr) self.headView?.logoView.kf.setImage(with: url) } } } } } extension LeftViewController:UITableViewDelegate,UITableViewDataSource{ func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 4 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: kLeftCell, for: indexPath) as? LeftTableViewCell cell?.accessoryType = .disclosureIndicator let dic = self.dataSource[indexPath.row] let image = dic.keys.first let name = dic.values.first cell?.imageView?.image = UIImage(named: image!) cell?.nameLabel.text = name return cell! } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) closeLeftView() NotificationCenter.default.post(name: NSNotification.Name(kSelectFun), object: indexPath) } }
mit
c92c2935831580b22fa222445b18256b
30.458564
150
0.592905
4.682566
false
false
false
false
vulgur/WeeklyFoodPlan
WeeklyFoodPlan/WeeklyFoodPlan/Views/Food/FoodViewController.swift
1
17052
// // FoodViewController.swift // WeeklyFoodPlan // // Created by vulgur on 2017/2/22. // Copyright © 2017年 MAD. All rights reserved. // import UIKit import RealmSwift class FoodViewController: UIViewController { @IBOutlet var tableView: UITableView! @IBOutlet var deleteButton: UIButton! let foodHeaderViewCellIdentifier = "FoodHeaderViewCell" let foodSectionViewCellIdentifier = "FoodSectionViewCell" let foodOptionViewCellIdentifier = "FoodOptionViewCell" let foodTagViewCellIdentifier = "FoodTagViewCell" let foodListViewCellIdentifier = "FoodViewListViewCell" let headerViewRow = 0 let optionViewRow = 2 let tagViewRow = 4 let ingredientViewRow = 6 let tipViewRow = 8 let whenOptions = ["Breakfast", "Lunch", "Dinner"] // MARK: Food info var food: Food? var foodType = Food.FoodType.homeCook var tagList = [String]() var ingredientList = [String]() var tipList = [String]() var whenList = [String]() var isFavored = false var foodName: String? var foodImage: UIImage? // MARK: Private properties override func viewDidLoad() { super.viewDidLoad() self.tabBarController?.tabBar.isHidden = true self.navigationController?.isNavigationBarHidden = false configFood() configSubviews() tableView.reloadData() if food != nil { navigationItem.title = "修改美食".localized() } else { navigationItem.title = "新增美食".localized() } navigationController?.navigationBar.backItem?.title = "" } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) // updateHeader() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } private func configFood() { if let food = self.food { foodName = food.name isFavored = food.isFavored for tag in food.tags { tagList.append(tag.name) } for ingredient in food.ingredients { ingredientList.append(ingredient.name) } for tip in food.tips { tipList.append(tip.content) } for when in food.whenList { whenList.append(when) } } } private func configSubviews() { // table view tableView.register(UINib.init(nibName: foodHeaderViewCellIdentifier, bundle: nil), forCellReuseIdentifier: foodHeaderViewCellIdentifier) tableView.register(UINib.init(nibName: foodSectionViewCellIdentifier, bundle: nil), forCellReuseIdentifier: foodSectionViewCellIdentifier) tableView.register(UINib.init(nibName: foodOptionViewCellIdentifier, bundle: nil), forCellReuseIdentifier: foodOptionViewCellIdentifier) tableView.register(UINib.init(nibName: foodTagViewCellIdentifier, bundle: nil), forCellReuseIdentifier: foodTagViewCellIdentifier) tableView.register(UINib.init(nibName: foodListViewCellIdentifier, bundle: nil), forCellReuseIdentifier: foodListViewCellIdentifier) tableView.rowHeight = UITableViewAutomaticDimension tableView.estimatedRowHeight = 40 tableView.separatorColor = UIColor.clear tableView.tableFooterView = UIView() // delete button if food == nil { deleteButton.isHidden = true } else { deleteButton.isHidden = false } } private func indexPathsOfFoodInfo() -> [IndexPath] { let headerViewIndexPath = IndexPath(row: headerViewRow, section: 0) let optionViewIndexPath = IndexPath(row: optionViewRow, section: 0) let tagViewIndexPath = IndexPath(row: tagViewRow, section: 0) let ingredientViewIndePath = IndexPath(row: ingredientViewRow, section: 0) let tipViewIndexPath = IndexPath(row: tipViewRow, section: 0) switch foodType { case .eatingOut, .takeOut: return [headerViewIndexPath, optionViewIndexPath, tagViewIndexPath] case .homeCook: return [headerViewIndexPath, optionViewIndexPath, tagViewIndexPath, ingredientViewIndePath, tipViewIndexPath] } } private func listOfTags() -> List<Tag> { let tags = List<Tag>() for title in tagList { let tag = Tag() tag.name = title tags.append(tag) } return tags } private func listOfIngredients() -> List<Ingredient> { let ingredients = List<Ingredient>() for title in ingredientList { let ingredient = Ingredient() ingredient.name = title ingredients.append(ingredient) } return ingredients } private func listOfTips() -> List<Tip> { let tips = List<Tip>() for title in tipList { let tip = Tip() tip.content = title tips.append(tip) } return tips } private func listOfWhenObjects() -> List<WhenObject> { let list = List<WhenObject>() for option in whenList { let when = WhenObject() when.value = option list.append(when) } return list } func updateCells() { tableView.reloadRows(at: indexPathsOfFoodInfo(), with: .none) } @IBAction func saveFood(_ sender: UIBarButtonItem) { guard let foodName = self.foodName else { showAlert(message: "请输入美食名称") return } if foodName.isEmpty { showAlert(message: "请输入美食名称") return } let foodToSave = Food() if let originalFood = self.food { foodToSave.id = originalFood.id foodToSave.typeRawValue = originalFood.typeRawValue } else { foodToSave.typeRawValue = foodType.rawValue } foodToSave.name = foodName foodToSave.isFavored = isFavored foodToSave.whenObjects = listOfWhenObjects() foodToSave.tags = listOfTags() foodToSave.ingredients = listOfIngredients() foodToSave.tips = listOfTips() BaseManager.shared.save(object: foodToSave) _ = navigationController?.popViewController(animated: true) } @IBAction func deleteFoodButtonTapped(_ sender: UIButton) { let message = "确定要删除吗?".localized() let deleteTitle = "删除".localized() let cancelTitle = "取消".localized() let alertController = UIAlertController(title: nil, message: message, preferredStyle: .alert) let deleteAction = UIAlertAction(title: deleteTitle, style: .destructive) { [unowned self] (action) in if let food = self.food { BaseManager.shared.delete(object: food) _ = self.navigationController?.popViewController(animated: true) } } let cancelAction = UIAlertAction(title: cancelTitle, style: .cancel, handler: nil) alertController.addAction(deleteAction) alertController.addAction(cancelAction) present(alertController, animated: true, completion: nil) } // MARK: Private methods func showAlert(message: String) { let alert = UIAlertController(title: nil, message: message, preferredStyle: .alert) let cancel = UIAlertAction(title: "Okay", style: .cancel, handler: { (action) in }) alert.addAction(cancel) present(alert, animated: true, completion: nil) } } // MARK: UITableViewDataSource extension FoodViewController: UITableViewDataSource { func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { switch foodType { case .eatingOut, .takeOut: return 5 case .homeCook: return 9 } } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { switch indexPath.row { case 0: let cell = tableView.dequeueReusableCell(withIdentifier: foodHeaderViewCellIdentifier, for: indexPath) as! FoodHeaderViewCell cell.backgroundColor = UIColor.white cell.delegate = self if foodName == nil || (foodName?.isEmpty)! { cell.headerLabel.text = FoodHeaderViewCell.placeholderText } else { cell.headerLabel.text = foodName } cell.headerImageView.image = foodImage cell.setFavorButtonState(isFavored) return cell case 1: let cell = tableView.dequeueReusableCell(withIdentifier: foodSectionViewCellIdentifier, for: indexPath) as! FoodSectionViewCell cell.backgroundColor = UIColor.cyan cell.sectionImageView.image = #imageLiteral(resourceName: "clock") cell.sectionLabel.text = "When do you want to enjoy?" cell.sectionButton.isHidden = true return cell case 2: let cell = tableView.dequeueReusableCell(withIdentifier: foodOptionViewCellIdentifier, for: indexPath) as! FoodOptionViewCell cell.optionTitles = whenOptions cell.selectedOptions = whenList cell.delegate = self cell.collectionView.reloadData() return cell case 3: let cell = tableView.dequeueReusableCell(withIdentifier: foodSectionViewCellIdentifier, for: indexPath) as! FoodSectionViewCell cell.backgroundColor = UIColor.cyan cell.sectionImageView.image = #imageLiteral(resourceName: "hashtag") cell.sectionLabel.text = "Tags" cell.sectionButton.addTarget(self, action: #selector(sectionButtonTapped(sender:)), for: .touchUpInside) cell.sectionButton.isHidden = false cell.sectionButton.tag = FoodSectionViewCell.ButtonType.AddTag.rawValue return cell case 4: let cell = tableView.dequeueReusableCell(withIdentifier: foodTagViewCellIdentifier, for: indexPath) as! FoodTagViewCell cell.delegate = self cell.tagList = tagList cell.collectionView.reloadData() return cell case 5: let cell = tableView.dequeueReusableCell(withIdentifier: foodSectionViewCellIdentifier, for: indexPath) as! FoodSectionViewCell cell.backgroundColor = UIColor.cyan cell.sectionLabel.text = "Ingredients" cell.sectionImageView.image = #imageLiteral(resourceName: "list") cell.sectionButton.addTarget(self, action: #selector(sectionButtonTapped(sender:)), for: .touchUpInside) cell.sectionButton.isHidden = false cell.sectionButton.tag = FoodSectionViewCell.ButtonType.AddIngredient.rawValue return cell case 6: let cell = tableView.dequeueReusableCell(withIdentifier: foodListViewCellIdentifier, for: indexPath) as! FoodViewListViewCell cell.delegate = self cell.itemType = .Ingredient cell.items = ingredientList cell.tableView.reloadData() return cell case 7: let cell = tableView.dequeueReusableCell(withIdentifier: foodSectionViewCellIdentifier, for: indexPath) as! FoodSectionViewCell cell.backgroundColor = UIColor.cyan cell.sectionLabel.text = "Tips" cell.sectionImageView.image = #imageLiteral(resourceName: "tip") cell.sectionButton.addTarget(self, action: #selector(sectionButtonTapped(sender:)), for: .touchUpInside) cell.sectionButton.isHidden = false cell.sectionButton.tag = FoodSectionViewCell.ButtonType.AddTip.rawValue return cell case 8: let cell = tableView.dequeueReusableCell(withIdentifier: foodListViewCellIdentifier, for: indexPath) as! FoodViewListViewCell cell.delegate = self cell.itemType = .Tip cell.items = tipList cell.tableView.reloadData() return cell default: fatalError() } } @objc private func sectionButtonTapped(sender: UIButton) { if let buttonType = FoodSectionViewCell.ButtonType(rawValue: sender.tag) { var style: InputItemView.Style switch buttonType { case .AddTag: style = .AddTag case .AddIngredient: style = .AddIngredient case .AddTip: style = .AddTip } let inputItemView = InputItemView(style: style) inputItemView.delegate = self if let keyWindow = UIApplication.shared.keyWindow { keyWindow.addSubview(inputItemView) inputItemView.show() } } } } // MARK: InputItemViewDelegate extension FoodViewController: InputItemViewDelegate { func done(item: String, style: InputItemView.Style) { switch style { case .AddTag: tagList.append(item) case .AddIngredient: ingredientList.append(item) case .AddTip: tipList.append(item) } updateCells() } } // MARK: FoodTagViewCellDelegate extension FoodViewController: FoodTagViewCellDelegate { func didRemoveTag(tag: String) { if let index = tagList.index(of: tag) { tagList.remove(at: index) updateCells() } } } // MARK: FoodViewListViewCellDelegate extension FoodViewController: FoodViewListViewCellDelegate { func didRemoveItem(_ item: String, type: FoodViewListViewCell.ItemType) { switch type { case .Ingredient: if let index = ingredientList.index(of: item) { ingredientList.remove(at: index) } case .Tip: if let index = tipList.index(of: item) { tipList.remove(at: index) } } updateCells() } } // MARK: FoodHeaderViewCellDelegate extension FoodViewController: FoodHeaderViewCellDelegate { func didInputName(_ name: String) { self.foodName = name updateCells() } func didToggleFavorButton() { isFavored = !isFavored updateCells() } func didTapHeaderImageView(_ imageView: UIImageView) { let alertController = UIAlertController.init(title: "选择照片", message: nil, preferredStyle: .actionSheet) if UIImagePickerController.isSourceTypeAvailable(.camera) { let action = UIAlertAction.init(title: "拍照", style: .default, handler: { (_) in let picker = UIImagePickerController() picker.delegate = self picker.sourceType = .camera picker.allowsEditing = false self.present(picker, animated: true, completion: nil) }) alertController.addAction(action) } if UIImagePickerController.isSourceTypeAvailable(.photoLibrary) { let action = UIAlertAction.init(title: "照片", style: .default, handler: { (_) in let picker = UIImagePickerController() picker.delegate = self picker.sourceType = .photoLibrary picker.allowsEditing = false self.present(picker, animated: true, completion: nil) }) alertController.addAction(action) } let cancelAction = UIAlertAction(title: "取消", style: .cancel) { (_) in } alertController.addAction(cancelAction) present(alertController, animated: true, completion: nil) } } // MARK: UIImagePickerControllerDelegate extension FoodViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate { func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) { picker.dismiss(animated: true, completion: nil) if let image = info[UIImagePickerControllerOriginalImage] as? UIImage { self.foodImage = image updateCells() } } } // MARK: FoodOptionViewDelegate extension FoodViewController: FoodOptionCellDelegate { func didAddOption(_ option: String) { whenList.append(option) } func didRemoveOption(_ option: String) { if let index = whenList.index(of: option) { whenList.remove(at: index) } } }
mit
2b2cab89de0b8745baf75470a7ce7a12
35.71645
146
0.621588
5.38337
false
false
false
false
netguru/inbbbox-ios
Inbbbox/Source Files/Views/UICollectionViewCell/ShotDetailsDescriptionCollectionViewCell.swift
1
3595
// // ShotDetailsDescriptionCollectionViewCell.swift // Inbbbox // // Created by Patryk Kaczmarek on 19/02/16. // Copyright © 2016 Netguru Sp. z o.o. All rights reserved. // import UIKit import TTTAttributedLabel class ShotDetailsDescriptionCollectionViewCell: UICollectionViewCell, Reusable { weak var delegate: UICollectionViewCellWithLabelContainingClickableLinksDelegate? fileprivate let descriptionLabel = TTTAttributedLabel.newAutoLayout() // Regards clickable links in description label fileprivate let layoutManager = NSLayoutManager() fileprivate let textContainer = NSTextContainer(size: CGSize.zero) lazy fileprivate var textStorage: NSTextStorage = { [unowned self] in return NSTextStorage(attributedString: self.descriptionLabel.attributedText ?? NSAttributedString()) }() fileprivate let separatorView = UIView.newAutoLayout() fileprivate var didUpdateConstraints = false override init(frame: CGRect) { super.init(frame: frame) descriptionLabel.numberOfLines = 0 descriptionLabel.isUserInteractionEnabled = true descriptionLabel.linkAttributes = [NSForegroundColorAttributeName : UIColor.pinkColor()] contentView.addSubview(descriptionLabel) separatorView.backgroundColor = ColorModeProvider.current().shotDetailsSeparatorColor contentView.addSubview(separatorView) } @available(*, unavailable, message: "Use init(frame:) instead") required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func layoutSubviews() { super.layoutSubviews() let insets = type(of: self).contentInsets descriptionLabel.preferredMaxLayoutWidth = frame.size.width - insets.left - insets.right textContainer.size = descriptionLabel.bounds.size } override func updateConstraints() { if !didUpdateConstraints { didUpdateConstraints = true let insets = type(of: self).contentInsets descriptionLabel.autoPinEdgesToSuperviewEdges(with: insets) separatorView.autoSetDimension(.height, toSize: 1) separatorView.autoPinEdgesToSuperviewEdges(with: UIEdgeInsets.zero, excludingEdge: .bottom) } super.updateConstraints() } override func prepareForReuse() { super.prepareForReuse() descriptionLabel.attributedText = nil } } // MARK: Regards clickable links in description label extension ShotDetailsDescriptionCollectionViewCell { func setDescriptionLabelAttributedText(_ attributedText: NSAttributedString) { descriptionLabel.setText(attributedText) layoutManager.addTextContainer(textContainer) textStorage.addLayoutManager(layoutManager) textContainer.lineFragmentPadding = 0.0 textContainer.lineBreakMode = descriptionLabel.lineBreakMode textContainer.maximumNumberOfLines = descriptionLabel.numberOfLines descriptionLabel.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(descriptionLabelDidTap(_:)))) } func descriptionLabelDidTap(_ tapGestureRecognizer: UITapGestureRecognizer) { delegate?.labelContainingClickableLinksDidTap(tapGestureRecognizer, textContainer: textContainer, layoutManager: layoutManager) } } extension ShotDetailsDescriptionCollectionViewCell: AutoSizable { static var contentInsets: UIEdgeInsets { return UIEdgeInsets(top: 20, left: 20, bottom: 20, right: 20) } }
gpl-3.0
dc5967fadf8aac42989ee44c1b243c1e
32.90566
108
0.731219
6.010033
false
false
false
false
hyperoslo/Sync
Tests/PropertyMapper/DictionaryTests.swift
1
13246
import CoreData import XCTest import Sync class DictionaryTests: XCTestCase { let sampleSnakeCaseJSON = [ "description": "reserved", "inflection_binary_data": ["one", "two"], "inflection_date": "1970-01-01", "custom_remote_key": "randomRemoteKey", "inflection_id": 1, "inflection_string": "string", "inflection_integer": 1, "ignored_parameter": "ignored", "ignore_transformable": "string", "inflection_uuid": "E621E1F8-C36C-495A-93FC-0C247A3E6E5F", "inflection_uri": "https://www.apple.com/" ] as [String : Any] func testExportDictionaryWithSnakeCase() { // Fill in transformable attributes is not supported in Swift 3. Crashes when saving the context. let dataStack = Helper.dataStackWithModelName("137") let user = NSEntityDescription.insertNewObject(forEntityName: "InflectionUser", into: dataStack.mainContext) user.hyp_fill(with: self.sampleSnakeCaseJSON) try! dataStack.mainContext.save() let compared = [ "description": "reserved", "inflection_binary_data": try! NSKeyedArchiver.archivedData(withRootObject: ["one", "two"], requiringSecureCoding: false) as NSData, "inflection_date": "1970-01-01", "randomRemoteKey": "randomRemoteKey", "inflection_id": 1, "inflection_string": "string", "inflection_integer": 1, "inflection_uuid": "E621E1F8-C36C-495A-93FC-0C247A3E6E5F", "inflection_uri": "https://www.apple.com/" ] as [String : Any] let formatter = DateFormatter() formatter.dateFormat = "yyyy-MM-dd" formatter.timeZone = TimeZone(identifier: "GMT") let result = user.hyp_dictionary(with: formatter, using: .snakeCase) for (key, value) in compared { if let comparedValue = result[key] { XCTAssertEqual(value as? NSObject, comparedValue as? NSObject) } } dataStack.drop() } func testExportDictionaryWithCamelCase() { // Fill in transformable attributes is not supported in Swift 3. Crashes when saving the context. let dataStack = Helper.dataStackWithModelName("137") let user = NSEntityDescription.insertNewObject(forEntityName: "InflectionUser", into: dataStack.mainContext) user.hyp_fill(with: self.sampleSnakeCaseJSON) try! dataStack.mainContext.save() let compared = [ "description": "reserved", "inflectionBinaryData": try! NSKeyedArchiver.archivedData(withRootObject: ["one", "two"], requiringSecureCoding: false) as NSData, "inflectionDate": "1970-01-01", "randomRemoteKey": "randomRemoteKey", "inflectionID": 1, "inflectionString": "string", "inflectionInteger": 1, "inflectionUUID": "E621E1F8-C36C-495A-93FC-0C247A3E6E5F", "inflectionURI": "https://www.apple.com/" ] as [String : Any] let formatter = DateFormatter() formatter.dateFormat = "yyyy-MM-dd" formatter.timeZone = TimeZone(identifier: "GMT") let result = user.hyp_dictionary(with: formatter, using: .camelCase) print(result) XCTAssertEqual(compared as NSDictionary, result as NSDictionary) dataStack.drop() } let sampleSnakeCaseJSONWithRelationship = ["inflection_id": 1] as [String : Any] func testExportDictionaryWithSnakeCaseRelationshipArray() { // Fill in transformable attributes is not supported in Swift 3. Crashes when saving the context. let dataStack = Helper.dataStackWithModelName("137") let user = NSEntityDescription.insertNewObject(forEntityName: "InflectionUser", into: dataStack.mainContext) user.hyp_fill(with: self.sampleSnakeCaseJSONWithRelationship) let company = NSEntityDescription.insertNewObject(forEntityName: "InflectionCompany", into: dataStack.mainContext) company.setValue(NSNumber(value: 1), forKey: "inflectionID") user.setValue(company, forKey: "camelCaseCompany") try! dataStack.mainContext.save() let compared = [ "inflection_binary_data": NSNull(), "inflection_date": NSNull(), "inflection_id": 1, "inflection_integer": NSNull(), "inflection_string": NSNull(), "randomRemoteKey": NSNull(), "description": NSNull(), "inflection_uuid": NSNull(), "inflection_uri": NSNull(), "camel_case_company": [ "inflection_id": 1 ] ] as [String : Any] let result = user.hyp_dictionary(using: .snakeCase, andRelationshipType: .array) print(result) XCTAssertEqual(compared as NSDictionary, result as NSDictionary) dataStack.drop() } func testExportDictionaryWithCamelCaseRelationshipArray() { // Fill in transformable attributes is not supported in Swift 3. Crashes when saving the context. let dataStack = Helper.dataStackWithModelName("137") let user = NSEntityDescription.insertNewObject(forEntityName: "InflectionUser", into: dataStack.mainContext) user.hyp_fill(with: self.sampleSnakeCaseJSONWithRelationship) let company = NSEntityDescription.insertNewObject(forEntityName: "InflectionCompany", into: dataStack.mainContext) company.setValue(NSNumber(value: 1), forKey: "inflectionID") user.setValue(company, forKey: "camelCaseCompany") try! dataStack.mainContext.save() let compared = [ "inflectionBinaryData": NSNull(), "inflectionDate": NSNull(), "inflectionID": 1, "inflectionInteger": NSNull(), "inflectionString": NSNull(), "randomRemoteKey": NSNull(), "description": NSNull(), "inflectionUUID": NSNull(), "inflectionURI": NSNull(), "camelCaseCompany": [ "inflectionID": 1 ] ] as [String : Any] let result = user.hyp_dictionary(using: .camelCase, andRelationshipType: .array) print(result) XCTAssertEqual(compared as NSDictionary, result as NSDictionary) dataStack.drop() } func testExportDictionaryWithSnakeCaseRelationshipNested() { // Fill in transformable attributes is not supported in Swift 3. Crashes when saving the context. let dataStack = Helper.dataStackWithModelName("137") let user = NSEntityDescription.insertNewObject(forEntityName: "InflectionUser", into: dataStack.mainContext) user.hyp_fill(with: self.sampleSnakeCaseJSONWithRelationship) let company = NSEntityDescription.insertNewObject(forEntityName: "InflectionCompany", into: dataStack.mainContext) company.setValue(NSNumber(value: 1), forKey: "inflectionID") user.setValue(company, forKey: "camelCaseCompany") try! dataStack.mainContext.save() let compared = [ "inflection_binary_data": NSNull(), "inflection_date": NSNull(), "inflection_id": 1, "inflection_integer": NSNull(), "inflection_string": NSNull(), "randomRemoteKey": NSNull(), "description": NSNull(), "inflection_uuid": NSNull(), "inflection_uri": NSNull(), "camel_case_company_attributes": [ "inflection_id": 1 ] ] as [String : Any] let result = user.hyp_dictionary(using: .snakeCase, andRelationshipType: .nested) print(result) XCTAssertEqual(compared as NSDictionary, result as NSDictionary) dataStack.drop() } func testExportDictionaryWithCamelCaseRelationshipNested() { // Fill in transformable attributes is not supported in Swift 3. Crashes when saving the context. let dataStack = Helper.dataStackWithModelName("137") let user = NSEntityDescription.insertNewObject(forEntityName: "InflectionUser", into: dataStack.mainContext) user.hyp_fill(with: self.sampleSnakeCaseJSONWithRelationship) let company = NSEntityDescription.insertNewObject(forEntityName: "InflectionCompany", into: dataStack.mainContext) company.setValue(NSNumber(value: 1), forKey: "inflectionID") user.setValue(company, forKey: "camelCaseCompany") try! dataStack.mainContext.save() let compared = [ "inflectionBinaryData": NSNull(), "inflectionDate": NSNull(), "inflectionID": 1, "inflectionInteger": NSNull(), "inflectionString": NSNull(), "randomRemoteKey": NSNull(), "description": NSNull(), "inflectionUUID": NSNull(), "inflectionURI": NSNull(), "camelCaseCompanyAttributes": [ "inflectionID": 1 ] ] as [String : Any] let result = user.hyp_dictionary(using: .camelCase, andRelationshipType: .nested) print(result) XCTAssertEqual(compared as NSDictionary, result as NSDictionary) dataStack.drop() } func testReservedAttributeNotExportingWell() { let dataStack = Helper.dataStackWithModelName("142") let user = NSEntityDescription.insertNewObject(forEntityName: "TwoLetterEntity", into: dataStack.mainContext) user.hyp_fill(with: ["description": "test"]) try! dataStack.mainContext.save() let compared = ["description": "test"] as [String : Any] let result = user.hyp_dictionary(using: .camelCase) print(result) XCTAssertEqual(compared as NSDictionary, result as NSDictionary) dataStack.drop() } func setUpWorkout(dataStack: DataStack) -> NSManagedObject { let workout = NSEntityDescription.insertNewObject(forEntityName: "Workout", into: dataStack.mainContext) workout.setValue(UUID().uuidString, forKey: "id") workout.setValue(UUID().uuidString, forKey: "workoutDesc") workout.setValue(UUID().uuidString, forKey: "workoutName") let calendar = NSEntityDescription.insertNewObject(forEntityName: "Calendar", into: dataStack.mainContext) calendar.setValue(UUID().uuidString, forKey: "eventSourceType") calendar.setValue(UUID().uuidString, forKey: "id") calendar.setValue(NSNumber(value: true), forKey: "isCompleted") calendar.setValue(Date(timeIntervalSince1970: 0), forKey: "start") let plannedToIDs = NSMutableSet() plannedToIDs.add(calendar) workout.setValue(plannedToIDs, forKey: "plannedToIDs") let exercise = NSEntityDescription.insertNewObject(forEntityName: "Exercise", into: dataStack.mainContext) exercise.setValue(UUID().uuidString, forKey: "exerciseDesc") exercise.setValue(UUID().uuidString, forKey: "exerciseName") exercise.setValue(UUID().uuidString, forKey: "id") exercise.setValue(UUID().uuidString, forKey: "mainMuscle") let exerciseSet = NSEntityDescription.insertNewObject(forEntityName: "ExerciseSet", into: dataStack.mainContext) exerciseSet.setValue(UUID().uuidString, forKey: "id") exerciseSet.setValue(NSNumber(value: true), forKey: "isCompleted") exerciseSet.setValue(NSNumber(value: 0), forKey: "setNumber") exerciseSet.setValue(NSNumber(value: 0), forKey: "setReps") exerciseSet.setValue(NSNumber(value: 0), forKey: "setWeight") let exerciseSets = NSMutableSet() exerciseSets.add(exerciseSet) exercise.setValue(exerciseSets, forKey: "exerciseSets") let workoutExercises = NSMutableSet() workoutExercises.add(exercise) workout.setValue(workoutExercises, forKey: "workoutExercises") try! dataStack.mainContext.save() return workout } func testBug140CamelCase() { let dataStack = Helper.dataStackWithModelName("140") let workout = self.setUpWorkout(dataStack: dataStack) let result = workout.hyp_dictionary(using: .camelCase, andRelationshipType: .array) let rootKeys = Array(result.keys).sorted() XCTAssertEqual(rootKeys.count, 5) XCTAssertEqual(rootKeys[0], "_id") XCTAssertEqual(rootKeys[1], "plannedToIDs") XCTAssertEqual(rootKeys[2], "workoutDesc") XCTAssertEqual(rootKeys[3], "workoutExercises") XCTAssertEqual(rootKeys[4], "workoutName") dataStack.drop() } func testBug140SnakeCase() { let dataStack = Helper.dataStackWithModelName("140") let workout = self.setUpWorkout(dataStack: dataStack) let result = workout.hyp_dictionary(using: .snakeCase, andRelationshipType: .array) let rootKeys = Array(result.keys).sorted() XCTAssertEqual(rootKeys.count, 5) XCTAssertEqual(rootKeys[0], "_id") XCTAssertEqual(rootKeys[1], "planned_to_ids") XCTAssertEqual(rootKeys[2], "workout_desc") XCTAssertEqual(rootKeys[3], "workout_exercises") XCTAssertEqual(rootKeys[4], "workout_name") dataStack.drop() } }
mit
24852b3edf88ba25e28c5adeea40c54a
41.184713
144
0.647516
4.959191
false
false
false
false
google/flatbuffers
swift/Sources/FlatBuffers/Table.swift
4
8385
/* * Copyright 2021 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. */ #if !os(WASI) import Foundation #else import SwiftOverlayShims #endif /// `Table` is a Flatbuffers object that can read, /// mutate scalar fields within a valid flatbuffers buffer @frozen public struct Table { /// Hosting Bytebuffer public private(set) var bb: ByteBuffer /// Current position of the table within the buffer public private(set) var postion: Int32 /// Initializer for the table interface to allow generated code to read /// data from memory /// - Parameters: /// - bb: ByteBuffer that stores data /// - position: Current table position /// - Note: This will `CRASH` if read on a big endian machine public init(bb: ByteBuffer, position: Int32 = 0) { guard isLitteEndian else { fatalError( "Reading/Writing a buffer in big endian machine is not supported on swift") } self.bb = bb postion = position } /// Gets the offset of the current field within the buffer by reading /// the vtable /// - Parameter o: current offset /// - Returns: offset of field within buffer public func offset(_ o: Int32) -> Int32 { let vtable = postion - bb.read(def: Int32.self, position: Int(postion)) return o < bb .read(def: VOffset.self, position: Int(vtable)) ? Int32(bb.read( def: Int16.self, position: Int(vtable + o))) : 0 } /// Gets the indirect offset of the current stored object /// (applicable only for object arrays) /// - Parameter o: current offset /// - Returns: offset of field within buffer public func indirect(_ o: Int32) -> Int32 { o + bb.read(def: Int32.self, position: Int(o)) } /// String reads from the buffer with respect to position of the current table. /// - Parameter offset: Offset of the string public func string(at offset: Int32) -> String? { directString(at: offset + postion) } /// Direct string reads from the buffer disregarding the position of the table. /// It would be preferable to use string unless the current position of the table /// is not needed /// - Parameter offset: Offset of the string public func directString(at offset: Int32) -> String? { var offset = offset offset += bb.read(def: Int32.self, position: Int(offset)) let count = bb.read(def: Int32.self, position: Int(offset)) let position = Int(offset) + MemoryLayout<Int32>.size return bb.readString(at: position, count: Int(count)) } /// Reads from the buffer with respect to the position in the table. /// - Parameters: /// - type: Type of Element that needs to be read from the buffer /// - o: Offset of the Element public func readBuffer<T>(of type: T.Type, at o: Int32) -> T { directRead(of: T.self, offset: o + postion) } /// Reads from the buffer disregarding the position of the table. /// It would be used when reading from an /// ``` /// let offset = __t.offset(10) /// //Only used when the we already know what is the /// // position in the table since __t.vector(at:) /// // returns the index with respect to the position /// __t.directRead(of: Byte.self, /// offset: __t.vector(at: offset) + index * 1) /// ``` /// - Parameters: /// - type: Type of Element that needs to be read from the buffer /// - o: Offset of the Element public func directRead<T>(of type: T.Type, offset o: Int32) -> T { let r = bb.read(def: T.self, position: Int(o)) return r } /// Returns that current `Union` object at a specific offset /// by adding offset to the current position of table /// - Parameter o: offset /// - Returns: A flatbuffers object public func union<T: FlatbuffersInitializable>(_ o: Int32) -> T { let o = o + postion return directUnion(o) } /// Returns a direct `Union` object at a specific offset /// - Parameter o: offset /// - Returns: A flatbuffers object public func directUnion<T: FlatbuffersInitializable>(_ o: Int32) -> T { T.init(bb, o: o + bb.read(def: Int32.self, position: Int(o))) } /// Returns a vector of type T at a specific offset /// This should only be used by `Scalars` /// - Parameter off: Readable offset /// - Returns: Returns a vector of type [T] public func getVector<T>(at off: Int32) -> [T]? { let o = offset(off) guard o != 0 else { return nil } return bb.readSlice(index: Int(vector(at: o)), count: Int(vector(count: o))) } /// Vector count gets the count of Elements within the array /// - Parameter o: start offset of the vector /// - returns: Count of elements public func vector(count o: Int32) -> Int32 { var o = o o += postion o += bb.read(def: Int32.self, position: Int(o)) return bb.read(def: Int32.self, position: Int(o)) } /// Vector start index in the buffer /// - Parameter o:start offset of the vector /// - returns: the start index of the vector public func vector(at o: Int32) -> Int32 { var o = o o += postion return o + bb.read(def: Int32.self, position: Int(o)) + 4 } /// Reading an indirect offset of a table. /// - Parameters: /// - o: position within the buffer /// - fbb: ByteBuffer /// - Returns: table offset static public func indirect(_ o: Int32, _ fbb: ByteBuffer) -> Int32 { o + fbb.read(def: Int32.self, position: Int(o)) } /// Gets a vtable value according to an table Offset and a field offset /// - Parameters: /// - o: offset relative to entire buffer /// - vOffset: Field offset within a vtable /// - fbb: ByteBuffer /// - Returns: an position of a field static public func offset( _ o: Int32, vOffset: Int32, fbb: ByteBuffer) -> Int32 { let vTable = Int32(fbb.capacity) - o return vTable + Int32(fbb.read( def: Int16.self, position: Int(vTable + vOffset - fbb.read( def: Int32.self, position: Int(vTable))))) } /// Compares two objects at offset A and offset B within a ByteBuffer /// - Parameters: /// - off1: first offset to compare /// - off2: second offset to compare /// - fbb: Bytebuffer /// - Returns: returns the difference between static public func compare( _ off1: Int32, _ off2: Int32, fbb: ByteBuffer) -> Int32 { let memorySize = Int32(MemoryLayout<Int32>.size) let _off1 = off1 + fbb.read(def: Int32.self, position: Int(off1)) let _off2 = off2 + fbb.read(def: Int32.self, position: Int(off2)) let len1 = fbb.read(def: Int32.self, position: Int(_off1)) let len2 = fbb.read(def: Int32.self, position: Int(_off2)) let startPos1 = _off1 + memorySize let startPos2 = _off2 + memorySize let minValue = min(len1, len2) for i in 0...minValue { let b1 = fbb.read(def: Int8.self, position: Int(i + startPos1)) let b2 = fbb.read(def: Int8.self, position: Int(i + startPos2)) if b1 != b2 { return Int32(b2 - b1) } } return len1 - len2 } /// Compares two objects at offset A and array of `Bytes` within a ByteBuffer /// - Parameters: /// - off1: Offset to compare to /// - key: bytes array to compare to /// - fbb: Bytebuffer /// - Returns: returns the difference between static public func compare( _ off1: Int32, _ key: [Byte], fbb: ByteBuffer) -> Int32 { let memorySize = Int32(MemoryLayout<Int32>.size) let _off1 = off1 + fbb.read(def: Int32.self, position: Int(off1)) let len1 = fbb.read(def: Int32.self, position: Int(_off1)) let len2 = Int32(key.count) let startPos1 = _off1 + memorySize let minValue = min(len1, len2) for i in 0..<minValue { let b = fbb.read(def: Int8.self, position: Int(i + startPos1)) let byte = key[Int(i)] if b != byte { return Int32(b - Int8(byte)) } } return len1 - len2 } }
apache-2.0
7e7c281b5e3701556f74bbafdb895335
33.9375
83
0.642099
3.645652
false
false
false
false
viWiD/VIAddressBookKit
VIAddressBookKit/Person.swift
1
2096
// // Person.swift // VIOSFramework // // Created by Nils Fischer on 16.08.14. // Copyright (c) 2014 viWiD Webdesign & iOS Development. All rights reserved. // import Foundation import UIKit @objc public class Person: AlphabeticOrdering { // MARK: Public Properties public var firstName: String? public var lastName: String? // MARK: Initializers public init() {} public convenience init(firstName: String?, lastName: String?) { self.init() self.firstName = firstName self.lastName = lastName } // MARK: Computed Properties public var fullName: String? { if firstName == nil { return lastName } else if lastName == nil { return firstName } else { return "\(firstName!) \(lastName!)" } } // TODO: char instead of string? public var leadingLastNameInitial: String? { if lastName != nil && count(lastName!) > 0 { // TODO: use String instead of NSString return (lastName! as NSString).substringToIndex(1).capitalizedString } else if firstName != nil && count(firstName!) > 0 { return (firstName! as NSString).substringToIndex(1).capitalizedString } return nil } public class func leadingLastNameInitial(person: Person) -> String? { return person.leadingLastNameInitial } // MARK: - Comparison public var alphabeticOrderingString: String? { if let alphabeticOrderingString = self.lastName ?? self.firstName ?? nil { // Remove diacritics return "".join(alphabeticOrderingString.decomposedStringWithCanonicalMapping.componentsSeparatedByCharactersInSet(NSCharacterSet.letterCharacterSet().invertedSet)) } else { return nil } } } // MARK: - Printable extension Person: Printable { public var description: String { let unnamedString = "Unnamed Person" return "\(fullName ?? unnamedString)" } }
mit
bf2354da1c65fa35cc439883ab256ae1
24.253012
175
0.607824
5.149877
false
false
false
false
nakau1/Formations
Formations/Sources/Extensions/UIViewController+Common.swift
1
2940
// ============================================================================= // Formations // Copyright 2017 yuichi.nakayasu All rights reserved. // ============================================================================= import UIKit // MARK: - Transfer - extension UIViewController { /// ビューコントローラをプッシュする /// - Parameter viewController: ビューコントローラ func push(_ viewController: UIViewController) { navigationController?.pushViewController(viewController, animated: true) } /// ビューコントローラをポップする func pop() { _ = navigationController?.popViewController(animated: true) } } extension UIViewController { /// ビューコントローラをモーダル表示する /// - Parameters: /// - viewController: ビューコントローラ /// - completion: 完了時処理 func present(_ viewController: UIViewController, completion: (() -> Void)? = nil) { present(viewController, animated: true, completion: completion) } /// モーダル表示している自身を閉じる /// - Parameters: /// - completion: 完了時処理 func dismiss(completion: (() -> Void)? = nil) { dismiss(animated: true, completion: completion) } } // MARK: - Navigation - class NavigationController: UINavigationController { override var prefersStatusBarHidden: Bool { return false } override var preferredStatusBarStyle: UIStatusBarStyle { return .lightContent } } extension UIViewController { var withinNavigation: NavigationController { var vc = self if let navi = vc as? UINavigationController { vc = navi.viewControllers.first! } return NavigationController(rootViewController: vc) } func prepareNavigationBar() { guard let navigationBar = navigationController?.navigationBar else { return } navigationBar.isTranslucent = false navigationBar.barTintColor = #colorLiteral(red: 0.03529411765, green: 0.08235294118, blue: 0.05098039216, alpha: 1) navigationBar.tintColor = #colorLiteral(red: 0.2980392157, green: 0.6588235294, blue: 0.4156862745, alpha: 1) navigationBar.titleTextAttributes = [ NSAttributedStringKey.foregroundColor: #colorLiteral(red: 0.2980392157, green: 0.6588235294, blue: 0.4156862745, alpha: 1), //NSAttributedStringKey.font: UIFont.bold5 ] navigationBar.layer.shadowOffset = CGSize(width: 0, height: 4) navigationBar.layer.shadowOpacity = 0.5 navigationBar.layer.shadowRadius = 2 navigationBar.layer.shadowColor = UIColor.black.cgColor let backButtonItem = UIBarButtonItem(title: "", style: .plain, target: nil, action: nil) navigationItem.backBarButtonItem = backButtonItem } }
apache-2.0
0ba847059d6788fd503d7d987f76c9c1
32.585366
135
0.625635
4.998185
false
false
false
false
FTChinese/iPhoneApp
FT富媒体速递/NotificationService.swift
1
3179
// // NotificationService.swift // FT富媒体速递 // // Created by Oliver Zhang on 2017/5/27. // Copyright © 2017年 Financial Times Ltd. All rights reserved. // import UserNotifications class NotificationService: UNNotificationServiceExtension { var contentHandler: ((UNNotificationContent) -> Void)? var bestAttemptContent: UNMutableNotificationContent? override func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) { self.contentHandler = contentHandler bestAttemptContent = (request.content.mutableCopy() as? UNMutableNotificationContent) if let bestAttemptContent = bestAttemptContent { // Modify the notification content here... // bestAttemptContent.title = "\(bestAttemptContent.title) [modified]" if let urlString = bestAttemptContent.userInfo["media"] as? String { let urlStringFinal: String if urlString.range(of:".jpg") != nil || urlString.range(of:".jpeg") != nil { urlStringFinal = "https://www.ft.com/__origami/service/image/v2/images/raw/\(urlString)?source=ftchinese&width=800&height=450&fit=cover" } else { urlStringFinal = urlString } let fileName: String if let url = URL(string: urlString) { fileName = url.lastPathComponent } else { fileName = "attachment" } // MARK: - Since the extension is already working background, we need to do all this in the main queue if let url = URL(string: urlStringFinal), let data = NSData(contentsOf: url){ let path = NSTemporaryDirectory() + fileName // MARK: - Apple only supports certain types of media formats. If the format is not supported, it will fall back to default notitication. data.write(toFile: path, atomically: true) print ("file downloaded") do { let file = URL(fileURLWithPath: path) let attachment = try UNNotificationAttachment( identifier: "attachment", url:file, options: nil ) bestAttemptContent.attachments = [attachment] } catch { print(error) } } } contentHandler(bestAttemptContent) } } override func serviceExtensionTimeWillExpire() { // Called just before the extension will be terminated by the system. // Use this as an opportunity to deliver your "best attempt" at modified content, otherwise the original push payload will be used. if let contentHandler = contentHandler, let bestAttemptContent = bestAttemptContent { contentHandler(bestAttemptContent) } } }
mit
34ade04a98abc8b6756c372efc6cede0
42.369863
157
0.568541
5.928839
false
false
false
false
qiuncheng/study-for-swift
learn-rx-swift/Chocotastic-starter/Pods/RxCocoa/RxCocoa/Common/Observables/Implementations/ControlTarget.swift
8
2184
// // ControlTarget.swift // RxCocoa // // Created by Krunoslav Zaher on 2/21/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // #if os(iOS) || os(tvOS) || os(OSX) import Foundation #if !RX_NO_MODULE import RxSwift #endif #if os(iOS) || os(tvOS) import UIKit typealias Control = UIKit.UIControl typealias ControlEvents = UIKit.UIControlEvents #elseif os(OSX) import Cocoa typealias Control = Cocoa.NSControl #endif // This should be only used from `MainScheduler` class ControlTarget: RxTarget { typealias Callback = (Control) -> Void let selector: Selector = #selector(ControlTarget.eventHandler(_:)) weak var control: Control? #if os(iOS) || os(tvOS) let controlEvents: UIControlEvents #endif var callback: Callback? #if os(iOS) || os(tvOS) init(control: Control, controlEvents: UIControlEvents, callback: @escaping Callback) { MainScheduler.ensureExecutingOnScheduler() self.control = control self.controlEvents = controlEvents self.callback = callback super.init() control.addTarget(self, action: selector, for: controlEvents) let method = self.method(for: selector) if method == nil { rxFatalError("Can't find method") } } #elseif os(OSX) init(control: Control, callback: @escaping Callback) { MainScheduler.ensureExecutingOnScheduler() self.control = control self.callback = callback super.init() control.target = self control.action = selector let method = self.method(for: selector) if method == nil { rxFatalError("Can't find method") } } #endif func eventHandler(_ sender: Control!) { if let callback = self.callback, let control = self.control { callback(control) } } override func dispose() { super.dispose() #if os(iOS) || os(tvOS) self.control?.removeTarget(self, action: self.selector, for: self.controlEvents) #elseif os(OSX) self.control?.target = nil self.control?.action = nil #endif self.callback = nil } } #endif
mit
3be686c8c11d6b0375185a9a62eb6c62
22.728261
90
0.635822
4.255361
false
false
false
false
spronin/hse-swift-course
HSEProject/NewFlightViewController.swift
1
6509
// // NewFlightViewController.swift // HSEProject // // Created by Sergey Pronin on 3/27/15. // Copyright (c) 2015 Sergey Pronin. All rights reserved. // import UIKit class NewFlightViewController: UIViewController { @IBOutlet weak var textFieldAirline: UITextField! @IBOutlet weak var textFieldNumber: UITextField! @IBOutlet weak var pickerAirline: UIPickerView! @IBOutlet weak var constraintPickerBottom: NSLayoutConstraint! var airlines = [Airline]() var selectedAirline: Airline? override func viewDidLoad() { super.viewDidLoad() pickerAirline.delegate = self pickerAirline.dataSource = self textFieldAirline.delegate = self textFieldNumber.delegate = self pickerAirline.hidden = true } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) airlines = Airline.allAirlines() //!! перезагрузить picker pickerAirline.reloadAllComponents() } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { //при переходе будем скрывать picker pickerAirline.hidden = true //!! подписываемся на события NewAirlineController, если переходим на него //первым там всё равно будет navigation controller if let navController = segue.destinationViewController as? UINavigationController { if let airlineController = navController.viewControllers.first as? NewAirlineViewController { airlineController.delegate = self } } } ///нажатие на "Создать" @IBAction func clickCreate(sender: AnyObject) { if selectedAirline == nil { return } //!! берем текст и обрезаем с обеих сторон переносы строки и проблемы let number = textFieldNumber.text.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()) if count(number) == 0 { return } let flight = Flight() flight.number = number flight.airline = selectedAirline! CoreDataHelper.instance.save() //!! возвращаемся на экран списка рейсов self.navigationController!.popViewControllerAnimated(true) //!! переход на один экран "вверх" в стеке Navigation Controller } func showPicker() { constraintPickerBottom.constant = -pickerAirline.frame.height pickerAirline.hidden = false pickerAirline.layoutIfNeeded() UIView.animateWithDuration(0.3, animations: { self.constraintPickerBottom.constant = 0 self.pickerAirline.layoutIfNeeded() }) } func hidePicker() { UIView.animateWithDuration(0.3, animations: { self.constraintPickerBottom.constant = -self.pickerAirline.frame.height self.pickerAirline.layoutIfNeeded() }, completion: { finished in self.pickerAirline.hidden = true //убрать из иерархии // self.pickerAirline.removeFromSuperview() }) } } extension NewFlightViewController: UIPickerViewDelegate { ///выделение заданной строчки в picker-е func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { selectedAirline = airlines[row] textFieldAirline.text = selectedAirline!.name } } extension NewFlightViewController: UIPickerViewDataSource { ///количество разделов (вертикальных) в picker func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int { return 1 } ///количество строчек в каждом разделе func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { return airlines.count } ///заголовок заданной строчки func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String! { let airline = airlines[row] return airline.name } } extension NewFlightViewController: UITextFieldDelegate { func textFieldShouldBeginEditing(textField: UITextField) -> Bool { //поле авиалинии нельзя редактировать вручную if textField == textFieldAirline { //но следует показать picker pickerAirline.hidden ? showPicker() : hidePicker() //!! выберем первую авиалинию, если она есть, т.к. didSelect не сработает //TODO: попробуйте убрать это и посмотреть, что будет if let airline = airlines.first where selectedAirline == nil { selectedAirline = airline textFieldAirline.text = airline.name } return false } else { return true } } func textFieldDidBeginEditing(textField: UITextField) { if textField == textFieldNumber { //скрываем при выборе номера pickerAirline.hidden = true } } } extension NewFlightViewController: NewAirlineViewControllerDelegate { func airlineController(controller: NewAirlineViewController, didCreateAirline airline: Airline) { //!! убираем модальный контроллер dismissViewControllerAnimated(true, completion: nil) //на самом деле с airline нам здесь делать нечего, т.к. она уже сохранена //lifecycle нашего контроллера вызовет viewWillAppear //и airlines заполнится всеми авиалиниями из базы } func airlineControllerDidCancel(controller: NewAirlineViewController) { //!! убираем модальный контроллер dismissViewControllerAnimated(true, completion: nil) } }
mit
20682d5e46eb078e1cbcd5db97c72375
32.505747
132
0.646998
4.940678
false
false
false
false
zhugejunwei/LeetCode
16. 3Sum Closest.swift
1
599
import Darwin // O(n^2), 68 ms func threeSumClosest(nums: [Int], _ target: Int) -> Int { let nums = nums.sort() var sum = Int.max/2 for i in 0..<nums.count { var tmp = 0 var left = i + 1, right = nums.count - 1 while left < right { tmp = nums[i] + nums[left] + nums[right] if tmp < target { left += 1 }else { right -= 1 } sum = abs(tmp - target) < abs(sum - target) ? tmp : sum } } return sum } let a = [0,1,2], target = 0 threeSumClosest(a, target)
mit
c2a4b3515cd36502b85540a82e8f26a9
21.185185
67
0.459098
3.365169
false
false
false
false
TouchInstinct/LeadKit
Sources/Extensions/TimeInterval/TimeInterval+DateComponents.swift
1
3317
// // Copyright (c) 2017 Touch Instinct // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation extension TimeInterval { private static let secondsInMinute = 60 private static let minutesInHour = 60 private static let hoursInDay = 24 private static let secondsInHour = secondsInMinute * minutesInHour private static let secondsInDay = secondsInHour * hoursInDay public typealias TimeComponents = (days: Int, hours: Int, minutes: Int, seconds: Int) /** Deserialize TimeInterval from string Works fine for values like 0:0, 0:0:0, 000:00:00, 0.00:00:00 - parameter timeString: serialized value - parameter timeSeparator: separator between hours and minutes and seconds - parameter daySeparator: separator between time value and days count value */ public init(timeString: String, timeSeparator: String = ":", daySeparator: String = ".") { let timeComponents = timeString.components(separatedBy: daySeparator) let dayComponent = timeComponents.first ?? "" let fullDays = Double(dayComponent) ?? 0 let timeComponent = timeComponents.last ?? "" let timeValue = timeComponent .components(separatedBy: timeSeparator) .reversed() .enumerated() .reduce(0.0) { interval, part in let partElement = Double(part.element) ?? 0 return interval + partElement * pow(Double(TimeInterval.secondsInMinute), Double(part.offset)) } self = (fullDays * Double(TimeInterval.secondsInDay)) + timeValue } /** Returns a tuple with date components, contained in TimeInterval value Supported components: days, hours, minutes, seconds */ public var timeComponents: TimeComponents { var timeInterval = Int(self) let days = (timeInterval / TimeInterval.secondsInDay) % TimeInterval.secondsInDay timeInterval -= days * TimeInterval.secondsInDay return ( days, (timeInterval / TimeInterval.secondsInHour) % TimeInterval.secondsInHour, (timeInterval / TimeInterval.secondsInMinute) % TimeInterval.secondsInMinute, timeInterval % TimeInterval.secondsInMinute ) } }
apache-2.0
a19459524e6a5348810c8b3329110304
40.4625
110
0.697015
4.856515
false
false
false
false
JarlRyan/IOSNote
Swift/EmptyNavigation/EmptyNavigation/RootViewController.swift
1
1056
// // RootViewController.swift // EmptyNavigation // // Created by bingoogol on 14-6-17. // Copyright (c) 2014年 bingoogol. All rights reserved. // import UIKit class RootViewController : UIViewController,FontSizeChangeDelegate { var myLabel:UILabel? override func viewDidLoad() { super.viewDidLoad() self.title = "首页" let nextButton = UIBarButtonItem(title:"下一页", style: .Plain, target: self, action: "nextPage") self.navigationItem.rightBarButtonItem = nextButton myLabel = UILabel(frame:CGRect(x:100,y:100,width:100,height:50)) myLabel!.text = "字体" self.view.addSubview(myLabel) } func nextPage() { let svc = SecondViewController() svc.delegate = self self.navigationController.pushViewController(svc,animated:true) } func fontSizeDidChange(controller:SecondViewController,fontSize:Int) { println("fontSize:\(fontSize)") myLabel!.font = UIFont.systemFontOfSize(CGFloat(fontSize)) } }
apache-2.0
230f3db1560a540eb148034029293ba4
28.714286
102
0.6625
4.502165
false
false
false
false
GuitarPlayer-Ma/Swiftweibo
weibo/Pods/SnapKit/Source/ConstraintMaker.swift
46
9091
// // SnapKit // // Copyright (c) 2011-2015 SnapKit Team - https://github.com/SnapKit // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. #if os(iOS) import UIKit #else import AppKit #endif /** Used to make constraints */ public class ConstraintMaker { /// left edge public var left: ConstraintDescriptionExtendable { return self.makeConstraintDescription(ConstraintAttributes.Left) } /// top edge public var top: ConstraintDescriptionExtendable { return self.makeConstraintDescription(ConstraintAttributes.Top) } /// right edge public var right: ConstraintDescriptionExtendable { return self.makeConstraintDescription(ConstraintAttributes.Right) } /// bottom edge public var bottom: ConstraintDescriptionExtendable { return self.makeConstraintDescription(ConstraintAttributes.Bottom) } /// leading edge public var leading: ConstraintDescriptionExtendable { return self.makeConstraintDescription(ConstraintAttributes.Leading) } /// trailing edge public var trailing: ConstraintDescriptionExtendable { return self.makeConstraintDescription(ConstraintAttributes.Trailing) } /// width dimension public var width: ConstraintDescriptionExtendable { return self.makeConstraintDescription(ConstraintAttributes.Width) } /// height dimension public var height: ConstraintDescriptionExtendable { return self.makeConstraintDescription(ConstraintAttributes.Height) } /// centerX dimension public var centerX: ConstraintDescriptionExtendable { return self.makeConstraintDescription(ConstraintAttributes.CenterX) } /// centerY dimension public var centerY: ConstraintDescriptionExtendable { return self.makeConstraintDescription(ConstraintAttributes.CenterY) } /// baseline position public var baseline: ConstraintDescriptionExtendable { return self.makeConstraintDescription(ConstraintAttributes.Baseline) } /// firse baseline position @available(iOS 8.0, *) public var firstBaseline: ConstraintDescriptionExtendable { return self.makeConstraintDescription(ConstraintAttributes.FirstBaseline) } /// left margin @available(iOS 8.0, *) public var leftMargin: ConstraintDescriptionExtendable { return self.makeConstraintDescription(ConstraintAttributes.LeftMargin) } /// right margin @available(iOS 8.0, *) public var rightMargin: ConstraintDescriptionExtendable { return self.makeConstraintDescription(ConstraintAttributes.RightMargin) } /// top margin @available(iOS 8.0, *) public var topMargin: ConstraintDescriptionExtendable { return self.makeConstraintDescription(ConstraintAttributes.TopMargin) } /// bottom margin @available(iOS 8.0, *) public var bottomMargin: ConstraintDescriptionExtendable { return self.makeConstraintDescription(ConstraintAttributes.BottomMargin) } /// leading margin @available(iOS 8.0, *) public var leadingMargin: ConstraintDescriptionExtendable { return self.makeConstraintDescription(ConstraintAttributes.LeadingMargin) } /// trailing margin @available(iOS 8.0, *) public var trailingMargin: ConstraintDescriptionExtendable { return self.makeConstraintDescription(ConstraintAttributes.TrailingMargin) } /// centerX within margins @available(iOS 8.0, *) public var centerXWithinMargins: ConstraintDescriptionExtendable { return self.makeConstraintDescription(ConstraintAttributes.CenterXWithinMargins) } /// centerY within margins @available(iOS 8.0, *) public var centerYWithinMargins: ConstraintDescriptionExtendable { return self.makeConstraintDescription(ConstraintAttributes.CenterYWithinMargins) } /// top + left + bottom + right edges public var edges: ConstraintDescriptionExtendable { return self.makeConstraintDescription(ConstraintAttributes.Edges) } /// width + height dimensions public var size: ConstraintDescriptionExtendable { return self.makeConstraintDescription(ConstraintAttributes.Size) } // centerX + centerY positions public var center: ConstraintDescriptionExtendable { return self.makeConstraintDescription(ConstraintAttributes.Center) } // top + left + bottom + right margins @available(iOS 8.0, *) public var margins: ConstraintDescriptionExtendable { return self.makeConstraintDescription(ConstraintAttributes.Margins) } // centerX + centerY within margins @available(iOS 8.0, *) public var centerWithinMargins: ConstraintDescriptionExtendable { return self.makeConstraintDescription(ConstraintAttributes.CenterWithinMargins) } internal init(view: View, file: String, line: UInt) { self.view = view self.file = file self.line = line } internal let file: String internal let line: UInt internal let view: View internal var constraintDescriptions = [ConstraintDescription]() internal func makeConstraintDescription(attributes: ConstraintAttributes) -> ConstraintDescription { let item = ConstraintItem(object: self.view, attributes: attributes) let constraintDescription = ConstraintDescription(fromItem: item) self.constraintDescriptions.append(constraintDescription) return constraintDescription } internal class func prepareConstraints(view view: View, file: String = "Unknown", line: UInt = 0, @noescape closure: (make: ConstraintMaker) -> Void) -> [Constraint] { let maker = ConstraintMaker(view: view, file: file, line: line) closure(make: maker) let constraints = maker.constraintDescriptions.map { $0.constraint } for constraint in constraints { constraint.makerFile = maker.file constraint.makerLine = maker.line } return constraints } internal class func makeConstraints(view view: View, file: String = "Unknown", line: UInt = 0, @noescape closure: (make: ConstraintMaker) -> Void) { view.translatesAutoresizingMaskIntoConstraints = false let maker = ConstraintMaker(view: view, file: file, line: line) closure(make: maker) let constraints = maker.constraintDescriptions.map { $0.constraint as! ConcreteConstraint } for constraint in constraints { constraint.makerFile = maker.file constraint.makerLine = maker.line constraint.installOnView(updateExisting: false) } } internal class func remakeConstraints(view view: View, file: String = "Unknown", line: UInt = 0, @noescape closure: (make: ConstraintMaker) -> Void) { view.translatesAutoresizingMaskIntoConstraints = false let maker = ConstraintMaker(view: view, file: file, line: line) closure(make: maker) self.removeConstraints(view: view) let constraints = maker.constraintDescriptions.map { $0.constraint as! ConcreteConstraint } for constraint in constraints { constraint.makerFile = maker.file constraint.makerLine = maker.line constraint.installOnView(updateExisting: false) } } internal class func updateConstraints(view view: View, file: String = "Unknown", line: UInt = 0, @noescape closure: (make: ConstraintMaker) -> Void) { view.translatesAutoresizingMaskIntoConstraints = false let maker = ConstraintMaker(view: view, file: file, line: line) closure(make: maker) let constraints = maker.constraintDescriptions.map { $0.constraint as! ConcreteConstraint} for constraint in constraints { constraint.makerFile = maker.file constraint.makerLine = maker.line constraint.installOnView(updateExisting: true) } } internal class func removeConstraints(view view: View) { for existingLayoutConstraint in view.snp_installedLayoutConstraints { existingLayoutConstraint.snp_constraint?.uninstall() } } }
mit
b731bcd55470f629d6706f8926abbeb3
45.382653
171
0.724893
5.660648
false
false
false
false
tjnet/MultipleTableViewModernNewsApp
NewsAppSample/SettingsViewController.swift
1
2246
// // SettingsViewController.swift // NewsAppSample // // Created by jun on 2014/11/29. // Copyright (c) 2014年 edu.self. All rights reserved. // import UIKit class SettingsViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { var dataArray: NSArray = NSArray() let paddingTop: CGFloat = 20.0 @IBOutlet weak var tableView: UITableView! override func viewDidLoad() { super.viewDidLoad() self.dataArray = [ ["title": "あとで見る", "icon": "bookmark_icon.png"], ["title": "お知らせ", "icon": "notification_icon.png"], ["title": "スタッフリスト", "icon": "people_icon.png"], ] self.tableView.contentInset = UIEdgeInsetsMake(self.paddingTop, 0, 0, 0) // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int{ return self.dataArray.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell{ // var cell: UITableViewCell = UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: "Cell") var cell:SettingsViewCell = self.tableView.dequeueReusableCellWithIdentifier("cell") as SettingsViewCell var rowData = self.dataArray[indexPath.row] as NSDictionary var title = rowData["title"] as String var image = rowData["icon"] as String // cell.textLabel.text = title cell.titleLabel?.text = title cell.icon?.image = UIImage(named: image) return cell } /* // 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
ca0d8f4eea97dc969463c44c1ffbc9e6
29.30137
116
0.646926
4.872247
false
false
false
false
jdbateman/Lendivine
Lendivine/LoansMapViewController.swift
1
5705
// // LoansMapViewController.swift // Lendivine // // Created by john bateman on 5/22/16. // Copyright © 2016 John Bateman. All rights reserved. // import UIKit import MapKit class LoansMapViewController: MapViewController, UIGestureRecognizerDelegate { //var tapRecognizer: UITapGestureRecognizer? = nil var longPressedRecognizer: UILongPressGestureRecognizer? = nil var annotation: MKAnnotation? var countryName: String? var cityName: String? override func viewDidLoad() { super.viewDidLoad() initTapRecognizer() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) initTapRecognizer() } override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) deinitTapRecognizer() } // MARK: Tap gesture recognizer func initTapRecognizer() { // tapRecognizer = UITapGestureRecognizer(target: self, action:#selector(LoansMapViewController.handleSingleTap(_:))) // // if let tr = tapRecognizer { // tr.numberOfTapsRequired = 1 // self.mapView.addGestureRecognizer(tr) // self.mapView.userInteractionEnabled = true // } longPressedRecognizer = UILongPressGestureRecognizer(target: self, action: #selector(LoansMapViewController.handleLongPressed(_:))) if let lpr = longPressedRecognizer { self.mapView.addGestureRecognizer(lpr) self.mapView.userInteractionEnabled = true } } func deinitTapRecognizer() { // if let tr = self.tapRecognizer { // self.mapView.removeGestureRecognizer(tr) // } if let lpr = self.longPressedRecognizer { self.mapView.removeGestureRecognizer(lpr) } } // User long pressed somewhere on the view. End editing. func handleLongPressed(sender: UILongPressGestureRecognizer) { // clear pins if let annotation = self.annotation { self.mapView.removeAnnotation(annotation) } if let point = longPressedRecognizer?.locationInView(self.mapView) { let tapPoint:CLLocationCoordinate2D = self.mapView.convertPoint(point, toCoordinateFromView: self.mapView) let location = CLLocation(latitude: tapPoint.latitude , longitude: tapPoint.longitude) // add a pin on the map let pin = MKPointAnnotation() pin.coordinate = tapPoint self.mapView.addAnnotation(pin) self.annotation = pin let geocoder = CLGeocoder() geocoder.reverseGeocodeLocation(location) { placemarks, error in if placemarks != nil { if let placemark = placemarks?.first { self.countryName = placemark.country if let city = placemark.addressDictionary!["City"] as? String { self.cityName = city } // show CountryLoans view controller self.presentCountryLoansController() } } else { if (error?.domain == kCLErrorDomain) && (error?.code == 2) { LDAlert(viewController: self).displayErrorAlertView("No Internet Connection", message: "Unable to Search for loans in the selected country.") } else { self.showAlert() } } } } } // func handleSingleTap(recognizer: UITapGestureRecognizer) { // print("single tap") // } // MARK: Navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "LoansMapToCountryLoans" { let controller = segue.destinationViewController as! CountryLoansTableViewController let activityIndicator = DVNActivityIndicator() activityIndicator.startActivityIndicator(self.view) var theCountry: Country? if let countries = DVNCountries.sharedInstance().fetchCountriesFilteredByNameOn(self.countryName) as? [Country] { theCountry = countries.first } controller.country = theCountry activityIndicator.stopActivityIndicator() } } /* Modally present the MapViewController on the main thread. */ func presentCountryLoansController() { dispatch_async(dispatch_get_main_queue()) { self.performSegueWithIdentifier("LoansMapToCountryLoans", sender: self) } } // MARK: Helpers func showAlert() { let alertController = UIAlertController(title: "Country Not Found", message: "Zoom in and try again.\n\nHint: Tap near the center of the country." , preferredStyle: .Alert) let cancelAction = UIAlertAction(title: "Ok", style: UIAlertActionStyle.Cancel) { UIAlertAction in // do nothing } alertController.addAction(cancelAction) self.presentViewController(alertController, animated: true, completion: nil) } }
mit
16eae605a2512ab43fb541946345c147
32.552941
180
0.582048
5.850256
false
false
false
false
ngageoint/mage-ios
MageTests/Mocks/MockObservationEditCardDelegate.swift
1
2464
// // MockObservationDelegate.swift // MAGETests // // Created by Daniel Barela on 11/5/20. // Copyright © 2020 National Geospatial Intelligence Agency. All rights reserved. // import Foundation @testable import MAGE class MockObservationEditCardDelegate: ObservationEditCardDelegate, FieldSelectionDelegate, ObservationEditListener { var addVoiceAttachmentCalled = false; var addVideoAttachmentCalled = false; var addCameraAttachmentCalled = false; var addGalleryAttachmentCalled = false; var deleteObservationCalled = false; var fieldSelectedCalled = false; var attachmentSelectedCalled = false; var addFormCalled = false; var saveObservationCalled = false; var cancelEditCalled = false; var launchFieldSelectionViewControllerCalled = false; var viewControllerToLaunch: UIViewController?; var reorderFormsCalled = false; var selectedAttachment: Attachment?; var selectedField: [String : Any]?; var selectedFieldCurrentValue: Any?; var observationSaved: Observation?; func addVoiceAttachment() { addVoiceAttachmentCalled = true; } func addVideoAttachment() { addVideoAttachmentCalled = true; } func addCameraAttachment() { addCameraAttachmentCalled = true; } func addGalleryAttachment() { addGalleryAttachmentCalled = true; } func deleteObservation() { deleteObservationCalled = true; } func fieldSelected(field: [String : Any], currentValue: Any?) { fieldSelectedCalled = true; selectedField = field; } func attachmentSelected(attachment: Attachment) { attachmentSelectedCalled = true; selectedAttachment = attachment; } func addForm() { addFormCalled = true; } func saveObservation(observation: Observation) { saveObservationCalled = true; observationSaved = observation; } func cancelEdit() { cancelEditCalled = true; } func reorderForms(observation: Observation) { print("reorder forms called") reorderFormsCalled = true; } func fieldValueChanged(_ field: [String : Any], value: Any?) { } func launchFieldSelectionViewController(viewController: UIViewController) { launchFieldSelectionViewControllerCalled = true; viewControllerToLaunch = viewController; } }
apache-2.0
7518bd378745eabc7717bea46d4069f2
26.366667
117
0.677223
5.285408
false
false
false
false
lukaszwas/mcommerce-api
Sources/App/Controllers/ProductController.swift
1
3748
import Vapor import HTTP // /products final class ProductController { // Routes func makeRoutes(routes: RouteBuilder) { let group = routes.grouped("products") group.get(handler: getAllProducts) group.get(Product.parameter, handler: getProductWithId) group.post(handler: createProduct) group.delete(Product.parameter, handler: deleteProduct) group.patch(Product.parameter, handler: updateProduct) group.get("category", Category.parameter, handler: getProductsWithCategory) group.get("recommended", handler: getRecommendedProducts) group.get("search", String.parameter, handler: searchProducts) } // METHODS // GET / // Get all products func getAllProducts(req: Request) throws -> ResponseRepresentable { return try Product.all().makeJSON() } // GET /:id // Get product with id func getProductWithId(req: Request) throws -> ResponseRepresentable { let product = try req.parameters.next(Product.self).makeJSONWithDetails() return product } // POST / // Create product func createProduct(req: Request) throws -> ResponseRepresentable { let product = try req.product() try product.save() return product } // DELETE /:id // Delete product with id func deleteProduct(req: Request) throws -> ResponseRepresentable { let product = try req.parameters.next(Product.self) try product.delete() return Response(status: .ok) } // PATCH /:id // Update product func updateProduct(req: Request) throws -> ResponseRepresentable { let product = try req.parameters.next(Product.self) try product.update(for: req) try product.save() return product } // GET /category/:id // Get products with category id func getProductsWithCategory(req: Request) throws -> ResponseRepresentable { let category = try req.parameters.next(Category.self) let childCategories = try Category.makeQuery().filter(Category.parentIdKey, .equals, category.id).all() var childCategoriesIds: [Int] = [(category.id?.int)!] for category in childCategories { childCategoriesIds.append((category.id?.int)!) } return try Product.makeQuery().or({ orGroup in for id in childCategoriesIds { try orGroup.filter(Product.categoryIdKey, id) } }).all().makeJSON() } // GET /recommended // Get recommended products func getRecommendedProducts(req: Request) throws -> ResponseRepresentable { let categories = try Category.makeQuery().join(kind: .inner, Product.self, baseKey: Category.idKey, joinedKey: Product.categoryIdKey).filter(Product.self, Product.recommendedKey, true).all() var categoriesJson: [JSON] = [] for category in categories { categoriesJson.append(try category.makeJSONWithProducts()) } var json = JSON() try json.set("recommended", categoriesJson) return json } // GET /search/:filter // Search products func searchProducts(req: Request) throws -> ResponseRepresentable { let filter = try req.parameters.next(String.self) return try Product.makeQuery().filter("name", .contains, filter).all().makeJSON() } } // Deserialize JSON extension Request { func product() throws -> Product { guard let json = json else { throw Abort.badRequest } return try Product(json: json) } } extension ProductController: EmptyInitializable { }
mit
e528ba2bec4c709ee3a8f14c9de086dd
31.591304
198
0.632337
4.836129
false
false
false
false
iOSDevLog/iOSDevLog
223-227. SelfSizingTabelViewCells/selfSizingCells/TableViewController.swift
1
2391
// // TableViewController.swift // selfSizingCells // // Created by iosdevlog on 15/12/8. // Copyright © 2015年 iosdevlog. All rights reserved. // import UIKit import Alamofire import SwiftyJSON import AlamofireImage import DZNEmptyDataSet class TableViewController: UITableViewController, DZNEmptyDataSetSource { var photos = [JSON]() override func viewDidLoad() { super.viewDidLoad() self.tableView.estimatedRowHeight = 60 self.tableView.rowHeight = UITableViewAutomaticDimension self.tableView.separatorStyle = .None Alamofire.request(.GET, "https://api.500px.com/v1/photos", parameters:["consumer_key":"uBuwcKGa9ktzoZQtGKI9otnF7yDlJBFQ9fCTHkHc"]).responseJSON() { jsonData in let data = JSON(data: jsonData.data!) self.photos = data["photos"].arrayValue self.tableView.separatorStyle = .SingleLine self.tableView.reloadData() } } // MARK: - Table view data source override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.photos.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath) as! TableViewCell // Configure the cell... let cellData = self.photos[indexPath.row].dictionaryValue let image_url = cellData["image_url"]?.stringValue let URL = NSURL(string:image_url!)! let placeholderImage = UIImage(named: "Earth")! cell.pxImageView.af_setImageWithURL(URL, placeholderImage: placeholderImage) cell.pxLabel.text = cellData["description"]?.stringValue return cell } //MARK: - DZNEmptyDataSetSource func titleForEmptyDataSet(scrollView: UIScrollView!) -> NSAttributedString! { return NSAttributedString(string: "Wait a minute...") } func imageForEmptyDataSet(scrollView: UIScrollView!) -> UIImage! { return UIImage(named: "Earth") } func descriptionForEmptyDataSet(scrollView: UIScrollView!) -> NSAttributedString! { return NSAttributedString(string: "Do you want beautiful photos ?\nLet's Go!") } }
mit
9e8b5736c5fd8b6730614ad144bbaad4
32.633803
155
0.670436
5.091684
false
false
false
false
nickqiao/NKBill
NKBill/Model/NKAccount.swift
1
863
// // NKAccount.swift // NKBill // // Created by nick on 16/1/30. // Copyright © 2016年 NickChen. All rights reserved. // import UIKit import RealmSwift enum TimeType: String { case MONTH case DAY } enum RepayType:String { case AverageCapital case InterestByMonth case InterestByDay case RepayAllAtLast } class NKAccount: Object { dynamic var id = "" dynamic var platform: NKPlatform! dynamic var invest = 0 dynamic var rate = 0.0 dynamic var timeSpan = 0 dynamic var created: NSDate = NSDate(timeIntervalSinceNow: 0.0) let items = List<NKItem>() dynamic var desc = "" dynamic var timeType = TimeType.MONTH.rawValue dynamic var repayType = RepayType.AverageCapital.rawValue override static func primaryKey() -> String? { return "id" } }
apache-2.0
510929f5e9bd8ae9aa3ea8f5f127e60c
17.297872
67
0.647674
3.944954
false
false
false
false
kingwangboss/OneJWeiBo
OneJWeiBo/OneJWeiBo/Classes/Home(首页)/PhotoBrowser/PhotoBrowserAnimator.swift
1
4062
// // PhotoBrowserAnimator.swift // OneJWeiBo // // Created by One'J on 16/4/16. // Copyright © 2016年 One'J. All rights reserved. // import UIKit // 面向协议开发 protocol AnimatorPresentedDelegate : NSObjectProtocol { func startRect(indexPath : NSIndexPath) -> CGRect func endRect(indexPath : NSIndexPath) -> CGRect func imageView(indexPath : NSIndexPath) -> UIImageView } protocol AnimatorDismissDelegate : NSObjectProtocol { func indexPathForDimissView() -> NSIndexPath func imageViewForDimissView() -> UIImageView } class PhotoBrowserAnimator: NSObject { var isPresented : Bool = false var dismissDelegate : AnimatorDismissDelegate? var presentedDelegate : AnimatorPresentedDelegate? var indexPath : NSIndexPath? } extension PhotoBrowserAnimator : UIViewControllerTransitioningDelegate { func animationControllerForPresentedController(presented: UIViewController, presentingController presenting: UIViewController, sourceController source: UIViewController) -> UIViewControllerAnimatedTransitioning? { isPresented = true return self } func animationControllerForDismissedController(dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? { isPresented = false return self } } extension PhotoBrowserAnimator : UIViewControllerAnimatedTransitioning { func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval { return 0.5 } func animateTransition(transitionContext: UIViewControllerContextTransitioning) { isPresented ? animationForPresentedView(transitionContext) : animationForDismissView(transitionContext) } func animationForPresentedView(transitionContext: UIViewControllerContextTransitioning) { // 0.nil值校验 guard let presentedDelegate = presentedDelegate, indexPath = indexPath else { return } // 1.取出弹出的View let presentedView = transitionContext.viewForKey(UITransitionContextToViewKey)! // 2.将prensentedView添加到containerView中 transitionContext.containerView()?.addSubview(presentedView) // 3.获取执行动画的imageView let startRect = presentedDelegate.startRect(indexPath) let imageView = presentedDelegate.imageView(indexPath) transitionContext.containerView()?.addSubview(imageView) imageView.frame = startRect // 4.执行动画 presentedView.alpha = 0.0 transitionContext.containerView()?.backgroundColor = UIColor.blackColor() UIView.animateWithDuration(transitionDuration(transitionContext), animations: { () -> Void in imageView.frame = presentedDelegate.endRect(indexPath) }) { (_) -> Void in imageView.removeFromSuperview() presentedView.alpha = 1.0 transitionContext.containerView()?.backgroundColor = UIColor.clearColor() transitionContext.completeTransition(true) } } func animationForDismissView(transitionContext: UIViewControllerContextTransitioning) { // nil值校验 guard let dismissDelegate = dismissDelegate, presentedDelegate = presentedDelegate else { return } // 1.取出消失的View let dismissView = transitionContext.viewForKey(UITransitionContextFromViewKey) dismissView?.removeFromSuperview() // 2.获取执行动画的ImageView let imageView = dismissDelegate.imageViewForDimissView() transitionContext.containerView()?.addSubview(imageView) let indexPath = dismissDelegate.indexPathForDimissView() // 3.执行动画 UIView.animateWithDuration(transitionDuration(transitionContext), animations: { () -> Void in imageView.frame = presentedDelegate.startRect(indexPath) }) { (_) -> Void in transitionContext.completeTransition(true) } } }
apache-2.0
304a0c7f5cd4469897d9c02a58870ec2
36.377358
217
0.706387
6.347756
false
false
false
false
airspeedswift/swift
validation-test/Reflection/existentials.swift
4
22923
// RUN: %empty-directory(%t) // RUN: %target-build-swift -lswiftSwiftReflectionTest %s -o %t/existentials // RUN: %target-codesign %t/existentials // RUN: %target-run %target-swift-reflection-test %t/existentials | %FileCheck %s --check-prefix=CHECK-%target-ptrsize %add_num_extra_inhabitants // REQUIRES: reflection_test_support // REQUIRES: executable_test // UNSUPPORTED: use_os_stdlib /* This file pokes at the swift_reflection_projectExistential API of the SwiftRemoteMirror library. It tests the three conditions of existential layout: - Class existentials - Existentials whose contained type fits in the 3-word buffer - Existentials whose contained type has to be allocated into a raw heap buffer. - Error existentials, a.k.a. `Error`. - See also: SwiftReflectionTest.reflect(any:) - See also: SwiftReflectionTest.reflect(error:) */ import SwiftReflectionTest class MyClass<T, U> { let x: T let y: (T, U) init(x: T, y: (T, U)) { self.x = x self.y = y } } struct MyStruct<T, U, V> { let x: T let y: U let z: V } protocol MyProtocol {} protocol MyErrorProtocol : Error {} struct MyError : MyProtocol, Error { let i = 0xFEDCBA } struct MyCustomError : MyProtocol, MyErrorProtocol {} struct HasError { let singleError: Error let errorInComposition: MyProtocol & Error let customError: MyErrorProtocol let customErrorInComposition: MyErrorProtocol & MyProtocol } // This will be projected as a class existential, so its // size doesn't matter. var mc = MyClass(x: 1010, y: (2020, 3030)) reflect(any: mc) // CHECK-64: Reflecting an existential. // CHECK-64: Instance pointer in child address space: 0x{{[0-9a-fA-F]+}} // CHECK-64: Type reference: // CHECK-64: (bound_generic_class existentials.MyClass // CHECK-64-NEXT: (struct Swift.Int) // CHECK-64-NEXT: (struct Swift.Int)) // CHECK-64: Type info: // CHECK-64: (reference kind=strong refcounting=native) // CHECK-64: Mangled name: $s12existentials7MyClassCyS2iG // CHECK-64: Demangled name: existentials.MyClass<Swift.Int, Swift.Int> // CHECK-32: Reflecting an existential. // CHECK-32: Instance pointer in child address space: 0x{{[0-9a-fA-F]+}} // CHECK-32: Type reference: // CHECK-32: (bound_generic_class existentials.MyClass // CHECK-32-NEXT: (struct Swift.Int) // CHECK-32-NEXT: (struct Swift.Int)) // CHECK-32: Type info: // CHECK-32: (reference kind=strong refcounting=native) // CHECK-32: Mangled name: $s12existentials7MyClassCyS2iG // CHECK-32: Demangled name: existentials.MyClass<Swift.Int, Swift.Int> // This value fits in the 3-word buffer in the container. var smallStruct = MyStruct(x: 1, y: 2, z: 3) reflect(any: smallStruct) // CHECK-64: Reflecting an existential. // CHECK-64: Instance pointer in child address space: 0x{{[0-9a-fA-F]+}} // CHECK-64: Type reference: // CHECK-64: (bound_generic_struct existentials.MyStruct // CHECK-64-NEXT: (struct Swift.Int) // CHECK-64-NEXT: (struct Swift.Int) // CHECK-64-NEXT: (struct Swift.Int)) // CHECK-64: Type info: // CHECK-64: (struct size=24 alignment=8 stride=24 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-64-NEXT: (field name=x offset=0 // CHECK-64-NEXT: (struct size=8 alignment=8 stride=8 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-64-NEXT: (field name=_value offset=0 // CHECK-64-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=0 bitwise_takable=1)))) // CHECK-64-NEXT: (field name=y offset=8 // CHECK-64-NEXT: (struct size=8 alignment=8 stride=8 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-64-NEXT: (field name=_value offset=0 // CHECK-64-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=0 bitwise_takable=1)))) // CHECK-64-NEXT: (field name=z offset=16 // CHECK-64-NEXT: (struct size=8 alignment=8 stride=8 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-64-NEXT: (field name=_value offset=0 // CHECK-64-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=0 bitwise_takable=1))))) // CHECK-64-NEXT: Mangled name: $s12existentials8MyStructVyS3iG // CHECK-64-NEXT: Demangled name: existentials.MyStruct<Swift.Int, Swift.Int, Swift.Int> // CHECK-32: Reflecting an existential. // CHECK-32: Instance pointer in child address space: 0x{{[0-9a-fA-F]+}} // CHECK-32: Type reference: // CHECK-32: (bound_generic_struct existentials.MyStruct // CHECK-32-NEXT: (struct Swift.Int) // CHECK-32-NEXT: (struct Swift.Int) // CHECK-32-NEXT: (struct Swift.Int)) // CHECK-32: Type info: // CHECK-32: (struct size=12 alignment=4 stride=12 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-32-NEXT: (field name=x offset=0 // CHECK-32-NEXT: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-32-NEXT: (field name=_value offset=0 // CHECK-32-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=0 bitwise_takable=1)))) // CHECK-32-NEXT: (field name=y offset=4 // CHECK-32-NEXT: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-32-NEXT: (field name=_value offset=0 // CHECK-32-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=0 bitwise_takable=1)))) // CHECK-32-NEXT: (field name=z offset=8 // CHECK-32-NEXT: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-32-NEXT: (field name=_value offset=0 // CHECK-32-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=0 bitwise_takable=1))))) // CHECK-32-NEXT: Mangled name: $s12existentials8MyStructVyS3iG // CHECK-32-NEXT: Demangled name: existentials.MyStruct<Swift.Int, Swift.Int, Swift.Int> // This value will be copied into a heap buffer, with a // pointer to it in the existential. var largeStruct = MyStruct(x: (1,1,1), y: (2,2,2), z: (3,3,3)) reflect(any: largeStruct) // CHECK-64: Reflecting an existential. // CHECK-64: Instance pointer in child address space: 0x{{[0-9a-fA-F]+}} // CHECK-64: Type reference: // CHECK-64: (bound_generic_struct existentials.MyStruct // CHECK-64-NEXT: (tuple // CHECK-64-NEXT: (struct Swift.Int) // CHECK-64-NEXT: (struct Swift.Int) // CHECK-64-NEXT: (struct Swift.Int)) // CHECK-64-NEXT: (tuple // CHECK-64-NEXT: (struct Swift.Int) // CHECK-64-NEXT: (struct Swift.Int) // CHECK-64-NEXT: (struct Swift.Int)) // CHECK-64-NEXT: (tuple // CHECK-64-NEXT: (struct Swift.Int) // CHECK-64-NEXT: (struct Swift.Int) // CHECK-64-NEXT: (struct Swift.Int))) // CHECK-64: Type info: // CHECK-64-NEXT: (struct size=72 alignment=8 stride=72 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-64-NEXT: (field name=x offset=0 // CHECK-64-NEXT: (tuple size=24 alignment=8 stride=24 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-64-NEXT: (field offset=0 // CHECK-64-NEXT: (struct size=8 alignment=8 stride=8 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-64-NEXT: (field name=_value offset=0 // CHECK-64-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=0 bitwise_takable=1)))) // CHECK-64-NEXT: (field offset=8 // CHECK-64-NEXT: (struct size=8 alignment=8 stride=8 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-64-NEXT: (field name=_value offset=0 // CHECK-64-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=0 bitwise_takable=1)))) // CHECK-64-NEXT: (field offset=16 // CHECK-64-NEXT: (struct size=8 alignment=8 stride=8 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-64-NEXT: (field name=_value offset=0 // CHECK-64-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=0 bitwise_takable=1)))))) // CHECK-64-NEXT: (field name=y offset=24 // CHECK-64-NEXT: (tuple size=24 alignment=8 stride=24 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-64-NEXT: (field offset=0 // CHECK-64-NEXT: (struct size=8 alignment=8 stride=8 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-64-NEXT: (field name=_value offset=0 // CHECK-64-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=0 bitwise_takable=1)))) // CHECK-64-NEXT: (field offset=8 // CHECK-64-NEXT: (struct size=8 alignment=8 stride=8 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-64-NEXT: (field name=_value offset=0 // CHECK-64-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=0 bitwise_takable=1)))) // CHECK-64-NEXT: (field offset=16 // CHECK-64-NEXT: (struct size=8 alignment=8 stride=8 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-64-NEXT: (field name=_value offset=0 // CHECK-64-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=0 bitwise_takable=1)))))) // CHECK-64-NEXT: (field name=z offset=48 // CHECK-64-NEXT: (tuple size=24 alignment=8 stride=24 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-64-NEXT: (field offset=0 // CHECK-64-NEXT: (struct size=8 alignment=8 stride=8 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-64-NEXT: (field name=_value offset=0 // CHECK-64-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=0 bitwise_takable=1)))) // CHECK-64-NEXT: (field offset=8 // CHECK-64-NEXT: (struct size=8 alignment=8 stride=8 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-64-NEXT: (field name=_value offset=0 // CHECK-64-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=0 bitwise_takable=1)))) // CHECK-64-NEXT: (field offset=16 // CHECK-64-NEXT: (struct size=8 alignment=8 stride=8 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-64-NEXT: (field name=_value offset=0 // CHECK-64-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=0 bitwise_takable=1))))))) // CHECK-64-NEXT: Mangled name: $s12existentials8MyStructVySi_S2itSi_S2itSi_S2itG // CHECK-64-NEXT: Demangled name: existentials.MyStruct<(Swift.Int, Swift.Int, Swift.Int), (Swift.Int, Swift.Int, Swift.Int), (Swift.Int, Swift.Int, Swift.Int)> // CHECK-32: Reflecting an existential. // CHECK-32: Instance pointer in child address space: 0x{{[0-9a-fA-F]+}} // CHECK-32: Type reference: // CHECK-32: (bound_generic_struct existentials.MyStruct // CHECK-32-NEXT: (tuple // CHECK-32-NEXT: (struct Swift.Int) // CHECK-32-NEXT: (struct Swift.Int) // CHECK-32-NEXT: (struct Swift.Int)) // CHECK-32-NEXT: (tuple // CHECK-32-NEXT: (struct Swift.Int) // CHECK-32-NEXT: (struct Swift.Int) // CHECK-32-NEXT: (struct Swift.Int)) // CHECK-32-NEXT: (tuple // CHECK-32-NEXT: (struct Swift.Int) // CHECK-32-NEXT: (struct Swift.Int) // CHECK-32-NEXT: (struct Swift.Int))) // CHECK-32: Type info: // CHECK-32: (struct size=36 alignment=4 stride=36 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-32-NEXT: (field name=x offset=0 // CHECK-32-NEXT: (tuple size=12 alignment=4 stride=12 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-32-NEXT: (field offset=0 // CHECK-32-NEXT: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-32-NEXT: (field name=_value offset=0 // CHECK-32-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=0 bitwise_takable=1)))) // CHECK-32-NEXT: (field offset=4 // CHECK-32-NEXT: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-32-NEXT: (field name=_value offset=0 // CHECK-32-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=0 bitwise_takable=1)))) // CHECK-32-NEXT: (field offset=8 // CHECK-32-NEXT: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-32-NEXT: (field name=_value offset=0 // CHECK-32-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=0 bitwise_takable=1)))))) // CHECK-32-NEXT: (field name=y offset=12 // CHECK-32-NEXT: (tuple size=12 alignment=4 stride=12 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-32-NEXT: (field offset=0 // CHECK-32-NEXT: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-32-NEXT: (field name=_value offset=0 // CHECK-32-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=0 bitwise_takable=1)))) // CHECK-32-NEXT: (field offset=4 // CHECK-32-NEXT: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-32-NEXT: (field name=_value offset=0 // CHECK-32-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=0 bitwise_takable=1)))) // CHECK-32-NEXT: (field offset=8 // CHECK-32-NEXT: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-32-NEXT: (field name=_value offset=0 // CHECK-32-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=0 bitwise_takable=1)))))) // CHECK-32-NEXT: (field name=z offset=24 // CHECK-32-NEXT: (tuple size=12 alignment=4 stride=12 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-32-NEXT: (field offset=0 // CHECK-32-NEXT: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-32-NEXT: (field name=_value offset=0 // CHECK-32-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=0 bitwise_takable=1)))) // CHECK-32-NEXT: (field offset=4 // CHECK-32-NEXT: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-32-NEXT: (field name=_value offset=0 // CHECK-32-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=0 bitwise_takable=1)))) // CHECK-32-NEXT: (field offset=8 // CHECK-32-NEXT: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-32-NEXT: (field name=_value offset=0 // CHECK-32-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=0 bitwise_takable=1))))))) // CHECK-32-NEXT: Mangled name: $s12existentials8MyStructVySi_S2itSi_S2itSi_S2itG // CHECK-32-NEXT: Demangled name: existentials.MyStruct<(Swift.Int, Swift.Int, Swift.Int), (Swift.Int, Swift.Int, Swift.Int), (Swift.Int, Swift.Int, Swift.Int)> // Function type: reflect(any: {largeStruct}) // CHECK-64: Mangled name: $s12existentials8MyStructVySi_S2itSi_S2itSi_S2itGyc // CHECK-64: Demangled name: () -> existentials.MyStruct<(Swift.Int, Swift.Int, Swift.Int), (Swift.Int, Swift.Int, Swift.Int), (Swift.Int, Swift.Int, Swift.Int)> // CHECK-32: Mangled name: $s12existentials8MyStructVySi_S2itSi_S2itSi_S2itGyc // CHECK-32: Demangled name: () -> existentials.MyStruct<(Swift.Int, Swift.Int, Swift.Int), (Swift.Int, Swift.Int, Swift.Int), (Swift.Int, Swift.Int, Swift.Int)> // Protocol composition: protocol P {} protocol Q {} protocol Composition : P, Q {} struct S : Composition {} func getComposition() -> P & Q { return S() } reflect(any: getComposition()) // CHECK-64: Mangled name: $s12existentials1PP_AA1QPp // CHECK-64: Demangled name: existentials.P & existentials.Q // CHECK-32: Mangled name: $s12existentials1PP_AA1QPp // CHECK-32: Demangled name: existentials.P & existentials.Q // Metatype: reflect(any: Int.self) // CHECK-64: Mangled name: $sSim // CHECK-64: Demangled name: Swift.Int.Type // CHECK-32: Mangled name: $sSim // CHECK-32: Demangled name: Swift.Int.Type protocol WithType { associatedtype T func f() -> T } struct S1 : WithType { typealias T = Int func f() -> Int { return 0 } } func getWithType<T>(_ t: T) where T: WithType { reflect(any: T.self) } getWithType(S1()) var he = HasError(singleError: MyError(), errorInComposition: MyError(), customError: MyCustomError(), customErrorInComposition: MyCustomError()) reflect(any: he) // CHECK-64: Reflecting an existential. // CHECK-64: Instance pointer in child address space: 0x{{[0-9a-fA-F+]}} // CHECK-64: Type reference: // CHECK-64: (struct existentials.HasError) // CHECK-64: Type info: // CHECK-64: (struct size=144 alignment=8 stride=144 // CHECK-64-NEXT: (field name=singleError offset=0 // CHECK-64-NEXT: (error_existential size=8 alignment=8 stride=8 num_extra_inhabitants=[[#num_extra_inhabitants_64bit]] bitwise_takable=1 // CHECK-64-NEXT: (field name=error offset=0 // CHECK-64-NEXT: (reference kind=strong refcounting=unknown)))) // CHECK-64-NEXT: (field name=errorInComposition offset=8 // CHECK-64-NEXT: (opaque_existential size=48 alignment=8 stride=48 num_extra_inhabitants=[[#num_extra_inhabitants_64bit]] bitwise_takable=1 // CHECK-64-NEXT: (field name=metadata offset=24 // CHECK-64-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=[[#num_extra_inhabitants_64bit]] bitwise_takable=1)) // CHECK-64-NEXT: (field name=wtable offset=32 // CHECK-64-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=1 bitwise_takable=1)) // CHECK-64-NEXT: (field name=wtable offset=40 // CHECK-64-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=1 bitwise_takable=1)))) // CHECK-64-NEXT: (field name=customError offset=56 // CHECK-64-NEXT: (opaque_existential size=40 alignment=8 stride=40 num_extra_inhabitants=[[#num_extra_inhabitants_64bit]] bitwise_takable=1 // CHECK-64-NEXT: (field name=metadata offset=24 // CHECK-64-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=[[#num_extra_inhabitants_64bit]] bitwise_takable=1)) // CHECK-64-NEXT: (field name=wtable offset=32 // CHECK-64-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=1 bitwise_takable=1)))) // CHECK-64-NEXT: (field name=customErrorInComposition offset=96 // CHECK-64-NEXT: (opaque_existential size=48 alignment=8 stride=48 num_extra_inhabitants=[[#num_extra_inhabitants_64bit]] bitwise_takable=1 // CHECK-64-NEXT: (field name=metadata offset=24 // CHECK-64-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=[[#num_extra_inhabitants_64bit]] bitwise_takable=1)) // CHECK-64-NEXT: (field name=wtable offset=32 // CHECK-64-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=1 bitwise_takable=1)) // CHECK-64-NEXT: (field name=wtable offset=40 // CHECK-64-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=1 bitwise_takable=1))))) // CHECK-64-NEXT: Mangled name: $s12existentials8HasErrorV // CHECK-64-NEXT: Demangled name: existentials.HasError // CHECK-32: Reflecting an existential. // CHECK-32: Instance pointer in child address space: 0x{{[0-9a-fA-F]+}} // CHECK-32: Type reference: // CHECK-32: (struct existentials.HasError) // CHECK-32: Type info: // CHECK-32: (struct size=72 alignment=4 stride=72 num_extra_inhabitants=4096 bitwise_takable=1 // CHECK-32-NEXT: (field name=singleError offset=0 // CHECK-32-NEXT: (error_existential size=4 alignment=4 stride=4 num_extra_inhabitants=4096 bitwise_takable=1 // CHECK-32-NEXT: (field name=error offset=0 // CHECK-32-NEXT: (reference kind=strong refcounting=unknown)))) // CHECK-32-NEXT: (field name=errorInComposition offset=4 // CHECK-32-NEXT: (opaque_existential size=24 alignment=4 stride=24 num_extra_inhabitants=4096 bitwise_takable=1 // CHECK-32-NEXT: (field name=metadata offset=12 // CHECK-32-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=4096 bitwise_takable=1)) // CHECK-32-NEXT: (field name=wtable offset=16 // CHECK-32-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=1 bitwise_takable=1)) // CHECK-32-NEXT: (field name=wtable offset=20 // CHECK-32-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=1 bitwise_takable=1)))) // CHECK-32-NEXT: (field name=customError offset=28 // CHECK-32-NEXT: (opaque_existential size=20 alignment=4 stride=20 num_extra_inhabitants=4096 bitwise_takable=1 // CHECK-32-NEXT: (field name=metadata offset=12 // CHECK-32-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=4096 bitwise_takable=1)) // CHECK-32-NEXT: (field name=wtable offset=16 // CHECK-32-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=1 bitwise_takable=1)))) // CHECK-32-NEXT: (field name=customErrorInComposition offset=48 // CHECK-32-NEXT: (opaque_existential size=24 alignment=4 stride=24 num_extra_inhabitants=4096 bitwise_takable=1 // CHECK-32-NEXT: (field name=metadata offset=12 // CHECK-32-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=4096 bitwise_takable=1)) // CHECK-32-NEXT: (field name=wtable offset=16 // CHECK-32-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=1 bitwise_takable=1)) // CHECK-32-NEXT: (field name=wtable offset=20 // CHECK-32-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=1 bitwise_takable=1))))) // CHECK-32-NEXT: Mangled name: $s12existentials8HasErrorV // CHECK-32-NEXT: Demangled name: existentials.HasError reflect(error: MyError()) // CHECK-64: Reflecting an error existential. // CHECK-64: Instance pointer in child address space: 0x{{[0-9a-fA-F]+}} // CHECK-64: Type reference: // CHECK-64: (struct existentials.MyError) // CHECK-64: Type info: // CHECK-64: (struct size=8 alignment=8 stride=8 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-64-NEXT: (field name=i offset=0 // CHECK-64-NEXT: (struct size=8 alignment=8 stride=8 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-64-NEXT: (field name=_value offset=0 // CHECK-64-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=0 bitwise_takable=1))))) // CHECK-64-NEXT: Mangled name: $s12existentials7MyErrorV // CHECK-64-NEXT: Demangled name: existentials.MyError // CHECK-32: Reflecting an error existential. // CHECK-32: Instance pointer in child address space: 0x{{[0-9a-fA-F]+}} // CHECK-32: Type reference: // CHECK-32: (struct existentials.MyError) // CHECK-32: Type info: // CHECK-32: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-32-NEXT: (field name=i offset=0 // CHECK-32-NEXT: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-32-NEXT: (field name=_value offset=0 // CHECK-32-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=0 bitwise_takable=1))))) // CHECK-32-NEXT: Mangled name: $s12existentials7MyErrorV // CHECK-32-NEXT: Demangled name: existentials.MyError doneReflecting()
apache-2.0
7502bde542180bb30b1915e468d3847e
54.236145
162
0.68573
3.217263
false
false
false
false
angelopino/APJExtensions
Source/UIWindow+extension.swift
1
1835
// // UIWindow+extension.swift // APJExtensions // // Created by Pino, Angelo on 03/12/2018. // Copyright © 2018 Pino, Angelo. All rights reserved. // import UIKit public extension UIWindow { var topController: UIViewController? { if var topController = rootViewController { while let presentedViewController = topController.presentedViewController, !(presentedViewController is UIAlertController) { topController = presentedViewController } return topController } return nil } func replaceRootViewControllerWith(_ replacementController: UIViewController, animated: Bool = true, duration: TimeInterval = 0.5, options: UIView.AnimationOptions = .transitionFlipFromRight, completion: (() -> Void)? = nil) { let replaceCallback: () -> Void = { self.rootViewController?.removeFromParent() self.rootViewController?.view.removeFromSuperview() self.rootViewController = nil self.rootViewController = replacementController } let completionCallback: (Bool) -> Void = { (Bool) in replacementController.modalPresentationCapturesStatusBarAppearance = true replacementController.setNeedsStatusBarAppearanceUpdate() completion?() } if animated { UIView.transition(with: self, duration: duration, options: options, animations: { let oldState: Bool = UIView.areAnimationsEnabled UIView.setAnimationsEnabled(false) replaceCallback() UIView.setAnimationsEnabled(oldState) }, completion: completionCallback) } else { replaceCallback() completionCallback(true) } } }
mit
0f4d1f3c12c0f56ab5edae8d05542b48
35.68
230
0.633043
6.195946
false
false
false
false
berzerker-io/soothe
SoothingKit/Source/Commands/AlignCommand.swift
1
2540
import Foundation import XcodeKit // [@bsarrazin] Jun 11, 2020 // Credit for this extension goes to https://github.com/tid-kijyun/XcodeSourceEditorExtension-Alignment // I have simply modified the code to make it more readable and more accurate. public struct AlignCommand { // MARK: - Initialization public init() { } public func perform(with invocation: XCSourceEditorCommandInvocation, completionHandler: @escaping (Error?) -> Void ) { guard let selection = invocation.buffer.selections.firstObject as? XCSourceTextRange else { return completionHandler(SelectionError.none) } let regex = try! NSRegularExpression( pattern: "[^+^%^*^^^<^>^&^|^?^=^-](\\s*)(=)[^=]", options: .caseInsensitive ) guard let position = invocation.buffer.lines .enumerated() .map({ index, line -> Int in guard index >= selection.start.line && index <= selection.end.line, let line = line as? String, let result = regex.firstMatch(in: line, options: .reportProgress, range: .init(location: 0, length: line.count)) else { return 0 } return result.range(at: 1).location }) .compactMap({ $0 }) .max() else { return completionHandler(nil) } (selection.start.line...selection.end.line).forEach { index in guard let line = invocation.buffer.lines[index] as? String, let result = regex.firstMatch(in: line, options: .reportProgress, range: NSRange(location: 0, length: line.count)) else { return } let range = result.range(at: 2) guard range.location != NSNotFound else { return } let repeatCount = position - range.location + 1 guard repeatCount != 0 else { return } let whiteSpaces = String(repeating: " ", count: abs(repeatCount)) if repeatCount > 0 { invocation.buffer.lines.replaceObject( at: index, with: line.replacingOccurrences(of: "=", with: "\(whiteSpaces)=") ) } else { invocation.buffer.lines.replaceObject( at: index, with: line.replacingOccurrences(of: "\(whiteSpaces)=", with: "=") ) } } completionHandler(nil) } }
unlicense
53884e6613d45a340bc1a5b83b8cb250
35.811594
132
0.548031
4.847328
false
false
false
false
russelhampton05/MenMew
App Prototypes/App_Prototype_A_001/App_Prototype_Alpha_001/PopupViewController.swift
1
5204
// // PopupViewController.swift // Test_003_TableViews // // Created by Jon Calanio on 9/12/16. // Copyright © 2016 Jon Calanio. All rights reserved. // import UIKit class PopupViewController: UIViewController { @IBOutlet weak var addedLabel: UILabel! @IBOutlet weak var confirmButton: UIButton! @IBOutlet weak var cancelButton: UIButton! @IBOutlet weak var popupView: UIView! var menuItem: String? var ticketString: String? var customMessage = String() var condition: String? var register = false var doubleValue: Double? var ticket: Ticket? override func viewDidLoad() { self.view.backgroundColor = UIColor.black.withAlphaComponent(0.6) self.showAnimate() loadTheme() } @IBAction func confirmButtonPressed(_ sender: AnyObject) { self.removeAnimate() } @IBAction func cancelButtonPressed(_ sender: AnyObject) { self.removeAnimate() } //Popup view animation func showAnimate() { self.view.transform = CGAffineTransform(scaleX: 1.3, y: 1.3) self.view.alpha = 0.0 UIView.animate(withDuration: 0.25, animations: { self.view.alpha = 1.0 self.view.transform = CGAffineTransform(scaleX: 1.0, y: 1.0) }) } //Popup remove animation func removeAnimate() { UIView.animate(withDuration: 0.25, animations: { self.view.transform = CGAffineTransform(scaleX: 1.3, y: 1.3) self.view.alpha = 0.0 }, completion:{(finished : Bool) in if (finished) { self.checkSegueCondition() self.view.removeFromSuperview() } }) } //Check for which controller the popup must segue into func checkSegueCondition() { if self.condition == "AddMenuItem" { if let parent = self.parent as? MenuDetailsViewController { parent.tableView.isScrollEnabled = true } } else if self.condition == "CancelMenuItems" { if let summaryP = self.parent as? SummaryViewController { var toRemove: [String] = [] for item in ticket!.itemsOrdered! { toRemove.append(item.item_ID!) } ticket!.itemsOrdered!.removeAll() ticket!.total = 0 UserManager.SetTicket(user: currentUser!, ticket: ticket!, toRemove: toRemove) { completed in if completed { UserManager.UpdateTicketStatus(user: currentUser!, ticket: self.ticket!.ticket_ID!, status: "Order Cancelled") } } summaryP.performSegue(withIdentifier: "UnwindMainMenu", sender: summaryP) } } else if self.register { if let registerVC = self.parent as? RegisterViewController { registerVC.performSegue(withIdentifier: "QRScanSegue", sender: registerVC) } } else if self.condition == "QRError" { if let restoVC = self.parent as? RestaurantViewController { restoVC.performSegue(withIdentifier: "QRReturnSegue", sender: restoVC) } } else if self.condition == "PayOrder" { if let payVC = self.parent as? PaymentDetailsViewController { payVC.performSegue(withIdentifier: "PaymentSummarySegue", sender: payVC) } } } //Custom message display func addMessage(context: String) { condition = context if context == "AddMenuItem" { addedLabel.text = menuItem! + " has been added to the order." } else if context == "CancelMenuItems" { addedLabel.text = "Are you sure you want to clear all orders?" cancelButton.isHidden = false } else if context == "FulfillOrder" { addedLabel.text = "The ticket has been fulfilled." } else if context == "QRError" { addedLabel.text = "Error in retrieving QR code data. Please scan again." } else if context == "PayOrder" { addedLabel.text = "Confirm paying for this ticket?" } else { addedLabel.text = context } } func loadTheme() { if currentTheme == nil { currentTheme = Theme(type: "Salmon") } //Background and Tint popupView.backgroundColor = currentTheme!.primary! self.view.tintColor = currentTheme!.highlight! //Labels addedLabel.textColor = currentTheme!.highlight! //Buttons confirmButton.backgroundColor = currentTheme!.highlight! confirmButton.setTitleColor(currentTheme!.primary!, for: .normal) cancelButton.backgroundColor = currentTheme!.highlight! cancelButton.setTitleColor(currentTheme!.primary!, for: .normal) } }
mit
7b6fdb5471fffb3ecf4ed60856c59b7e
31.51875
134
0.561599
5.111002
false
false
false
false
bcylin/QuickTableViewController
Source/QuickTableViewController.swift
1
7608
// // QuickTableViewController.swift // QuickTableViewController // // Created by Ben on 25/08/2015. // Copyright (c) 2015 bcylin. // // 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 /// A table view controller that shows `tableContents` as formatted sections and rows. open class QuickTableViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { /// A Boolean value indicating if the controller clears the selection when the collection view appears. open var clearsSelectionOnViewWillAppear = true /// Returns the table view managed by the controller object. open var tableView: UITableView = UITableView(frame: .zero, style: .grouped) /// The layout of sections and rows to display in the table view. open var tableContents: [Section] = [] { didSet { tableView.reloadData() } } // MARK: - Initialization /// Initializes a table view controller to manage a table view of a given style. /// /// - Parameter style: A constant that specifies the style of table view that the controller object is to manage. public init(style: UITableView.Style) { super.init(nibName: nil, bundle: nil) tableView = UITableView(frame: .zero, style: style) } /// Returns a newly initialized view controller with the nib file in the specified bundle. /// /// - Parameters: /// - nibNameOrNil: The name of the nib file to associate with the view controller. /// - nibBundleOrNil: The bundle in which to search for the nib file. public override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) } /// Returns an object initialized from data in a given unarchiver. /// /// - Parameter coder: An unarchiver object. public required init?(coder: NSCoder) { super.init(coder: coder) } deinit { tableView.dataSource = nil tableView.delegate = nil } // MARK: - UIViewController open override func viewDidLoad() { super.viewDidLoad() view.addSubview(tableView) tableView.frame = view.bounds tableView.autoresizingMask = [.flexibleWidth, .flexibleHeight] tableView.rowHeight = UITableView.automaticDimension tableView.estimatedRowHeight = 44 tableView.dataSource = self tableView.delegate = self #if os(tvOS) tableView.remembersLastFocusedIndexPath = true #endif } open override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) if let indexPath = tableView.indexPathForSelectedRow, clearsSelectionOnViewWillAppear { tableView.deselectRow(at: indexPath, animated: true) } } // MARK: - UITableViewDataSource open func numberOfSections(in tableView: UITableView) -> Int { return tableContents.count } open func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return tableContents[section].rows.count } open func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return tableContents[section].title } open func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let row = tableContents[indexPath.section].rows[indexPath.row] let cell = tableView.dequeueReusableCell(withIdentifier: row.cellReuseIdentifier) ?? row.cellType.init(style: row.cellStyle, reuseIdentifier: row.cellReuseIdentifier) cell.defaultSetUp(with: row) (cell as? Configurable)?.configure(with: row) #if os(iOS) (cell as? SwitchCell)?.delegate = self #endif row.customize?(cell, row) return cell } open func tableView(_ tableView: UITableView, titleForFooterInSection section: Int) -> String? { return tableContents[section].footer } // MARK: - UITableViewDelegate open func tableView(_ tableView: UITableView, shouldHighlightRowAt indexPath: IndexPath) -> Bool { return tableContents[indexPath.section].rows[indexPath.row].isSelectable } open func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let section = tableContents[indexPath.section] let row = section.rows[indexPath.row] switch (section, row) { case let (radio as RadioSection, option as OptionRowCompatible): let changes: [IndexPath] = radio.toggle(option).map { IndexPath(row: $0, section: indexPath.section) } if changes.isEmpty { tableView.deselectRow(at: indexPath, animated: false) } else { tableView.reloadRows(at: changes, with: .automatic) } case let (_, option as OptionRowCompatible): // Allow OptionRow to be used without RadioSection. option.isSelected = !option.isSelected tableView.reloadData() #if os(tvOS) case let (_, row as SwitchRowCompatible): // SwitchRow on tvOS behaves like OptionRow. row.switchValue = !row.switchValue tableView.reloadData() #endif case (_, is TapActionRowCompatible): tableView.deselectRow(at: indexPath, animated: true) // Avoid some unwanted animation when the action also involves table view reload. DispatchQueue.main.async { row.action?(row) } case let (_, row) where row.isSelectable: DispatchQueue.main.async { row.action?(row) } default: break } } #if os(iOS) public func tableView(_ tableView: UITableView, accessoryButtonTappedForRowWith indexPath: IndexPath) { switch tableContents[indexPath.section].rows[indexPath.row] { case let row as NavigationRowCompatible: DispatchQueue.main.async { row.accessoryButtonAction?(row) } default: break } } #endif #if os(tvOS) private var currentFocusedIndexPath: IndexPath? open override func didUpdateFocus(in context: UIFocusUpdateContext, with coordinator: UIFocusAnimationCoordinator) { currentFocusedIndexPath = (context.nextFocusedView as? UITableViewCell).flatMap(tableView.indexPath(for:)) } public func indexPathForPreferredFocusedView(in tableView: UITableView) -> IndexPath? { return currentFocusedIndexPath } #endif } // MARK: - SwitchCellDelegate #if os(iOS) extension QuickTableViewController: SwitchCellDelegate { open func switchCell(_ cell: SwitchCell, didToggleSwitch isOn: Bool) { guard let indexPath = tableView.indexPath(for: cell), let row = tableContents[indexPath.section].rows[indexPath.row] as? SwitchRowCompatible else { return } row.switchValue = isOn } } #endif
mit
89a73ea4ec929f0f64aa5ab9448d02b9
32.663717
118
0.716746
4.734287
false
false
false
false