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
rmorbach/pagandopave
Apps/iOS/PagandoPave/PagandoPave/Network.swift
1
1212
// // Network.swift // PagandoPave // // Created by Rodrigo Morbach on 26/08/17. // Copyright © 2017 Morbach Inc. All rights reserved. // import UIKit class Network: NSObject { private class func httpCall(request: NSMutableURLRequest, completion: @escaping (Data?, URLResponse?, Error?) -> Swift.Void) { let session = URLSession(configuration: .default, delegate: nil, delegateQueue: nil) let putTask = session.dataTask(with: request as URLRequest) {data, response, err in completion(data, response, err) } putTask.resume() } public class func post(url: URL, contentType: String?, accept: String, payload: Data?, completionHandler: @escaping (Data?, HTTPURLResponse?, Error?) -> Swift.Void) { let request = NSMutableURLRequest(url: url) request.httpMethod = "POST" request.setValue(contentType, forHTTPHeaderField: "Content-Type") request.setValue(accept, forHTTPHeaderField: "Accept") request.httpBody = payload httpCall(request: request) { data, response, error in completionHandler(data, response as? HTTPURLResponse, error) } } }
apache-2.0
97de198eeab7e9007cd6317d0cc51a51
30.868421
168
0.648225
4.452206
false
false
false
false
drinkapoint/DrinkPoint-iOS
DrinkPoint/Pods/FacebookShare/Sources/Share/Content Sharing/GraphSharer.swift
1
5305
// Copyright (c) 2016-present, Facebook, Inc. All rights reserved. // // You are hereby granted a non-exclusive, worldwide, royalty-free license to use, // copy, modify, and distribute this software in source code or binary form for use // in connection with the web services and APIs provided by Facebook. // // As with any software that integrates with the Facebook platform, your use of // this software is subject to the Facebook Developer Principles and Policies // [http://developers.facebook.com/policy/]. This copyright 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 FBSDKShareKit @testable import FacebookCore /** A utility class for sharing through the graph API. Using this class requires an access token that has been granted the "publish_actions" permission. GraphSharer network requests are scheduled on the current run loop in the default run loop mode (like NSURLConnection). If you want to use GraphSharer in a background thread, you must manage the run loop yourself. */ public final class GraphSharer<Content: ContentProtocol> { private let sdkSharer: FBSDKShareAPI private let sdkShareDelegate: SDKSharingDelegateBridge<Content> /// The message the person has provided through the custom dialog that will accompany the share content. public var message: String? { get { return sdkSharer.message } set { sdkSharer.message = newValue } } /// The graph node to which content should be shared. public var graphNode: String? { get { return sdkSharer.graphNode } set { sdkSharer.graphNode = newValue } } /// The access token used when performing a share. The access token must have the "publish_actions" permission granted. public var accessToken: AccessToken? { get { let accessToken: FBSDKAccessToken? = sdkSharer.accessToken return accessToken.flatMap(AccessToken.init) } set { sdkSharer.accessToken = newValue.map { $0.sdkAccessTokenRepresentation } } } /** Create a new Graph API sharer. - parameter content: The content to share. */ public init(content: Content) { sdkSharer = FBSDKShareAPI() sdkShareDelegate = SDKSharingDelegateBridge() sdkShareDelegate.setupAsDelegateFor(sdkSharer) sdkSharer.shareContent = ContentBridger.bridgeToObjC(content) } } //-------------------------------------- // MARK: - Share //-------------------------------------- extension GraphSharer { /** Attempt to share `content` with the graph API. - throws: If the content fails to share. */ public func share() throws { var error: ErrorType? let completionHandler = sdkShareDelegate.completion sdkShareDelegate.completion = { if case .Failed(let resultError) = $0 { error = resultError } } sdkSharer.share() sdkShareDelegate.completion = completionHandler if let error = error { throw error } } } //-------------------------------------- // MARK: - ContentSharingProtocol //-------------------------------------- extension GraphSharer: ContentSharingProtocol { /// The content that is being shared. public var content: Content { get { guard let swiftContent: Content = ContentBridger.bridgeToSwift(sdkSharer.shareContent) else { fatalError("Content of our private sharer has changed type. Something horrible has happened.") } return swiftContent } } /// The completion handler to be invoked upon the share performing. public var completion: ((ContentSharerResult<Content>) -> Void)? { get { return sdkShareDelegate.completion } set { sdkShareDelegate.completion = newValue } } /// Whether or not this sharer fails on invalid data. public var failsOnInvalidData: Bool { get { return sdkSharer.shouldFailOnDataError } set { sdkSharer.shouldFailOnDataError = newValue } } /** Validates the content on the receiver. - throws: If The content could not be validated. */ public func validate() throws { try sdkSharer.validate() } } //-------------------------------------- // MARK: - Convenience //-------------------------------------- extension GraphSharer { /** Share a given `content` to the Graph API, with a completion handler. - parameter content: The content to share. - parameter completion: The completion handler to invoke. - returns: Whether or not the operation was successfully started. - throws: If the share fails. */ public static func share(content: Content, completion: (ContentSharerResult<Content> -> Void)? = nil) throws -> GraphSharer { let sharer = self.init(content: content) sharer.completion = completion try sharer.share() return sharer } }
mit
8f877f76f571eefd5fec96241a237019
29.488506
127
0.678794
4.853614
false
false
false
false
pierreg256/ticTacSprite
ticTacSprite/GameViewController.swift
1
1579
// // GameViewController.swift // ticTacSprite // // Created by Pierre Gilot on 28/09/2015. // Copyright (c) 2015 Pierre Gilot. All rights reserved. // import UIKit import SpriteKit class GameViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() let scene = GameScene(size: view.bounds.size) // Configure the view. let skView = self.view as! SKView skView.showsFPS = true skView.showsNodeCount = true /* Sprite Kit applies additional optimizations to improve rendering performance */ //skView.ignoresSiblingOrder = true /* Set the scale mode to scale to fit the window */ scene.scaleMode = .AspectFill scene.gameController = GameController() skView.presentScene(scene) } override func shouldAutorotate() -> Bool { return true } override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask { if UIDevice.currentDevice().userInterfaceIdiom == .Phone { return .AllButUpsideDown } else { return .All } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Release any cached data, images, etc that aren't in use. } override func prefersStatusBarHidden() -> Bool { return true } //MARK: - Game Methods methods func toto() -> Void { //TODO: Fill in the gaps } }
mit
10d84c3ebc1598044d3274abaabe5551
24.885246
94
0.594047
5.444828
false
false
false
false
PopcornTimeTV/PopcornTimeTV
PopcornTime/UI/tvOS/Views/TVExpandableTextView.swift
1
1527
import Foundation import TvOSMoreButton class TVExpandableTextView: TvOSMoreButton { var isDark: Bool = true { didSet { let colorPallete: ColorPallete = isDark ? .light : .dark trailingTextColor = colorPallete.secondary textColor = colorPallete.primary blurStyle = isDark ? .dark : .extraLight } } var blurStyle: UIBlurEffect.Style = .dark { didSet { blurredView.effect = UIBlurEffect(style: blurStyle) } } override func layoutSubviews() { super.layoutSubviews() updateUI() } var blurredView: UIVisualEffectView { return recursiveSubviews.compactMap({$0 as? UIVisualEffectView}).first! } override init(frame: CGRect) { super.init(frame: frame) sharedSetup() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) sharedSetup() } func sharedSetup() { isDark = true blurredView.contentView.backgroundColor = UIColor(white: 1.0, alpha: 0.2) font = .systemFont(ofSize: 30, weight: UIFont.Weight.medium) trailingTextFont = .boldSystemFont(ofSize: 25) focusedShadowOpacity = 0.5 cornerRadius = 5 focusedViewAlpha = 1 } override func layoutIfNeeded() { if let label = recursiveSubviews.compactMap({$0 as? UILabel}).first { label.layoutIfNeeded() } } }
gpl-3.0
1deebeb0b83e90850d77c5234805854e
24.881356
81
0.586117
4.957792
false
false
false
false
yongtang/tensorflow
tensorflow/lite/swift/Sources/MetalDelegate.swift
12
3802
// Copyright 2019 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. import TensorFlowLiteCMetal /// A delegate that uses the `Metal` framework for performing TensorFlow Lite graph operations with /// GPU acceleration. /// /// - Important: This is an experimental interface that is subject to change. public final class MetalDelegate: Delegate { /// The configuration options for the `MetalDelegate`. public let options: Options // Conformance to the `Delegate` protocol. public private(set) var cDelegate: CDelegate /// Creates a new instance configured with the given `options`. /// /// - Parameters: /// - options: Configurations for the delegate. The default is a new instance of /// `MetalDelegate.Options` with the default configuration values. public init(options: Options = Options()) { self.options = options var delegateOptions = TFLGpuDelegateOptions() delegateOptions.allow_precision_loss = options.isPrecisionLossAllowed delegateOptions.wait_type = options.waitType.cWaitType delegateOptions.enable_quantization = options.isQuantizationEnabled cDelegate = TFLGpuDelegateCreate(&delegateOptions) } deinit { TFLGpuDelegateDelete(cDelegate) } } extension MetalDelegate { /// Options for configuring the `MetalDelegate`. public struct Options: Equatable, Hashable { /// Indicates whether the GPU delegate allows precision loss, such as allowing `Float16` /// precision for a `Float32` computation. The default is `false`. public var isPrecisionLossAllowed = false @available( *, deprecated, message: "Deprecated since TensorFlow Lite 2.4", renamed: "isPrecisionLossAllowed" ) public var allowsPrecisionLoss: Bool { get { return isPrecisionLossAllowed } set(value) { isPrecisionLossAllowed = value } } /// A type indicating how the current thread should wait for work on the GPU to complete. The /// default is `passive`. public var waitType: ThreadWaitType = .passive /// Indicates whether the GPU delegate allows execution of an 8-bit quantized model. The default /// is `true`. public var isQuantizationEnabled = true /// Creates a new instance with the default values. public init() {} } } /// A type indicating how the current thread should wait for work scheduled on the GPU to complete. public enum ThreadWaitType: Equatable, Hashable { /// The thread does not wait for the work to complete. Useful when the output of the work is used /// with the GPU pipeline. case none /// The thread waits until the work is complete. case passive /// The thread waits for the work to complete with minimal latency, which may require additional /// CPU resources. case active /// The thread waits for the work while trying to prevent the GPU from going into sleep mode. case aggressive /// The C `TFLGpuDelegateWaitType` for the current `ThreadWaitType`. var cWaitType: TFLGpuDelegateWaitType { switch self { case .none: return TFLGpuDelegateWaitTypeDoNotWait case .passive: return TFLGpuDelegateWaitTypePassive case .active: return TFLGpuDelegateWaitTypeActive case .aggressive: return TFLGpuDelegateWaitTypeAggressive } } }
apache-2.0
e706191a38332a25b51dd49a02c3d3c5
36.27451
100
0.729879
4.676507
false
false
false
false
BinaryDennis/SwiftPocketBible
Extensions/CollectionExtensions.swift
1
1247
import Foundation extension Collection { public subscript (safe index: Index?) -> Iterator.Element? { guard let index = index else { return nil } return (startIndex..<endIndex).contains(index) ? self[index] : nil } } extension Collection where Iterator.Element : Equatable { public func indexesOf(predicate: (Iterator.Element) -> Bool) -> [Index] { let x: [Iterator.Element] = self.filter(predicate) let y: [Index?] = x.map { index(of: $0) } return y.filter { $0 != nil }.map { $0! } } } extension MutableCollection { public subscript (safe index: Index?) -> Iterator.Element? { guard let index = index else { return nil } return (startIndex..<endIndex).contains(index) ? self[index] : nil } } extension Collection where Iterator.Element : CustomStringConvertible { public func implode(with separator: String = ",") -> String { return self.reduce("") { (result, elem) -> String in if result == "" { return result.appending(elem.description) } else { return result.appending(separator + " " + elem.description) } } } }
mit
90fe98e7c2acb46a0e0a4db1bf8c1aa4
27.340909
77
0.577386
4.344948
false
false
false
false
arciem/Lores
LoresPlay/LoresPlay/Programs/Example Programs/005-MoveProgram.swift
1
922
import Lores class MoveProgram : Program { var redPosition = Point(x: 0, y: 0) var bluePosition = Point(x: 0, y: 0) var redDirection = 1 var blueDirection = 1 override func setup() { framesPerSecond = 30 // canvasSize = Size(width: 100, height: 100) } override func update() { let newx = redPosition.x + redDirection if newx == canvas.maxX { redDirection = -1 } else if newx == 0 { redDirection = 1 } redPosition = Point(x: newx, y: canvas.midY) let newy = bluePosition.y + blueDirection if newy == canvas.maxY { blueDirection = -1 } else if newy == 0 { blueDirection = 1 } bluePosition = Point(x: canvas.midX, y: newy) } override func draw() { canvas[redPosition] = .Red canvas[bluePosition] = .Blue } }
apache-2.0
62b7f48dfedaa79f3fe9058ec5a3e867
23.945946
53
0.533623
3.857741
false
false
false
false
LinDing/Positano
Positano/Helpers/YepSoundEffect.swift
1
853
// // YepSoundEffect.swift // Yep // // Created by zhowkevin on 15/9/23. // Copyright © 2015年 Catch Inc. All rights reserved. // import AudioToolbox.AudioServices final public class YepSoundEffect: NSObject { var soundID: SystemSoundID? public init(fileURL: URL) { super.init() var theSoundID: SystemSoundID = 0 let error = AudioServicesCreateSystemSoundID(fileURL as CFURL, &theSoundID) if (error == kAudioServicesNoError) { soundID = theSoundID } else { fatalError("YepSoundEffect: init failed!") } } deinit { if let soundID = soundID { AudioServicesDisposeSystemSoundID(soundID) } } public func play() { if let soundID = soundID { AudioServicesPlaySystemSound(soundID) } } }
mit
2c078ac4d40eea5ed277027fccbd25d0
20.794872
83
0.604706
4.696133
false
false
false
false
zhangzichen/Pontus
Pontus/UIKit+Pontus/UIColor+Pontus.swift
1
3509
import UIKit public let White = UIColor.white public let Black = UIColor.black public let Clear = UIColor.clear public let Red = UIColor.red public let Orange = UIColor.orange public let Yellow = UIColor.yellow public let Green = UIColor.green public let Blue = UIColor.blue public let Purple = UIColor.purple /// 系统分割线颜色 -> RGB(200, 199, 204) public var SystemSeparatorColor : UIColor { return UIColor(red: 200/255, green: 199/255, blue: 204/255, alpha: 1) } public func RGB(_ red:CGFloat, _ green:CGFloat, _ blue:CGFloat) -> UIColor { return UIColor(red: red/255, green: green/255, blue: blue/255, alpha: 1) } public func RGBA(_ red:CGFloat, _ green:CGFloat, _ blue:CGFloat, _ alpha:CGFloat) -> UIColor { return UIColor(red: red/255, green: green/255, blue: blue/255, alpha: alpha) } /// "RRGGBBAA" public func HEX(_ hexString:String) -> UIColor { return UIColor(hexString: hexString) } public extension UIColor { func alpha(_ alpha:CGFloatable) -> UIColor { var _red = 0.f var _green = 0.f var _blue = 0.f var _alpha = 0.f getRed(&_red, green: &_green, blue: &_blue, alpha: &_alpha) return UIColor(red: _red, green: _green, blue: _blue, alpha: alpha.f) } /** 使用 hex 色值初始化 UIColor 传入的 hexString格式可以为: --- RGB --- - 12F - #12F - 1234EF - #1234EF --- RGBA --- - 123F - #123F - 12345678 - #123456EF */ convenience init(hexString: String) { var red : CGFloat = 0.0 var green: CGFloat = 0.0 var blue : CGFloat = 0.0 var alpha: CGFloat = 1.0 let _hexString = hexString.hasPrefix("#") ? hexString : "#\(hexString)" let index = _hexString.characters.index(_hexString.startIndex, offsetBy: 1) let hex = _hexString.substring(from: index) let scanner = Scanner(string: hex) var hexValue: CUnsignedLongLong = 0 if scanner.scanHexInt64(&hexValue) { switch (hex.characters.count) { case 3: red = CGFloat((hexValue & 0xF00) >> 8) / 15.0 green = CGFloat((hexValue & 0x0F0) >> 4) / 15.0 blue = CGFloat(hexValue & 0x00F) / 15.0 case 4: red = CGFloat((hexValue & 0xF000) >> 12) / 15.0 green = CGFloat((hexValue & 0x0F00) >> 8) / 15.0 blue = CGFloat((hexValue & 0x00F0) >> 4) / 15.0 alpha = CGFloat(hexValue & 0x000F) / 15.0 case 6: red = CGFloat((hexValue & 0xFF0000) >> 16) / 255.0 green = CGFloat((hexValue & 0x00FF00) >> 8) / 255.0 blue = CGFloat(hexValue & 0x0000FF) / 255.0 case 8: red = CGFloat((hexValue & 0xFF000000) >> 24) / 255.0 green = CGFloat((hexValue & 0x00FF0000) >> 16) / 255.0 blue = CGFloat((hexValue & 0x0000FF00) >> 8) / 255.0 alpha = CGFloat(hexValue & 0x000000FF) / 255.0 default: ccLogWarning("Number of characters after '#' should be either 3, 4, 6 or 8") } } else { ccLogWarning("Scan hex error") } self.init(red:red, green:green, blue:blue, alpha:alpha) } }
mit
43a11484a4d639078f06f5e40e57f360
29.377193
94
0.531042
3.735707
false
false
false
false
CrowdShelf/ios
CrowdShelf/CrowdShelf/Models/Shelf.swift
1
756
// // Shelf.swift // CrowdShelf // // Created by Øyvind Grimnes on 13/10/15. // Copyright © 2015 Øyvind Grimnes. All rights reserved. // import Foundation class Shelf { let name: String let filter: ((Book)->Bool) let parameters: [String: AnyObject]? /// All valid books in the shelf var books: [Book] = [] var titles: [BookInformation] { let titles = books.filter{$0.details != nil}.map {$0.details!} let uniqueTitles = Set(titles) return Array(uniqueTitles).sort {$0.title > $1.title} } init(name: String, parameters: [String: AnyObject]?, filter: ((Book)->Bool)) { self.filter = filter self.parameters = parameters self.name = name } }
mit
977bb360ce437e50aea2d666eb1d3a0b
23.322581
82
0.592297
3.841837
false
false
false
false
QuarkX/Quark
Sources/Quark/HTTP/Message/Message.swift
1
1928
public protocol Message: CustomDataStore { var version: Version { get set } var headers: Headers { get set } var body: Body { get set } } extension Message { public var contentType: MediaType? { get { return headers["Content-Type"].flatMap({try? MediaType(string: $0)}) } set(contentType) { headers["Content-Type"] = contentType?.description } } public var contentLength: Int? { get { return headers["Content-Length"].flatMap({Int($0)}) } set(contentLength) { headers["Content-Length"] = contentLength?.description } } public var transferEncoding: String? { get { return headers["Transfer-Encoding"] } set(transferEncoding) { headers["Transfer-Encoding"] = transferEncoding } } public var isChunkEncoded: Bool { return transferEncoding == "chunked" } public var connection: String? { get { return headers["Connection"] } set(connection) { headers["Connection"] = connection } } public var isKeepAlive: Bool { if version.minor == 0 { return connection?.lowercased() == "keep-alive" } return connection?.lowercased() != "close" } public var isUpgrade: Bool { return connection?.lowercased() == "upgrade" } public var upgrade: String? { get { return headers["Upgrade"] } set(upgrade) { headers["Upgrade"] = upgrade } } } extension Message { public var storageDescription: String { var string = "Storage:\n" if storage.isEmpty { string += "-" } for (key, value) in storage { string += "\(key): \(value)\n" } return string } }
mit
025629f10741cf862f1886201084b693
20.662921
80
0.526452
4.80798
false
false
false
false
pitput/SwiftWamp
SwiftWamp/Transport/WebSocketSwampTransport.swift
1
1934
// // WebSocketTransport.swift // swamp // // Created by Yossi Abraham on 18/08/2016. // Copyright © 2016 Yossi Abraham. All rights reserved. // import Foundation import Starscream open class WebSocketSwampTransport: SwampTransport, WebSocketDelegate { enum WebsocketMode { case binary, text } open var delegate: SwampTransportDelegate? let socket: WebSocket let mode: WebsocketMode fileprivate var disconnectionReason: String? public init(wsEndpoint: URL){ self.socket = WebSocket(url: wsEndpoint, protocols: ["wamp.2.json"]) self.mode = .text socket.delegate = self } // MARK: Transport open func connect() { self.socket.connect() } open func disconnect(_ reason: String) { self.disconnectionReason = reason self.socket.disconnect() } open func sendData(_ data: Data) { if self.mode == .text { self.socket.write(string: String(data: data, encoding: String.Encoding.utf8)!) } else { self.socket.write(data: data) } } // MARK: WebSocketDelegate open func websocketDidConnect(socket: WebSocketClient) { // TODO: Check which serializer is supported by the server, and choose self.mode and serializer delegate?.swampTransportDidConnectWithSerializer(JSONSwampSerializer()) } open func websocketDidDisconnect(socket: WebSocketClient, error: Error?) { delegate?.swampTransportDidDisconnect(error as NSError?, reason: self.disconnectionReason) } open func websocketDidReceiveMessage(socket: WebSocketClient, text: String) { if let data = text.data(using: String.Encoding.utf8) { self.websocketDidReceiveData(socket: socket, data: data) } } open func websocketDidReceiveData(socket: WebSocketClient, data: Data) { delegate?.swampTransportReceivedData(data) } }
mit
d9da00cb766b706e255a6a8bce4a5bdd
27.014493
103
0.668908
4.537559
false
false
false
false
matsuda/MuddlerKit
MuddlerKit/UIAlertControllerExtensions.swift
1
2370
// // UIAlertControllerExtensions.swift // MuddlerKit // // Created by Kosuke Matsuda on 2015/12/28. // Copyright © 2015年 Kosuke Matsuda. All rights reserved. // import UIKit // // MARK: - UIAlertController // extension UIAlertController { public class func alertController(title: String? = nil, message: String?) -> Self { return self.init(title: title ?? "", message: message, preferredStyle: .alert) } public func addOKAction(handler: ((UIAlertAction) -> Void)? = nil) { addAction(UIAlertAction.ok(handler: handler)) } public func addCancelAction(handler: ((UIAlertAction) -> Void)? = nil) { addAction(UIAlertAction.cancel(handler: handler)) } } /// present based on the window /// http://stackoverflow.com/a/30941356 /// private var UIAlertControllerWindowKey: UInt8 = 0 extension UIAlertController { fileprivate var alertWindow: UIWindow? { get { return objc_getAssociatedObject(self, &UIAlertControllerWindowKey) as? UIWindow } set { objc_setAssociatedObject(self, &UIAlertControllerWindowKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } open override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) self.alertWindow?.isHidden = true self.alertWindow = nil } public func show(_ animated: Bool = true, completion: (() -> Void)? = nil) { let controller = UIViewController() controller.view.backgroundColor = UIColor.clear let window = UIWindow(frame: UIScreen.main.bounds) window.rootViewController = controller window.backgroundColor = UIColor.clear window.windowLevel = UIWindowLevelAlert + 1 window.makeKeyAndVisible() self.alertWindow = window controller.present(self, animated: animated, completion: completion) } } // // MARK: - UIAlertAction // extension UIAlertAction { class func ok(handler: ((UIAlertAction) -> Void)? = nil) -> UIAlertAction { return UIAlertAction(title: NSLocalizedString("OK", comment: "OK"), style: .default, handler: handler) } class func cancel(handler: ((UIAlertAction) -> Void)? = nil) -> UIAlertAction { return UIAlertAction(title: NSLocalizedString("Cancel", comment: "Cancel"), style: .cancel, handler: handler) } }
mit
abf16d2eaa3a8b711ba94b1b3f6746bd
28.5875
117
0.667512
4.569498
false
false
false
false
WE-St0r/SwiftyVK
Library/UI/macOS/Share/SharePreferencesController_macOS.swift
2
1450
import Cocoa final class SharePreferencesControllerMacOS: NSViewController, NSTableViewDelegate, NSTableViewDataSource { @IBOutlet private weak var tableView: NSTableView? var preferences = [ShareContextPreference]() override func viewDidLoad() { super.viewDidLoad() tableView?.dataSource = self tableView?.delegate = self } override func viewWillAppear() { super.viewWillAppear() tableView?.reloadData() } func set(preferences: [ShareContextPreference]) { self.preferences = preferences DispatchQueue.anywayOnMain { tableView?.reloadData() } } func numberOfRows(in tableView: NSTableView) -> Int { return preferences.count } func tableView(_ tableView: NSTableView, heightOfRow row: Int) -> CGFloat { return 50 } func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? { let view = tableView.makeView( withIdentifier: NSUserInterfaceItemIdentifier(rawValue: "SharePreferencesCell"), owner: nil ) if let shareView = view as? SharePreferencesCellMacOS { shareView.set(preference: preferences[row]) } return view } func selectionShouldChange(in tableView: NSTableView) -> Bool { return false } }
mit
6f706d7f9c9852f66ef1286ecd8104e9
26.884615
107
0.622759
5.753968
false
false
false
false
EricHein/Swift3.0Practice2016
01.Applicatons/Blog Reader/Blog Reader/MasterViewController.swift
1
10043
// // MasterViewController.swift // Blog Reader // // Created by Eric H on 29/10/2016. // Copyright © 2016 FabledRealm. All rights reserved. // import UIKit import CoreData class MasterViewController: UITableViewController, NSFetchedResultsControllerDelegate { var detailViewController: DetailViewController? = nil var managedObjectContext: NSManagedObjectContext? = nil override func viewDidLoad() { super.viewDidLoad() let url = URL(string: "https://www.googleapis.com/blogger/v3/blogs/10861780/posts?key=AIzaSyCU02fMOymxx4nOM01CT7RW2wQ2tJzFNJE")! let task = URLSession.shared.dataTask(with: url) { (data, response, error) in if error != nil{ print(error) }else{ if let urlContent = data { do{ let jsonResult = try JSONSerialization.jsonObject(with: urlContent, options: JSONSerialization.ReadingOptions.mutableContainers) as AnyObject if let items = jsonResult["items"] as? NSArray { let context = self.fetchedResultsController.managedObjectContext let request = NSFetchRequest<Event>(entityName: "Event") do{ let results = try context.fetch(request) if results.count > 0 { for result in results { context.delete(result) do{ try context.save() }catch{ print("delete failed") } } } }catch{ print("delete failed") } for item in items as Array{ print(item["published"]) let newEvent = Event(context: context) newEvent.timestamp = NSDate() newEvent.setValue(item["published"] as! String, forKey: "published") newEvent.setValue(item["title"] as! String, forKey: "title") newEvent.setValue(item["content"] as! String, forKey: "content") do { try context.save() } catch { let nserror = error as NSError fatalError("Unresolved error \(nserror), \(nserror.userInfo)") } } } self.tableView.reloadData() }catch{ print("json failed") } } } } task.resume() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } func insertNewObject(_ sender: Any) { let context = self.fetchedResultsController.managedObjectContext let newEvent = Event(context: context) // If appropriate, configure the new managed object. newEvent.timestamp = NSDate() // Save the context. do { try context.save() } catch { // Replace this implementation with code to handle the error appropriately. // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. let nserror = error as NSError fatalError("Unresolved error \(nserror), \(nserror.userInfo)") } } // MARK: - Segues override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "showDetail" { if let indexPath = self.tableView.indexPathForSelectedRow { let object = self.fetchedResultsController.object(at: indexPath) let controller = (segue.destination as! UINavigationController).topViewController as! DetailViewController controller.detailItem = object controller.navigationItem.leftBarButtonItem = self.splitViewController?.displayModeButtonItem controller.navigationItem.leftItemsSupplementBackButton = true } } } // MARK: - Table View override func numberOfSections(in tableView: UITableView) -> Int { return self.fetchedResultsController.sections?.count ?? 0 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { let sectionInfo = self.fetchedResultsController.sections![section] return sectionInfo.numberOfObjects } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) let event = self.fetchedResultsController.object(at: indexPath) self.configureCell(cell, withEvent: event) return cell } override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return false } func configureCell(_ cell: UITableViewCell, withEvent event: Event) { cell.textLabel!.text = event.value(forKey: "title") as? String } // MARK: - Fetched results controller var fetchedResultsController: NSFetchedResultsController<Event> { if _fetchedResultsController != nil { return _fetchedResultsController! } let fetchRequest: NSFetchRequest<Event> = Event.fetchRequest() // Set the batch size to a suitable number. fetchRequest.fetchBatchSize = 20 // Edit the sort key as appropriate. let sortDescriptor = NSSortDescriptor(key: "published", ascending: false) fetchRequest.sortDescriptors = [sortDescriptor] // Edit the section name key path and cache name if appropriate. // nil for section name key path means "no sections". let aFetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: self.managedObjectContext!, sectionNameKeyPath: nil, cacheName: "Master") aFetchedResultsController.delegate = self _fetchedResultsController = aFetchedResultsController do { try _fetchedResultsController!.performFetch() } catch { // Replace this implementation with code to handle the error appropriately. // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. let nserror = error as NSError fatalError("Unresolved error \(nserror), \(nserror.userInfo)") } return _fetchedResultsController! } var _fetchedResultsController: NSFetchedResultsController<Event>? = nil func controllerWillChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) { self.tableView.beginUpdates() } func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange sectionInfo: NSFetchedResultsSectionInfo, atSectionIndex sectionIndex: Int, for type: NSFetchedResultsChangeType) { switch type { case .insert: self.tableView.insertSections(IndexSet(integer: sectionIndex), with: .fade) case .delete: self.tableView.deleteSections(IndexSet(integer: sectionIndex), with: .fade) default: return } } func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange anObject: Any, at indexPath: IndexPath?, for type: NSFetchedResultsChangeType, newIndexPath: IndexPath?) { switch type { case .insert: tableView.insertRows(at: [newIndexPath!], with: .fade) case .delete: tableView.deleteRows(at: [indexPath!], with: .fade) case .update: self.configureCell(tableView.cellForRow(at: indexPath!)!, withEvent: anObject as! Event) case .move: tableView.moveRow(at: indexPath!, to: newIndexPath!) } } func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) { self.tableView.endUpdates() } /* // Implementing the above methods to update the table view in response to individual changes may have performance implications if a large number of changes are made simultaneously. If this proves to be an issue, you can instead just implement controllerDidChangeContent: which notifies the delegate that all section and object changes have been processed. func controllerDidChangeContent(controller: NSFetchedResultsController) { // In the simplest, most efficient, case, reload the table view. self.tableView.reloadData() } */ }
gpl-3.0
a55c397b5973a795254255c2c8ef473f
41.91453
360
0.562438
6.499676
false
false
false
false
ALmanCoder/SwiftyGuesturesView
SwiftyGuesturesView/Classes/GH_UIViewExtension.swift
1
2992
// // GH_UIViewExtension.swift // SwiftyRefresh // // Created by guanghuiwu on 16/5/12. // // 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 // MARK: - UIView extension public extension UIView { // MARK: - x public var x : CGFloat { set { var frame = self.frame frame.origin.x = newValue self.frame = frame } get { return frame.origin.x } } // MARK: - y public var y : CGFloat { set { var frame = self.frame frame.origin.y = newValue self.frame = frame } get { return frame.origin.y } } // MARK: - width public var width : CGFloat { set { var frame = self.frame frame.size.width = newValue self.frame = frame } get { return frame.width } } // MARK: - height public var height : CGFloat { set { var frame = self.frame frame.size.height = newValue self.frame = frame } get { return frame.height } } // MARK: - centerX public var centerX : CGFloat { set { var center = self.center center.x = newValue self.center = center } get { return center.x } } // MARK: - centerY public var centerY : CGFloat { set { var center = self.center center.y = newValue self.center = center } get { return center.y } } // MARK: - size public var size : CGSize { set { var frame = self.frame frame.size = newValue self.frame = frame } get { return frame.size } } }
mit
8e1073d47a52170f8ad1d973a811827c
25.017391
81
0.550802
4.540212
false
false
false
false
iOSWizards/AwesomeMedia
Example/Pods/Mixpanel-swift/Mixpanel/Persistence.swift
1
20009
// // Persistence.swift // Mixpanel // // Created by Yarden Eitan on 6/2/16. // Copyright © 2016 Mixpanel. All rights reserved. // import Foundation struct ArchivedProperties { let superProperties: InternalProperties let timedEvents: InternalProperties let distinctId: String let anonymousId: String? let userId: String? let alias: String? let hadPersistedDistinctId: Bool? let peopleDistinctId: String? let peopleUnidentifiedQueue: Queue #if DECIDE let shownNotifications: Set<Int> let automaticEventsEnabled: Bool? #endif // DECIDE } class Persistence { private static let archiveEventQueue: DispatchQueue = DispatchQueue(label: "com.mixpanel.event.archive", qos: .utility) private static let archivePeopleQueue: DispatchQueue = DispatchQueue(label: "com.mixpanel.people.archive", qos: .utility) private static let archiveGroupsQueue: DispatchQueue = DispatchQueue(label: "com.mixpanel.groups.archive", qos: .utility) private static let archiveOptOutStatusQueue: DispatchQueue = DispatchQueue(label: "com.mixpanel.optout.archive", qos: .utility) private static let archiveCodelessQueue: DispatchQueue = DispatchQueue(label: "com.mixpanel.codeless.archive", qos: .utility) private static let archivePropertiesQueue: DispatchQueue = DispatchQueue(label: "com.mixpanel.properties.archive", qos: .utility) private static let archiveVariantQueue: DispatchQueue = DispatchQueue(label: "com.mixpanel.variant.archive", qos: .utility) enum ArchiveType: String { case events case people case groups case properties case codelessBindings case variants case optOutStatus } class func filePathWithType(_ type: ArchiveType, token: String) -> String? { return filePathFor(type.rawValue, token: token) } class private func filePathFor(_ archiveType: String, token: String) -> String? { let filename = "mixpanel-\(token)-\(archiveType)" let manager = FileManager.default #if os(iOS) let url = manager.urls(for: .libraryDirectory, in: .userDomainMask).last #else let url = manager.urls(for: .cachesDirectory, in: .userDomainMask).last #endif // os(iOS) guard let urlUnwrapped = url?.appendingPathComponent(filename).path else { return nil } return urlUnwrapped } #if DECIDE class func archive(eventsQueue: Queue, peopleQueue: Queue, groupsQueue: Queue, properties: ArchivedProperties, codelessBindings: Set<CodelessBinding>, variants: Set<Variant>, token: String) { archiveEvents(eventsQueue, token: token) archivePeople(peopleQueue, token: token) archiveGroups(groupsQueue, token: token) archiveProperties(properties, token: token) archiveVariants(variants, token: token) archiveCodelessBindings(codelessBindings, token: token) } #else class func archive(eventsQueue: Queue, peopleQueue: Queue, groupsQueue: Queue, properties: ArchivedProperties, token: String) { archiveEvents(eventsQueue, token: token) archivePeople(peopleQueue, token: token) archiveGroups(groupsQueue, token: token) archiveProperties(properties, token: token) } #endif // DECIDE class func archiveEvents(_ eventsQueue: Queue, token: String) { archiveEventQueue.sync { [eventsQueue, token] in archiveToFile(.events, object: eventsQueue, token: token) } } class func archivePeople(_ peopleQueue: Queue, token: String) { archivePeopleQueue.sync { [peopleQueue, token] in archiveToFile(.people, object: peopleQueue, token: token) } } class func archiveGroups(_ groupsQueue: Queue, token: String) { archiveGroupsQueue.sync { [groupsQueue, token] in archiveToFile(.groups, object: groupsQueue, token: token) } } class func archiveOptOutStatus(_ optOutStatus: Bool, token: String) { archiveOptOutStatusQueue.sync { [optOutStatus, token] in archiveToFile(.optOutStatus, object: optOutStatus, token: token) } } class func archiveProperties(_ properties: ArchivedProperties, token: String) { archivePropertiesQueue.sync { [properties, token] in var p = InternalProperties() p["distinctId"] = properties.distinctId p["anonymousId"] = properties.anonymousId p["userId"] = properties.userId p["alias"] = properties.alias p["hadPersistedDistinctId"] = properties.hadPersistedDistinctId p["superProperties"] = properties.superProperties p["peopleDistinctId"] = properties.peopleDistinctId p["peopleUnidentifiedQueue"] = properties.peopleUnidentifiedQueue p["timedEvents"] = properties.timedEvents #if DECIDE p["shownNotifications"] = properties.shownNotifications p["automaticEvents"] = properties.automaticEventsEnabled #endif // DECIDE archiveToFile(.properties, object: p, token: token) } } #if DECIDE class func archiveVariants(_ variants: Set<Variant>, token: String) { archiveVariantQueue.sync { [variants, token] in archiveToFile(.variants, object: variants, token: token) } } class func archiveCodelessBindings(_ codelessBindings: Set<CodelessBinding>, token: String) { archiveCodelessQueue.sync { [codelessBindings, token] in archiveToFile(.codelessBindings, object: codelessBindings, token: token) } } #endif // DECIDE class private func archiveToFile(_ type: ArchiveType, object: Any, token: String) { let filePath = filePathWithType(type, token: token) guard let path = filePath else { Logger.error(message: "bad file path, cant fetch file") return } ExceptionWrapper.try({ [cObject = object, cPath = path, cType = type] in if !NSKeyedArchiver.archiveRootObject(cObject, toFile: cPath) { Logger.error(message: "failed to archive \(cType.rawValue)") return } }, catch: { [cType = type] (error) in Logger.error(message: "failed to archive \(cType.rawValue) due to an uncaught exception") return }, finally: {}) addSkipBackupAttributeToItem(at: path) } class private func addSkipBackupAttributeToItem(at path: String) { var url = URL.init(fileURLWithPath: path) var resourceValues = URLResourceValues() resourceValues.isExcludedFromBackup = true do { try url.setResourceValues(resourceValues) } catch { Logger.info(message: "Error excluding \(path) from backup.") } } #if DECIDE class func unarchive(token: String) -> (eventsQueue: Queue, peopleQueue: Queue, groupsQueue: Queue, superProperties: InternalProperties, timedEvents: InternalProperties, distinctId: String, anonymousId: String?, userId: String?, alias: String?, hadPersistedDistinctId: Bool?, peopleDistinctId: String?, peopleUnidentifiedQueue: Queue, shownNotifications: Set<Int>, codelessBindings: Set<CodelessBinding>, variants: Set<Variant>, optOutStatus: Bool?, automaticEventsEnabled: Bool?) { let eventsQueue = unarchiveEvents(token: token) let peopleQueue = unarchivePeople(token: token) let groupsQueue = unarchiveGroups(token: token) let codelessBindings = unarchiveCodelessBindings(token: token) let variants = unarchiveVariants(token: token) let optOutStatus = unarchiveOptOutStatus(token: token) let (superProperties, timedEvents, distinctId, anonymousId, userId, alias, hadPersistedDistinctId, peopleDistinctId, peopleUnidentifiedQueue, shownNotifications, automaticEventsEnabled) = unarchiveProperties(token: token) return (eventsQueue, peopleQueue, groupsQueue, superProperties, timedEvents, distinctId, anonymousId, userId, alias, hadPersistedDistinctId, peopleDistinctId, peopleUnidentifiedQueue, shownNotifications, codelessBindings, variants, optOutStatus, automaticEventsEnabled) } #else class func unarchive(token: String) -> (eventsQueue: Queue, peopleQueue: Queue, groupsQueue: Queue, superProperties: InternalProperties, timedEvents: InternalProperties, distinctId: String, anonymousId: String?, userId: String?, alias: String?, hadPersistedDistinctId: Bool?, peopleDistinctId: String?, peopleUnidentifiedQueue: Queue) { let eventsQueue = unarchiveEvents(token: token) let peopleQueue = unarchivePeople(token: token) let groupsQueue = unarchiveGroups(token: token) let (superProperties, timedEvents, distinctId, anonymousId, userId, alias, hadPersistedDistinctId, peopleDistinctId, peopleUnidentifiedQueue, _) = unarchiveProperties(token: token) return (eventsQueue, peopleQueue, groupsQueue, superProperties, timedEvents, distinctId, anonymousId, userId, alias, hadPersistedDistinctId, peopleDistinctId, peopleUnidentifiedQueue) } #endif // DECIDE class private func unarchiveWithFilePath(_ filePath: String) -> Any? { var unarchivedData: Any? = nil ExceptionWrapper.try({ [filePath] in unarchivedData = NSKeyedUnarchiver.unarchiveObject(withFile: filePath) if unarchivedData == nil { Logger.info(message: "Unable to read file at path: \(filePath)") removeArchivedFile(atPath: filePath) } }, catch: { [filePath] (error) in removeArchivedFile(atPath: filePath) Logger.info(message: "Unable to read file at path: \(filePath), error: \(String(describing: error))") }, finally: {}) return unarchivedData } class private func removeArchivedFile(atPath filePath: String) { do { try FileManager.default.removeItem(atPath: filePath) } catch let err { Logger.info(message: "Unable to remove file at path: \(filePath), error: \(err)") } } class private func unarchiveEvents(token: String) -> Queue { let data = unarchiveWithType(.events, token: token) return data as? Queue ?? [] } class private func unarchivePeople(token: String) -> Queue { let data = unarchiveWithType(.people, token: token) return data as? Queue ?? [] } class private func unarchiveGroups(token: String) -> Queue { let data = unarchiveWithType(.groups, token: token) return data as? Queue ?? [] } class private func unarchiveOptOutStatus(token: String) -> Bool? { return unarchiveWithType(.optOutStatus, token: token) as? Bool } #if DECIDE class private func unarchiveProperties(token: String) -> (InternalProperties, InternalProperties, String, String?, String?, String?, Bool?, String?, Queue, Set<Int>, Bool?) { let properties = unarchiveWithType(.properties, token: token) as? InternalProperties let (superProperties, timedEvents, distinctId, anonymousId, userId, alias, hadPersistedDistinctId, peopleDistinctId, peopleUnidentifiedQueue, automaticEventsEnabled) = unarchivePropertiesHelper(token: token) let shownNotifications = properties?["shownNotifications"] as? Set<Int> ?? Set<Int>() return (superProperties, timedEvents, distinctId, anonymousId, userId, alias, hadPersistedDistinctId, peopleDistinctId, peopleUnidentifiedQueue, shownNotifications, automaticEventsEnabled) } #else class private func unarchiveProperties(token: String) -> (InternalProperties, InternalProperties, String, String?, String?, String?, Bool?, String?, Queue, Bool?) { return unarchivePropertiesHelper(token: token) } #endif // DECIDE class private func unarchivePropertiesHelper(token: String) -> (InternalProperties, InternalProperties, String, String?, String?, String?, Bool?, String?, Queue, Bool?) { let properties = unarchiveWithType(.properties, token: token) as? InternalProperties let superProperties = properties?["superProperties"] as? InternalProperties ?? InternalProperties() let timedEvents = properties?["timedEvents"] as? InternalProperties ?? InternalProperties() var distinctId = properties?["distinctId"] as? String ?? "" var anonymousId = properties?["anonymousId"] as? String ?? nil var userId = properties?["userId"] as? String ?? nil var alias = properties?["alias"] as? String ?? nil var hadPersistedDistinctId = properties?["hadPersistedDistinctId"] as? Bool ?? nil var peopleDistinctId = properties?["peopleDistinctId"] as? String ?? nil let peopleUnidentifiedQueue = properties?["peopleUnidentifiedQueue"] as? Queue ?? Queue() let automaticEventsEnabled = properties?["automaticEvents"] as? Bool ?? nil if properties == nil { (distinctId, peopleDistinctId, anonymousId, userId, alias, hadPersistedDistinctId) = restoreIdentity(token: token) } return (superProperties, timedEvents, distinctId, anonymousId, userId, alias, hadPersistedDistinctId, peopleDistinctId, peopleUnidentifiedQueue, automaticEventsEnabled) } #if DECIDE class private func unarchiveCodelessBindings(token: String) -> Set<CodelessBinding> { let data = unarchiveWithType(.codelessBindings, token: token) return data as? Set<CodelessBinding> ?? Set() } class private func unarchiveVariants(token: String) -> Set<Variant> { let data = unarchiveWithType(.variants, token: token) as? Set<Variant> return data ?? Set() } #endif // DECIDE class private func unarchiveWithType(_ type: ArchiveType, token: String) -> Any? { let filePath = filePathWithType(type, token: token) guard let path = filePath else { Logger.info(message: "bad file path, cant fetch file") return nil } guard let unarchivedData = unarchiveWithFilePath(path) else { Logger.info(message: "can't unarchive file") return nil } return unarchivedData } class func storeIdentity(token: String, distinctID: String, peopleDistinctID: String?, anonymousID: String?, userID: String?, alias: String?, hadPersistedDistinctId: Bool?) { guard let defaults = UserDefaults(suiteName: "Mixpanel") else { return } let prefix = "mixpanel-\(token)-" defaults.set(distinctID, forKey: prefix + "MPDistinctID") defaults.set(peopleDistinctID, forKey: prefix + "MPPeopleDistinctID") defaults.set(anonymousID, forKey: prefix + "MPAnonymousId") defaults.set(userID, forKey: prefix + "MPUserId") defaults.set(alias, forKey: prefix + "MPAlias") defaults.set(hadPersistedDistinctId, forKey: prefix + "MPHadPersistedDistinctId") defaults.synchronize() } class func restoreIdentity(token: String) -> (String, String?, String?, String?, String?, Bool?) { guard let defaults = UserDefaults(suiteName: "Mixpanel") else { return ("", nil, nil, nil, nil, nil) } let prefix = "mixpanel-\(token)-" return (defaults.string(forKey: prefix + "MPDistinctID") ?? "", defaults.string(forKey: prefix + "MPPeopleDistinctID"), defaults.string(forKey: prefix + "MPAnonymousId"), defaults.string(forKey: prefix + "MPUserId"), defaults.string(forKey: prefix + "MPAlias"), defaults.bool(forKey: prefix + "MPHadPersistedDistinctId")) } class func deleteMPUserDefaultsData(token: String) { guard let defaults = UserDefaults(suiteName: "Mixpanel") else { return } let prefix = "mixpanel-\(token)-" defaults.removeObject(forKey: prefix + "MPDistinctID") defaults.removeObject(forKey: prefix + "MPPeopleDistinctID") defaults.removeObject(forKey: prefix + "MPAnonymousId") defaults.removeObject(forKey: prefix + "MPUserId") defaults.removeObject(forKey: prefix + "MPAlias") defaults.removeObject(forKey: prefix + "MPHadPersistedDistinctId") defaults.synchronize() } }
mit
0a43c3c82049bab3076ae376dbf790be
39.584178
178
0.555678
5.981465
false
false
false
false
OpenKitten/BSON
Sources/BSON/Document/Document+Subscripts.swift
1
2291
extension Document { /// Extracts any `Primitive` fom the value at key `key` public subscript(key: String) -> Primitive? { get { var offset = 4 repeat { guard let typeId = storage.getInteger(at: offset, as: UInt8.self), let type = TypeIdentifier(rawValue: typeId) else { return nil } offset += 1 let matches = matchesKey(key, at: offset) guard skipKey(at: &offset) else { return nil } if matches { return value(forType: type, at: offset) } guard skipValue(ofType: type, at: &offset) else { return nil } } while offset + 1 < storage.readableBytes return nil } set { var offset = 4 findKey: repeat { let baseOffset = offset guard let typeId = storage.getInteger(at: offset, as: UInt8.self) else { return } guard let type = TypeIdentifier(rawValue: typeId) else { if typeId == 0x00 { break findKey } return } offset += 1 let matches = matchesKey(key, at: offset) guard skipKey(at: &offset) else { return } if matches, let valueLength = self.valueLength(forType: type, at: offset) { let end = offset + valueLength let length = end - baseOffset self.removeBytes(at: baseOffset, length: length) break findKey } guard skipValue(ofType: type, at: &offset) else { return } } while offset + 1 < storage.readableBytes if let newValue = newValue { appendValue(newValue, forKey: key) } } } }
mit
3bb82349c5b70b594999e2fb67fb80cf
27.6375
91
0.403754
5.8
false
false
false
false
ngquerol/Diurna
App/Sources/Views/StoryCellView.swift
1
2294
// // StoryCellView.swift // Diurna // // Created by Nicolas Gaulard-Querol on 20/01/2016. // Copyright © 2016 Nicolas Gaulard-Querol. All rights reserved. // import AppKit import HackerNewsAPI class StoryCellView: NSTableCellView { // MARK: Outlets @IBOutlet var containerStackView: NSStackView! @IBOutlet var titleTextField: NSTextField! @IBOutlet var urlButton: NSButton! @IBOutlet var authorDateTextField: NSTextField! @IBOutlet var storyStatusView: StoryStatusView! // MARK: Properties override var objectValue: Any? { didSet { guard let story = objectValue as? Story else { return } titleTextField.stringValue = story.title if let URL = story.url, let shortURL = URL.shortURL { urlButton.title = shortURL urlButton.toolTip = URL.absoluteString urlButton.isHidden = false } else { urlButton.isHidden = true } authorDateTextField.stringValue = "by \(story.by), \(story.time.timeIntervalString)" if story.type == .story { storyStatusView.score = story.score - 1 storyStatusView.comments = story.descendants ?? 0 storyStatusView.isHidden = false } else { storyStatusView.isHidden = true } } } // MARK: Methods override func layout() { super.layout() titleTextField.preferredMaxLayoutWidth = containerStackView.frame.width - (containerStackView.edgeInsets.left + containerStackView.edgeInsets.right) needsLayout = true } @IBAction private func visitURL(_: NSButton) { guard let story = objectValue as? Story, story.url != nil, let url = story.url else { return } do { try NSWorkspace.shared.open(url, options: .withoutActivation, configuration: [:]) } catch let error as NSError { NSAlert(error: error).runModal() } } } // MARK: - NSUserInterfaceItemIdentifier extension NSUserInterfaceItemIdentifier { static let storyCell = NSUserInterfaceItemIdentifier("StoryCell") }
mit
c1f22d3e4ec019cdd041a820e65c4b03
25.356322
96
0.598779
5.223235
false
false
false
false
carabina/Static
Static/TableViewController.swift
2
3077
import UIKit /// Table view controller with a `DataSource` setup to use its `tableView`. public class TableViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { // MARK: - Properties /// Returns the table view managed by the controller object. public let tableView: UITableView /// A Boolean value indicating if the controller clears the selection when the table appears. /// /// The default value of this property is YES. When YES, the table view controller clears the table’s current selection when it receives a viewWillAppear: message. Setting this property to NO preserves the selection. public var clearsSelectionOnViewWillAppear: Bool = true /// Table view data source. public let dataSource = DataSource() // MARK: - Initialization public init(style: UITableViewStyle) { tableView = UITableView(frame: .zeroRect, style: style) super.init(nibName: nil, bundle: nil) } public override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) { tableView = UITableView(frame: .zeroRect, style: .Plain) super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) } public required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } public convenience init() { self.init(style: .Plain) } // MARK: - UIViewController public override func loadView() { tableView.autoresizingMask = [.FlexibleWidth, .FlexibleHeight] tableView.delegate = self tableView.dataSource = self view = tableView } public override func viewDidLoad() { super.viewDidLoad() dataSource.tableView = tableView } public override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) performInitialLoad() clearSelectionsIfNecessary() } public override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) tableView.flashScrollIndicators() } public override func setEditing(editing: Bool, animated: Bool) { super.setEditing(editing, animated: animated) tableView.setEditing(editing, animated: animated) } // MARK: - UITableViewControllerDataSource public func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 0 } public func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { return UITableViewCell(style: .Default, reuseIdentifier: nil) } // MARK: - Private private var initialLoadOnceToken = dispatch_once_t() private func performInitialLoad() { dispatch_once(&initialLoadOnceToken) { self.tableView.reloadData() } } private func clearSelectionsIfNecessary() { guard clearsSelectionOnViewWillAppear else { return } tableView.indexPathsForSelectedRows?.forEach { tableView.deselectRowAtIndexPath($0, animated: true) } } }
mit
d72f940ec22fd55438a83fd5bdd2df77
31.03125
220
0.691707
5.385289
false
false
false
false
parrotbait/CorkWeather
Pods/CodableFirebase/CodableFirebase/Encoder.swift
1
25026
// // Encoder.swift // CodableFirebase // // Created by Oleksii on 27/12/2017. // Copyright © 2017 ViolentOctopus. All rights reserved. // import Foundation class _FirebaseEncoder : Encoder { /// Options set on the top-level encoder to pass down the encoding hierarchy. struct _Options { let dateEncodingStrategy: FirebaseEncoder.DateEncodingStrategy? let dataEncodingStrategy: FirebaseEncoder.DataEncodingStrategy? let skipFirestoreTypes: Bool let userInfo: [CodingUserInfoKey : Any] } fileprivate var storage: _FirebaseEncodingStorage fileprivate let options: _Options fileprivate(set) public var codingPath: [CodingKey] public var userInfo: [CodingUserInfoKey : Any] { return options.userInfo } init(options: _Options, codingPath: [CodingKey] = []) { self.storage = _FirebaseEncodingStorage() self.codingPath = codingPath self.options = options } /// Returns whether a new element can be encoded at this coding path. /// /// `true` if an element has not yet been encoded at this coding path; `false` otherwise. fileprivate var canEncodeNewValue: Bool { // Every time a new value gets encoded, the key it's encoded for is pushed onto the coding path (even if it's a nil key from an unkeyed container). // At the same time, every time a container is requested, a new value gets pushed onto the storage stack. // If there are more values on the storage stack than on the coding path, it means the value is requesting more than one container, which violates the precondition. // // This means that anytime something that can request a new container goes onto the stack, we MUST push a key onto the coding path. // Things which will not request containers do not need to have the coding path extended for them (but it doesn't matter if it is, because they will not reach here). return self.storage.count == self.codingPath.count } // MARK: - Encoder Methods public func container<Key>(keyedBy: Key.Type) -> KeyedEncodingContainer<Key> { // If an existing keyed container was already requested, return that one. let topContainer: NSMutableDictionary if canEncodeNewValue { // We haven't yet pushed a container at this level; do so here. topContainer = storage.pushKeyedContainer() } else { guard let container = self.storage.containers.last as? NSMutableDictionary else { preconditionFailure("Attempt to push new keyed encoding container when already previously encoded at this path.") } topContainer = container } let container = _FirebaseKeyedEncodingContainer<Key>(referencing: self, codingPath: self.codingPath, wrapping: topContainer) return KeyedEncodingContainer(container) } public func unkeyedContainer() -> UnkeyedEncodingContainer { // If an existing unkeyed container was already requested, return that one. let topContainer: NSMutableArray if canEncodeNewValue { // We haven't yet pushed a container at this level; do so here. topContainer = self.storage.pushUnkeyedContainer() } else { guard let container = self.storage.containers.last as? NSMutableArray else { preconditionFailure("Attempt to push new unkeyed encoding container when already previously encoded at this path.") } topContainer = container } return _FirebaseUnkeyedEncodingContainer(referencing: self, codingPath: self.codingPath, wrapping: topContainer) } public func singleValueContainer() -> SingleValueEncodingContainer { return self } } fileprivate struct _FirebaseEncodingStorage { // MARK: Properties /// The container stack. /// Elements may be any one of the plist types (NSNumber, NSString, NSDate, NSArray, NSDictionary). private(set) fileprivate var containers: [NSObject] = [] // MARK: - Initialization /// Initializes `self` with no containers. fileprivate init() {} // MARK: - Modifying the Stack fileprivate var count: Int { return containers.count } fileprivate mutating func pushKeyedContainer() -> NSMutableDictionary { let dictionary = NSMutableDictionary() containers.append(dictionary) return dictionary } fileprivate mutating func pushUnkeyedContainer() -> NSMutableArray { let array = NSMutableArray() containers.append(array) return array } fileprivate mutating func push(container: NSObject) { containers.append(container) } fileprivate mutating func popContainer() -> NSObject { precondition(containers.count > 0, "Empty container stack.") return containers.popLast()! } } fileprivate struct _FirebaseKeyedEncodingContainer<K : CodingKey> : KeyedEncodingContainerProtocol { typealias Key = K // MARK: Properties /// A reference to the encoder we're writing to. private let encoder: _FirebaseEncoder /// A reference to the container we're writing to. private let container: NSMutableDictionary /// The path of coding keys taken to get to this point in encoding. private(set) public var codingPath: [CodingKey] // MARK: - Initialization /// Initializes `self` with the given references. fileprivate init(referencing encoder: _FirebaseEncoder, codingPath: [CodingKey], wrapping container: NSMutableDictionary) { self.encoder = encoder self.codingPath = codingPath self.container = container } // MARK: - KeyedEncodingContainerProtocol Methods public mutating func encodeNil(forKey key: Key) throws { container[key.stringValue] = NSNull() } public mutating func encode(_ value: Bool, forKey key: Key) throws { container[key.stringValue] = encoder.box(value) } public mutating func encode(_ value: Int, forKey key: Key) throws { container[key.stringValue] = encoder.box(value) } public mutating func encode(_ value: Int8, forKey key: Key) throws { container[key.stringValue] = encoder.box(value) } public mutating func encode(_ value: Int16, forKey key: Key) throws { container[key.stringValue] = encoder.box(value) } public mutating func encode(_ value: Int32, forKey key: Key) throws { container[key.stringValue] = encoder.box(value) } public mutating func encode(_ value: Int64, forKey key: Key) throws { container[key.stringValue] = encoder.box(value) } public mutating func encode(_ value: UInt, forKey key: Key) throws { container[key.stringValue] = encoder.box(value) } public mutating func encode(_ value: UInt8, forKey key: Key) throws { container[key.stringValue] = encoder.box(value) } public mutating func encode(_ value: UInt16, forKey key: Key) throws { container[key.stringValue] = encoder.box(value) } public mutating func encode(_ value: UInt32, forKey key: Key) throws { container[key.stringValue] = encoder.box(value) } public mutating func encode(_ value: UInt64, forKey key: Key) throws { container[key.stringValue] = encoder.box(value) } public mutating func encode(_ value: String, forKey key: Key) throws { container[key.stringValue] = encoder.box(value) } public mutating func encode(_ value: Float, forKey key: Key) throws { container[key.stringValue] = encoder.box(value) } public mutating func encode(_ value: Double, forKey key: Key) throws { container[key.stringValue] = encoder.box(value) } public mutating func encode<T : Encodable>(_ value: T, forKey key: Key) throws { encoder.codingPath.append(key) defer { encoder.codingPath.removeLast() } container[key.stringValue] = try encoder.box(value) } public mutating func nestedContainer<NestedKey>(keyedBy keyType: NestedKey.Type, forKey key: Key) -> KeyedEncodingContainer<NestedKey> { let dictionary = NSMutableDictionary() self.container[key.stringValue] = dictionary codingPath.append(key) defer { codingPath.removeLast() } let container = _FirebaseKeyedEncodingContainer<NestedKey>(referencing: encoder, codingPath: codingPath, wrapping: dictionary) return KeyedEncodingContainer(container) } public mutating func nestedUnkeyedContainer(forKey key: Key) -> UnkeyedEncodingContainer { let array = NSMutableArray() container[key.stringValue] = array codingPath.append(key) defer { codingPath.removeLast() } return _FirebaseUnkeyedEncodingContainer(referencing: encoder, codingPath: codingPath, wrapping: array) } public mutating func superEncoder() -> Encoder { return _FirebaseReferencingEncoder(referencing: encoder, at: _FirebaseKey.super, wrapping: container) } public mutating func superEncoder(forKey key: Key) -> Encoder { return _FirebaseReferencingEncoder(referencing: encoder, at: key, wrapping: container) } } fileprivate struct _FirebaseUnkeyedEncodingContainer : UnkeyedEncodingContainer { // MARK: Properties /// A reference to the encoder we're writing to. private let encoder: _FirebaseEncoder /// A reference to the container we're writing to. private let container: NSMutableArray /// The path of coding keys taken to get to this point in encoding. private(set) public var codingPath: [CodingKey] /// The number of elements encoded into the container. public var count: Int { return container.count } // MARK: - Initialization /// Initializes `self` with the given references. fileprivate init(referencing encoder: _FirebaseEncoder, codingPath: [CodingKey], wrapping container: NSMutableArray) { self.encoder = encoder self.codingPath = codingPath self.container = container } // MARK: - UnkeyedEncodingContainer Methods public mutating func encodeNil() throws { container.add(NSNull()) } public mutating func encode(_ value: Bool) throws { container.add(self.encoder.box(value)) } public mutating func encode(_ value: Int) throws { container.add(self.encoder.box(value)) } public mutating func encode(_ value: Int8) throws { container.add(self.encoder.box(value)) } public mutating func encode(_ value: Int16) throws { container.add(self.encoder.box(value)) } public mutating func encode(_ value: Int32) throws { container.add(self.encoder.box(value)) } public mutating func encode(_ value: Int64) throws { container.add(self.encoder.box(value)) } public mutating func encode(_ value: UInt) throws { container.add(self.encoder.box(value)) } public mutating func encode(_ value: UInt8) throws { container.add(self.encoder.box(value)) } public mutating func encode(_ value: UInt16) throws { container.add(self.encoder.box(value)) } public mutating func encode(_ value: UInt32) throws { container.add(self.encoder.box(value)) } public mutating func encode(_ value: UInt64) throws { container.add(self.encoder.box(value)) } public mutating func encode(_ value: Float) throws { container.add(self.encoder.box(value)) } public mutating func encode(_ value: Double) throws { container.add(self.encoder.box(value)) } public mutating func encode(_ value: String) throws { container.add(self.encoder.box(value)) } public mutating func encode<T : Encodable>(_ value: T) throws { encoder.codingPath.append(_FirebaseKey(index: count)) defer { encoder.codingPath.removeLast() } container.add(try encoder.box(value)) } public mutating func nestedContainer<NestedKey>(keyedBy keyType: NestedKey.Type) -> KeyedEncodingContainer<NestedKey> { self.codingPath.append(_FirebaseKey(index: self.count)) defer { self.codingPath.removeLast() } let dictionary = NSMutableDictionary() self.container.add(dictionary) let container = _FirebaseKeyedEncodingContainer<NestedKey>(referencing: self.encoder, codingPath: self.codingPath, wrapping: dictionary) return KeyedEncodingContainer(container) } public mutating func nestedUnkeyedContainer() -> UnkeyedEncodingContainer { self.codingPath.append(_FirebaseKey(index: self.count)) defer { self.codingPath.removeLast() } let array = NSMutableArray() self.container.add(array) return _FirebaseUnkeyedEncodingContainer(referencing: self.encoder, codingPath: self.codingPath, wrapping: array) } public mutating func superEncoder() -> Encoder { return _FirebaseReferencingEncoder(referencing: encoder, at: container.count, wrapping: container) } } struct _FirebaseKey : CodingKey { public var stringValue: String public var intValue: Int? public init?(stringValue: String) { self.stringValue = stringValue self.intValue = nil } public init?(intValue: Int) { self.stringValue = "\(intValue)" self.intValue = intValue } init(index: Int) { self.stringValue = "Index \(index)" self.intValue = index } static let `super` = _FirebaseKey(stringValue: "super")! } extension _FirebaseEncoder { /// Returns the given value boxed in a container appropriate for pushing onto the container stack. fileprivate func box(_ value: Bool) -> NSObject { return NSNumber(value: value) } fileprivate func box(_ value: Int) -> NSObject { return NSNumber(value: value) } fileprivate func box(_ value: Int8) -> NSObject { return NSNumber(value: value) } fileprivate func box(_ value: Int16) -> NSObject { return NSNumber(value: value) } fileprivate func box(_ value: Int32) -> NSObject { return NSNumber(value: value) } fileprivate func box(_ value: Int64) -> NSObject { return NSNumber(value: value) } fileprivate func box(_ value: UInt) -> NSObject { return NSNumber(value: value) } fileprivate func box(_ value: UInt8) -> NSObject { return NSNumber(value: value) } fileprivate func box(_ value: UInt16) -> NSObject { return NSNumber(value: value) } fileprivate func box(_ value: UInt32) -> NSObject { return NSNumber(value: value) } fileprivate func box(_ value: UInt64) -> NSObject { return NSNumber(value: value) } fileprivate func box(_ value: Float) -> NSObject { return NSNumber(value: value) } fileprivate func box(_ value: Double) -> NSObject { return NSNumber(value: value) } fileprivate func box(_ value: String) -> NSObject { return NSString(string: value) } fileprivate func box<T : Encodable>(_ value: T) throws -> NSObject { return try self.box_(value) ?? NSDictionary() } fileprivate func box(_ date: Date) throws -> NSObject { guard let options = options.dateEncodingStrategy else { return date as NSDate } switch options { case .deferredToDate: // Must be called with a surrounding with(pushedKey:) call. try date.encode(to: self) return self.storage.popContainer() case .secondsSince1970: return NSNumber(value: date.timeIntervalSince1970) case .millisecondsSince1970: return NSNumber(value: 1000.0 * date.timeIntervalSince1970) case .iso8601: if #available(OSX 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *) { return NSString(string: _iso8601Formatter.string(from: date)) } else { fatalError("ISO8601DateFormatter is unavailable on this platform.") } case .formatted(let formatter): return NSString(string: formatter.string(from: date)) case .custom(let closure): let depth = self.storage.count try closure(date, self) guard self.storage.count > depth else { // The closure didn't encode anything. Return the default keyed container. return NSDictionary() } // We can pop because the closure encoded something. return self.storage.popContainer() } } fileprivate func box(_ data: Data) throws -> NSObject { guard let options = options.dataEncodingStrategy else { return data as NSData } switch options { case .deferredToData: // Must be called with a surrounding with(pushedKey:) call. try data.encode(to: self) return self.storage.popContainer() case .base64: return NSString(string: data.base64EncodedString()) case .custom(let closure): let depth = self.storage.count try closure(data, self) guard self.storage.count > depth else { // The closure didn't encode anything. Return the default keyed container. return NSDictionary() } // We can pop because the closure encoded something. return self.storage.popContainer() } } func box_<T : Encodable>(_ value: T) throws -> NSObject? { if T.self == Date.self || T.self == NSDate.self { return try self.box((value as! Date)) } else if T.self == Data.self || T.self == NSData.self { return try self.box((value as! Data)) } else if T.self == URL.self || T.self == NSURL.self { return self.box((value as! URL).absoluteString) } else if T.self == Decimal.self || T.self == NSDecimalNumber.self { return (value as! NSDecimalNumber) } else if options.skipFirestoreTypes && (value is FirestoreEncodable) { guard let value = value as? NSObject else { throw DocumentReferenceError.typeIsNotNSObject } return value } // The value should request a container from the _FirebaseEncoder. let depth = self.storage.count do { try value.encode(to: self) } catch { // If the value pushed a container before throwing, pop it back off to restore state. if self.storage.count > depth { let _ = self.storage.popContainer() } throw error } // The top container should be a new container. guard self.storage.count > depth else { return nil } return storage.popContainer() } } extension _FirebaseEncoder : SingleValueEncodingContainer { // MARK: - SingleValueEncodingContainer Methods private func assertCanEncodeNewValue() { precondition(canEncodeNewValue, "Attempt to encode value through single value container when previously value already encoded.") } public func encodeNil() throws { assertCanEncodeNewValue() storage.push(container: NSNull()) } public func encode(_ value: Bool) throws { assertCanEncodeNewValue() storage.push(container: box(value)) } public func encode(_ value: Int) throws { assertCanEncodeNewValue() storage.push(container: box(value)) } public func encode(_ value: Int8) throws { assertCanEncodeNewValue() storage.push(container: box(value)) } public func encode(_ value: Int16) throws { assertCanEncodeNewValue() storage.push(container: box(value)) } public func encode(_ value: Int32) throws { assertCanEncodeNewValue() storage.push(container: box(value)) } public func encode(_ value: Int64) throws { assertCanEncodeNewValue() storage.push(container: box(value)) } public func encode(_ value: UInt) throws { assertCanEncodeNewValue() storage.push(container: box(value)) } public func encode(_ value: UInt8) throws { assertCanEncodeNewValue() storage.push(container: box(value)) } public func encode(_ value: UInt16) throws { assertCanEncodeNewValue() storage.push(container: box(value)) } public func encode(_ value: UInt32) throws { assertCanEncodeNewValue() storage.push(container: box(value)) } public func encode(_ value: UInt64) throws { assertCanEncodeNewValue() storage.push(container: box(value)) } public func encode(_ value: String) throws { assertCanEncodeNewValue() storage.push(container: box(value)) } public func encode(_ value: Float) throws { assertCanEncodeNewValue() storage.push(container: box(value)) } public func encode(_ value: Double) throws { assertCanEncodeNewValue() storage.push(container: box(value)) } public func encode<T : Encodable>(_ value: T) throws { assertCanEncodeNewValue() try storage.push(container: box(value)) } } fileprivate class _FirebaseReferencingEncoder : _FirebaseEncoder { // MARK: Reference types. /// The type of container we're referencing. private enum Reference { /// Referencing a specific index in an array container. case array(NSMutableArray, Int) /// Referencing a specific key in a dictionary container. case dictionary(NSMutableDictionary, String) } // MARK: - Properties /// The encoder we're referencing. private let encoder: _FirebaseEncoder /// The container reference itself. private let reference: Reference // MARK: - Initialization /// Initializes `self` by referencing the given array container in the given encoder. fileprivate init(referencing encoder: _FirebaseEncoder, at index: Int, wrapping array: NSMutableArray) { self.encoder = encoder self.reference = .array(array, index) super.init(options: encoder.options, codingPath: encoder.codingPath) self.codingPath.append(_FirebaseKey(index: index)) } /// Initializes `self` by referencing the given dictionary container in the given encoder. fileprivate init(referencing encoder: _FirebaseEncoder, at key: CodingKey, wrapping dictionary: NSMutableDictionary) { self.encoder = encoder reference = .dictionary(dictionary, key.stringValue) super.init(options: encoder.options, codingPath: encoder.codingPath) codingPath.append(key) } // MARK: - Coding Path Operations fileprivate override var canEncodeNewValue: Bool { // With a regular encoder, the storage and coding path grow together. // A referencing encoder, however, inherits its parents coding path, as well as the key it was created for. // We have to take this into account. return storage.count == codingPath.count - encoder.codingPath.count - 1 } // MARK: - Deinitialization // Finalizes `self` by writing the contents of our storage to the referenced encoder's storage. deinit { let value: Any switch storage.count { case 0: value = NSDictionary() case 1: value = self.storage.popContainer() default: fatalError("Referencing encoder deallocated with multiple containers on stack.") } switch self.reference { case .array(let array, let index): array.insert(value, at: index) case .dictionary(let dictionary, let key): dictionary[NSString(string: key)] = value } } } internal extension DecodingError { internal static func _typeMismatch(at path: [CodingKey], expectation: Any.Type, reality: Any) -> DecodingError { let description = "Expected to decode \(expectation) but found \(_typeDescription(of: reality)) instead." return .typeMismatch(expectation, Context(codingPath: path, debugDescription: description)) } fileprivate static func _typeDescription(of value: Any) -> String { if value is NSNull { return "a null value" } else if value is NSNumber /* FIXME: If swift-corelibs-foundation isn't updated to use NSNumber, this check will be necessary: || value is Int || value is Double */ { return "a number" } else if value is String { return "a string/data" } else if value is [Any] { return "an array" } else if value is [String : Any] { return "a dictionary" } else { return "\(type(of: value))" } } }
mit
0aa376754de48552dfdab9114b7e1714
41.487267
175
0.650709
4.950544
false
false
false
false
bitboylabs/selluv-ios
selluv-ios/Pods/PickerView/Pod/Classes/PickerView.swift
2
29112
// // PickerView.swift // // Created by Filipe Alvarenga on 19/05/15. // Copyright (c) 2015 Filipe Alvarenga. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import UIKit // MARK: - Protocols @objc public protocol PickerViewDataSource: class { func pickerViewNumberOfRows(_ pickerView: PickerView) -> Int func pickerView(_ pickerView: PickerView, titleForRow row: Int, index: Int) -> String } @objc public protocol PickerViewDelegate: class { func pickerViewHeightForRows(_ pickerView: PickerView) -> CGFloat @objc optional func pickerView(_ pickerView: PickerView, didSelectRow row: Int, index: Int) @objc optional func pickerView(_ pickerView: PickerView, didTapRow row: Int, index: Int) @objc optional func pickerView(_ pickerView: PickerView, styleForLabel label: UILabel, highlighted: Bool) @objc optional func pickerView(_ pickerView: PickerView, viewForRow row: Int, index: Int, highlighted: Bool, reusingView view: UIView?) -> UIView? } open class PickerView: UIView { // MARK: Nested Types fileprivate class SimplePickerTableViewCell: UITableViewCell { lazy var titleLabel: UILabel = { let titleLabel = UILabel(frame: CGRect(x: 0.0, y: 0.0, width: self.contentView.frame.width, height: self.contentView.frame.height)) titleLabel.textAlignment = .center return titleLabel }() var customView: UIView? } /** ScrollingStyle Enum. - parameter Default: Show only the number of rows informed in data source. - parameter Infinite: Loop through the data source offering a infinite scrolling experience to the user. */ @objc public enum ScrollingStyle: Int { case `default`, infinite } /** SelectionStyle Enum. - parameter None: Don't uses any aditional view to highlight the selection, only the label style customization provided by delegate. - parameter DefaultIndicator: Provide a simple selection indicator on the bottom of the highlighted row with full width and 2pt of height. The default color is its superview `tintColor` but you have free access to customize the DefaultIndicator through the `defaultSelectionIndicator` property. - parameter Overlay: Provide a full width and height (the height you provided on delegate) view that overlay the highlighted row. The default color is its superview `tintColor` and the alpha is set to 0.25, but you have free access to customize it through the `selectionOverlay` property. Tip: You can set the alpha to 1.0 and background color to .clearColor() and add your custom selection view to make it looks as you want (don't forget to properly add the constraints related to `selectionOverlay` to keep your experience with any screen size). - parameter Image: Provide a full width and height image view selection indicator (the height you provided on delegate) without any image. You must have a selection indicator as a image and set it to the image view through the `selectionImageView` property. */ @objc public enum SelectionStyle: Int { case none, defaultIndicator, overlay, image } // MARK: Properties var enabled = true { didSet { if enabled { turnPickerViewOn() } else { turnPickerViewOff() } } } fileprivate var selectionOverlayH: NSLayoutConstraint! fileprivate var selectionImageH: NSLayoutConstraint! fileprivate var selectionIndicatorB: NSLayoutConstraint! fileprivate var pickerCellBackgroundColor: UIColor? var numberOfRowsByDataSource: Int { get { return dataSource?.pickerViewNumberOfRows(self) ?? 0 } } var rowHeight: CGFloat { get { return delegate?.pickerViewHeightForRows(self) ?? 0 } } override open var backgroundColor: UIColor? { didSet { self.tableView.backgroundColor = self.backgroundColor self.pickerCellBackgroundColor = self.backgroundColor } } fileprivate let pickerViewCellIdentifier = "pickerViewCell" open weak var dataSource: PickerViewDataSource? open weak var delegate: PickerViewDelegate? open lazy var defaultSelectionIndicator: UIView = { let selectionIndicator = UIView() selectionIndicator.backgroundColor = self.tintColor selectionIndicator.alpha = 0.0 return selectionIndicator }() open lazy var selectionOverlay: UIView = { let selectionOverlay = UIView() selectionOverlay.backgroundColor = self.tintColor selectionOverlay.alpha = 0.0 return selectionOverlay }() open lazy var selectionImageView: UIImageView = { let selectionImageView = UIImageView() selectionImageView.alpha = 0.0 return selectionImageView }() lazy var tableView: UITableView = { let tableView = UITableView() return tableView }() fileprivate var infinityRowsMultiplier: Int = 1 open var currentSelectedRow: Int! open var currentSelectedIndex: Int { get { return indexForRow(currentSelectedRow) } } fileprivate var firstTimeOrientationChanged = true fileprivate var orientationChanged = false fileprivate var isScrolling = false fileprivate var setupHasBeenDone = false open var scrollingStyle = ScrollingStyle.default { didSet { switch scrollingStyle { case .default: infinityRowsMultiplier = 1 case .infinite: infinityRowsMultiplier = generateInfinityRowsMultiplier() } } } open var selectionStyle = SelectionStyle.none { didSet { switch selectionStyle { case .defaultIndicator: defaultSelectionIndicator.alpha = 1.0 selectionOverlay.alpha = 0.0 selectionImageView.alpha = 0.0 case .overlay: selectionOverlay.alpha = 0.25 defaultSelectionIndicator.alpha = 0.0 selectionImageView.alpha = 0.0 case .image: selectionImageView.alpha = 1.0 selectionOverlay.alpha = 0.0 defaultSelectionIndicator.alpha = 0.0 case .none: selectionOverlay.alpha = 0.0 defaultSelectionIndicator.alpha = 0.0 selectionImageView.alpha = 0.0 } } } // MARK: Initialization required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override public init(frame: CGRect) { super.init(frame: frame) } // MARK: Subviews Setup fileprivate func setup() { infinityRowsMultiplier = generateInfinityRowsMultiplier() // Setup subviews constraints and apperance translatesAutoresizingMaskIntoConstraints = false setupTableView() setupSelectionOverlay() setupSelectionImageView() setupDefaultSelectionIndicator() self.tableView.delegate = self self.tableView.dataSource = self self.tableView.reloadData() // This needs to be done after a delay - I am guessing it basically needs to be called once // the view is already displaying DispatchQueue.main.asyncAfter(deadline: .now()) { // Some UI Adjustments we need to do after setting UITableView data source & delegate. self.configureFirstSelection() self.adjustSelectionOverlayHeightConstraint() } } fileprivate func setupTableView() { tableView.backgroundColor = .clear tableView.separatorStyle = .none tableView.separatorColor = .none tableView.allowsSelection = true tableView.allowsMultipleSelection = false tableView.showsVerticalScrollIndicator = false tableView.showsHorizontalScrollIndicator = false tableView.scrollsToTop = false tableView.register(SimplePickerTableViewCell.classForCoder(), forCellReuseIdentifier: self.pickerViewCellIdentifier) tableView.translatesAutoresizingMaskIntoConstraints = false addSubview(tableView) let tableViewH = NSLayoutConstraint(item: tableView, attribute: .height, relatedBy: .equal, toItem: self, attribute: .height, multiplier: 1, constant: 0) addConstraint(tableViewH) let tableViewW = NSLayoutConstraint(item: tableView, attribute: .width, relatedBy: .equal, toItem: self, attribute: .width, multiplier: 1, constant: 0) addConstraint(tableViewW) let tableViewL = NSLayoutConstraint(item: tableView, attribute: .leading, relatedBy: .equal, toItem: self, attribute: .leading, multiplier: 1, constant: 0) addConstraint(tableViewL) let tableViewTop = NSLayoutConstraint(item: tableView, attribute: .top, relatedBy: .equal, toItem: self, attribute: .top, multiplier: 1, constant: 0) addConstraint(tableViewTop) let tableViewBottom = NSLayoutConstraint(item: tableView, attribute: .bottom, relatedBy: .equal, toItem: self, attribute: .bottom, multiplier: 1, constant: 0) addConstraint(tableViewBottom) let tableViewT = NSLayoutConstraint(item: tableView, attribute: .trailing, relatedBy: .equal, toItem: self, attribute: .trailing, multiplier: 1, constant: 0) addConstraint(tableViewT) } fileprivate func setupSelectionOverlay() { selectionOverlay.isUserInteractionEnabled = false selectionOverlay.translatesAutoresizingMaskIntoConstraints = false self.addSubview(selectionOverlay) selectionOverlayH = NSLayoutConstraint(item: selectionOverlay, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: rowHeight) self.addConstraint(selectionOverlayH) let selectionOverlayW = NSLayoutConstraint(item: selectionOverlay, attribute: .width, relatedBy: .equal, toItem: self, attribute: .width, multiplier: 1, constant: 0) addConstraint(selectionOverlayW) let selectionOverlayL = NSLayoutConstraint(item: selectionOverlay, attribute: .leading, relatedBy: .equal, toItem: self, attribute: .leading, multiplier: 1, constant: 0) addConstraint(selectionOverlayL) let selectionOverlayT = NSLayoutConstraint(item: selectionOverlay, attribute: .trailing, relatedBy: .equal, toItem: self, attribute: .trailing, multiplier: 1, constant: 0) addConstraint(selectionOverlayT) let selectionOverlayY = NSLayoutConstraint(item: selectionOverlay, attribute: .centerY, relatedBy: .equal, toItem: self, attribute: .centerY, multiplier: 1, constant: 0) addConstraint(selectionOverlayY) } fileprivate func setupSelectionImageView() { selectionImageView.isUserInteractionEnabled = false selectionImageView.translatesAutoresizingMaskIntoConstraints = false self.addSubview(selectionImageView) selectionImageH = NSLayoutConstraint(item: selectionImageView, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: rowHeight) self.addConstraint(selectionImageH) let selectionImageW = NSLayoutConstraint(item: selectionImageView, attribute: .width, relatedBy: .equal, toItem: self, attribute: .width, multiplier: 1, constant: 0) addConstraint(selectionImageW) let selectionImageL = NSLayoutConstraint(item: selectionImageView, attribute: .leading, relatedBy: .equal, toItem: self, attribute: .leading, multiplier: 1, constant: 0) addConstraint(selectionImageL) let selectionImageT = NSLayoutConstraint(item: selectionImageView, attribute: .trailing, relatedBy: .equal, toItem: self, attribute: .trailing, multiplier: 1, constant: 0) addConstraint(selectionImageT) let selectionImageY = NSLayoutConstraint(item: selectionImageView, attribute: .centerY, relatedBy: .equal, toItem: self, attribute: .centerY, multiplier: 1, constant: 0) addConstraint(selectionImageY) } fileprivate func setupDefaultSelectionIndicator() { defaultSelectionIndicator.translatesAutoresizingMaskIntoConstraints = false addSubview(defaultSelectionIndicator) let selectionIndicatorH = NSLayoutConstraint(item: defaultSelectionIndicator, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 2.0) addConstraint(selectionIndicatorH) let selectionIndicatorW = NSLayoutConstraint(item: defaultSelectionIndicator, attribute: .width, relatedBy: .equal, toItem: self, attribute: .width, multiplier: 1, constant: 0) addConstraint(selectionIndicatorW) let selectionIndicatorL = NSLayoutConstraint(item: defaultSelectionIndicator, attribute: .leading, relatedBy: .equal, toItem: self, attribute: .leading, multiplier: 1, constant: 0) addConstraint(selectionIndicatorL) selectionIndicatorB = NSLayoutConstraint(item: defaultSelectionIndicator, attribute: .bottom, relatedBy: .equal, toItem: self, attribute: .centerY, multiplier: 1, constant: (rowHeight / 2)) addConstraint(selectionIndicatorB) let selectionIndicatorT = NSLayoutConstraint(item: defaultSelectionIndicator, attribute: .trailing, relatedBy: .equal, toItem: self, attribute: .trailing, multiplier: 1, constant: 0) addConstraint(selectionIndicatorT) } // MARK: Infinite Scrolling Helpers fileprivate func generateInfinityRowsMultiplier() -> Int { if scrollingStyle == .default { return 1 } if numberOfRowsByDataSource > 100 { return 100 } else if numberOfRowsByDataSource < 100 && numberOfRowsByDataSource > 50 { return 200 } else if numberOfRowsByDataSource < 50 && numberOfRowsByDataSource > 25 { return 400 } else { return 800 } } // MARK: Life Cycle open override func willMove(toWindow newWindow: UIWindow?) { super.willMove(toWindow: newWindow) if let _ = newWindow { NotificationCenter.default.addObserver(self, selector: #selector(PickerView.adjustCurrentSelectedAfterOrientationChanges), name: NSNotification.Name.UIDeviceOrientationDidChange, object: nil) } else { NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIDeviceOrientationDidChange, object: nil) } } override open func layoutSubviews() { super.layoutSubviews() if !setupHasBeenDone { setup() setupHasBeenDone = true } } fileprivate func adjustSelectionOverlayHeightConstraint() { if selectionOverlayH.constant != rowHeight || selectionImageH.constant != rowHeight || selectionIndicatorB.constant != (rowHeight / 2) { selectionOverlayH.constant = rowHeight selectionImageH.constant = rowHeight selectionIndicatorB.constant = -(rowHeight / 2) layoutIfNeeded() } } func adjustCurrentSelectedAfterOrientationChanges() { setNeedsLayout() layoutIfNeeded() // Configure the PickerView to select the middle row when the orientation changes during scroll if isScrolling { let middleRow = Int(ceil(Float(numberOfRowsByDataSource) / 2.0)) selectedNearbyToMiddleRow(middleRow) } else { let rowToSelect = currentSelectedRow != nil ? currentSelectedRow : Int(ceil(Float(numberOfRowsByDataSource) / 2.0)) selectedNearbyToMiddleRow(rowToSelect!) } if firstTimeOrientationChanged { firstTimeOrientationChanged = false return } if !isScrolling { return } orientationChanged = true } fileprivate func indexForRow(_ row: Int) -> Int { return row % (numberOfRowsByDataSource > 0 ? numberOfRowsByDataSource : 1) } // MARK: - Actions /** Selects the nearby to middle row that matches with the provided index. - parameter row: A valid index provided by Data Source. */ fileprivate func selectedNearbyToMiddleRow(_ row: Int) { currentSelectedRow = row tableView.reloadData() repeat { // This line adjust the contentInset to UIEdgeInsetZero because when the PickerView are inside of a UIViewController // presented by a UINavigation controller, the tableView contentInset is affected. tableView.contentInset = UIEdgeInsets.zero let indexOfSelectedRow = visibleIndexOfSelectedRow() tableView.setContentOffset(CGPoint(x: 0.0, y: CGFloat(indexOfSelectedRow) * rowHeight), animated: false) delegate?.pickerView?(self, didSelectRow: currentSelectedRow, index: currentSelectedIndex) } while !(numberOfRowsByDataSource > 0 && tableView.numberOfRows(inSection: 0) > 0) } /** Selects literally the row with index that the user tapped. - parameter row: The row index that the user tapped, i.e. the Data Source index times the `infinityRowsMultiplier`. */ fileprivate func selectTappedRow(_ row: Int) { delegate?.pickerView?(self, didTapRow: row, index: indexForRow(row)) selectRow(row, animated: true) } /** Configure the first row selection: If some pre-selected row was set, we select it, else we select the nearby to middle at all. */ fileprivate func configureFirstSelection() { let rowToSelect = currentSelectedRow != nil ? currentSelectedRow : Int(ceil(Float(numberOfRowsByDataSource) / 2.0)) selectedNearbyToMiddleRow(rowToSelect!) } fileprivate func turnPickerViewOn() { tableView.isScrollEnabled = true } fileprivate func turnPickerViewOff() { tableView.isScrollEnabled = false } /** This is an private helper that we use to reach the visible index of the current selected row. Because of we multiply the rows several times to create an Infinite Scrolling experience, the index of a visible selected row may not be the same as the index provided on Data Source. - returns: The visible index of current selected row. */ fileprivate func visibleIndexOfSelectedRow() -> Int { let middleMultiplier = scrollingStyle == .infinite ? (infinityRowsMultiplier / 2) : infinityRowsMultiplier let middleIndex = numberOfRowsByDataSource * middleMultiplier let indexForSelectedRow: Int if let _ = currentSelectedRow , scrollingStyle == .default && currentSelectedRow == 0 { indexForSelectedRow = 0 } else if let _ = currentSelectedRow { indexForSelectedRow = middleIndex - (numberOfRowsByDataSource - currentSelectedRow) } else { let middleRow = Int(ceil(Float(numberOfRowsByDataSource) / 2.0)) indexForSelectedRow = middleIndex - (numberOfRowsByDataSource - middleRow) } return indexForSelectedRow } open func selectRow(_ row : Int, animated: Bool) { var finalRow = row; if (scrollingStyle == .infinite && row < numberOfRowsByDataSource) { let selectedRow = currentSelectedRow ?? Int(ceil(Float(numberOfRowsByDataSource) / 2.0)) let diff = (row % numberOfRowsByDataSource) - (selectedRow % numberOfRowsByDataSource) finalRow = selectedRow + diff } currentSelectedRow = finalRow delegate?.pickerView?(self, didSelectRow: currentSelectedRow, index: currentSelectedIndex) tableView.setContentOffset(CGPoint(x: 0.0, y: CGFloat(finalRow) * rowHeight), animated: animated) } open func reloadPickerView() { tableView.reloadData() } } extension PickerView: UITableViewDataSource { // MARK: UITableViewDataSource public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return numberOfRowsByDataSource * infinityRowsMultiplier } public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let indexOfSelectedRow = visibleIndexOfSelectedRow() let pickerViewCell = tableView.dequeueReusableCell(withIdentifier: pickerViewCellIdentifier, for: indexPath) as! SimplePickerTableViewCell let view = delegate?.pickerView?(self, viewForRow: (indexPath as NSIndexPath).row, index: indexForRow((indexPath as NSIndexPath).row), highlighted: (indexPath as NSIndexPath).row == indexOfSelectedRow, reusingView: pickerViewCell.customView) pickerViewCell.selectionStyle = .none pickerViewCell.backgroundColor = pickerCellBackgroundColor ?? UIColor.white if (view != nil) { var frame = view!.frame frame.origin.y = (indexPath as NSIndexPath).row == 0 ? (self.frame.height / 2) - (rowHeight / 2) : 0.0 view!.frame = frame pickerViewCell.customView = view pickerViewCell.contentView.addSubview(pickerViewCell.customView!) } else { // As the first row have a different size to fit in the middle of the PickerView and rows below, the titleLabel position must be adjusted. let centerY = (indexPath as NSIndexPath).row == 0 ? (self.frame.height / 2) - (rowHeight / 2) : 0.0 pickerViewCell.titleLabel.frame = CGRect(x: 0.0, y: centerY, width: frame.width, height: rowHeight) pickerViewCell.contentView.addSubview(pickerViewCell.titleLabel) pickerViewCell.titleLabel.backgroundColor = UIColor.clear pickerViewCell.titleLabel.text = dataSource?.pickerView(self, titleForRow: (indexPath as NSIndexPath).row, index: indexForRow((indexPath as NSIndexPath).row)) delegate?.pickerView?(self, styleForLabel: pickerViewCell.titleLabel, highlighted: (indexPath as NSIndexPath).row == indexOfSelectedRow) } return pickerViewCell } } extension PickerView: UITableViewDelegate { // MARK: UITableViewDelegate public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { selectTappedRow((indexPath as NSIndexPath).row) } public func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { let numberOfRowsInPickerView = dataSource!.pickerViewNumberOfRows(self) * infinityRowsMultiplier // When the scrolling reach the end on top/bottom we need to set the first/last row to appear in the center of PickerView, so that row must be bigger. if (indexPath as NSIndexPath).row == 0 { return (frame.height / 2) + (rowHeight / 2) } else if numberOfRowsInPickerView > 0 && (indexPath as NSIndexPath).row == numberOfRowsInPickerView - 1 { return (frame.height / 2) + (rowHeight / 2) } return rowHeight } } extension PickerView: UIScrollViewDelegate { // MARK: UIScrollViewDelegate public func scrollViewWillBeginDragging(_ scrollView: UIScrollView) { isScrolling = true } public func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) { let partialRow = Float(targetContentOffset.pointee.y / rowHeight) // Get the estimative of what row will be the selected when the scroll animation ends. var roundedRow = Int(lroundf(partialRow)) // Round the estimative to a row if roundedRow < 0 { roundedRow = 0 } else { targetContentOffset.pointee.y = CGFloat(roundedRow) * rowHeight // Set the targetContentOffset (where the scrolling position will be when the animation ends) to a rounded value. } // Update the currentSelectedRow and notify the delegate that we have a new selected row. currentSelectedRow = roundedRow delegate?.pickerView?(self, didSelectRow: currentSelectedRow, index: currentSelectedIndex) } public func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) { // When the orientation changes during the scroll, is required to reset the picker to select the nearby to middle row. if orientationChanged { selectedNearbyToMiddleRow(currentSelectedRow) orientationChanged = false } isScrolling = false } public func scrollViewDidScroll(_ scrollView: UIScrollView) { let partialRow = Float(scrollView.contentOffset.y / rowHeight) let roundedRow = Int(lroundf(partialRow)) // Avoid to have two highlighted rows at the same time if let visibleRows = tableView.indexPathsForVisibleRows { for indexPath in visibleRows { if let cellToUnhighlight = tableView.cellForRow(at: indexPath) as? SimplePickerTableViewCell , (indexPath as NSIndexPath).row != roundedRow { delegate?.pickerView?(self, viewForRow: (indexPath as NSIndexPath).row, index: indexForRow((indexPath as NSIndexPath).row), highlighted: false, reusingView: cellToUnhighlight.customView) delegate?.pickerView?(self, styleForLabel: cellToUnhighlight.titleLabel, highlighted: false) } } } // Highlight the current selected cell during scroll if let cellToHighlight = tableView.cellForRow(at: IndexPath(row: roundedRow, section: 0)) as? SimplePickerTableViewCell { delegate?.pickerView?(self, viewForRow: roundedRow, index: indexForRow(roundedRow), highlighted: true, reusingView: cellToHighlight.customView) delegate?.pickerView?(self, styleForLabel: cellToHighlight.titleLabel, highlighted: true) } } }
mit
2d7acb055098fbb3c222b1aa1fe769c4
43.513761
249
0.641007
5.848132
false
false
false
false
yoichitgy/Swinject
Tests/SwinjectTests/EmploymentAssembly.swift
2
2446
// // Copyright © 2019 Swinject Contributors. All rights reserved. // import Swinject class Customer {} class Employee { let customer: Customer let lazyCustomer: Lazy<Customer> let providedCustomer: Provider<Customer> var employer: Employer? init(customer: Customer, lazyCustomer: Lazy<Customer>, providedCustomer: Provider<Customer>) { self.customer = customer self.lazyCustomer = lazyCustomer self.providedCustomer = providedCustomer } } class Employer { let customer: Customer let lazyCustomer: Lazy<Customer> let providedCustomer: Provider<Customer> let employee: Employee let lazyEmployee: Lazy<Employee> let providedEmployee: Provider<Employee> init( customer: Customer, lazyCustomer: Lazy<Customer>, providedCustomer: Provider<Customer>, employee: Employee, lazyEmployee: Lazy<Employee>, providedEmployee: Provider<Employee> ) { self.customer = customer self.lazyCustomer = lazyCustomer self.providedCustomer = providedCustomer self.employee = employee self.lazyEmployee = lazyEmployee self.providedEmployee = providedEmployee } } final class EmploymentAssembly: Assembly { private let scope: ObjectScope init(scope: ObjectScope) { self.scope = scope } func assemble(container: Container) { container.register(Customer.self) { _ in Customer() }.inObjectScope(scope) container.register(Employee.self) { Employee( customer: $0.resolve(Customer.self)!, lazyCustomer: $0.resolve(Lazy<Customer>.self)!, providedCustomer: $0.resolve(Provider<Customer>.self)! ) }.initCompleted { if self.scope !== ObjectScope.transient { $1.employer = $0.resolve(Employer.self) } }.inObjectScope(scope) container.register(Employer.self) { Employer( customer: $0.resolve(Customer.self)!, lazyCustomer: $0.resolve(Lazy<Customer>.self)!, providedCustomer: $0.resolve(Provider<Customer>.self)!, employee: $0.resolve(Employee.self)!, lazyEmployee: $0.resolve(Lazy<Employee>.self)!, providedEmployee: $0.resolve(Provider<Employee>.self)! ) }.inObjectScope(scope) } }
mit
2ffca2b1e6e52fb129f0750a852c98eb
29.5625
98
0.626176
4.832016
false
false
false
false
eurofurence/ef-app_ios
Packages/EurofurenceModel/Sources/XCTEurofurenceModel/FakeEventsService.swift
1
2862
import EurofurenceModel import Foundation public class FakeScheduleRepository: ScheduleRepository { public var runningEvents: [Event] = [] public var upcomingEvents: [Event] = [] public var allEvents: [Event] = [] public var favourites: [EventIdentifier] = [] private var currentDay: Day? public init(favourites: [EventIdentifier] = []) { self.favourites = favourites } private var observers = [ScheduleRepositoryObserver]() public func add(_ observer: ScheduleRepositoryObserver) { observers.append(observer) observer.eventsDidChange(to: allEvents) observer.runningEventsDidChange(to: runningEvents) observer.upcomingEventsDidChange(to: upcomingEvents) observer.favouriteEventsDidChange(favourites) } public private(set) var lastProducedSchedule: FakeEventsSchedule? private var schedulesByTag = [String: FakeEventsSchedule]() public func loadSchedule(tag: String) -> Schedule { let schedule = FakeEventsSchedule(events: allEvents, currentDay: currentDay) lastProducedSchedule = schedule schedulesByTag[tag] = schedule return schedule } public func schedule(for tag: String) -> FakeEventsSchedule? { return schedulesByTag[tag] } } extension FakeScheduleRepository { public func stubSomeFavouriteEvents() { allEvents = [FakeEvent].random(minimum: 3) allEvents.forEach({ $0.favourite() }) favourites = allEvents.filter(\.isFavourite).map(\.identifier) } public func simulateEventFavourited(identifier: EventIdentifier) { allEvents.first(where: { $0.identifier == identifier })?.favourite() // Legacy pathway. let favourites = allEvents.filter(\.isFavourite).map(\.identifier) observers.forEach { $0.favouriteEventsDidChange(favourites) } } public func simulateEventFavouritesChanged(to identifiers: [EventIdentifier]) { identifiers.forEach(simulateEventFavourited(identifier:)) } public func simulateEventUnfavourited(identifier: EventIdentifier) { allEvents.first(where: { $0.identifier == identifier })?.unfavourite() // Legacy pathway. if let idx = favourites.firstIndex(of: identifier) { favourites.remove(at: idx) } observers.forEach { $0.favouriteEventsDidChange(favourites) } } public func simulateEventsChanged(_ events: [Event]) { schedulesByTag.values.forEach({ $0.simulateEventsChanged(events) }) } public func simulateDaysChanged(_ days: [Day]) { schedulesByTag.values.forEach({ $0.simulateDaysChanged(days) }) } public func simulateDayChanged(to day: Day?) { currentDay = day schedulesByTag.values.forEach({ $0.simulateDayChanged(to: day) }) } }
mit
9e8e24254ea5c37f479573b7c6e83c75
32.670588
84
0.679595
5.003497
false
false
false
false
BBRick/wp
wp/Marco/AppConst.swift
1
5457
// // AppConfig.swift // viossvc // // Created by yaowang on 2016/10/31. // Copyright © 2016年 ywwlcom.yundian. All rights reserved. // import UIKit typealias CompleteBlock = (AnyObject?) ->()? typealias ErrorBlock = (NSError) ->()? typealias paramBlock = (AnyObject?) ->()? //MARK: --正则表达 func isTelNumber(num: String)->Bool { let predicate:NSPredicate = NSPredicate(format: "SELF MATCHES %@", "^1[3|4|5|7|8][0-9]\\d{8}$") return predicate.evaluate(with: num) } class AppConst { static let DefaultPageSize = 15 static let UMAppkey = "584a3eb345297d271600127e" static let isMock = false static let sha256Key = "t1@s#df!" static let pid = 1002 static let klineCount: Double = 30 static let bundleId = "com.newxfin.goods" enum KVOKey: String { case selectProduct = "selectProduct" case allProduct = "allProduct" case currentUserId = "currentUserId" case balance = "balance" } enum NoticeKey: String { case logoutNotice = "LogoutNotice" } class Color { static let C0 = UIColor(rgbHex:0x131f32) static let CR = UIColor(rgbHex:0xb82525) static let C1 = UIColor.black static let C2 = UIColor(rgbHex:0x666666) static let C3 = UIColor(rgbHex:0x999999) static let C4 = UIColor(rgbHex:0xaaaaaa) static let C5 = UIColor(rgbHex:0xe2e2e2) static let C6 = UIColor(rgbHex:0xf2f2f2) //wp static let CMain = UIColor(rgbHex: 0x268dcf) static let CGreen = UIColor(rgbHex: 0x009944) static let main = "main" static let background = "background" static let buyUp = "buyUp" static let buyDown = "buyDown" static let auxiliary = "auxiliary" static let lightBlue = "lightBlue" }; class SystemFont { static let S1 = UIFont.systemFont(ofSize: 18) static let S2 = UIFont.systemFont(ofSize: 15) static let S3 = UIFont.systemFont(ofSize: 13) static let S4 = UIFont.systemFont(ofSize: 12) static let S5 = UIFont.systemFont(ofSize: 10) static let S14 = UIFont.systemFont(ofSize: 14) }; class Network { #if true //是否测试环境 static let TcpServerIP:String = "61.147.114.87"; static let TcpServerPort:UInt16 = 16008 static let TttpHostUrl:String = "http://61.147.114.87"; #else static let TcpServerIP:String = "192.168.8.131"; static let TcpServerPort:UInt16 = 30001; static let HttpHostUrl:String = "http://192.168.8.131"; #endif static let TimeoutSec:UInt16 = 10 static let qiniuHost = "http://ofr5nvpm7.bkt.clouddn.com/" } class Text { static let PhoneFormatErr = "请输入正确的手机号" static let VerifyCodeErr = "请输入正确的验证码" static let SMSVerifyCodeErr = "获取验证码失败" static let PasswordTwoErr = "两次密码不一致" static let ReSMSVerifyCode = "重新获取" static let ErrorDomain = "com.newxfin.goods" static let PhoneFormat = "^1[3|4|5|7|8][0-9]\\d{8}$" static let RegisterPhoneError = "输入的手机号已注册" } enum Action:UInt { case callPhone = 10001 case handleOrder = 11001 } enum BundleInfo:String { case CFBundleDisplayName = "CFBundleDisplayName" case CFBundleShortVersionString = "CFBundleShortVersionString" case CFBundleVersion = "CFBundleVersion" } class WechatKey { static let Scope = "snsapi_userinfo" static let State = "wpstate" static let AccessTokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code" static let Appid = "wx9dc39aec13ee3158" static let Secret = "Secret" static let ErrorCode = "ErrorCode" } class WechatPay { static let WechatKeyErrorCode = "WechatKeyErrorCode" } class UnionPay { static let UnionErrorCode = "UnionErrorCode" } class NotifyDefine { static let jumpToMyMessage = "jumpToMyMessage" static let jumpToMyAttention = "jumpToMyAttention" static let jumpToMyPush = "jumpToMyPush" static let jumpToMyBask = "jumpToMyBask" static let jumpToDeal = "jumpToDeal" static let jumpToFeedback = "jumpToFeedback" static let jumpToProductGrade = "jumpToProductGrade" static let jumpToAttentionUs = "jumpToAttentionUs" static let jumpToMyWealtVC = "jumpToMyWealtVC" static let jumpToWithdraw = "jumoToWithdraw" static let jumpToRecharge = "jumpToRecharge" static let UpdateUserInfo = "UpdateUserInfo" static let BingPhoneVCToPwdVC = "BingPhoneVCToPwdVC" static let LoginToBingPhoneVC = "LoginToBingPhoneVC" static let RegisterToBingPhoneVC = "RegisterToBingPhoneVC" static let HistoryDealDetailVC = "HistoryDealDetailVC" static let QuitEnterClick = "QuitEnterClick" static let ChangeUserinfo = "ChangeUserinfo" static let BuyToMyWealtVC = "BuyToMyWealtVC" static let DealToMyWealtVC = "DealToMyWealtVC" static let SelectKind = "SelectKind" static let EnterBackground = "EnterBackground" static let RequestPrice = "RequestPrice" } }
apache-2.0
d9515b2cb4f146c63f88570b888f4554
33.25641
153
0.644274
3.982116
false
false
false
false
hollance/swift-algorithm-club
Bucket Sort/BucketSort.swift
3
4997
// // BucketSort.swift // // Created by Barbara Rodeker on 4/4/16. // // 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. // // ////////////////////////////////////// // MARK: Main algorithm ////////////////////////////////////// /** Performs bucket sort algorithm on the given input elements. [Bucket Sort Algorithm Reference](https://en.wikipedia.org/wiki/Bucket_sort) - Parameter elements: Array of Sortable elements - Parameter distributor: Performs the distribution of each element of a bucket - Parameter sorter: Performs the sorting inside each bucket, after all the elements are distributed - Parameter buckets: An array of buckets - Returns: A new array with sorted elements */ public func bucketSort<T>(_ elements: [T], distributor: Distributor, sorter: Sorter, buckets: [Bucket<T>]) -> [T] { precondition(allPositiveNumbers(elements)) precondition(enoughSpaceInBuckets(buckets, elements: elements)) var bucketsCopy = buckets for elem in elements { distributor.distribute(elem, buckets: &bucketsCopy) } var results = [T]() for bucket in bucketsCopy { results += bucket.sort(sorter) } return results } private func allPositiveNumbers<T: Sortable>(_ array: [T]) -> Bool { return array.filter { $0.toInt() >= 0 }.count > 0 } private func enoughSpaceInBuckets<T>(_ buckets: [Bucket<T>], elements: [T]) -> Bool { let maximumValue = elements.max()?.toInt() let totalCapacity = buckets.count * (buckets.first?.capacity)! guard let max = maximumValue else { return false } return totalCapacity >= max } ////////////////////////////////////// // MARK: Distributor ////////////////////////////////////// public protocol Distributor { func distribute<T>(_ element: T, buckets: inout [Bucket<T>]) } /* * An example of a simple distribution function that send every elements to * the bucket representing the range in which it fits.An * * If the range of values to sort is 0..<49 i.e, there could be 5 buckets of capacity = 10 * So every element will be classified by the ranges: * * - 0 ..< 10 * - 10 ..< 20 * - 20 ..< 30 * - 30 ..< 40 * - 40 ..< 50 * * By following the formula: element / capacity = #ofBucket */ public struct RangeDistributor: Distributor { public init() {} public func distribute<T>(_ element: T, buckets: inout [Bucket<T>]) { let value = element.toInt() let bucketCapacity = buckets.first!.capacity let bucketIndex = value / bucketCapacity buckets[bucketIndex].add(element) } } ////////////////////////////////////// // MARK: Sortable ////////////////////////////////////// public protocol IntConvertible { func toInt() -> Int } public protocol Sortable: IntConvertible, Comparable { } ////////////////////////////////////// // MARK: Sorter ////////////////////////////////////// public protocol Sorter { func sort<T: Sortable>(_ items: [T]) -> [T] } public struct InsertionSorter: Sorter { public init() {} public func sort<T: Sortable>(_ items: [T]) -> [T] { var results = items for i in 0 ..< results.count { var j = i while j > 0 && results[j-1] > results[j] { let auxiliar = results[j-1] results[j-1] = results[j] results[j] = auxiliar j -= 1 } } return results } } ////////////////////////////////////// // MARK: Bucket ////////////////////////////////////// public struct Bucket<T: Sortable> { var elements: [T] let capacity: Int public init(capacity: Int) { self.capacity = capacity elements = [T]() } public mutating func add(_ item: T) { if elements.count < capacity { elements.append(item) } } public func sort(_ algorithm: Sorter) -> [T] { return algorithm.sort(elements) } }
mit
6fff34abae7c18dc243f0079b49a5964
28.394118
115
0.602562
4.398768
false
false
false
false
clayellis/StringScanner
Sources/StringScanner/StringExtension.swift
1
3292
// // StringExtension.swift // StringScanner // // Created by Omar Abdelhafith on 30/10/2016. // // // MARK: - Utility string functions, not relying on foundation extension String { /// Finds a string in the string /// /// - parameter string: the string to find /// /// - returns: the index public func find(string: String) -> String.Index? { var currentIndex = self.startIndex var searchIndex = string.startIndex while true { if currentIndex == self.endIndex { return nil } if self[currentIndex] == string[searchIndex] { currentIndex = self.index(after: currentIndex) searchIndex = string.index(after: searchIndex) if searchIndex == string.endIndex { return self.index( currentIndex, offsetBy: -string.characters.count) } } else { currentIndex = self.index(after: currentIndex) if searchIndex != string.startIndex { searchIndex = string.startIndex } } } } /// Checks if the string is prefixed by another string /// /// - parameter string: string to search /// /// - returns: true if found public func isPrefixed(by string: String) -> Bool { var currentIndex = self.startIndex var searchIndex = string.startIndex while true { if currentIndex == self.endIndex { return false } if self[currentIndex] == string[searchIndex] { currentIndex = self.index(after: currentIndex) searchIndex = string.index(after: searchIndex) if searchIndex == string.endIndex { return true } } else { return false } } } /// Substring from index /// /// - parameter index: the index to start /// /// - returns: the substring public subscript(from index: String.Index) -> String { return String(self.characters[index..<self.endIndex]) } /// Substring from index /// /// - parameter index: the index to start /// /// - returns: the substring public subscript(from index: Int) -> String { let start = self.index(self.startIndex, offsetBy: index) return self[from: start] } /// Substring to index /// /// - parameter index: the index to end /// /// - returns: the substring public subscript(to index: String.Index) -> String { return String(self.characters[self.startIndex..<index]) } /// Substring to index /// /// - parameter index: the index to end /// /// - returns: the substring public subscript(to index: Int) -> String { let end = self.index(self.startIndex, offsetBy: index) return self[to: end] } /// Substring with range /// /// - parameter range: the range /// /// - returns: the substring public subscript(with ranage: Range<String.Index>) -> String { return String(self.characters[ranage]) } /// Substring with range /// /// - parameter range: the range /// /// - returns: the substring public subscript(with range: Range<Int>) -> String { let start = self.index(self.startIndex, offsetBy: range.lowerBound) let end = self.index(self.startIndex, offsetBy: range.upperBound) return self[with: start..<end] } }
mit
c3eb13539d1135264ed6ff8797dca72b
23.75188
71
0.606318
4.383489
false
false
false
false
dfuerle/kuroo
kuroo/Contact.swift
1
1655
// // Contact.swift // kuroo // // Copyright © 2016 Dmitri Fuerle. All rights reserved. // import Foundation class Contact: NSObject, NSCoding { struct Constants { static let archiveName = "name" static let archiveValue = "value" static let archiveType = "type" } enum ContactType { case phoneNumber case email } var name = "" var type: ContactType = .phoneNumber var value = "" var isEmpty: Bool { get { return value.isEmpty } } // MARK: - Init override init () { } init(withName name: String, value: String, type: ContactType) { self.name = name self.value = value self.type = type } // MARK: - NSCoding required init?(coder aDecoder: NSCoder) { if let name = aDecoder.decodeObject(forKey: Constants.archiveName) as? String { self.name = name } if let value = aDecoder.decodeObject(forKey: Constants.archiveValue) as? String { self.value = value } let typeInt = aDecoder.decodeInt32(forKey: Constants.archiveType) if typeInt == 0 { self.type = .phoneNumber } else { self.type = .email } } func encode(with aCoder: NSCoder) { aCoder.encode(name, forKey: Constants.archiveName) aCoder.encode(value, forKey: Constants.archiveValue) switch type { case .phoneNumber: aCoder.encode(0, forKey: Constants.archiveType) case .email: aCoder.encode(1, forKey: Constants.archiveType) } } }
gpl-2.0
3e64326561117fa902a1d33bb530f8cf
23.686567
89
0.568319
4.375661
false
false
false
false
dmauro/WeakArray
WeakArray/WeakArray.swift
1
5581
// // WeakArray.swift // WeakArray // // Created by David Mauro on 7/27/14. // Copyright (c) 2014 David Mauro. All rights reserved. // // MARK: Operator Overloads public func ==<T: Equatable>(lhs: WeakArray<T>, rhs: WeakArray<T>) -> Bool { var areEqual = false if lhs.count == rhs.count { areEqual = true for i in 0..<lhs.count { if lhs[i] != rhs[i] { areEqual = false break } } } return areEqual } public func !=<T: Equatable>(lhs: WeakArray<T>, rhs: WeakArray<T>) -> Bool { return !(lhs == rhs) } public func ==<T: Equatable>(lhs: Slice<T?>, rhs: Slice<T?>) -> Bool { var areEqual = false if lhs.count == rhs.count { areEqual = true for i in 0..<lhs.count { if lhs[i] != rhs[i] { areEqual = false break } } } return areEqual } public func !=<T: Equatable>(lhs: Slice<T?>, rhs: Slice<T?>) -> Bool { return !(lhs == rhs) } public func +=<T> (inout lhs: WeakArray<T>, rhs: WeakArray<T>) -> WeakArray<T> { lhs.items += rhs.items return lhs } public func +=<T> (inout lhs: WeakArray<T>, rhs: Array<T>) -> WeakArray<T> { for item in rhs { lhs.append(item) } return lhs } private class Weak<T: AnyObject> { weak var value : T? var description: String { if let val = value? { return "\(val)" } else { return "nil" } } init (value: T?) { self.value = value } } // MARK:- public struct WeakArray<T: AnyObject>: SequenceType, Printable, DebugPrintable, ArrayLiteralConvertible { // MARK: Private private typealias WeakObject = Weak<T> private typealias GeneratorType = WeakGenerator<T> private var items = [WeakObject]() // MARK: Public public var description: String { return items.description } public var debugDescription: String { return items.debugDescription } public var count: Int { return items.count } public var isEmpty: Bool { return items.isEmpty } public var first: T? { return self[0] } public var last: T? { return self[count - 1] } // MARK: Methods public init() {} public init(arrayLiteral elements: T...) { for element in elements { append(element) } } public func generate() -> GeneratorType { let weakSlice: Slice<WeakObject> = items[0..<items.count] let slice: Slice<T?> = weakSlice.map { $0.value } return GeneratorType(items: slice) } // MARK: - Slice-like Implementation public subscript(index: Int) -> T? { get { let weak = items[index] return weak.value } set(value) { let weak = Weak(value: value) items[index] = weak } } public subscript(range: Range<Int>) -> Slice<T?> { get { let weakSlice: Slice<WeakObject> = items[range] let slice: Slice<T?> = weakSlice.map { $0.value } return slice } set(value) { items[range] = value.map { (value: T?) -> WeakObject in return Weak(value: value) } } } mutating public func append(value: T?) { let weak = Weak(value: value) items.append(weak) } mutating public func insert(newElement: T?, atIndex i: Int) { let weak = Weak(value: newElement) items.insert(weak, atIndex: i) } mutating public func removeAtIndex(index: Int) -> T? { let weak = items.removeAtIndex(index) return weak.value } mutating public func removeLast() -> T? { let weak = items.removeLast() return weak.value } mutating public func removeAll(keepCapacity: Bool) { items.removeAll(keepCapacity: keepCapacity) } mutating public func removeRange(subRange: Range<Int>) { items.removeRange(subRange) } mutating public func replaceRange(subRange: Range<Int>, with newElements: Slice<T?>) { let weakElements = newElements.map { Weak(value: $0) } items.replaceRange(subRange, with: weakElements) } mutating public func splice(newElements: Slice<T?>, atIndex i: Int) { let weakElements = newElements.map { Weak(value: $0) } items.splice(weakElements, atIndex: i) } mutating public func extend(newElements: Slice<T?>) { let weakElements = newElements.map { Weak(value: $0) } items.extend(weakElements) } public func filter(includeElement: (T?) -> Bool) -> WeakArray<T> { var filtered: WeakArray<T> = [] for item in items { if includeElement(item.value) { filtered.append(item.value) } } return filtered } public func reverse() -> WeakArray<T> { var reversed: WeakArray<T> = [] let reversedItems = items.reverse() for item in reversedItems { reversed.append(item.value) } return reversed } } // MARK:- public struct WeakGenerator<T>: GeneratorType { typealias Element = T private var items: Slice<T?> mutating public func next() -> T? { while !items.isEmpty { let next = items[0] items = items[1..<items.count] if next != nil { return next } } return nil } }
apache-2.0
1a3a09c9e0904bab45e95e0f092e0642
23.915179
105
0.550439
4.124908
false
false
false
false
ChristianKienle/highway
Sources/Task/SystemProtocol.swift
1
1801
import Foundation import Result import SourceryAutoProtocols /// A `System` is able to do two things: /// 1. Create new *executable* Tasks. A System can do that because it /// is initialized with an executable provider. /// 2. Execute Tasks. It can do that because it has an executor. /// Everytime you would write a class that needs to create and execute Tasks /// you no longer have to initialize it with both but rather use the System /// class for that. It is just a little bit of convenience. public protocol SystemProtocol: AutoMockable { /// sourcery:inline:LocalSystem.AutoGenerateProtocol @discardableResult func task(named name: String) throws -> Task @discardableResult func execute(_ task: Task) throws -> Bool @discardableResult func launch(_ task: Task, wait: Bool) throws -> Bool /// sourcery:end } public extension SystemProtocol { func execute(_ task: Task) throws -> Bool { return try launch(task, wait: true) } } // MARK: - Errors public enum TaskCreationError: Swift.Error { case executableNotFound(commandName: String) } public enum ExecutionError: Swift.Error { case currentDirectoryDoesNotExist case invalidStateAfterExecuting case taskDidExitWithFailure(Termination) } // MARK: - Equatable for ExecutionError extension ExecutionError: Equatable { public static func ==(lhs: ExecutionError, rhs: ExecutionError) -> Bool { let errors = (lhs, rhs) switch errors { case (.currentDirectoryDoesNotExist, .currentDirectoryDoesNotExist), (.invalidStateAfterExecuting, .invalidStateAfterExecuting): return true case (.taskDidExitWithFailure(let lf), .taskDidExitWithFailure(let rf)): return lf == rf default: return false } } }
mit
7c955f2b797e5097acbaf25e8b34ebbf
34.313725
80
0.70794
4.71466
false
false
false
false
brlittle86/picfeed
PicFeed/PicFeed/GalleryCell.swift
1
839
// // GalleryCell.swift // PicFeed // // Created by Brandon Little on 3/29/17. // Copyright © 2017 Brandon Little. All rights reserved. // import UIKit class GalleryCell: UICollectionViewCell { @IBOutlet weak var imageView: UIImageView! @IBOutlet weak var dateLabel: UILabel! func stringFromDate(date: Date) -> String { let dateFormatter = DateFormatter() dateFormatter.dateStyle = .short dateFormatter.timeStyle = .short return dateFormatter.string(from: date) } var post : Post! { didSet { self.imageView.image = post.image self.dateLabel.text = self.stringFromDate(date: post.date) } } override func prepareForReuse() { super.prepareForReuse() self.imageView.image = nil } }
mit
cdc6c8e6aa914b6a52e1e381f3904371
22.277778
70
0.614558
4.579235
false
false
false
false
arbitur/Func
source/Func.swift
1
6743
// // Func.swift // Pods // // Created by Philip Fryklund on 17/Feb/17. // // import Foundation public typealias Dict = [String: Any] public typealias Arr = [Any] public typealias Closure = () -> Void infix operator ?== : ComparisonPrecedence internal let funcDirectory = "se.arbitur.Func" public func clamp <T: Comparable> (_ value: T, min: T, max: T) -> T { return Swift.min(Swift.max(value, min), max) } public func clamp <T: Comparable> (_ value: T, max: T) -> T { return min(value, max) } public func clamp <T: Comparable> (_ value: T, min: T) -> T { return max(value, min) } // Renamings of min and max functions //public func lowest <T: Comparable> (_ lhs: T, _ rhs: T) -> T { // return min(lhs, rhs) //} // //public func highest <T: Comparable> (_ lhs: T, _ rhs: T) -> T { // return min(lhs, rhs) //} public extension NSObject { func `as` <T: NSObject> (_ class: T.Type) -> T? { return self as? T } } public final class Debug { public static func printDeinit <T> (_ obj: T) { print("~\(type(of: obj))") } internal init() {} } open class Observable<T> { public typealias Bond = (T) -> () private var bonds = [Bond]() public typealias Observer = (_ old: T, _ new: T) -> () private var observers = [Observer]() open var value: T { didSet { notify(value: value) observers.forEach { $0(getValueModifier?(oldValue) ?? oldValue, getValueModifier?(value) ?? value) } } } private var getValueModifier: ((T) -> T)? open func notify(value: T) { bonds.forEach { $0(getValueModifier?(value) ?? value) } } public func notify() { self.notify(value: self.value) } public init(_ initialValue: T) { self.value = initialValue } /// Use [weak/unowned self] to prevent retain cycle open func bind(_ bond: @escaping Bond) { bindNext(bond) bond(value) } open func bindNext(_ bond: @escaping Bond) { bonds ++= bond } open func observe(_ observer: @escaping Observer) { observers ++= observer } open func valueModifier(_ modifier: @escaping (T) -> T) { getValueModifier = modifier } } extension Observable: Equatable where T: Equatable { public static func == (lhs: Observable, rhs: Observable) -> Bool { return lhs.value == rhs.value } public static func == (lhs: T, rhs: Observable) -> Bool { return lhs == rhs.value } public static func == (lhs: Observable, rhs: T) -> Bool { return rhs == lhs.value } } open class FormObservable<T: Equatable>: Observable<T> { open var isDirty: Bool = false open private(set) var isValid: Bool private let initialValue: T private final let validation: (T) -> Bool open override func notify(value: T) { isDirty = value != initialValue isValid = validation(value) super.notify(value: value) } public init(_ initialValue: T, validation: @escaping (T) -> Bool) { self.initialValue = initialValue self.validation = validation self.isValid = validation(initialValue) super.init(initialValue) } } public final class Channel<T> { public typealias Listener = (T) -> () private var listeners = [Listener]() private var getValueModifier: ((T) -> T)? public func broadcast(_ value: T) { listeners.forEach { $0(getValueModifier?(value) ?? value) } } /// Use [weak/unowned self] to prevent retain cycle public func listen(_ listener: @escaping Listener) { listeners ++= listener } /// Use [weak/unowned self] to prevent retain cycle public func onGet(_ modifier: @escaping (T) -> T) { getValueModifier = modifier } // Anti-Error: Channel<T> initializer is inacccessible due to 'internal' protection level public init() {} } //public class Event { // private var observers = [() -> Void]() // // func addObserver<T: AnyObject>(_ observer: T, using closure: @escaping (T) -> Void) { // observers.append { [weak observer] in // observer.map(closure) // } // } //} public enum Result <T> { case success(T) case failure(String) } public class Queue { private(set) var isRunning: Bool = false typealias Observer = Closure private var observers = [Observer]() func wait(callback: @escaping Observer) { observers ++= callback } func begin() { guard !isRunning else { return } isRunning = true } func end() { guard isRunning else { return } isRunning = false observers.forEach { $0() } } } // MARK: - Observable // MARK: Generic observable open class Observable2<T> { public typealias Observer = (T) -> Void private var observers: [ObservableTokenIdType: WeakRef<ObserverToken<Observer>>] private var totalNumberOfObservers: UInt32 public init() { observers = [:] totalNumberOfObservers = 0 } /// Returns a token that must be stored with a strong reference to keep it in memory, once token is released the observer closure is also released. public func observe(_ observer: @escaping Observer) -> Any { let id = ObservableTokenIdType(totalNumberOfObservers) let token = ObserverToken(id: id, observer: observer, observable: self) observers[id] = WeakRef(reference: token) totalNumberOfObservers += 1 return token } open func notify(with value: T) { observers.forEach { _, weakRef in weakRef.reference?.observer(value) } } } extension Observable2: ObservableTokenRemovable { fileprivate final func removeToken(for id: ObservableTokenIdType) { observers[id] = nil } } // MARK: Property observable @propertyWrapper open class PropertyObservable<T>: Observable2<T> { open var wrappedValue: T { didSet { notify() } } open var projectedValue: PropertyObservable<T> { self } private var bonds: [Observer] = [] public required init(wrappedValue: T) { self.wrappedValue = wrappedValue super.init() } open func bind(_ observer: @escaping Observer) { bindNext(observer) observer(wrappedValue) } open func bindNext(_ observer: @escaping Observer) { bonds.append(observer) } open func notify() { self.notify(with: wrappedValue) } override open func notify(with value: T) { super.notify(with: value) bonds.forEach { $0(value) } } } // MARK: Observer token private typealias ObservableTokenIdType = Int private class ObserverToken<T> { let id: ObservableTokenIdType let observer: T weak var observable: ObservableTokenRemovable? init(id: ObservableTokenIdType, observer: T, observable: ObservableTokenRemovable?) { self.id = id self.observer = observer self.observable = observable } deinit { observable?.removeToken(for: id) } } private protocol ObservableTokenRemovable: AnyObject { func removeToken(for id: ObservableTokenIdType) } // MARK: - Weak ref type private struct WeakRef<T: AnyObject> { weak var reference: T? }
mit
9697fff2b92711cda9b49e1b43731c84
16.744737
148
0.669435
3.402119
false
false
false
false
banxi1988/BXAppKit
BXViewPager/BXSegmentTabViewController.swift
1
2632
// // BXSegmentTabViewController.swift // BXAppKit // // Created by Haizhen Lee on 11/05/2017. // Copyright © 2017 banxi1988. All rights reserved. // import Foundation import UIKit open class BXSegmentTabViewController:UIViewController,ViewControllerContainerProtocol{ open var containerView = UIView(frame: .zero) public var containerViewController: UIViewController{ return self} public private(set) var segmentIndexViewControllerMap:[Int:UIViewController] = [:] public let segmentControl = UISegmentedControl(frame: .zero) public func add(segmentTitle:String,viewController:UIViewController) -> Int{ let index = segmentControl.numberOfSegments segmentIndexViewControllerMap[index] = viewController segmentControl.insertSegment(withTitle: segmentTitle, at: index, animated: false) return index } private var previousSelectedSegmentIndex = -1 open override func loadView() { super.loadView() view.addSubview(containerView) containerView.translatesAutoresizingMaskIntoConstraints = false containerView.pac_horizontal(0) containerView.pa_below(topLayoutGuide).install() containerView.pa_above(bottomLayoutGuide).install() automaticallyAdjustsScrollViewInsets = false } open override func viewDidLoad() { super.viewDidLoad() setupSegmentTab() segmentControl.addTarget(self, action: #selector(onSelectedSegmentalChanged), for: .valueChanged) segmentControl.sizeToFit() navigationItem.titleView = segmentControl if segmentControl.numberOfSegments > 0 { segmentControl.selectedSegmentIndex = 0 showSegmentTab(index: 0) } } /// setup segment tab before /// 通过 add(segmentTitle:viewController:) 来设置好对应的 segment 和 VC open func setupSegmentTab(){ } @objc func onSelectedSegmentalChanged(){ showSegmentTab(index: segmentControl.selectedSegmentIndex) } public func showSegmentTab(index:Int){ if index == previousSelectedSegmentIndex{ return } var oldTabVC:UIViewController? if previousSelectedSegmentIndex > -1{ oldTabVC = segmentIndexViewControllerMap[previousSelectedSegmentIndex] } guard let newTabVC = segmentIndexViewControllerMap[index] else{ return } if let oldVC = oldTabVC{ let direction : UIPageViewControllerNavigationDirection = (index > previousSelectedSegmentIndex) ? .forward : .reverse switchFromViewController(oldVC, toViewController: newTabVC, navigationDirection: direction) }else{ displayTabViewController(newTabVC) } previousSelectedSegmentIndex = index } }
mit
cf0dd586319df9487988103a2af6ad08
29.011494
126
0.750287
5.222
false
false
false
false
coderwjq/swiftweibo
SwiftWeibo/SwiftWeibo/Classes/Home/Controller/WJQPresentationController.swift
1
1460
// // WJQPresentationController.swift // SwiftWeibo // // Created by mzzdxt on 2016/10/31. // Copyright © 2016年 wjq. All rights reserved. // import UIKit class WJQPresentationController: UIPresentationController { // MARK:- 对外提供的属性 var presentedFrame: CGRect = CGRect.zero // MARK:- 懒加载属性 fileprivate lazy var coverView: UIView = UIView() // MARK:- 系统回调函数 override func containerViewWillLayoutSubviews() { super.containerViewWillLayoutSubviews() // 设置弹出View的尺寸 presentedView?.frame = presentedFrame // 添加蒙版 setupCoverView() } } // MARK:- 设置UI界面相关 extension WJQPresentationController { fileprivate func setupCoverView() { // 添加蒙版 containerView?.insertSubview(coverView, at: 0) // 设置蒙版属性 coverView.backgroundColor = UIColor(white: 0.2, alpha: 0.5) coverView.frame = containerView!.bounds // 添加Tap手势 let tapGesture = UITapGestureRecognizer(target: self, action: #selector(WJQPresentationController.coverViewClick)) coverView.addGestureRecognizer(tapGesture) } } // MARK:- 事件监听 extension WJQPresentationController { @objc fileprivate func coverViewClick() { presentedViewController.dismiss(animated: true, completion: nil) print("撤销蒙版") } }
apache-2.0
d748fd3bfe204854a0188504e297a019
24.826923
122
0.662695
4.830935
false
false
false
false
xmartlabs/Bender
Sources/Layers/DepthwiseConvolution.swift
1
1606
// // DepthwiseConvolution.swift // MetalBender // // Created by Mathias Claassen on 2/23/18. // import MetalPerformanceShaders import MetalPerformanceShadersProxy /// Depthwise Convolution layer @available(iOS 11.0, *) open class DepthwiseConvolution: Convolution { public required override init(convSize: ConvSize, neuronType: ActivationNeuronType = .none, useBias: Bool = false, padding: PaddingType = .same, weights: Data? = nil, bias: Data? = nil, id: String? = nil) { super.init(convSize: convSize, neuronType: neuronType, useBias: useBias, padding: padding, weights: weights, bias: bias, id: id) } open override func createCNNDescriptor(device: MTLDevice) { cnnDescriptor = MPSCNNDepthWiseConvolutionDescriptor(kernelWidth: convSize.kernelWidth, kernelHeight: convSize.kernelHeight, inputFeatureChannels: prevSize.f, outputFeatureChannels: convSize.outputChannels, neuronFilter: neuronType.createNeuron(device: device)) cnnDescriptor.dilationRateX = convSize.dilationX cnnDescriptor.dilationRateY = convSize.dilationY cnnDescriptor.strideInPixelsX = convSize.strideX cnnDescriptor.strideInPixelsY = convSize.strideY } open override func getWeightsSize() -> Int { return prevSize.f * convSize.kernelHeight * convSize.kernelWidth } }
mit
8c2aa56c239e763286a74a44f6c4c497
43.611111
136
0.620797
4.92638
false
false
false
false
antonio081014/LeetCode-CodeBase
Swift/search-a-2d-matrix.swift
1
2445
/** * https://leetcode.com/problems/search-a-2d-matrix/ * * */ // Date: Thu Oct 29 10:43:49 PDT 2020 class Solution { /// - Complexity: /// - Time: O(n + m), n and m are the sizes of matrix. /// - Space: O(1) func searchMatrix(_ matrix: [[Int]], _ target: Int) -> Bool { guard let last = matrix.last, last.count > 0 else { return false } var r = matrix.count - 1 var c = 0 while r >= 0, c < last.count { if matrix[r][c] == target { return true } if matrix[r][c] > target { r -= 1 } else { c += 1 } } return false } } class Solution { /// - Complexity: /// - Time: O(logm + logn), n = matrix.count, m = matrix.first?.count ?? 0 /// - Space: O(1) func searchMatrix(_ matrix: [[Int]], _ target: Int) -> Bool { let n = matrix.count guard let m = matrix.first?.count else { return false } var left = 0 var right = n - 1 var row = -1 while left <= right { let mid = left + (right - left) / 2 if matrix[mid][0] <= target, matrix[mid][m - 1] >= target { row = mid break } else if matrix[mid][0] > target { right = mid - 1 } else { left = mid + 1 } } if row < 0 { return false } left = 0 right = m - 1 while left <= right { let mid = left + (right - left) / 2 if matrix[row][mid] == target { return true } if matrix[row][mid] > target { right = mid - 1 } else {left = mid + 1 } } return false } } class Solution { /// - Complexity: /// - Time: O(log(m * n)), n = matrix.count, m = matrix.first?.count ?? 0 /// - Space: O(1) func searchMatrix2(_ matrix: [[Int]], _ target: Int) -> Bool { let n = matrix.count guard let m = matrix.first?.count else { return false } var left = 0 var right = m * n - 1 while left <= right { let mid = left + (right - left) / 2 let r = mid / m let c = mid % m if matrix[r][c] == target { return true } if matrix[r][c] > target { right = mid - 1 } else { left = mid + 1 } } return false } }
mit
169c2356fc09351067875dbd8a342de4
29.185185
82
0.439673
3.744257
false
false
false
false
white-rabbit-apps/Fusuma
Sources/FSAlbumViewCell.swift
1
793
// // FSAlbumViewCell.swift // Fusuma // // Created by Yuta Akizuki on 2015/11/14. // Copyright © 2015年 ytakzk. All rights reserved. // import UIKit import Photos final class FSAlbumViewCell: UICollectionViewCell { @IBOutlet weak var imageView: UIImageView! var creationDate: NSDate? = nil var image: UIImage? { didSet { self.imageView.image = image } } override func awakeFromNib() { super.awakeFromNib() self.selected = false } override var selected : Bool { didSet { self.layer.borderColor = selected ? fusumaTintColor.CGColor : UIColor.clearColor().CGColor self.layer.borderWidth = selected ? 2 : 0 } } }
mit
87995291ca76b22020dde835a90736fa
20.351351
102
0.575949
4.787879
false
false
false
false
boyXiong/XWSwiftRefreshT
XWSwiftRefreshT/Footer/XWRefreshFooter.swift
2
1839
// // XWRefreshFooter.swift // XWRefresh // // Created by Xiong Wei on 15/9/11. // Copyright © 2015年 Xiong Wei. All rights reserved. // 新浪微博: @爱吃香干炒肉 import UIKit /** 抽象类,不直接使用,用于继承后,重写*/ public class XWRefreshFooter: XWRefreshComponent { //MARK: 提供外界访问的 /** 提示没有更多的数据 */ public func noticeNoMoreData(){ self.state = XWRefreshState.NoMoreData } /** 重置没有更多的数据(消除没有更多数据的状态) */ public func resetNoMoreData(){ self.state = XWRefreshState.Idle } /** 忽略多少scrollView的contentInset的bottom */ public var ignoredScrollViewContentInsetBottom:CGFloat = 0 /** 自动根据有无数据来显示和隐藏(有数据就显示,没有数据隐藏) */ public var automaticallyHidden:Bool = true //MARK: 私有的 //重写父类方法 override func prepare() { super.prepare() self.xw_height = XWRefreshFooterHeight } override public func willMoveToSuperview(newSuperview: UIView?) { super.willMoveToSuperview(newSuperview) if let _ = newSuperview { //监听scrollView数据的变化 //由于闭包是Any 所以不能采用关联对象 let tmpClass = xwReloadDataClosureInClass() tmpClass.reloadDataClosure = { (totalCount:Int) -> Void in if self.automaticallyHidden == true { //如果开启了自动隐藏,那就是在检查到总数量为 请求后的加载0 的时候就隐藏 self.hidden = totalCount == 0 } } self.scrollView.reloadDataClosureClass = tmpClass } } }
mit
58468423e7c898547c8baca51f3b9393
24.525424
76
0.596946
4.254237
false
false
false
false
iida-hayato/Moya-SwiftyJSONMapper
Example/Moya-SwiftyJSONMapper/ExampleAPI.swift
1
2961
// // ExampleAPI.swift // Moya-SwiftyJSONMapper // // Created by Antoine van der Lee on 25/01/16. // Copyright © 2016 CocoaPods. All rights reserved. // import Foundation import Moya import Moya_SwiftyJSONMapper import ReactiveCocoa import SwiftyJSON let stubbedProvider = MoyaProvider<ExampleAPI>(stubClosure: MoyaProvider.ImmediatelyStub) let RCStubbedProvider = ReactiveCocoaMoyaProvider<ExampleAPI>(stubClosure: MoyaProvider.ImmediatelyStub) let RXStubbedProvider = RxMoyaProvider<ExampleAPI>(stubClosure: MoyaProvider.ImmediatelyStub) enum ExampleAPI { case GetObject case GetArray } extension ExampleAPI: JSONMappableTargetType { var baseURL: NSURL { return NSURL(string: "https://httpbin.org")! } var path: String { switch self { case .GetObject: return "/get" case .GetArray: return "/getarray" // Does not really works, but will work for stubbed response } } var method: Moya.Method { return .GET } var parameters: [String: AnyObject]? { return nil } var sampleData: NSData { switch self { case .GetObject: return stubbedResponseFromJSONFile("object_response") case .GetArray: return stubbedResponseFromJSONFile("array_response") } } var responseType: ALSwiftyJSONAble.Type { switch self { case .GetObject: return GetResponse.self case .GetArray: return GetResponse.self } } var multipartBody: [MultipartFormData]? { return nil } } // Then add an additional request method // Is not working: //func requestType<T:ALSwiftyJSONAble>(target: ExampleAPI) -> SignalProducer<T, Moya.Error> { // return RCStubbedProvider.request(target).mapObject(target.responseType) //} // Works but has al the mapping logic in it, I don't want that! func requestType<T:ALSwiftyJSONAble>(target: ExampleAPI) -> SignalProducer<T, Moya.Error> { return RCStubbedProvider.request(target).flatMap(FlattenStrategy.Latest, transform: { (response) -> SignalProducer<T, Moya.Error> in do { let jsonObject = try response.mapJSON() guard let mappedObject = T(jsonData: JSON(jsonObject)) else { throw Error.JSONMapping(response) } return SignalProducer(value: mappedObject) } catch let error { return SignalProducer(error: Moya.Error.Underlying(error as NSError)) } }) } protocol JSONMappableTargetType: TargetType { var responseType: ALSwiftyJSONAble.Type { get } } private func stubbedResponseFromJSONFile(filename: String, inDirectory subpath: String = "", bundle:NSBundle = NSBundle.mainBundle() ) -> NSData { guard let path = bundle.pathForResource(filename, ofType: "json", inDirectory: subpath) else { return NSData() } return NSData(contentsOfFile: path) ?? NSData() }
mit
ecfb3b9033c0d2e21b2828c22f3a028d
31.538462
146
0.672635
4.720893
false
false
false
false
nguyenantinhbk77/practice-swift
CoreData/Reading data from CoreData/Reading data from CoreData/AppDelegate.swift
2
8099
// // AppDelegate.swift // Reading data from CoreData // // Created by Domenico Solazzo on 17/05/15. // License MIT // import UIKit import CoreData @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? //- MARK: Helper methods func createNewPerson(firstName: String, lastName: String, age:Int) -> Bool{ let entityName = NSStringFromClass(Person.classForCoder()) let newPerson = NSEntityDescription.insertNewObjectForEntityForName(entityName, inManagedObjectContext: managedObjectContext!) as! Person (newPerson.firstName, newPerson.lastName, newPerson.age) = (firstName, lastName, age) var savingError: NSError? if managedObjectContext!.save(&savingError){ println("Successfully saved...") }else{ if let error = savingError{ println("Failed to save the new person. Error = \(error)") } } return false } //- MARK: Application Delegate func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. // Creating new person self.createNewPerson("Domenico", lastName: "Solazzo", age: 33) self.createNewPerson("Steve", lastName: "Jobs", age: 55) /* Tell the request that we want to read the contents from the Person entity */ // Create the fetch request let fetchRequest = NSFetchRequest(entityName: "Person") var requestError: NSError? let persons = managedObjectContext!.executeFetchRequest(fetchRequest, error: &requestError) as! [Person] /* Make sure we get the array */ if persons.count > 0{ var counter = 1 for person in persons{ println("Person \(counter) first name = \(person.firstName)") println("Person \(counter) last name = \(person.lastName)") println("Person \(counter) age = \(person.age)") counter++ } } else { println("Could not find any Person entities in the context") } return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. // Saves changes in the application's managed object context before the application terminates. self.saveContext() } // MARK: - Core Data stack lazy var applicationDocumentsDirectory: NSURL = { // The directory the application uses to store the Core Data store file. This code uses a directory named "com.domenicosolazzo.swift.Reading_data_from_CoreData" in the application's documents Application Support directory. let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask) return urls[urls.count-1] as! NSURL }() lazy var managedObjectModel: NSManagedObjectModel = { // The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model. let modelURL = NSBundle.mainBundle().URLForResource("Reading_data_from_CoreData", withExtension: "momd")! return NSManagedObjectModel(contentsOfURL: modelURL)! }() lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = { // The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. // Create the coordinator and store var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel) let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("Reading_data_from_CoreData.sqlite") var error: NSError? = nil var failureReason = "There was an error creating or loading the application's saved data." if coordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil, error: &error) == nil { coordinator = nil // Report any error we got. var dict = [String: AnyObject]() dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" dict[NSLocalizedFailureReasonErrorKey] = failureReason dict[NSUnderlyingErrorKey] = error error = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict) // Replace this with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. NSLog("Unresolved error \(error), \(error!.userInfo)") abort() } return coordinator }() lazy var managedObjectContext: NSManagedObjectContext? = { // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail. let coordinator = self.persistentStoreCoordinator if coordinator == nil { return nil } var managedObjectContext = NSManagedObjectContext() managedObjectContext.persistentStoreCoordinator = coordinator return managedObjectContext }() // MARK: - Core Data Saving support func saveContext () { if let moc = self.managedObjectContext { var error: NSError? = nil if moc.hasChanges && !moc.save(&error) { // Replace this implementation with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. NSLog("Unresolved error \(error), \(error!.userInfo)") abort() } } } }
mit
9c7759aaf4330043de14ae6073d38d04
48.993827
290
0.679467
5.735836
false
false
false
false
haitran2011/Rocket.Chat.iOS
Rocket.Chat/Controllers/Subscriptions/SubscriptionsViewController.swift
1
15209
// // SubscriptionsViewController.swift // Rocket.Chat // // Created by Rafael K. Streit on 7/21/16. // Copyright © 2016 Rocket.Chat. All rights reserved. // import RealmSwift // swiftlint:disable file_length final class SubscriptionsViewController: BaseViewController { @IBOutlet weak var tableView: UITableView! @IBOutlet weak var activityViewSearching: UIActivityIndicatorView! let defaultButtonCancelSearchWidth = CGFloat(65) @IBOutlet weak var buttonCancelSearch: UIButton! { didSet { buttonCancelSearch.setTitle(localized("global.cancel"), for: .normal) } } @IBOutlet weak var buttonCancelSearchWidthConstraint: NSLayoutConstraint! { didSet { buttonCancelSearchWidthConstraint.constant = 0 } } @IBOutlet weak var textFieldSearch: UITextField! { didSet { textFieldSearch.placeholder = localized("subscriptions.search") if let placeholder = textFieldSearch.placeholder { let color = UIColor(rgb: 0x9AB1BF, alphaVal: 1) textFieldSearch.attributedPlaceholder = NSAttributedString(string:placeholder, attributes: [NSForegroundColorAttributeName: color]) } } } @IBOutlet weak var viewTextField: UIView! { didSet { viewTextField.layer.cornerRadius = 4 viewTextField.layer.masksToBounds = true } } weak var viewUserMenu: SubscriptionUserStatusView? @IBOutlet weak var viewUser: UIView! { didSet { let gesture = UITapGestureRecognizer(target: self, action: #selector(viewUserDidTap)) viewUser.addGestureRecognizer(gesture) } } @IBOutlet weak var viewUserStatus: UIView! @IBOutlet weak var labelUsername: UILabel! @IBOutlet weak var imageViewArrowDown: UIImageView! { didSet { imageViewArrowDown.image = imageViewArrowDown.image?.imageWithTint(.RCLightBlue()) } } class func sharedInstance() -> SubscriptionsViewController? { if let main = UIApplication.shared.delegate?.window??.rootViewController as? MainChatViewController { if let nav = main.sideViewController as? UINavigationController { return nav.viewControllers.first as? SubscriptionsViewController } } return nil } var assigned = false var isSearchingLocally = false var isSearchingRemotely = false var searchResult: [Subscription]? var subscriptions: Results<Subscription>? var subscriptionsToken: NotificationToken? var usersToken: NotificationToken? var groupInfomation: [[String: String]]? var groupSubscriptions: [[Subscription]]? override func awakeFromNib() { super.awakeFromNib() subscribeModelChanges() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) updateCurrentUserInformation() } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) unregisterKeyboardNotifications() dismissUserMenu() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) tableView.reloadData() registerKeyboardHandlers(tableView) } } extension SubscriptionsViewController { @IBAction func buttonCancelSearchDidPressed(_ sender: Any) { textFieldSearch.resignFirstResponder() } func searchBy(_ text: String = "") { guard let auth = AuthManager.isAuthenticated() else { return } subscriptions = auth.subscriptions.filter("name CONTAINS %@", text) if text.characters.count == 0 { isSearchingLocally = false isSearchingRemotely = false searchResult = [] groupSubscription() tableView.reloadData() tableView.tableFooterView = nil activityViewSearching.stopAnimating() return } if subscriptions?.count == 0 { searchOnSpotlight(text) return } isSearchingLocally = true isSearchingRemotely = false groupSubscription() tableView.reloadData() if let footerView = SubscriptionSearchMoreView.instantiateFromNib() { footerView.delegate = self tableView.tableFooterView = footerView } } func searchOnSpotlight(_ text: String = "") { tableView.tableFooterView = nil activityViewSearching.startAnimating() SubscriptionManager.spotlight(text) { [weak self] result in let currentText = self?.textFieldSearch.text ?? "" if currentText.characters.count == 0 { return } self?.activityViewSearching.stopAnimating() self?.isSearchingRemotely = true self?.searchResult = result self?.groupSubscription() self?.tableView.reloadData() } } func handleModelUpdates<T>(_: RealmCollectionChange<RealmSwift.Results<T>>?) { guard !isSearchingLocally && !isSearchingRemotely else { return } guard let auth = AuthManager.isAuthenticated() else { return } subscriptions = auth.subscriptions.sorted(byKeyPath: "lastSeen", ascending: false) groupSubscription() updateCurrentUserInformation() tableView?.reloadData() } func updateCurrentUserInformation() { guard let user = AuthManager.currentUser() else { return } guard let labelUsername = self.labelUsername else { return } guard let viewUserStatus = self.viewUserStatus else { return } labelUsername.text = user.username ?? "" switch user.status { case .online: viewUserStatus.backgroundColor = .RCOnline() break case .busy: viewUserStatus.backgroundColor = .RCBusy() break case .away: viewUserStatus.backgroundColor = .RCAway() break case .offline: viewUserStatus.backgroundColor = .RCInvisible() break } } func subscribeModelChanges() { guard !assigned else { return } guard let auth = AuthManager.isAuthenticated() else { return } assigned = true subscriptions = auth.subscriptions.sorted(byKeyPath: "lastSeen", ascending: false) subscriptionsToken = subscriptions?.addNotificationBlock(handleModelUpdates) usersToken = try? Realm().addNotificationBlock { [weak self] _, _ in self?.handleModelUpdates(nil) } groupSubscription() } // swiftlint:disable function_body_length cyclomatic_complexity func groupSubscription() { var unreadGroup: [Subscription] = [] var favoriteGroup: [Subscription] = [] var channelGroup: [Subscription] = [] var directMessageGroup: [Subscription] = [] var searchResultsGroup: [Subscription] = [] guard let subscriptions = subscriptions else { return } let orderSubscriptions = isSearchingRemotely ? searchResult : Array(subscriptions.sorted(byKeyPath: "name", ascending: true)) for subscription in orderSubscriptions ?? [] { if isSearchingRemotely { searchResultsGroup.append(subscription) } if !isSearchingLocally && !subscription.open { continue } if subscription.alert { unreadGroup.append(subscription) continue } if subscription.favorite { favoriteGroup.append(subscription) continue } switch subscription.type { case .channel, .group: channelGroup.append(subscription) case .directMessage: directMessageGroup.append(subscription) } } groupInfomation = [[String: String]]() groupSubscriptions = [[Subscription]]() if searchResultsGroup.count > 0 { groupInfomation?.append([ "name": String(format: "%@ (%d)", localized("subscriptions.search_results"), searchResultsGroup.count) ]) searchResultsGroup = searchResultsGroup.sorted { return $0.name < $1.name } groupSubscriptions?.append(searchResultsGroup) } else { if unreadGroup.count > 0 { groupInfomation?.append([ "name": String(format: "%@ (%d)", localized("subscriptions.unreads"), unreadGroup.count) ]) unreadGroup = unreadGroup.sorted { return $0.type.rawValue < $1.type.rawValue } groupSubscriptions?.append(unreadGroup) } if favoriteGroup.count > 0 { groupInfomation?.append([ "icon": "Star", "name": String(format: "%@ (%d)", localized("subscriptions.favorites"), favoriteGroup.count) ]) favoriteGroup = favoriteGroup.sorted { return $0.type.rawValue < $1.type.rawValue } groupSubscriptions?.append(favoriteGroup) } if channelGroup.count > 0 { groupInfomation?.append([ "name": String(format: "%@ (%d)", localized("subscriptions.channels"), channelGroup.count) ]) groupSubscriptions?.append(channelGroup) } if directMessageGroup.count > 0 { groupInfomation?.append([ "name": String(format: "%@ (%d)", localized("subscriptions.direct_messages"), directMessageGroup.count) ]) groupSubscriptions?.append(directMessageGroup) } } } } extension SubscriptionsViewController: UITableViewDataSource { func numberOfSections(in tableView: UITableView) -> Int { return groupInfomation?.count ?? 0 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return groupSubscriptions?[section].count ?? 0 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { guard let cell = tableView.dequeueReusableCell(withIdentifier: SubscriptionCell.identifier) as? SubscriptionCell else { return UITableViewCell() } let subscription = groupSubscriptions?[indexPath.section][indexPath.row] cell.subscription = subscription return cell } } extension SubscriptionsViewController: UITableViewDelegate { func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return section == 0 ? 50 : 60 } func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { guard let group = groupInfomation?[section] else { return nil } guard let view = SubscriptionSectionView.instantiateFromNib() else { return nil } view.setIconName(group["icon"]) view.setTitle(group["name"]) return view } func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? { if let selected = tableView.indexPathForSelectedRow { tableView.deselectRow(at: selected, animated: true) } return indexPath } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let subscription = self.groupSubscriptions?[indexPath.section][indexPath.row] let controller = ChatViewController.sharedInstance() controller?.closeSidebarAfterSubscriptionUpdate = true controller?.subscription = subscription } func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) { guard let subscriptionCell = cell as? SubscriptionCell else { return } guard let selectedSubscription = ChatViewController.sharedInstance()?.subscription else { return } if subscriptionCell.subscription == selectedSubscription { tableView.selectRow(at: indexPath, animated: false, scrollPosition: .none) } } } extension SubscriptionsViewController: UITextFieldDelegate { func textFieldDidBeginEditing(_ textField: UITextField) { buttonCancelSearchWidthConstraint.constant = defaultButtonCancelSearchWidth UIView.animate(withDuration: 0.1) { self.view.layoutIfNeeded() } } func textFieldDidEndEditing(_ textField: UITextField) { buttonCancelSearchWidthConstraint.constant = 0 UIView.animate(withDuration: 0.1) { self.view.layoutIfNeeded() } } func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { let currentText = textField.text ?? "" let prospectiveText = (currentText as NSString).replacingCharacters(in: range, with: string) if string == "\n" { if currentText.characters.count > 0 { searchOnSpotlight(currentText) } return false } searchBy(prospectiveText) return true } func textFieldShouldClear(_ textField: UITextField) -> Bool { searchBy() return true } } extension SubscriptionsViewController: SubscriptionSearchMoreViewDelegate { func buttonLoadMoreDidPressed() { searchOnSpotlight(textFieldSearch.text ?? "") } } extension SubscriptionsViewController: SubscriptionUserStatusViewProtocol { func presentUserMenu() { guard let viewUserMenu = SubscriptionUserStatusView.instantiateFromNib() else { return } var newFrame = view.frame newFrame.origin.y = -newFrame.height viewUserMenu.frame = newFrame viewUserMenu.delegate = self viewUserMenu.parentController = self view.addSubview(viewUserMenu) self.viewUserMenu = viewUserMenu newFrame.origin.y = 64 UIView.animate(withDuration: 0.15) { viewUserMenu.frame = newFrame self.imageViewArrowDown.transform = CGAffineTransform(rotationAngle: CGFloat.pi) } } func dismissUserMenu() { guard let viewUserMenu = viewUserMenu else { return } var newFrame = viewUserMenu.frame newFrame.origin.y = -newFrame.height UIView.animate(withDuration: 0.15, animations: { viewUserMenu.frame = newFrame self.imageViewArrowDown.transform = CGAffineTransform(rotationAngle: CGFloat(0)) }) { (_) in viewUserMenu.removeFromSuperview() } } func viewUserDidTap(sender: Any) { textFieldSearch.resignFirstResponder() if viewUserMenu != nil { dismissUserMenu() } else { presentUserMenu() } } func userDidPressedOption() { dismissUserMenu() } }
mit
b3d058814819aec179079694ec3a1be3
31.495726
147
0.62717
5.738868
false
false
false
false
lorentey/swift
test/IRGen/generic_tuples.swift
6
6798
// RUN: %target-swift-frontend -module-name generic_tuples -emit-ir -primary-file %s | %FileCheck %s // Make sure that optimization passes don't choke on storage types for generic tuples // RUN: %target-swift-frontend -module-name generic_tuples -emit-ir -O %s // REQUIRES: CPU=x86_64 // CHECK: [[TYPE:%swift.type]] = type { // CHECK: [[OPAQUE:%swift.opaque]] = type opaque // CHECK: [[TUPLE_TYPE:%swift.tuple_type]] = type { [[TYPE]], i64, i8*, [0 x %swift.tuple_element_type] } // CHECK: %swift.tuple_element_type = type { [[TYPE]]*, i32 } func dup<T>(_ x: T) -> (T, T) { var x = x; return (x,x) } // CHECK: define hidden swiftcc void @"$s14generic_tuples3dupyx_xtxlF"(%swift.opaque* noalias nocapture, %swift.opaque* noalias nocapture, %swift.opaque* noalias nocapture, %swift.type* %T) // CHECK: entry: // Allocate a local variable for 'x'. // CHECK: [[TYPE_ADDR:%.*]] = bitcast %swift.type* %T to i8*** // CHECK: [[VWT_ADDR:%.*]] = getelementptr inbounds i8**, i8*** [[TYPE_ADDR]], i64 -1 // CHECK: [[VWT:%.*]] = load i8**, i8*** [[VWT_ADDR]] // CHECK: [[VWT_CAST:%.*]] = bitcast i8** [[VWT]] to %swift.vwtable* // CHECK: [[SIZE_ADDR:%.*]] = getelementptr inbounds %swift.vwtable, %swift.vwtable* [[VWT_CAST]], i32 0, i32 8 // CHECK: [[SIZE:%.*]] = load i64, i64* [[SIZE_ADDR]] // CHECK: [[X_ALLOCA:%.*]] = alloca i8, {{.*}} [[SIZE]], align 16 // CHECK: [[X_TMP:%.*]] = bitcast i8* [[X_ALLOCA]] to %swift.opaque* // Debug info shadow copy. // CHECK-NEXT: store i8* [[X_ALLOCA]] // CHECK-NEXT: [[WITNESS_ADDR:%.*]] = getelementptr inbounds i8*, i8** [[VWT]], i32 2 // CHECK-NEXT: [[WITNESS:%.*]] = load i8*, i8** [[WITNESS_ADDR]], align 8 // CHECK-NEXT: [[INITIALIZE_WITH_COPY:%.*]] = bitcast i8* [[WITNESS]] to [[OPAQUE]]* ([[OPAQUE]]*, [[OPAQUE]]*, [[TYPE]]*)* // CHECK-NEXT: [[X:%.*]] = call [[OPAQUE]]* [[INITIALIZE_WITH_COPY]]([[OPAQUE]]* noalias [[X_TMP]], [[OPAQUE]]* noalias {{.*}}, [[TYPE]]* %T) // Copy 'x' into the first result. // CHECK-NEXT: call [[OPAQUE]]* [[INITIALIZE_WITH_COPY]]([[OPAQUE]]* noalias %0, [[OPAQUE]]* noalias [[X_TMP]], [[TYPE]]* %T) // Copy 'x' into the second element. // CHECK-NEXT: [[WITNESS_ADDR:%.*]] = getelementptr inbounds i8*, i8** [[VWT]], i32 4 // CHECK-NEXT: [[WITNESS:%.*]] = load i8*, i8** [[WITNESS_ADDR]], align 8 // CHECK-NEXT: [[TAKE_FN:%.*]] = bitcast i8* [[WITNESS]] to [[OPAQUE]]* ([[OPAQUE]]*, [[OPAQUE]]*, [[TYPE]]*)* // CHECK-NEXT: call [[OPAQUE]]* [[TAKE_FN]]([[OPAQUE]]* noalias %1, [[OPAQUE]]* noalias [[X_TMP]], [[TYPE]]* %T) struct S {} func callDup(_ s: S) { _ = dup(s) } // CHECK-LABEL: define hidden swiftcc void @"$s14generic_tuples7callDupyyAA1SVF"() // CHECK-NEXT: entry: // CHECK-NEXT: call swiftcc void @"$s14generic_tuples3dupyx_xtxlF"({{.*}} undef, {{.*}} undef, %swift.type* {{.*}} @"$s14generic_tuples1SVMf", {{.*}}) // CHECK-NEXT: ret void class C {} func dupC<T : C>(_ x: T) -> (T, T) { return (x, x) } // CHECK-LABEL: define hidden swiftcc { %T14generic_tuples1CC*, %T14generic_tuples1CC* } @"$s14generic_tuples4dupCyx_xtxAA1CCRbzlF"(%T14generic_tuples1CC*, %swift.type* %T) // CHECK-NEXT: entry: // CHECK: [[REF:%.*]] = bitcast %T14generic_tuples1CC* %0 to %swift.refcounted* // CHECK-NEXT: call %swift.refcounted* @swift_retain(%swift.refcounted* returned [[REF]]) // CHECK-NEXT: [[REF:%.*]] = bitcast %T14generic_tuples1CC* %0 to %swift.refcounted* // CHECK-NEXT: call %swift.refcounted* @swift_retain(%swift.refcounted* returned [[REF]]) // CHECK-NEXT: [[TUP1:%.*]] = insertvalue { %T14generic_tuples1CC*, %T14generic_tuples1CC* } undef, %T14generic_tuples1CC* %0, 0 // CHECK-NEXT: [[TUP2:%.*]] = insertvalue { %T14generic_tuples1CC*, %T14generic_tuples1CC* } [[TUP1:%.*]], %T14generic_tuples1CC* %0, 1 // CHECK-NEXT: ret { %T14generic_tuples1CC*, %T14generic_tuples1CC* } [[TUP2]] func callDupC(_ c: C) { _ = dupC(c) } // CHECK-LABEL: define hidden swiftcc void @"$s14generic_tuples8callDupCyyAA1CCF"(%T14generic_tuples1CC*) // CHECK-NEXT: entry: // CHECK: [[REQUEST:%.*]] = call {{.*}} @"$s14generic_tuples1CCMa" // CHECK-NEXT: [[METATYPE:%.*]] = extractvalue {{.*}} [[REQUEST]] // CHECK-NEXT: [[TUPLE:%.*]] = call swiftcc { %T14generic_tuples1CC*, %T14generic_tuples1CC* } @"$s14generic_tuples4dupCyx_xtxAA1CCRbzlF"(%T14generic_tuples1CC* %0, %swift.type* [[METATYPE]]) // CHECK-NEXT: [[LEFT:%.*]] = extractvalue { %T14generic_tuples1CC*, %T14generic_tuples1CC* } [[TUPLE]], 0 // CHECK-NEXT: [[RIGHT:%.*]] = extractvalue { %T14generic_tuples1CC*, %T14generic_tuples1CC* } [[TUPLE]], 1 // CHECK-NEXT: call void bitcast (void (%swift.refcounted*)* @swift_release to void (%T14generic_tuples1CC*)*)(%T14generic_tuples1CC* [[RIGHT]]) // CHECK-NEXT: call void bitcast (void (%swift.refcounted*)* @swift_release to void (%T14generic_tuples1CC*)*)(%T14generic_tuples1CC* [[LEFT]]) // CHECK-NEXT: ret void // CHECK: define hidden swiftcc i64 @"$s14generic_tuples4lumpySi_xxtxlF"(%swift.opaque* noalias nocapture, %swift.opaque* noalias nocapture, %swift.opaque* noalias nocapture, %swift.type* %T) func lump<T>(_ x: T) -> (Int, T, T) { return (0,x,x) } // CHECK: define hidden swiftcc { i64, i64 } @"$s14generic_tuples5lump2ySi_SixtxlF"(%swift.opaque* noalias nocapture, %swift.opaque* noalias nocapture, %swift.type* %T) func lump2<T>(_ x: T) -> (Int, Int, T) { return (0,0,x) } // CHECK: define hidden swiftcc void @"$s14generic_tuples5lump3yx_xxtxlF"(%swift.opaque* noalias nocapture, %swift.opaque* noalias nocapture, %swift.opaque* noalias nocapture, %swift.opaque* noalias nocapture, %swift.type* %T) func lump3<T>(_ x: T) -> (T, T, T) { return (x,x,x) } // CHECK: define hidden swiftcc i64 @"$s14generic_tuples5lump4yx_SixtxlF"(%swift.opaque* noalias nocapture, %swift.opaque* noalias nocapture, %swift.opaque* noalias nocapture, %swift.type* %T) func lump4<T>(_ x: T) -> (T, Int, T) { return (x,0,x) } // CHECK: define hidden swiftcc i64 @"$s14generic_tuples6unlumpyS2i_xxt_tlF"(i64, %swift.opaque* noalias nocapture, %swift.opaque* noalias nocapture, %swift.type* %T) func unlump<T>(_ x: (Int, T, T)) -> Int { return x.0 } // CHECK: define hidden swiftcc void @"$s14generic_tuples7unlump1yxSi_xxt_tlF"(%swift.opaque* noalias nocapture sret, i64, %swift.opaque* noalias nocapture, %swift.opaque* noalias nocapture, %swift.type* %T) func unlump1<T>(_ x: (Int, T, T)) -> T { return x.1 } // CHECK: define hidden swiftcc void @"$s14generic_tuples7unlump2yxx_Sixt_tlF"(%swift.opaque* noalias nocapture sret, %swift.opaque* noalias nocapture, i64, %swift.opaque* noalias nocapture, %swift.type* %T) func unlump2<T>(_ x: (T, Int, T)) -> T { return x.0 } // CHECK: define hidden swiftcc i64 @"$s14generic_tuples7unlump3ySix_Sixt_tlF"(%swift.opaque* noalias nocapture, i64, %swift.opaque* noalias nocapture, %swift.type* %T) func unlump3<T>(_ x: (T, Int, T)) -> Int { return x.1 }
apache-2.0
dabf4ea7adeaca7f2adc3d0896f89223
72.891304
226
0.650191
3.053908
false
false
false
false
alblue/swift
stdlib/public/SDK/Foundation/Data.swift
1
81976
//===----------------------------------------------------------------------===// // // 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 // //===----------------------------------------------------------------------===// #if DEPLOYMENT_RUNTIME_SWIFT #if os(macOS) || os(iOS) import Darwin #elseif os(Linux) import Glibc #endif import CoreFoundation internal func __NSDataInvokeDeallocatorUnmap(_ mem: UnsafeMutableRawPointer, _ length: Int) { munmap(mem, length) } internal func __NSDataInvokeDeallocatorFree(_ mem: UnsafeMutableRawPointer, _ length: Int) { free(mem) } internal func __NSDataIsCompact(_ data: NSData) -> Bool { return data._isCompact() } #else @_exported import Foundation // Clang module import _SwiftFoundationOverlayShims import _SwiftCoreFoundationOverlayShims internal func __NSDataIsCompact(_ data: NSData) -> Bool { if #available(OSX 10.10, iOS 8.0, tvOS 9.0, watchOS 2.0, *) { return data._isCompact() } else { var compact = true let len = data.length data.enumerateBytes { (_, byteRange, stop) in if byteRange.length != len { compact = false } stop.pointee = true } return compact } } #endif @usableFromInline internal final class _DataStorage { @usableFromInline enum Backing { // A mirror of the Objective-C implementation that is suitable to inline in Swift case swift // these two storage points for immutable and mutable data are reserved for references that are returned by "known" // cases from Foundation in which implement the backing of struct Data, these have signed up for the concept that // the backing bytes/mutableBytes pointer does not change per call (unless mutated) as well as the length is ok // to be cached, this means that as long as the backing reference is retained no further objc_msgSends need to be // dynamically dispatched out to the reference. case immutable(NSData) // This will most often (perhaps always) be NSConcreteData case mutable(NSMutableData) // This will often (perhaps always) be NSConcreteMutableData // These are reserved for foreign sources where neither Swift nor Foundation are fully certain whom they belong // to from an object inheritance standpoint, this means that all bets are off and the values of bytes, mutableBytes, // and length cannot be cached. This also means that all methods are expected to dynamically dispatch out to the // backing reference. case customReference(NSData) // tracks data references that are only known to be immutable case customMutableReference(NSMutableData) // tracks data references that are known to be mutable } static let maxSize = Int.max >> 1 static let vmOpsThreshold = NSPageSize() * 4 static func allocate(_ size: Int, _ clear: Bool) -> UnsafeMutableRawPointer? { if clear { return calloc(1, size) } else { return malloc(size) } } @usableFromInline static func move(_ dest_: UnsafeMutableRawPointer, _ source_: UnsafeRawPointer?, _ num_: Int) { var dest = dest_ var source = source_ var num = num_ if _DataStorage.vmOpsThreshold <= num && ((unsafeBitCast(source, to: Int.self) | Int(bitPattern: dest)) & (NSPageSize() - 1)) == 0 { let pages = NSRoundDownToMultipleOfPageSize(num) NSCopyMemoryPages(source!, dest, pages) source = source!.advanced(by: pages) dest = dest.advanced(by: pages) num -= pages } if num > 0 { memmove(dest, source!, num) } } static func shouldAllocateCleared(_ size: Int) -> Bool { return (size > (128 * 1024)) } @usableFromInline var _bytes: UnsafeMutableRawPointer? @usableFromInline var _length: Int @usableFromInline var _capacity: Int @usableFromInline var _needToZero: Bool @usableFromInline var _deallocator: ((UnsafeMutableRawPointer, Int) -> Void)? @usableFromInline var _backing: Backing = .swift @usableFromInline var _offset: Int @usableFromInline var bytes: UnsafeRawPointer? { @inlinable get { switch _backing { case .swift: return UnsafeRawPointer(_bytes)?.advanced(by: -_offset) case .immutable: return UnsafeRawPointer(_bytes)?.advanced(by: -_offset) case .mutable: return UnsafeRawPointer(_bytes)?.advanced(by: -_offset) case .customReference(let d): return d.bytes.advanced(by: -_offset) case .customMutableReference(let d): return d.bytes.advanced(by: -_offset) @unknown default: fatalError("Unknown Data backing type") } } } @usableFromInline @discardableResult func withUnsafeBytes<Result>(in range: Range<Int>, apply: (UnsafeRawBufferPointer) throws -> Result) rethrows -> Result { switch _backing { case .swift: fallthrough case .immutable: fallthrough case .mutable: return try apply(UnsafeRawBufferPointer(start: _bytes?.advanced(by: range.lowerBound - _offset), count: Swift.min(range.count, _length))) case .customReference(let d): if __NSDataIsCompact(d) { let len = d.length guard len > 0 else { return try apply(UnsafeRawBufferPointer(start: nil, count: 0)) } return try apply(UnsafeRawBufferPointer(start: d.bytes.advanced(by: range.lowerBound - _offset), count: Swift.min(range.count, len))) } else { var buffer = UnsafeMutableRawBufferPointer.allocate(byteCount: range.count, alignment: MemoryLayout<UInt>.alignment) defer { buffer.deallocate() } let sliceRange = NSRange(location: range.lowerBound - _offset, length: range.count) var enumerated = 0 d.enumerateBytes { (ptr, byteRange, stop) in if byteRange.upperBound - _offset < range.lowerBound { // before the range that we are looking for... } else if byteRange.lowerBound - _offset > range.upperBound { stop.pointee = true // we are past the range in question so we need to stop } else { // the byteRange somehow intersects the range in question that we are looking for... let lower = Swift.max(byteRange.lowerBound - _offset, range.lowerBound) let upper = Swift.min(byteRange.upperBound - _offset, range.upperBound) let len = upper - lower memcpy(buffer.baseAddress!.advanced(by: enumerated), ptr.advanced(by: lower - (byteRange.lowerBound - _offset)), len) enumerated += len if upper == range.upperBound { stop.pointee = true } } } return try apply(UnsafeRawBufferPointer(buffer)) } case .customMutableReference(let d): if __NSDataIsCompact(d) { let len = d.length guard len > 0 else { return try apply(UnsafeRawBufferPointer(start: nil, count: 0)) } return try apply(UnsafeRawBufferPointer(start: d.bytes.advanced(by: range.lowerBound - _offset), count: Swift.min(range.count, len))) } else { var buffer = UnsafeMutableRawBufferPointer.allocate(byteCount: range.count, alignment: MemoryLayout<UInt>.alignment) defer { buffer.deallocate() } var enumerated = 0 d.enumerateBytes { (ptr, byteRange, stop) in if byteRange.upperBound - _offset < range.lowerBound { // before the range that we are looking for... } else if byteRange.lowerBound - _offset > range.upperBound { stop.pointee = true // we are past the range in question so we need to stop } else { // the byteRange somehow intersects the range in question that we are looking for... let lower = Swift.max(byteRange.lowerBound - _offset, range.lowerBound) let upper = Swift.min(byteRange.upperBound - _offset, range.upperBound) let len = upper - lower memcpy(buffer.baseAddress!.advanced(by: enumerated), ptr.advanced(by: lower - (byteRange.lowerBound - _offset)), len) enumerated += len if upper == range.upperBound { stop.pointee = true } } } return try apply(UnsafeRawBufferPointer(buffer)) } } } @usableFromInline @discardableResult func withUnsafeMutableBytes<Result>(in range: Range<Int>, apply: (UnsafeMutableRawBufferPointer) throws -> Result) rethrows -> Result { switch _backing { case .swift: fallthrough case .mutable: return try apply(UnsafeMutableRawBufferPointer(start: _bytes!.advanced(by:range.lowerBound - _offset), count: Swift.min(range.count, _length))) case .customMutableReference(let d): let len = d.length return try apply(UnsafeMutableRawBufferPointer(start: d.mutableBytes.advanced(by:range.lowerBound - _offset), count: Swift.min(range.count, len))) case .immutable(let d): let data = d.mutableCopy() as! NSMutableData _backing = .mutable(data) _bytes = data.mutableBytes return try apply(UnsafeMutableRawBufferPointer(start: _bytes!.advanced(by:range.lowerBound - _offset), count: Swift.min(range.count, _length))) case .customReference(let d): let data = d.mutableCopy() as! NSMutableData _backing = .customMutableReference(data) let len = data.length return try apply(UnsafeMutableRawBufferPointer(start: data.mutableBytes.advanced(by:range.lowerBound - _offset), count: Swift.min(range.count, len))) } } var mutableBytes: UnsafeMutableRawPointer? { @inlinable get { switch _backing { case .swift: return _bytes?.advanced(by: -_offset) case .immutable(let d): let data = d.mutableCopy() as! NSMutableData data.length = length _backing = .mutable(data) _bytes = data.mutableBytes return _bytes?.advanced(by: -_offset) case .mutable: return _bytes?.advanced(by: -_offset) case .customReference(let d): let data = d.mutableCopy() as! NSMutableData data.length = length _backing = .customMutableReference(data) return data.mutableBytes.advanced(by: -_offset) case .customMutableReference(let d): return d.mutableBytes.advanced(by: -_offset) @unknown default: fatalError("Unknown Data backing type") } } } @usableFromInline var length: Int { @inlinable get { switch _backing { case .swift: return _length case .immutable: return _length case .mutable: return _length case .customReference(let d): return d.length case .customMutableReference(let d): return d.length @unknown default: fatalError("Unknown Data backing type") } } @inlinable set { setLength(newValue) } } func _freeBytes() { if let bytes = _bytes { if let dealloc = _deallocator { dealloc(bytes, length) } else { free(bytes) } } } func enumerateBytes(in range: Range<Int>, _ block: (_ buffer: UnsafeBufferPointer<UInt8>, _ byteIndex: Data.Index, _ stop: inout Bool) -> Void) { var stopv: Bool = false var data: NSData switch _backing { case .swift: fallthrough case .immutable: fallthrough case .mutable: block(UnsafeBufferPointer<UInt8>(start: _bytes?.advanced(by: range.lowerBound - _offset).assumingMemoryBound(to: UInt8.self), count: Swift.min(range.count, _length)), 0, &stopv) return case .customReference(let d): data = d break case .customMutableReference(let d): data = d break } data.enumerateBytes { (ptr, region, stop) in // any region that is not in the range should be skipped guard range.contains(region.lowerBound) || range.contains(region.upperBound) else { return } var regionAdjustment = 0 if region.lowerBound < range.lowerBound { regionAdjustment = range.lowerBound - (region.lowerBound - _offset) } let bytePtr = ptr.advanced(by: regionAdjustment).assumingMemoryBound(to: UInt8.self) let effectiveLength = Swift.min((region.location - _offset) + region.length, range.upperBound) - (region.location - _offset) block(UnsafeBufferPointer(start: bytePtr, count: effectiveLength - regionAdjustment), region.location + regionAdjustment - _offset, &stopv) if stopv { stop.pointee = true } } } @usableFromInline @inline(never) func _grow(_ newLength: Int, _ clear: Bool) { let cap = _capacity var additionalCapacity = (newLength >> (_DataStorage.vmOpsThreshold <= newLength ? 2 : 1)) if Int.max - additionalCapacity < newLength { additionalCapacity = 0 } var newCapacity = Swift.max(cap, newLength + additionalCapacity) let origLength = _length var allocateCleared = clear && _DataStorage.shouldAllocateCleared(newCapacity) var newBytes: UnsafeMutableRawPointer? = nil if _bytes == nil { newBytes = _DataStorage.allocate(newCapacity, allocateCleared) if newBytes == nil { /* Try again with minimum length */ allocateCleared = clear && _DataStorage.shouldAllocateCleared(newLength) newBytes = _DataStorage.allocate(newLength, allocateCleared) } } else { let tryCalloc = (origLength == 0 || (newLength / origLength) >= 4) if allocateCleared && tryCalloc { newBytes = _DataStorage.allocate(newCapacity, true) if let newBytes = newBytes { _DataStorage.move(newBytes, _bytes!, origLength) _freeBytes() } } /* Where calloc/memmove/free fails, realloc might succeed */ if newBytes == nil { allocateCleared = false if _deallocator != nil { newBytes = _DataStorage.allocate(newCapacity, true) if let newBytes = newBytes { _DataStorage.move(newBytes, _bytes!, origLength) _freeBytes() _deallocator = nil } } else { newBytes = realloc(_bytes!, newCapacity) } } /* Try again with minimum length */ if newBytes == nil { newCapacity = newLength allocateCleared = clear && _DataStorage.shouldAllocateCleared(newCapacity) if allocateCleared && tryCalloc { newBytes = _DataStorage.allocate(newCapacity, true) if let newBytes = newBytes { _DataStorage.move(newBytes, _bytes!, origLength) _freeBytes() } } if newBytes == nil { allocateCleared = false newBytes = realloc(_bytes!, newCapacity) } } } if newBytes == nil { /* Could not allocate bytes */ // At this point if the allocation cannot occur the process is likely out of memory // and Bad-Things™ are going to happen anyhow fatalError("unable to allocate memory for length (\(newLength))") } if origLength < newLength && clear && !allocateCleared { memset(newBytes!.advanced(by: origLength), 0, newLength - origLength) } /* _length set by caller */ _bytes = newBytes _capacity = newCapacity /* Realloc/memset doesn't zero out the entire capacity, so we must be safe and clear next time we grow the length */ _needToZero = !allocateCleared } @inlinable func setLength(_ length: Int) { switch _backing { case .swift: let origLength = _length let newLength = length if _capacity < newLength || _bytes == nil { _grow(newLength, true) } else if origLength < newLength && _needToZero { memset(_bytes! + origLength, 0, newLength - origLength) } else if newLength < origLength { _needToZero = true } _length = newLength case .immutable(let d): let data = d.mutableCopy() as! NSMutableData data.length = length _backing = .mutable(data) _length = length _bytes = data.mutableBytes case .mutable(let d): d.length = length _length = length _bytes = d.mutableBytes case .customReference(let d): let data = d.mutableCopy() as! NSMutableData data.length = length _backing = .customMutableReference(data) case .customMutableReference(let d): d.length = length @unknown default: fatalError("Unknown Data backing type") } } @inlinable func append(_ bytes: UnsafeRawPointer, length: Int) { precondition(length >= 0, "Length of appending bytes must not be negative") switch _backing { case .swift: let origLength = _length let newLength = origLength + length if _capacity < newLength || _bytes == nil { _grow(newLength, false) } _length = newLength _DataStorage.move(_bytes!.advanced(by: origLength), bytes, length) case .immutable(let d): let data = d.mutableCopy() as! NSMutableData data.append(bytes, length: length) _backing = .mutable(data) _length = data.length _bytes = data.mutableBytes case .mutable(let d): d.append(bytes, length: length) _length = d.length _bytes = d.mutableBytes case .customReference(let d): let data = d.mutableCopy() as! NSMutableData data.append(bytes, length: length) _backing = .customMutableReference(data) case .customMutableReference(let d): d.append(bytes, length: length) @unknown default: fatalError("Unknown Data backing type") } } // fast-path for appending directly from another data storage @inlinable func append(_ otherData: _DataStorage, startingAt start: Int, endingAt end: Int) { let otherLength = otherData.length if otherLength == 0 { return } if let bytes = otherData.bytes { append(bytes.advanced(by: start), length: end - start) } } @inlinable func append(_ otherData: Data) { otherData.enumerateBytes { (buffer: UnsafeBufferPointer<UInt8>, _, _) in append(buffer.baseAddress!, length: buffer.count) } } @inlinable func increaseLength(by extraLength: Int) { if extraLength == 0 { return } switch _backing { case .swift: let origLength = _length let newLength = origLength + extraLength if _capacity < newLength || _bytes == nil { _grow(newLength, true) } else if _needToZero { memset(_bytes!.advanced(by: origLength), 0, extraLength) } _length = newLength case .immutable(let d): let data = d.mutableCopy() as! NSMutableData data.increaseLength(by: extraLength) _backing = .mutable(data) _length += extraLength _bytes = data.mutableBytes case .mutable(let d): d.increaseLength(by: extraLength) _length += extraLength _bytes = d.mutableBytes case .customReference(let d): let data = d.mutableCopy() as! NSMutableData data.increaseLength(by: extraLength) _backing = .customReference(data) case .customMutableReference(let d): d.increaseLength(by: extraLength) @unknown default: fatalError("Unknown Data backing type") } } @usableFromInline func get(_ index: Int) -> UInt8 { switch _backing { case .swift: fallthrough case .immutable: fallthrough case .mutable: return _bytes!.advanced(by: index - _offset).assumingMemoryBound(to: UInt8.self).pointee case .customReference(let d): if __NSDataIsCompact(d) { return d.bytes.advanced(by: index - _offset).assumingMemoryBound(to: UInt8.self).pointee } else { var byte: UInt8 = 0 d.enumerateBytes { (ptr, range, stop) in if NSLocationInRange(index, range) { let offset = index - range.location - _offset byte = ptr.advanced(by: offset).assumingMemoryBound(to: UInt8.self).pointee stop.pointee = true } } return byte } case .customMutableReference(let d): if __NSDataIsCompact(d) { return d.bytes.advanced(by: index - _offset).assumingMemoryBound(to: UInt8.self).pointee } else { var byte: UInt8 = 0 d.enumerateBytes { (ptr, range, stop) in if NSLocationInRange(index, range) { let offset = index - range.location - _offset byte = ptr.advanced(by: offset).assumingMemoryBound(to: UInt8.self).pointee stop.pointee = true } } return byte } } } @inlinable func set(_ index: Int, to value: UInt8) { switch _backing { case .swift: fallthrough case .mutable: _bytes!.advanced(by: index - _offset).assumingMemoryBound(to: UInt8.self).pointee = value default: var theByte = value let range = NSRange(location: index, length: 1) replaceBytes(in: range, with: &theByte, length: 1) } } @inlinable func replaceBytes(in range: NSRange, with bytes: UnsafeRawPointer?) { if range.length == 0 { return } switch _backing { case .swift: if _length < range.location + range.length { let newLength = range.location + range.length if _capacity < newLength { _grow(newLength, false) } _length = newLength } _DataStorage.move(_bytes!.advanced(by: range.location - _offset), bytes!, range.length) case .immutable(let d): let data = d.mutableCopy() as! NSMutableData data.replaceBytes(in: NSRange(location: range.location - _offset, length: range.length), withBytes: bytes!) _backing = .mutable(data) _length = data.length _bytes = data.mutableBytes case .mutable(let d): d.replaceBytes(in: NSRange(location: range.location - _offset, length: range.length), withBytes: bytes!) _length = d.length _bytes = d.mutableBytes case .customReference(let d): let data = d.mutableCopy() as! NSMutableData data.replaceBytes(in: NSRange(location: range.location - _offset, length: range.length), withBytes: bytes!) _backing = .customMutableReference(data) case .customMutableReference(let d): d.replaceBytes(in: NSRange(location: range.location - _offset, length: range.length), withBytes: bytes!) @unknown default: fatalError("Unknown Data backing type") } } @inlinable func replaceBytes(in range_: NSRange, with replacementBytes: UnsafeRawPointer?, length replacementLength: Int) { let range = NSRange(location: range_.location - _offset, length: range_.length) let currentLength = _length let resultingLength = currentLength - range.length + replacementLength switch _backing { case .swift: let shift = resultingLength - currentLength var mutableBytes = _bytes if resultingLength > currentLength { setLength(resultingLength) mutableBytes = _bytes! } /* shift the trailing bytes */ let start = range.location let length = range.length if shift != 0 { memmove(mutableBytes! + start + replacementLength, mutableBytes! + start + length, currentLength - start - length) } if replacementLength != 0 { if let replacementBytes = replacementBytes { memmove(mutableBytes! + start, replacementBytes, replacementLength) } else { memset(mutableBytes! + start, 0, replacementLength) } } if resultingLength < currentLength { setLength(resultingLength) } case .immutable(let d): let data = d.mutableCopy() as! NSMutableData data.replaceBytes(in: range, withBytes: replacementBytes, length: replacementLength) _backing = .mutable(data) _length = data.length _bytes = data.mutableBytes case .mutable(let d): d.replaceBytes(in: range, withBytes: replacementBytes, length: replacementLength) _backing = .mutable(d) _length = d.length _bytes = d.mutableBytes case .customReference(let d): let data = d.mutableCopy() as! NSMutableData data.replaceBytes(in: range, withBytes: replacementBytes, length: replacementLength) _backing = .customMutableReference(data) case .customMutableReference(let d): d.replaceBytes(in: range, withBytes: replacementBytes, length: replacementLength) @unknown default: fatalError("Unknown Data backing type") } } @inlinable func resetBytes(in range_: NSRange) { let range = NSRange(location: range_.location - _offset, length: range_.length) if range.length == 0 { return } switch _backing { case .swift: if _length < range.location + range.length { let newLength = range.location + range.length if _capacity < newLength { _grow(newLength, false) } _length = newLength } memset(_bytes!.advanced(by: range.location), 0, range.length) case .immutable(let d): let data = d.mutableCopy() as! NSMutableData data.resetBytes(in: range) _backing = .mutable(data) _length = data.length _bytes = data.mutableBytes case .mutable(let d): d.resetBytes(in: range) _length = d.length _bytes = d.mutableBytes case .customReference(let d): let data = d.mutableCopy() as! NSMutableData data.resetBytes(in: range) _backing = .customMutableReference(data) case .customMutableReference(let d): d.resetBytes(in: range) @unknown default: fatalError("Unknown Data backing type") } } @usableFromInline convenience init() { self.init(capacity: 0) } @usableFromInline init(length: Int) { precondition(length < _DataStorage.maxSize) var capacity = (length < 1024 * 1024 * 1024) ? length + (length >> 2) : length if _DataStorage.vmOpsThreshold <= capacity { capacity = NSRoundUpToMultipleOfPageSize(capacity) } let clear = _DataStorage.shouldAllocateCleared(length) _bytes = _DataStorage.allocate(capacity, clear)! _capacity = capacity _needToZero = !clear _length = 0 _offset = 0 setLength(length) } @usableFromInline init(capacity capacity_: Int) { var capacity = capacity_ precondition(capacity < _DataStorage.maxSize) if _DataStorage.vmOpsThreshold <= capacity { capacity = NSRoundUpToMultipleOfPageSize(capacity) } _length = 0 _bytes = _DataStorage.allocate(capacity, false)! _capacity = capacity _needToZero = true _offset = 0 } @usableFromInline init(bytes: UnsafeRawPointer?, length: Int) { precondition(length < _DataStorage.maxSize) _offset = 0 if length == 0 { _capacity = 0 _length = 0 _needToZero = false _bytes = nil } else if _DataStorage.vmOpsThreshold <= length { _capacity = length _length = length _needToZero = true _bytes = _DataStorage.allocate(length, false)! _DataStorage.move(_bytes!, bytes, length) } else { var capacity = length if _DataStorage.vmOpsThreshold <= capacity { capacity = NSRoundUpToMultipleOfPageSize(capacity) } _length = length _bytes = _DataStorage.allocate(capacity, false)! _capacity = capacity _needToZero = true _DataStorage.move(_bytes!, bytes, length) } } @usableFromInline init(bytes: UnsafeMutableRawPointer?, length: Int, copy: Bool, deallocator: ((UnsafeMutableRawPointer, Int) -> Void)?, offset: Int) { precondition(length < _DataStorage.maxSize) _offset = offset if length == 0 { _capacity = 0 _length = 0 _needToZero = false _bytes = nil if let dealloc = deallocator, let bytes_ = bytes { dealloc(bytes_, length) } } else if !copy { _capacity = length _length = length _needToZero = false _bytes = bytes _deallocator = deallocator } else if _DataStorage.vmOpsThreshold <= length { _capacity = length _length = length _needToZero = true _bytes = _DataStorage.allocate(length, false)! _DataStorage.move(_bytes!, bytes, length) if let dealloc = deallocator { dealloc(bytes!, length) } } else { var capacity = length if _DataStorage.vmOpsThreshold <= capacity { capacity = NSRoundUpToMultipleOfPageSize(capacity) } _length = length _bytes = _DataStorage.allocate(capacity, false)! _capacity = capacity _needToZero = true _DataStorage.move(_bytes!, bytes, length) if let dealloc = deallocator { dealloc(bytes!, length) } } } @usableFromInline init(immutableReference: NSData, offset: Int) { _offset = offset _bytes = UnsafeMutableRawPointer(mutating: immutableReference.bytes) _capacity = 0 _needToZero = false _length = immutableReference.length _backing = .immutable(immutableReference) } @usableFromInline init(mutableReference: NSMutableData, offset: Int) { _offset = offset _bytes = mutableReference.mutableBytes _capacity = 0 _needToZero = false _length = mutableReference.length _backing = .mutable(mutableReference) } @usableFromInline init(customReference: NSData, offset: Int) { _offset = offset _bytes = nil _capacity = 0 _needToZero = false _length = 0 _backing = .customReference(customReference) } @usableFromInline init(customMutableReference: NSMutableData, offset: Int) { _offset = offset _bytes = nil _capacity = 0 _needToZero = false _length = 0 _backing = .customMutableReference(customMutableReference) } deinit { switch _backing { case .swift: _freeBytes() default: break } } @inlinable func mutableCopy(_ range: Range<Int>) -> _DataStorage { switch _backing { case .swift: return _DataStorage(bytes: _bytes?.advanced(by: range.lowerBound - _offset), length: range.count, copy: true, deallocator: nil, offset: range.lowerBound) case .immutable(let d): if range.lowerBound == 0 && range.upperBound == _length { return _DataStorage(mutableReference: d.mutableCopy() as! NSMutableData, offset: range.lowerBound) } else { return _DataStorage(mutableReference: d.subdata(with: NSRange(location: range.lowerBound, length: range.count))._bridgeToObjectiveC().mutableCopy() as! NSMutableData, offset: range.lowerBound) } case .mutable(let d): if range.lowerBound == 0 && range.upperBound == _length { return _DataStorage(mutableReference: d.mutableCopy() as! NSMutableData, offset: range.lowerBound) } else { return _DataStorage(mutableReference: d.subdata(with: NSRange(location: range.lowerBound, length: range.count))._bridgeToObjectiveC().mutableCopy() as! NSMutableData, offset: range.lowerBound) } case .customReference(let d): if range.lowerBound == 0 && range.upperBound == _length { return _DataStorage(mutableReference: d.mutableCopy() as! NSMutableData, offset: range.lowerBound) } else { return _DataStorage(mutableReference: d.subdata(with: NSRange(location: range.lowerBound, length: range.count))._bridgeToObjectiveC().mutableCopy() as! NSMutableData, offset: range.lowerBound) } case .customMutableReference(let d): if range.lowerBound == 0 && range.upperBound == _length { return _DataStorage(mutableReference: d.mutableCopy() as! NSMutableData, offset: range.lowerBound) } else { return _DataStorage(mutableReference: d.subdata(with: NSRange(location: range.lowerBound, length: range.count))._bridgeToObjectiveC().mutableCopy() as! NSMutableData, offset: range.lowerBound) } @unknown default: fatalError("Unknown Data backing type") } } func withInteriorPointerReference<T>(_ range: Range<Int>, _ work: (NSData) throws -> T) rethrows -> T { if range.isEmpty { return try work(NSData()) // zero length data can be optimized as a singleton } switch _backing { case .swift: return try work(NSData(bytesNoCopy: _bytes!.advanced(by: range.lowerBound - _offset), length: range.count, freeWhenDone: false)) case .immutable(let d): guard range.lowerBound == 0 && range.upperBound == _length else { return try work(NSData(bytesNoCopy: _bytes!.advanced(by: range.lowerBound - _offset), length: range.count, freeWhenDone: false)) } return try work(d) case .mutable(let d): guard range.lowerBound == 0 && range.upperBound == _length else { return try work(NSData(bytesNoCopy: _bytes!.advanced(by: range.lowerBound - _offset), length: range.count, freeWhenDone: false)) } return try work(d) case .customReference(let d): guard range.lowerBound == 0 && range.upperBound == _length else { return try work(NSData(bytesNoCopy: UnsafeMutableRawPointer(mutating: d.bytes.advanced(by: range.lowerBound - _offset)), length: range.count, freeWhenDone: false)) } return try work(d) case .customMutableReference(let d): guard range.lowerBound == 0 && range.upperBound == _length else { return try work(NSData(bytesNoCopy: UnsafeMutableRawPointer(mutating: d.bytes.advanced(by: range.lowerBound - _offset)), length: range.count, freeWhenDone: false)) } return try work(d) } } func bridgedReference(_ range: Range<Int>) -> NSData { if range.isEmpty { return NSData() // zero length data can be optimized as a singleton } switch _backing { case .swift: return __NSSwiftData(backing: self, range: range) case .immutable(let d): guard range.lowerBound == 0 && range.upperBound == _length else { return __NSSwiftData(backing: self, range: range) } return d case .mutable(let d): guard range.lowerBound == 0 && range.upperBound == _length else { return __NSSwiftData(backing: self, range: range) } return d case .customReference(let d): guard range.lowerBound == 0 && range.upperBound == d.length else { return __NSSwiftData(backing: self, range: range) } return d case .customMutableReference(let d): guard range.lowerBound == 0 && range.upperBound == d.length else { return d.subdata(with: NSRange(location: range.lowerBound, length: range.count))._bridgeToObjectiveC() } return d.copy() as! NSData } } @usableFromInline func subdata(in range: Range<Data.Index>) -> Data { switch _backing { case .customReference(let d): return d.subdata(with: NSRange(location: range.lowerBound - _offset, length: range.count)) case .customMutableReference(let d): return d.subdata(with: NSRange(location: range.lowerBound - _offset, length: range.count)) default: return Data(bytes: _bytes!.advanced(by: range.lowerBound - _offset), count: range.count) } } } // NOTE: older runtimes called this _NSSwiftData. The two must // coexist, so it was renamed. The old name must not be used in the new // runtime. internal class __NSSwiftData : NSData { var _backing: _DataStorage! var _range: Range<Data.Index>! convenience init(backing: _DataStorage, range: Range<Data.Index>) { self.init() _backing = backing _range = range } override var length: Int { return _range.count } override var bytes: UnsafeRawPointer { // NSData's byte pointer methods are not annotated for nullability correctly // (but assume non-null by the wrapping macro guards). This placeholder value // is to work-around this bug. Any indirection to the underlying bytes of an NSData // with a length of zero would have been a programmer error anyhow so the actual // return value here is not needed to be an allocated value. This is specifically // needed to live like this to be source compatible with Swift3. Beyond that point // this API may be subject to correction. guard let bytes = _backing.bytes else { return UnsafeRawPointer(bitPattern: 0xBAD0)! } return bytes.advanced(by: _range.lowerBound) } override func copy(with zone: NSZone? = nil) -> Any { return self } override func mutableCopy(with zone: NSZone? = nil) -> Any { return NSMutableData(bytes: bytes, length: length) } #if !DEPLOYMENT_RUNTIME_SWIFT @objc override func _isCompact() -> Bool { return true } #endif #if DEPLOYMENT_RUNTIME_SWIFT override func _providesConcreteBacking() -> Bool { return true } #else @objc(_providesConcreteBacking) func _providesConcreteBacking() -> Bool { return true } #endif } public struct Data : ReferenceConvertible, Equatable, Hashable, RandomAccessCollection, MutableCollection, RangeReplaceableCollection { public typealias ReferenceType = NSData public typealias ReadingOptions = NSData.ReadingOptions public typealias WritingOptions = NSData.WritingOptions public typealias SearchOptions = NSData.SearchOptions public typealias Base64EncodingOptions = NSData.Base64EncodingOptions public typealias Base64DecodingOptions = NSData.Base64DecodingOptions public typealias Index = Int public typealias Indices = Range<Int> @usableFromInline internal var _backing : _DataStorage @usableFromInline internal var _sliceRange: Range<Index> // A standard or custom deallocator for `Data`. /// /// When creating a `Data` with the no-copy initializer, you may specify a `Data.Deallocator` to customize the behavior of how the backing store is deallocated. public enum Deallocator { /// Use a virtual memory deallocator. #if !DEPLOYMENT_RUNTIME_SWIFT case virtualMemory #endif /// Use `munmap`. case unmap /// Use `free`. case free /// Do nothing upon deallocation. case none /// A custom deallocator. case custom((UnsafeMutableRawPointer, Int) -> Void) fileprivate var _deallocator : ((UnsafeMutableRawPointer, Int) -> Void) { #if DEPLOYMENT_RUNTIME_SWIFT switch self { case .unmap: return { __NSDataInvokeDeallocatorUnmap($0, $1) } case .free: return { __NSDataInvokeDeallocatorFree($0, $1) } case .none: return { _, _ in } case .custom(let b): return { (ptr, len) in b(ptr, len) } } #else switch self { case .virtualMemory: return { NSDataDeallocatorVM($0, $1) } case .unmap: return { NSDataDeallocatorUnmap($0, $1) } case .free: return { NSDataDeallocatorFree($0, $1) } case .none: return { _, _ in } case .custom(let b): return { (ptr, len) in b(ptr, len) } } #endif } } // MARK: - // MARK: Init methods /// Initialize a `Data` with copied memory content. /// /// - parameter bytes: A pointer to the memory. It will be copied. /// - parameter count: The number of bytes to copy. public init(bytes: UnsafeRawPointer, count: Int) { _backing = _DataStorage(bytes: bytes, length: count) _sliceRange = 0..<count } /// Initialize a `Data` with copied memory content. /// /// - parameter buffer: A buffer pointer to copy. The size is calculated from `SourceType` and `buffer.count`. public init<SourceType>(buffer: UnsafeBufferPointer<SourceType>) { let count = MemoryLayout<SourceType>.stride * buffer.count _backing = _DataStorage(bytes: buffer.baseAddress, length: count) _sliceRange = 0..<count } /// Initialize a `Data` with copied memory content. /// /// - parameter buffer: A buffer pointer to copy. The size is calculated from `SourceType` and `buffer.count`. public init<SourceType>(buffer: UnsafeMutableBufferPointer<SourceType>) { let count = MemoryLayout<SourceType>.stride * buffer.count _backing = _DataStorage(bytes: buffer.baseAddress, length: count) _sliceRange = 0..<count } /// Initialize a `Data` with a repeating byte pattern /// /// - parameter repeatedValue: A byte to initialize the pattern /// - parameter count: The number of bytes the data initially contains initialized to the repeatedValue public init(repeating repeatedValue: UInt8, count: Int) { self.init(count: count) withUnsafeMutableBytes { (bytes: UnsafeMutablePointer<UInt8>) -> Void in memset(bytes, Int32(repeatedValue), count) } } /// Initialize a `Data` with the specified size. /// /// This initializer doesn't necessarily allocate the requested memory right away. `Data` allocates additional memory as needed, so `capacity` simply establishes the initial capacity. When it does allocate the initial memory, though, it allocates the specified amount. /// /// This method sets the `count` of the data to 0. /// /// If the capacity specified in `capacity` is greater than four memory pages in size, this may round the amount of requested memory up to the nearest full page. /// /// - parameter capacity: The size of the data. public init(capacity: Int) { _backing = _DataStorage(capacity: capacity) _sliceRange = 0..<0 } /// Initialize a `Data` with the specified count of zeroed bytes. /// /// - parameter count: The number of bytes the data initially contains. public init(count: Int) { _backing = _DataStorage(length: count) _sliceRange = 0..<count } /// Initialize an empty `Data`. public init() { _backing = _DataStorage(length: 0) _sliceRange = 0..<0 } /// Initialize a `Data` without copying the bytes. /// /// If the result is mutated and is not a unique reference, then the `Data` will still follow copy-on-write semantics. In this case, the copy will use its own deallocator. Therefore, it is usually best to only use this initializer when you either enforce immutability with `let` or ensure that no other references to the underlying data are formed. /// - parameter bytes: A pointer to the bytes. /// - parameter count: The size of the bytes. /// - parameter deallocator: Specifies the mechanism to free the indicated buffer, or `.none`. public init(bytesNoCopy bytes: UnsafeMutableRawPointer, count: Int, deallocator: Deallocator) { let whichDeallocator = deallocator._deallocator _backing = _DataStorage(bytes: bytes, length: count, copy: false, deallocator: whichDeallocator, offset: 0) _sliceRange = 0..<count } /// Initialize a `Data` with the contents of a `URL`. /// /// - parameter url: The `URL` to read. /// - parameter options: Options for the read operation. Default value is `[]`. /// - throws: An error in the Cocoa domain, if `url` cannot be read. public init(contentsOf url: __shared URL, options: Data.ReadingOptions = []) throws { let d = try NSData(contentsOf: url, options: ReadingOptions(rawValue: options.rawValue)) _backing = _DataStorage(immutableReference: d, offset: 0) _sliceRange = 0..<d.length } /// Initialize a `Data` from a Base-64 encoded String using the given options. /// /// Returns nil when the input is not recognized as valid Base-64. /// - parameter base64String: The string to parse. /// - parameter options: Encoding options. Default value is `[]`. public init?(base64Encoded base64String: __shared String, options: Data.Base64DecodingOptions = []) { if let d = NSData(base64Encoded: base64String, options: Base64DecodingOptions(rawValue: options.rawValue)) { _backing = _DataStorage(immutableReference: d, offset: 0) _sliceRange = 0..<d.length } else { return nil } } /// Initialize a `Data` from a Base-64, UTF-8 encoded `Data`. /// /// Returns nil when the input is not recognized as valid Base-64. /// /// - parameter base64Data: Base-64, UTF-8 encoded input data. /// - parameter options: Decoding options. Default value is `[]`. public init?(base64Encoded base64Data: __shared Data, options: Data.Base64DecodingOptions = []) { if let d = NSData(base64Encoded: base64Data, options: Base64DecodingOptions(rawValue: options.rawValue)) { _backing = _DataStorage(immutableReference: d, offset: 0) _sliceRange = 0..<d.length } else { return nil } } /// Initialize a `Data` by adopting a reference type. /// /// You can use this initializer to create a `struct Data` that wraps a `class NSData`. `struct Data` will use the `class NSData` for all operations. Other initializers (including casting using `as Data`) may choose to hold a reference or not, based on a what is the most efficient representation. /// /// If the resulting value is mutated, then `Data` will invoke the `mutableCopy()` function on the reference to copy the contents. You may customize the behavior of that function if you wish to return a specialized mutable subclass. /// /// - parameter reference: The instance of `NSData` that you wish to wrap. This instance will be copied by `struct Data`. public init(referencing reference: __shared NSData) { #if DEPLOYMENT_RUNTIME_SWIFT let providesConcreteBacking = reference._providesConcreteBacking() #else let providesConcreteBacking = (reference as AnyObject)._providesConcreteBacking?() ?? false #endif if providesConcreteBacking { _backing = _DataStorage(immutableReference: reference.copy() as! NSData, offset: 0) _sliceRange = 0..<reference.length } else { _backing = _DataStorage(customReference: reference.copy() as! NSData, offset: 0) _sliceRange = 0..<reference.length } } // slightly faster paths for common sequences @inlinable public init<S: Sequence>(_ elements: S) where S.Iterator.Element == UInt8 { let backing = _DataStorage(capacity: Swift.max(elements.underestimatedCount, 1)) var (iter, endIndex) = elements._copyContents(initializing: UnsafeMutableBufferPointer(start: backing._bytes?.bindMemory(to: UInt8.self, capacity: backing._capacity), count: backing._capacity)) backing._length = endIndex while var element = iter.next() { backing.append(&element, length: 1) } self.init(backing: backing, range: 0..<backing._length) } @available(swift, introduced: 4.2) @inlinable public init<S: Sequence>(bytes elements: S) where S.Iterator.Element == UInt8 { self.init(elements) } @available(swift, obsoleted: 4.2) public init(bytes: Array<UInt8>) { self.init(bytes) } @available(swift, obsoleted: 4.2) public init(bytes: ArraySlice<UInt8>) { self.init(bytes) } @usableFromInline internal init(backing: _DataStorage, range: Range<Index>) { _backing = backing _sliceRange = range } @usableFromInline internal func _validateIndex(_ index: Int, message: String? = nil) { precondition(_sliceRange.contains(index), message ?? "Index \(index) is out of bounds of range \(_sliceRange)") } @usableFromInline internal func _validateRange<R: RangeExpression>(_ range: R) where R.Bound == Int { let lower = R.Bound(_sliceRange.lowerBound) let upper = R.Bound(_sliceRange.upperBound) let r = range.relative(to: lower..<upper) precondition(r.lowerBound >= _sliceRange.lowerBound && r.lowerBound <= _sliceRange.upperBound, "Range \(r) is out of bounds of range \(_sliceRange)") precondition(r.upperBound >= _sliceRange.lowerBound && r.upperBound <= _sliceRange.upperBound, "Range \(r) is out of bounds of range \(_sliceRange)") } // ----------------------------------- // MARK: - Properties and Functions /// The number of bytes in the data. public var count: Int { get { return _sliceRange.count } set { precondition(count >= 0, "count must not be negative") if !isKnownUniquelyReferenced(&_backing) { _backing = _backing.mutableCopy(_sliceRange) } _backing.length = newValue _sliceRange = _sliceRange.lowerBound..<(_sliceRange.lowerBound + newValue) } } /// Access the bytes in the data. /// /// - warning: The byte pointer argument should not be stored and used outside of the lifetime of the call to the closure. public func withUnsafeBytes<ResultType, ContentType>(_ body: (UnsafePointer<ContentType>) throws -> ResultType) rethrows -> ResultType { return try _backing.withUnsafeBytes(in: _sliceRange) { return try body($0.baseAddress?.assumingMemoryBound(to: ContentType.self) ?? UnsafePointer<ContentType>(bitPattern: 0xBAD0)!) } } /// Mutate the bytes in the data. /// /// This function assumes that you are mutating the contents. /// - warning: The byte pointer argument should not be stored and used outside of the lifetime of the call to the closure. public mutating func withUnsafeMutableBytes<ResultType, ContentType>(_ body: (UnsafeMutablePointer<ContentType>) throws -> ResultType) rethrows -> ResultType { if !isKnownUniquelyReferenced(&_backing) { _backing = _backing.mutableCopy(_sliceRange) } return try _backing.withUnsafeMutableBytes(in: _sliceRange) { return try body($0.baseAddress?.assumingMemoryBound(to: ContentType.self) ?? UnsafeMutablePointer<ContentType>(bitPattern: 0xBAD0)!) } } // MARK: - // MARK: Copy Bytes /// Copy the contents of the data to a pointer. /// /// - parameter pointer: A pointer to the buffer you wish to copy the bytes into. /// - parameter count: The number of bytes to copy. /// - warning: This method does not verify that the contents at pointer have enough space to hold `count` bytes. public func copyBytes(to pointer: UnsafeMutablePointer<UInt8>, count: Int) { precondition(count >= 0, "count of bytes to copy must not be negative") if count == 0 { return } _backing.withUnsafeBytes(in: _sliceRange) { memcpy(UnsafeMutableRawPointer(pointer), $0.baseAddress!, Swift.min(count, $0.count)) } } private func _copyBytesHelper(to pointer: UnsafeMutableRawPointer, from range: NSRange) { if range.length == 0 { return } _backing.withUnsafeBytes(in: range.lowerBound..<range.upperBound) { memcpy(UnsafeMutableRawPointer(pointer), $0.baseAddress!, Swift.min(range.length, $0.count)) } } /// Copy a subset of the contents of the data to a pointer. /// /// - parameter pointer: A pointer to the buffer you wish to copy the bytes into. /// - parameter range: The range in the `Data` to copy. /// - warning: This method does not verify that the contents at pointer have enough space to hold the required number of bytes. public func copyBytes(to pointer: UnsafeMutablePointer<UInt8>, from range: Range<Index>) { _copyBytesHelper(to: pointer, from: NSRange(range)) } // Copy the contents of the data into a buffer. /// /// This function copies the bytes in `range` from the data into the buffer. If the count of the `range` is greater than `MemoryLayout<DestinationType>.stride * buffer.count` then the first N bytes will be copied into the buffer. /// - precondition: The range must be within the bounds of the data. Otherwise `fatalError` is called. /// - parameter buffer: A buffer to copy the data into. /// - parameter range: A range in the data to copy into the buffer. If the range is empty, this function will return 0 without copying anything. If the range is nil, as much data as will fit into `buffer` is copied. /// - returns: Number of bytes copied into the destination buffer. public func copyBytes<DestinationType>(to buffer: UnsafeMutableBufferPointer<DestinationType>, from range: Range<Index>? = nil) -> Int { let cnt = count guard cnt > 0 else { return 0 } let copyRange : Range<Index> if let r = range { guard !r.isEmpty else { return 0 } copyRange = r.lowerBound..<(r.lowerBound + Swift.min(buffer.count * MemoryLayout<DestinationType>.stride, r.count)) } else { copyRange = 0..<Swift.min(buffer.count * MemoryLayout<DestinationType>.stride, cnt) } _validateRange(copyRange) guard !copyRange.isEmpty else { return 0 } let nsRange = NSRange(location: copyRange.lowerBound, length: copyRange.upperBound - copyRange.lowerBound) _copyBytesHelper(to: buffer.baseAddress!, from: nsRange) return copyRange.count } // MARK: - #if !DEPLOYMENT_RUNTIME_SWIFT private func _shouldUseNonAtomicWriteReimplementation(options: Data.WritingOptions = []) -> Bool { // Avoid a crash that happens on OS X 10.11.x and iOS 9.x or before when writing a bridged Data non-atomically with Foundation's standard write() implementation. if !options.contains(.atomic) { #if os(macOS) return NSFoundationVersionNumber <= Double(NSFoundationVersionNumber10_11_Max) #else return NSFoundationVersionNumber <= Double(NSFoundationVersionNumber_iOS_9_x_Max) #endif } else { return false } } #endif /// Write the contents of the `Data` to a location. /// /// - parameter url: The location to write the data into. /// - parameter options: Options for writing the data. Default value is `[]`. /// - throws: An error in the Cocoa domain, if there is an error writing to the `URL`. public func write(to url: URL, options: Data.WritingOptions = []) throws { try _backing.withInteriorPointerReference(_sliceRange) { #if DEPLOYMENT_RUNTIME_SWIFT try $0.write(to: url, options: WritingOptions(rawValue: options.rawValue)) #else if _shouldUseNonAtomicWriteReimplementation(options: options) { var error: NSError? = nil guard __NSDataWriteToURL($0, url, options, &error) else { throw error! } } else { try $0.write(to: url, options: options) } #endif } } // MARK: - /// Find the given `Data` in the content of this `Data`. /// /// - parameter dataToFind: The data to be searched for. /// - parameter options: Options for the search. Default value is `[]`. /// - parameter range: The range of this data in which to perform the search. Default value is `nil`, which means the entire content of this data. /// - returns: A `Range` specifying the location of the found data, or nil if a match could not be found. /// - precondition: `range` must be in the bounds of the Data. public func range(of dataToFind: Data, options: Data.SearchOptions = [], in range: Range<Index>? = nil) -> Range<Index>? { let nsRange : NSRange if let r = range { _validateRange(r) nsRange = NSRange(location: r.lowerBound - startIndex, length: r.upperBound - r.lowerBound) } else { nsRange = NSRange(location: 0, length: count) } let result = _backing.withInteriorPointerReference(_sliceRange) { $0.range(of: dataToFind, options: options, in: nsRange) } if result.location == NSNotFound { return nil } return (result.location + startIndex)..<((result.location + startIndex) + result.length) } /// Enumerate the contents of the data. /// /// In some cases, (for example, a `Data` backed by a `dispatch_data_t`, the bytes may be stored discontiguously. In those cases, this function invokes the closure for each contiguous region of bytes. /// - parameter block: The closure to invoke for each region of data. You may stop the enumeration by setting the `stop` parameter to `true`. public func enumerateBytes(_ block: (_ buffer: UnsafeBufferPointer<UInt8>, _ byteIndex: Index, _ stop: inout Bool) -> Void) { _backing.enumerateBytes(in: _sliceRange, block) } @inlinable internal mutating func _append<SourceType>(_ buffer : UnsafeBufferPointer<SourceType>) { if buffer.isEmpty { return } if !isKnownUniquelyReferenced(&_backing) { _backing = _backing.mutableCopy(_sliceRange) } _backing.replaceBytes(in: NSRange(location: _sliceRange.upperBound, length: _backing.length - (_sliceRange.upperBound - _backing._offset)), with: buffer.baseAddress, length: buffer.count * MemoryLayout<SourceType>.stride) _sliceRange = _sliceRange.lowerBound..<(_sliceRange.upperBound + buffer.count * MemoryLayout<SourceType>.stride) } public mutating func append(_ bytes: UnsafePointer<UInt8>, count: Int) { if count == 0 { return } _append(UnsafeBufferPointer(start: bytes, count: count)) } public mutating func append(_ other: Data) { other.enumerateBytes { (buffer, _, _) in _append(buffer) } } /// Append a buffer of bytes to the data. /// /// - parameter buffer: The buffer of bytes to append. The size is calculated from `SourceType` and `buffer.count`. public mutating func append<SourceType>(_ buffer : UnsafeBufferPointer<SourceType>) { _append(buffer) } public mutating func append(contentsOf bytes: [UInt8]) { bytes.withUnsafeBufferPointer { (buffer: UnsafeBufferPointer<UInt8>) -> Void in _append(buffer) } } @inlinable public mutating func append<S : Sequence>(contentsOf newElements: S) where S.Iterator.Element == Iterator.Element { let underestimatedCount = Swift.max(newElements.underestimatedCount, 1) _withStackOrHeapBuffer(underestimatedCount) { (buffer) in let capacity = buffer.pointee.capacity let base = buffer.pointee.memory.bindMemory(to: UInt8.self, capacity: capacity) var (iter, endIndex) = newElements._copyContents(initializing: UnsafeMutableBufferPointer(start: base, count: capacity)) _append(UnsafeBufferPointer(start: base, count: endIndex)) while var element = iter.next() { append(&element, count: 1) } } } // MARK: - /// Set a region of the data to `0`. /// /// If `range` exceeds the bounds of the data, then the data is resized to fit. /// - parameter range: The range in the data to set to `0`. public mutating func resetBytes(in range: Range<Index>) { // it is worth noting that the range here may be out of bounds of the Data itself (which triggers a growth) precondition(range.lowerBound >= 0, "Ranges must not be negative bounds") precondition(range.upperBound >= 0, "Ranges must not be negative bounds") let range = NSRange(location: range.lowerBound, length: range.upperBound - range.lowerBound) if !isKnownUniquelyReferenced(&_backing) { _backing = _backing.mutableCopy(_sliceRange) } _backing.resetBytes(in: range) if _sliceRange.upperBound < range.upperBound { _sliceRange = _sliceRange.lowerBound..<range.upperBound } } /// Replace a region of bytes in the data with new data. /// /// This will resize the data if required, to fit the entire contents of `data`. /// /// - precondition: The bounds of `subrange` must be valid indices of the collection. /// - parameter subrange: The range in the data to replace. If `subrange.lowerBound == data.count && subrange.count == 0` then this operation is an append. /// - parameter data: The replacement data. public mutating func replaceSubrange(_ subrange: Range<Index>, with data: Data) { let cnt = data.count data.withUnsafeBytes { replaceSubrange(subrange, with: $0, count: cnt) } } /// Replace a region of bytes in the data with new bytes from a buffer. /// /// This will resize the data if required, to fit the entire contents of `buffer`. /// /// - precondition: The bounds of `subrange` must be valid indices of the collection. /// - parameter subrange: The range in the data to replace. /// - parameter buffer: The replacement bytes. public mutating func replaceSubrange<SourceType>(_ subrange: Range<Index>, with buffer: UnsafeBufferPointer<SourceType>) { guard !buffer.isEmpty else { return } replaceSubrange(subrange, with: buffer.baseAddress!, count: buffer.count * MemoryLayout<SourceType>.stride) } /// Replace a region of bytes in the data with new bytes from a collection. /// /// This will resize the data if required, to fit the entire contents of `newElements`. /// /// - precondition: The bounds of `subrange` must be valid indices of the collection. /// - parameter subrange: The range in the data to replace. /// - parameter newElements: The replacement bytes. public mutating func replaceSubrange<ByteCollection : Collection>(_ subrange: Range<Index>, with newElements: ByteCollection) where ByteCollection.Iterator.Element == Data.Iterator.Element { _validateRange(subrange) let totalCount: Int = numericCast(newElements.count) _withStackOrHeapBuffer(totalCount) { conditionalBuffer in let buffer = UnsafeMutableBufferPointer(start: conditionalBuffer.pointee.memory.assumingMemoryBound(to: UInt8.self), count: totalCount) var (iterator, index) = newElements._copyContents(initializing: buffer) while let byte = iterator.next() { buffer[index] = byte index = buffer.index(after: index) } replaceSubrange(subrange, with: conditionalBuffer.pointee.memory, count: totalCount) } } public mutating func replaceSubrange(_ subrange: Range<Index>, with bytes: UnsafeRawPointer, count cnt: Int) { _validateRange(subrange) let nsRange = NSRange(location: subrange.lowerBound, length: subrange.upperBound - subrange.lowerBound) if !isKnownUniquelyReferenced(&_backing) { _backing = _backing.mutableCopy(_sliceRange) } let upper = _sliceRange.upperBound _backing.replaceBytes(in: nsRange, with: bytes, length: cnt) let resultingUpper = upper - nsRange.length + cnt _sliceRange = _sliceRange.lowerBound..<resultingUpper } /// Return a new copy of the data in a specified range. /// /// - parameter range: The range to copy. public func subdata(in range: Range<Index>) -> Data { _validateRange(range) if isEmpty { return Data() } return _backing.subdata(in: range) } // MARK: - // /// Returns a Base-64 encoded string. /// /// - parameter options: The options to use for the encoding. Default value is `[]`. /// - returns: The Base-64 encoded string. public func base64EncodedString(options: Data.Base64EncodingOptions = []) -> String { return _backing.withInteriorPointerReference(_sliceRange) { return $0.base64EncodedString(options: options) } } /// Returns a Base-64 encoded `Data`. /// /// - parameter options: The options to use for the encoding. Default value is `[]`. /// - returns: The Base-64 encoded data. public func base64EncodedData(options: Data.Base64EncodingOptions = []) -> Data { return _backing.withInteriorPointerReference(_sliceRange) { return $0.base64EncodedData(options: options) } } // MARK: - // /// The hash value for the data. public var hashValue: Int { var hashValue = 0 let hashRange: Range<Int> = _sliceRange.lowerBound..<Swift.min(_sliceRange.lowerBound + 80, _sliceRange.upperBound) _withStackOrHeapBuffer(hashRange.count + 1) { buffer in if !hashRange.isEmpty { _backing.withUnsafeBytes(in: hashRange) { memcpy(buffer.pointee.memory, $0.baseAddress!, hashRange.count) } } hashValue = Int(bitPattern: CFHashBytes(buffer.pointee.memory.assumingMemoryBound(to: UInt8.self), hashRange.count)) } return hashValue } public func advanced(by amount: Int) -> Data { _validateIndex(startIndex + amount) let length = count - amount precondition(length > 0) return withUnsafeBytes { (ptr: UnsafePointer<UInt8>) -> Data in return Data(bytes: ptr.advanced(by: amount), count: length) } } // MARK: - // MARK: - // MARK: Index and Subscript /// Sets or returns the byte at the specified index. public subscript(index: Index) -> UInt8 { get { _validateIndex(index) return _backing.get(index) } set { _validateIndex(index) if !isKnownUniquelyReferenced(&_backing) { _backing = _backing.mutableCopy(_sliceRange) } _backing.set(index, to: newValue) } } public subscript(bounds: Range<Index>) -> Data { get { _validateRange(bounds) return Data(backing: _backing, range: bounds) } set { replaceSubrange(bounds, with: newValue) } } public subscript<R: RangeExpression>(_ rangeExpression: R) -> Data where R.Bound: FixedWidthInteger { get { let lower = R.Bound(_sliceRange.lowerBound) let upper = R.Bound(_sliceRange.upperBound) let range = rangeExpression.relative(to: lower..<upper) let start: Int = numericCast(range.lowerBound) let end: Int = numericCast(range.upperBound) let r: Range<Int> = start..<end _validateRange(r) return Data(backing: _backing, range: r) } set { let lower = R.Bound(_sliceRange.lowerBound) let upper = R.Bound(_sliceRange.upperBound) let range = rangeExpression.relative(to: lower..<upper) let start: Int = numericCast(range.lowerBound) let end: Int = numericCast(range.upperBound) let r: Range<Int> = start..<end _validateRange(r) replaceSubrange(r, with: newValue) } } /// The start `Index` in the data. public var startIndex: Index { get { return _sliceRange.lowerBound } } /// The end `Index` into the data. /// /// This is the "one-past-the-end" position, and will always be equal to the `count`. public var endIndex: Index { get { return _sliceRange.upperBound } } public func index(before i: Index) -> Index { return i - 1 } public func index(after i: Index) -> Index { return i + 1 } public var indices: Range<Int> { get { return startIndex..<endIndex } } public func _copyContents(initializing buffer: UnsafeMutableBufferPointer<UInt8>) -> (Iterator, UnsafeMutableBufferPointer<UInt8>.Index) { guard !isEmpty else { return (makeIterator(), buffer.startIndex) } guard let p = buffer.baseAddress else { preconditionFailure("Attempt to copy contents into nil buffer pointer") } let cnt = count precondition(cnt <= buffer.count, "Insufficient space allocated to copy Data contents") withUnsafeBytes { p.initialize(from: $0, count: cnt) } return (Iterator(endOf: self), buffer.index(buffer.startIndex, offsetBy: cnt)) } /// An iterator over the contents of the data. /// /// The iterator will increment byte-by-byte. public func makeIterator() -> Data.Iterator { return Iterator(self) } public struct Iterator : IteratorProtocol { // Both _data and _endIdx should be 'let' rather than 'var'. // They are 'var' so that the stored properties can be read // independently of the other contents of the struct. This prevents // an exclusivity violation when reading '_endIdx' and '_data' // while simultaneously mutating '_buffer' with the call to // withUnsafeMutablePointer(). Once we support accessing struct // let properties independently we should make these variables // 'let' again. private var _data: Data private var _buffer: ( UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8) private var _idx: Data.Index private var _endIdx: Data.Index fileprivate init(_ data: Data) { _data = data _buffer = (0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0) _idx = data.startIndex _endIdx = data.endIndex } fileprivate init(endOf data: Data) { self._data = data _buffer = (0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0) _idx = data.endIndex _endIdx = data.endIndex } public mutating func next() -> UInt8? { guard _idx < _endIdx else { return nil } defer { _idx += 1 } let bufferSize = MemoryLayout.size(ofValue: _buffer) return withUnsafeMutablePointer(to: &_buffer) { ptr_ in let ptr = UnsafeMutableRawPointer(ptr_).assumingMemoryBound(to: UInt8.self) let bufferIdx = (_idx - _data.startIndex) % bufferSize if bufferIdx == 0 { // populate the buffer _data.copyBytes(to: ptr, from: _idx..<(_endIdx - _idx > bufferSize ? _idx + bufferSize : _endIdx)) } return ptr[bufferIdx] } } } // MARK: - // @available(*, unavailable, renamed: "count") public var length: Int { get { fatalError() } set { fatalError() } } @available(*, unavailable, message: "use withUnsafeBytes instead") public var bytes: UnsafeRawPointer { fatalError() } @available(*, unavailable, message: "use withUnsafeMutableBytes instead") public var mutableBytes: UnsafeMutableRawPointer { fatalError() } /// Returns `true` if the two `Data` arguments are equal. public static func ==(d1 : Data, d2 : Data) -> Bool { let backing1 = d1._backing let backing2 = d2._backing if backing1 === backing2 { if d1._sliceRange == d2._sliceRange { return true } } let length1 = d1.count if length1 != d2.count { return false } if backing1.bytes == backing2.bytes { if d1._sliceRange == d2._sliceRange { return true } } if length1 > 0 { return d1.withUnsafeBytes { (b1) in return d2.withUnsafeBytes { (b2) in return memcmp(b1, b2, length1) == 0 } } } return true } } extension Data : CustomStringConvertible, CustomDebugStringConvertible, CustomReflectable { /// A human-readable description for the data. public var description: String { return "\(self.count) bytes" } /// A human-readable debug description for the data. public var debugDescription: String { return self.description } public var customMirror: Mirror { let nBytes = self.count var children: [(label: String?, value: Any)] = [] children.append((label: "count", value: nBytes)) self.withUnsafeBytes { (bytes : UnsafePointer<UInt8>) in children.append((label: "pointer", value: bytes)) } // Minimal size data is output as an array if nBytes < 64 { children.append((label: "bytes", value: Array(self[startIndex..<Swift.min(nBytes + startIndex, endIndex)]))) } let m = Mirror(self, children:children, displayStyle: Mirror.DisplayStyle.struct) return m } } extension Data { @available(*, unavailable, renamed: "copyBytes(to:count:)") public func getBytes<UnsafeMutablePointerVoid: _Pointer>(_ buffer: UnsafeMutablePointerVoid, length: Int) { } @available(*, unavailable, renamed: "copyBytes(to:from:)") public func getBytes<UnsafeMutablePointerVoid: _Pointer>(_ buffer: UnsafeMutablePointerVoid, range: NSRange) { } } /// Provides bridging functionality for struct Data to class NSData and vice-versa. extension Data : _ObjectiveCBridgeable { @_semantics("convertToObjectiveC") public func _bridgeToObjectiveC() -> NSData { return _backing.bridgedReference(_sliceRange) } public static func _forceBridgeFromObjectiveC(_ input: NSData, result: inout Data?) { // We must copy the input because it might be mutable; just like storing a value type in ObjC result = Data(referencing: input) } public static func _conditionallyBridgeFromObjectiveC(_ input: NSData, result: inout Data?) -> Bool { // We must copy the input because it might be mutable; just like storing a value type in ObjC result = Data(referencing: input) return true } @_effects(readonly) public static func _unconditionallyBridgeFromObjectiveC(_ source: NSData?) -> Data { guard let src = source else { return Data() } return Data(referencing: src) } } extension NSData : _HasCustomAnyHashableRepresentation { // Must be @nonobjc to avoid infinite recursion during bridging. @nonobjc public func _toCustomAnyHashable() -> AnyHashable? { return AnyHashable(Data._unconditionallyBridgeFromObjectiveC(self)) } } extension Data : Codable { public init(from decoder: Decoder) throws { var container = try decoder.unkeyedContainer() // It's more efficient to pre-allocate the buffer if we can. if let count = container.count { self.init(count: count) // Loop only until count, not while !container.isAtEnd, in case count is underestimated (this is misbehavior) and we haven't allocated enough space. // We don't want to write past the end of what we allocated. for i in 0 ..< count { let byte = try container.decode(UInt8.self) self[i] = byte } } else { self.init() } while !container.isAtEnd { var byte = try container.decode(UInt8.self) self.append(&byte, count: 1) } } public func encode(to encoder: Encoder) throws { var container = encoder.unkeyedContainer() // Since enumerateBytes does not rethrow, we need to catch the error, stow it away, and rethrow if we stopped. var caughtError: Error? = nil self.enumerateBytes { (buffer: UnsafeBufferPointer<UInt8>, byteIndex: Data.Index, stop: inout Bool) in do { try container.encode(contentsOf: buffer) } catch { caughtError = error stop = true } } if let error = caughtError { throw error } } }
apache-2.0
7559adeffe136f8e1853d8293f52558a
40.338376
352
0.593115
4.936706
false
false
false
false
fhbystudy/TYMutiTaskKit
TYMutiTaskKit/Tasks/TYDownloadImageTask.swift
1
2603
// // TYDownloadImageTask.swift // TYMutiTaskKit // // Created by Tonny.hao on 2/10/15. // Copyright (c) 2015 Tonny.hao. All rights reserved. // import Foundation import UIKit //import Alamofire class TYDlImageTaskParam: TYBaseTaskParam { let imageUrl:String! var isCached = true required init(url:String) { super.init() self.imageUrl = url; } } class TYDlImageTaskResponse: TYBaseTaskResponse { } class TYDownloadImageTask: TYBaseTask { let dlService:TYBaseNetworkService = TYBaseNetworkService() var innerTask:Request? override weak var taskDelegate:TYTaskProtocol? { didSet { if self.taskResponse == nil { self.taskResponse = TYDlImageTaskResponse(id:self.taskID) } } } required init(param:TYBaseTaskParam) { super.init(param: param) if isIOS8orLater { self.qualityOfService = .Background self.name = "TYDownloadImageTask" } self.completionBlock = { var taskParam = self.taskParam as TYDlImageTaskParam println("the finished image url is \(taskParam.imageUrl)") if self.taskDelegate != nil { self.taskDelegate?.taskFinished(self.taskResponse!) } } } convenience init(imageUrl:String) { var param = TYDlImageTaskParam(url: imageUrl) self.init(param:param); } override func entry() { if self.cancelled { return } super.entry() var isServiceFinished = false var taskParam = self.taskParam as TYDlImageTaskParam dlService.Get(taskParam.imageUrl, parameters: nil, isCached:taskParam.isCached, success: { (jsonObj:AnyObject?, requestTask:Request) -> () in var jsonDic: AnyObject? = jsonObj isServiceFinished = true println("dlService.Get image url is \(taskParam.imageUrl)") }) { (errorDes:String?, requestTask:Request) -> () in var errorInfo = errorDes isServiceFinished = true println("dlService.Get image failed: \(errorDes)") } while !isServiceFinished { NSRunLoop.currentRunLoop().runUntilDate(NSDate(timeIntervalSinceReferenceDate:0.01)) } } override func cancel() { if let dlTask = innerTask { // TODO : clear the cache if requirement needed dlTask.cancel() } super.cancel() } }
apache-2.0
e7fa92e0863c54ec78dcecf0e867ddfa
25.835052
149
0.588167
4.758684
false
false
false
false
dreamsxin/swift
test/Constraints/overload.swift
6
4093
// RUN: %target-parse-verify-swift func markUsed<T>(_ t: T) {} func f0(_: Float) -> Float {} func f0(_: Int) -> Int {} func f1(_: Int) {} func identity<T>(_: T) -> T {} func f2<T>(_: T) -> T {} // FIXME: Fun things happen when we make this T, U! func f2<T>(_: T, _: T) -> (T, T) { } struct X {} var x : X var i : Int var f : Float _ = f0(i) _ = f0(1.0) _ = f0(1) f1(f0(1)) f1(identity(1)) f0(x) // expected-error{{cannot invoke 'f0' with an argument list of type '(X)'}} // expected-note @-1 {{overloads for 'f0' exist with these partially matching parameter lists: (Float), (Int)}} _ = f + 1 _ = f2(i) _ = f2((i, f)) class A { init() {} } class B : A { override init() { super.init() } } class C : B { override init() { super.init() } } func bar(_ b: B) -> Int {} // #1 func bar(_ a: A) -> Float {} // #2 var barResult = bar(C()) // selects #1, which is more specialized i = barResult // make sure we got #1 f = bar(C()) // selects #2 because of context // Overload resolution for constructors protocol P1 { } struct X1a : P1 { } struct X1b { init(x : X1a) { } init<T : P1>(x : T) { } } X1b(x: X1a()) // expected-warning{{unused}} // Overload resolution for subscript operators. class X2a { } class X2b : X2a { } class X2c : X2b { } struct X2d { subscript (index : X2a) -> Int { return 5 } subscript (index : X2b) -> Int { return 7 } func foo(_ x : X2c) -> Int { return self[x] } } // Invalid declarations // FIXME: Suppress the diagnostic for the call below, because the invalid // declaration would have matched. func f3(_ x: Intthingy) -> Int { } // expected-error{{use of undeclared type 'Intthingy'}} func f3(_ x: Float) -> Float { } f3(i) // expected-error{{cannot convert value of type 'Int' to expected argument type 'Float'}} func f4(_ i: Wonka) { } // expected-error{{use of undeclared type 'Wonka'}} func f4(_ j: Wibble) { } // expected-error{{use of undeclared type 'Wibble'}} f4(5) func f1() { var c : Class // expected-error{{use of undeclared type 'Class'}} markUsed(c.x) // make sure error does not cascade here } // We don't provide return-type sensitivity unless there is context. func f5(_ i: Int) -> A { return A() } // expected-note{{candidate}} func f5(_ i: Int) -> B { return B() } // expected-note{{candidate}} f5(5) // expected-error{{ambiguous use of 'f5'}} struct HasX1aProperty { func write(_: X1a) {} func write(_: P1) {} var prop = X1a() func test() { write(prop) // no error, not ambiguous } } // rdar://problem/16554496 @available(*, unavailable) func availTest(_ x: Int) {} func availTest(_ x: Any) { markUsed("this one") } func doAvailTest(_ x: Int) { availTest(x) } // rdar://problem/20886179 func test20886179(_ handlers: [(Int) -> Void], buttonIndex: Int) { handlers[buttonIndex](buttonIndex) } // The problem here is that the call has a contextual result type incompatible // with *all* overload set candidates. This is not an ambiguity. func overloaded_identity(_ a : Int) -> Int {} func overloaded_identity(_ b : Float) -> Float {} func test_contextual_result() { return overloaded_identity() // expected-error {{no 'overloaded_identity' candidates produce the expected contextual result type '()'}} // expected-note @-1 {{overloads for 'overloaded_identity' exist with these result types: Int, Float}} } // rdar://problem/24128153 struct X0 { init(_ i: Any.Type) { } init?(_ i: Any.Type, _ names: String...) { } } let x0 = X0(Int.self) let x0check: X0 = x0 // okay: chooses first initializer struct X1 { init?(_ i: Any.Type) { } init(_ i: Any.Type, _ names: String...) { } } let x1 = X1(Int.self) let x1check: X1 = x1 // expected-error{{value of optional type 'X1?' not unwrapped; did you mean to use '!' or '?'?}} struct X2 { init?(_ i: Any.Type) { } init(_ i: Any.Type, a: Int = 0) { } init(_ i: Any.Type, a: Int = 0, b: Int = 0) { } init(_ i: Any.Type, a: Int = 0, c: Int = 0) { } } let x2 = X2(Int.self) let x2check: X2 = x2 // expected-error{{value of optional type 'X2?' not unwrapped; did you mean to use '!' or '?'?}}
apache-2.0
900f25a342a88f0d3ad62194beeb4d89
24.110429
138
0.614708
2.946724
false
false
false
false
dreamsxin/swift
test/decl/func/keyword-argument-labels.swift
6
1171
// RUN: %target-parse-verify-swift struct SomeRange { } // Function declarations. func paramName(_ func: Int, in: SomeRange) { } func firstArgumentLabelWithParamName(in range: SomeRange) { } func firstArgumentLabelWithParamName2(range in: SomeRange) { } func escapedInout(`inout` value: SomeRange) { } struct SomeType { // Initializers init(func: () -> ()) { } init(init func: () -> ()) { } // Subscripts subscript (class index: AnyClass) -> Int { return 0 } subscript (class: AnyClass) -> Int { return 0 } subscript (struct: Any.Type) -> Int { return 0 } } class SomeClass { } // Function types. typealias functionType = (in: SomeRange) -> Bool // Calls func testCalls(_ range: SomeRange) { paramName(0, in: range) firstArgumentLabelWithParamName(in: range) firstArgumentLabelWithParamName2(range: range) var st = SomeType(func: {}) st = SomeType(init: {}) _ = st[class: SomeClass.self] _ = st[SomeClass.self] _ = st[SomeType.self] escapedInout(`inout`: range) // Fix-Its paramName(0, `in`: range) // expected-warning{{keyword 'in' does not need to be escaped in argument list}}{{16-17=}}{{19-20=}} }
apache-2.0
95e667437a3b84ae9c835714d7f7438d
21.960784
128
0.658412
3.570122
false
false
false
false
benlangmuir/swift
test/IRGen/prespecialized-metadata/class-fileprivate-inmodule-1argument-1distinct_use.swift
14
5936
// RUN: %swift -prespecialize-generic-metadata -target %module-target-future -emit-ir %s | %FileCheck %s -DINT=i%target-ptrsize -DALIGNMENT=%target-alignment --check-prefix=CHECK --check-prefix=CHECK-%target-vendor // REQUIRES: VENDOR=apple || OS=linux-gnu // UNSUPPORTED: CPU=i386 && OS=ios // UNSUPPORTED: CPU=armv7 && OS=ios // UNSUPPORTED: CPU=armv7s && OS=ios // CHECK: @"$s4main5Value[[UNIQUE_ID_1:[0-9A-Z_]+]]CySiGMf" = linkonce_odr hidden // CHECK-apple-SAME: global // CHECK-unknown-SAME: constant // CHECK-SAME: <{ // CHECK-SAME: void (%T4main5Value[[UNIQUE_ID_1]]C*)*, // CHECK-SAME: i8**, // : [[INT]], // CHECK-apple-SAME: %objc_class* // CHECK-unknown-SAME: %swift.type*, // CHECK-apple-SAME: %swift.opaque*, // CHECK-apple-SAME: %swift.opaque*, // CHECK-apple-SAME: [[INT]], // CHECK-SAME: i32, // CHECK-SAME: i32, // CHECK-SAME: i32, // CHECK-SAME: i16, // CHECK-SAME: i16, // CHECK-SAME: i32, // CHECK-SAME: i32, // CHECK-SAME: %swift.type_descriptor*, // CHECK-SAME: i8*, // CHECK-SAME: %swift.type*, // CHECK-SAME: [[INT]], // CHECK-apple-SAME: %T4main5Value[[UNIQUE_ID_1]]C* (%swift.opaque*, %swift.type*)* // CHECK-SAME: }> <{ // CHECK-SAME: void (%T4main5Value[[UNIQUE_ID_1]]C*)* // CHECK-SAME: $s4main5Value[[UNIQUE_ID_1]]CfD // CHECK-SAME: $sBoWV // CHECK-apple-SAME: $s4main5Value[[UNIQUE_ID_1]]CySiGMM // CHECK-apple-SAME: OBJC_CLASS_$__TtCs12_SwiftObject // CHECK-apple-SAME: %swift.opaque* @_objc_empty_cache, // CHECK-apple-SAME: %swift.opaque* null, // CHECK-apple-SAME: [[INT]] add ( // CHECK-apple-SAME: [[INT]] ptrtoint ( // CHECK-apple-SAME: { // CHECK-apple-SAME: i32, // CHECK-apple-SAME: i32, // CHECK-apple-SAME: i32, // : i32, // CHECK-apple-SAME: i8*, // CHECK-apple-SAME: i8*, // CHECK-apple-SAME: i8*, // CHECK-apple-SAME: i8*, // CHECK-apple-SAME: { i32, i32, [1 x { [[INT]]*, i8*, i8*, i32, i32 }] }*, // CHECK-apple-SAME: i8*, // CHECK-apple-SAME: i8* // CHECK-apple-SAME: }* @"_DATA_$s4main5Value[[UNIQUE_ID_1]]CySiGMf" to [[INT]] // CHECK-apple-SAME: ), // CHECK-apple-SAME: [[INT]] 2 // CHECK-apple-SAME: ), // CHECK-unknown-SAME: i64 0, // CHECK-SAME: i32 26, // CHECK-SAME: i32 0, // CHECK-SAME: i32 {{(24|12)}}, // CHECK-SAME: i16 {{(7|3)}}, // CHECK-SAME: i16 0, // CHECK-apple-SAME: i32 {{(120|72)}}, // CHECK-unknown-SAME: i32 96, // CHECK-SAME: i32 {{(16|8)}}, // : %swift.type_descriptor* bitcast (<{ i32, i32, i32, i32, i32, i32, i32, i32, i32, i32, i32, i32, i32, i16, i16, i16, i16, i8, i8, i8, i8, i32, i32, %swift.method_descriptor }>* @"$s4main5Value[[UNIQUE_ID_1]]CMn" to %swift.type_descriptor*), // CHECK-SAME: i8* null, // CHECK-SAME: %swift.type* @"$sSiN", // CHECK-SAME: [[INT]] {{(16|8)}}, // CHECK-SAME: %T4main5Value[[UNIQUE_ID_1]]C* (%swift.opaque*, %swift.type*)* // CHECK-SAME: $s4main5Value[[UNIQUE_ID_1]]C5firstADyxGx_tcfC // CHECK-SAME: }>, align [[ALIGNMENT]] fileprivate class Value<First> { let first: First init(first: First) { self.first = first } } @inline(never) func consume<T>(_ t: T) { withExtendedLifetime(t) { t in } } // CHECK: define hidden swiftcc void @"$s4main4doityyF"() #{{[0-9]+}} { // CHECK: [[METADATA_RESPONSE:%[0-9]+]] = call swiftcc %swift.metadata_response @"$s4main5Value[[UNIQUE_ID_4:[0-9A-Z_]+]]CySiGMb"([[INT]] 0) // CHECK: [[METADATA:%[0-9]+]] = extractvalue %swift.metadata_response [[METADATA_RESPONSE]], 0 // CHECK: call swiftcc void @"$s4main7consumeyyxlF"( // CHECK-SAME: %swift.opaque* noalias nocapture {{%[0-9]+}}, // CHECK-SAME: %swift.type* [[METADATA]]) // CHECK: } func doit() { consume( Value(first: 13) ) } doit() // CHECK: define internal swiftcc %swift.metadata_response @"$s4main5Value[[UNIQUE_ID_1]]CMa"([[INT]] [[METADATA_REQUEST:%[0-9]+]], %swift.type* %1) #{{[0-9]+}} { // CHECK: entry: // CHECK: [[ERASED_TYPE:%[0-9]+]] = bitcast %swift.type* %1 to i8* // CHECK: {{%[0-9]+}} = call swiftcc %swift.metadata_response @__swift_instantiateCanonicalPrespecializedGenericMetadata( // CHECK: [[INT]] [[METADATA_REQUEST]], // CHECK: i8* [[ERASED_TYPE]], // CHECK: i8* undef, // CHECK: i8* undef, // CHECK: %swift.type_descriptor* bitcast ( // : <{ i32, i32, i32, i32, i32, i32, i32, i32, i32, i32, i32, i32, i32, i16, i16, i16, i16, i8, i8, i8, i8, i32, i32, %swift.method_descriptor }>* // CHECK: $s4main5Value[[UNIQUE_ID_1]]CMn // CHECK: to %swift.type_descriptor* // CHECK: ) // CHECK: ) #{{[0-9]+}} // CHECK: ret %swift.metadata_response {{%[0-9]+}} // CHECK: } // CHECK: define linkonce_odr hidden swiftcc %swift.metadata_response @"$s4main5Value[[UNIQUE_ID_4]]CySiGMb"([[INT]] {{%[0-9]+}}) {{#[0-9]}} { // CHECK: entry: // CHECK-apple: [[INITIALIZED_CLASS:%[0-9]+]] = call %objc_class* @objc_opt_self( // CHECK-apple: %objc_class* bitcast ( // CHECK-unknown: ret // CHECK-SAME: @"$s4main5Value[[UNIQUE_ID_1]]CySiGMf" // CHECK-apple: [[INITIALIZED_METADATA:%[0-9]+]] = bitcast %objc_class* [[INITIALIZED_CLASS]] to %swift.type* // CHECK-apple: [[PARTIAL_METADATA_RESPONSE:%[0-9]+]] = insertvalue %swift.metadata_response undef, %swift.type* [[INITIALIZED_METADATA]], 0 // CHECK-apple: [[METADATA_RESPONSE:%[0-9]+]] = insertvalue %swift.metadata_response [[PARTIAL_METADATA_RESPONSE]], [[INT]] 0, 1 // CHECK-apple: ret %swift.metadata_response [[METADATA_RESPONSE]] // CHECK: }
apache-2.0
d70334633eb745af10f8d024f5392825
45.015504
265
0.562163
2.823977
false
false
false
false
benlangmuir/swift
test/diagnostics/Localization/fr_debug_diagnostic_name.swift
4
834
// RUN: %empty-directory(%t) // RUN: swift-serialize-diagnostics --input-file-path=%S/Inputs/fr.strings --output-directory=%t/ // RUN: swift-serialize-diagnostics --input-file-path=%S/Inputs/en.strings --output-directory=%t/ // RUN: not %target-swift-frontend -debug-diagnostic-names -localization-path %S/Inputs -locale fr -typecheck %s 2>&1 | %FileCheck %s --check-prefix=CHECK_NAMES _ = "HI! // CHECK_NAMES: error: chaîne non terminée littérale [lex_unterminated_string]{{$}} // FIXME: This used to produce a localized diagnostic. var self1 = self1 // CHECK_NAMES: error: circular reference [circular_reference]{{$}} // CHECK_NAMES: note: through reference here [circular_reference_through]{{$}} struct Broken { var b : Bool = True } // CHECK_NAMES: error: impossible de trouver 'True' portée [cannot_find_in_scope]{{$}}
apache-2.0
5deb6c869c73faeee5ae376908073896
45.111111
160
0.715663
3.360324
false
false
false
false
KrishMunot/swift
test/1_stdlib/NewString.swift
3
7168
// RUN: %target-run-stdlib-swift | FileCheck %s // REQUIRES: executable_test // REQUIRES: objc_interop import Foundation import Swift // ==== Tests ===== func hex(_ x: UInt64) -> String { return String(x, radix:16) } func hexAddrVal<T>(_ x: T) -> String { return "@0x" + hex(UInt64(unsafeBitCast(x, to: UInt.self))) } func hexAddr(_ x: AnyObject?) -> String { if let owner = x { if let y = owner as? _StringBuffer._Storage.Storage { return ".native\(hexAddrVal(y))" } if let y = owner as? NSString { return ".cocoa\(hexAddrVal(y))" } else { return "?Uknown?\(hexAddrVal(owner))" } } return "null" } func repr(_ x: NSString) -> String { return "\(NSStringFromClass(object_getClass(x)))\(hexAddrVal(x)) = \"\(x)\"" } func repr(_ x: _StringCore) -> String { if x.hasContiguousStorage { if let b = x.nativeBuffer { var offset = x.elementWidth == 2 ? UnsafeMutablePointer(b.start) - x.startUTF16 : UnsafeMutablePointer(b.start) - x.startASCII return "Contiguous(owner: " + "\(hexAddr(x._owner))[\(offset)...\(x.count + offset)]" + ", capacity = \(b.capacity))" } return "Contiguous(owner: \(hexAddr(x._owner)), count: \(x.count))" } else if let b2 = x.cocoaBuffer { return "Opaque(buffer: \(hexAddr(b2))[0...\(x.count)])" } return "?????" } func repr(_ x: String) -> String { return "String(\(repr(x._core))) = \"\(x)\"" } // CHECK: Testing print("Testing...") //===--------- Native Strings ---------=== // Force the string literal representation into a Native, heap-allocated buffer var nsb = "🏂☃❅❆❄︎⛄️❄️" // CHECK-NEXT: Hello, snowy world: 🏂☃❅❆❄︎⛄️❄️ print("Hello, snowy world: \(nsb)") // CHECK-NEXT: String(Contiguous(owner: null, count: 11)) print(" \(repr(nsb))") var empty = String() // CHECK-NEXT: These are empty: <> print("These are empty: <\(empty)>") // CHECK-NEXT: String(Contiguous(owner: null, count: 0)) print(" \(repr(empty))") //===--------- non-ASCII ---------=== func nonASCII() { // Cocoa stores non-ASCII in a UTF-16 buffer // Code units in each character: 2 1 1 1 2 2 2 // Offset of each character: 0 2 3 4 5 7 9 11 var nsUTF16 = NSString(utf8String: "🏂☃❅❆❄︎⛄️❄️")! // CHECK-NEXT: has UTF-16: true print("has UTF-16: \(CFStringGetCharactersPtr(unsafeBitCast(nsUTF16, to: CFString.self)) != nil)") // CHECK: --- UTF-16 basic round-tripping --- print("--- UTF-16 basic round-tripping ---") // check that no extraneous objects are created // CHECK-NEXT: __NSCFString@[[utf16address:[x0-9a-f]+]] = "🏂☃❅❆❄︎⛄️❄️" print(" \(repr(nsUTF16))") // CHECK-NEXT: String(Contiguous(owner: .cocoa@[[utf16address]], count: 11)) var newNSUTF16 = nsUTF16 as String print(" \(repr(newNSUTF16))") // CHECK-NEXT: __NSCFString@[[utf16address]] = "🏂☃❅❆❄︎⛄️❄️" var nsRoundTripUTF16 = newNSUTF16 as NSString print(" \(repr(nsRoundTripUTF16))") // CHECK: --- UTF-16 slicing --- print("--- UTF-16 slicing ---") // Slicing the String does not allocate // CHECK-NEXT: String(Contiguous(owner: .cocoa@[[utf16address]], count: 6)) let i2 = newNSUTF16.startIndex.advanced(by: 2) let i8 = newNSUTF16.startIndex.advanced(by: 6) print(" \(repr(newNSUTF16[i2..<i8]))") // Representing a slice as an NSString requires a new object // CHECK-NOT: NSString@[[utf16address]] = "❅❆❄︎⛄️" // CHECK-NEXT: _NSContiguousString@[[nsContiguousStringAddress:[x0-9a-f]+]] = "❅❆❄︎⛄️" var nsSliceUTF16 = newNSUTF16[i2..<i8] as NSString print(" \(repr(nsSliceUTF16))") // Check that we can recover the original buffer // CHECK-NEXT: String(Contiguous(owner: .cocoa@[[utf16address]], count: 6)) print(" \(repr(nsSliceUTF16 as String))") } nonASCII() //===--------- ASCII ---------=== func ascii() { // Cocoa stores ASCII in a buffer of bytes. This is an important case // because it doesn't provide a contiguous array of UTF-16, so we'll be // treating it as an opaque NSString. var nsASCII = NSString(utf8String: "foobar")! // CHECK-NEXT: has UTF-16: false print("has UTF-16: \(CFStringGetCharactersPtr(unsafeBitCast(nsASCII, to: CFString.self)) != nil)") // CHECK: --- ASCII basic round-tripping --- print("--- ASCII basic round-tripping ---") // CHECK-NEXT: [[nsstringclass:(__NSCFString|NSTaggedPointerString)]]@[[asciiaddress:[x0-9a-f]+]] = "foobar" print(" \(repr(nsASCII))") // CHECK-NEXT NO: String(Opaque(buffer: @[[asciiaddress]][0...6])) var newNSASCII = nsASCII as String // print(" \(repr(newNSASCII))") // CHECK-NEXT: [[nsstringclass]]@[[asciiaddress]] = "foobar" var nsRoundTripASCII = newNSASCII as NSString print(" \(repr(nsRoundTripASCII))") // CHECK: --- ASCII slicing --- print("--- ASCII slicing ---") let i3 = newNSASCII.startIndex.advanced(by: 3) let i6 = newNSASCII.startIndex.advanced(by: 6) // Slicing the String print(" \(repr(newNSASCII[i3..<i6]))") // Representing a slice as an NSString var nsSliceASCII = newNSASCII[i3..<i6] as NSString print(" \(repr(nsSliceASCII))") // Round-tripped back to Swift print(" \(repr(nsSliceASCII as String))") } ascii() //===-------- Literals --------=== // String literals default to UTF-16. // CHECK: --- Literals --- print("--- Literals ---") // CHECK-NEXT: String(Contiguous(owner: null, count: 6)) = "foobar" // CHECK-NEXT: true var asciiLiteral: String = "foobar" print(" \(repr(asciiLiteral))") print(" \(asciiLiteral._core.isASCII)") // CHECK-NEXT: String(Contiguous(owner: null, count: 11)) = "🏂☃❅❆❄︎⛄️❄️" // CHECK-NEXT: false var nonASCIILiteral: String = "🏂☃❅❆❄︎⛄️❄️" print(" \(repr(nonASCIILiteral))") print(" \(!asciiLiteral._core.isASCII)") // ===------- Appending -------=== // These tests are in NewStringAppending.swift. // ===---------- Comparison --------=== var s = "ABCDEF" var s1 = s + "G" // CHECK-NEXT: true print("\(s) == \(s) => \(s == s)") // CHECK-NEXT: false print("\(s) == \(s1) => \(s == s1)") // CHECK-NEXT: true let abcdef: String = "ABCDEF" print("\(s) == \"\(abcdef)\" => \(s == abcdef)") let so: String = "so" let sox: String = "sox" let tocks: String = "tocks" // CHECK-NEXT: false print("so < so => \(so < so)") // CHECK-NEXT: true print("so < sox => \(so < sox)") // CHECK-NEXT: true print("so < tocks => \(so < tocks)") // CHECK-NEXT: true print("sox < tocks => \(sox < tocks)") let qqq = nonASCIILiteral.hasPrefix("🏂☃") let rrr = nonASCIILiteral.hasPrefix("☃") let zz = ( nonASCIILiteral.hasPrefix("🏂☃"), nonASCIILiteral.hasPrefix("☃"), nonASCIILiteral.hasSuffix("⛄️❄️"), nonASCIILiteral.hasSuffix("☃")) // CHECK-NEXT: <true, false, true, false> print("<\(zz.0), \(zz.1), \(zz.2), \(zz.3)>") // ===---------- Interpolation --------=== // CHECK-NEXT: {{.*}}"interpolated: foobar 🏂☃❅❆❄︎⛄️❄️ 42 3.14 true" s = "interpolated: \(asciiLiteral) \(nonASCIILiteral) \(42) \(3.14) \(true)" print("\(repr(s))") // ===---------- Done --------=== // CHECK-NEXT: Done. print("Done.")
apache-2.0
a50f4b81a2b9e6f28fece64b2bad9077
28.709402
110
0.605006
3.434783
false
false
false
false
shlyren/ONE-Swift
ONE_Swift/Classes/Reading-阅读/View/Cell/JENReadCell.swift
1
1900
// // JENReadCell.swift // ONE_Swift // // Created by 任玉祥 on 16/5/4. // Copyright © 2016年 任玉祥. All rights reserved. // import UIKit class JENReadCell: UITableViewCell { // MARK: - 私有属性 @IBOutlet private weak var titleLabel: UILabel! @IBOutlet private weak var nameLabel: UILabel! @IBOutlet private weak var maketimeLabel: UILabel! @IBOutlet private weak var contentLabel: UILabel! // MARK: - 短篇 var essay = JENReadEssayItem() { didSet { titleLabel.text = essay.hp_title nameLabel.text = essay.author.first?.user_name maketimeLabel.text = essay.hp_makettime contentLabel.text = essay.guide_word } } // MARK: - 连载 var serial = JENReadSerialItem() { didSet { titleLabel.text = serial.title nameLabel.text = serial.author.user_name maketimeLabel.text = serial.maketime contentLabel.text = serial.excerpt } } // MARK: - 问答 var question = JENReadQuestionItem() { didSet { titleLabel.text = question.question_title nameLabel.text = question.answer_title maketimeLabel.text = question.question_makettime contentLabel.text = question.answer_content } } override func awakeFromNib() { super.awakeFromNib() backgroundView = UIImageView(image: UIImage(named: "mainCellBackground")) backgroundColor = UIColor.clearColor() selectionStyle = .None } override var frame: CGRect { set { var frame = newValue frame.origin.x += JENDefaultMargin frame.size.width -= 2 * JENDefaultMargin frame.size.height -= JENDefaultMargin super.frame = frame } get { return super.frame } } }
mit
581f3ff770e1cf9aabf8aec79ecbbe18
27.257576
81
0.594102
4.388235
false
false
false
false
insidegui/WWDC
PlayerUI/MediaPlayer Support/PUINowPlayingInfo.swift
1
1189
// // PUINowPlayingInfo.swift // PlayerUI // // Created by Guilherme Rambo on 22/04/18. // Copyright © 2018 Guilherme Rambo. All rights reserved. // import Cocoa import MediaPlayer public struct PUINowPlayingInfo { public var title: String public var artist: String public var progress: Double public var isLive: Bool public var image: NSImage? public init(title: String, artist: String, progress: Double = 0, isLive: Bool = false, image: NSImage? = nil) { self.title = title self.artist = artist self.progress = progress self.isLive = isLive self.image = image } } extension PUINowPlayingInfo { var dictionaryRepresentation: [String: Any] { var info: [String: Any] = [ MPMediaItemPropertyTitle: title, MPMediaItemPropertyArtist: artist ] info[MPNowPlayingInfoPropertyPlaybackProgress] = progress info[MPNowPlayingInfoPropertyIsLiveStream] = isLive if let image = self.image { info[MPMediaItemPropertyArtwork] = MPMediaItemArtwork(boundsSize: image.size, requestHandler: { _ in image }) } return info } }
bsd-2-clause
4d35b5c9753038af355e447cd624c6f8
23.75
121
0.65404
4.733068
false
false
false
false
insidegui/WWDC
Packages/ConfCore/ConfCore/Environment.swift
1
4573
// // Environment.swift // WWDC // // Created by Guilherme Rambo on 21/02/17. // Copyright © 2017 Guilherme Rambo. All rights reserved. // import Foundation import os.log public extension Notification.Name { static let WWDCEnvironmentDidChange = Notification.Name("WWDCEnvironmentDidChange") } public struct Environment: Equatable { public let baseURL: String public let cocoaHubBaseURL: String public let configPath: String public let sessionsPath: String public let newsPath: String public let liveVideosPath: String public let featuredSectionsPath: String public init(baseURL: String, cocoaHubBaseURL: String, configPath: String, sessionsPath: String, newsPath: String, liveVideosPath: String, featuredSectionsPath: String) { self.baseURL = baseURL self.cocoaHubBaseURL = cocoaHubBaseURL self.configPath = configPath self.sessionsPath = sessionsPath self.newsPath = newsPath self.liveVideosPath = liveVideosPath self.featuredSectionsPath = featuredSectionsPath } public static func setCurrent(_ environment: Environment) { objc_sync_enter(self) defer { objc_sync_exit(self) } let shouldNotify = (environment != Environment.current) _storedEnvironment = environment UserDefaults.standard.set(environment.baseURL, forKey: _storedEnvDefaultsKey) if shouldNotify { DispatchQueue.main.async { os_log("Environment base URL: %@", log: .default, type: .info, environment.baseURL) NotificationCenter.default.post(name: .WWDCEnvironmentDidChange, object: environment) } } } } private let _storedEnvDefaultsKey = "_confCoreEnvironmentBaseURL" private var _storedEnvironment: Environment? = Environment.readFromDefaults() extension Environment { public static let defaultCocoaHubBaseURL = "https://cocoahub.wwdc.io" static func readFromDefaults() -> Environment? { guard let baseURL = UserDefaults.standard.object(forKey: _storedEnvDefaultsKey) as? String else { return nil } return Environment( baseURL: baseURL, cocoaHubBaseURL: Self.defaultCocoaHubBaseURL, configPath: "/config.json", sessionsPath: "/sessions.json", newsPath: "/news.json", liveVideosPath: "/videos_live.json", featuredSectionsPath: "/_featured.json" ) } public static var current: Environment { #if DEBUG if let baseURL = UserDefaults.standard.string(forKey: "WWDCEnvironmentBaseURL") { return Environment(baseURL: baseURL, cocoaHubBaseURL: Self.defaultCocoaHubBaseURL, configPath: "/config.json", sessionsPath: "/contents.json", newsPath: "/news.json", liveVideosPath: "/videos_live.json", featuredSectionsPath: "/_featured.json") } #endif if ProcessInfo.processInfo.arguments.contains("--test") { return .test } else { if let stored = _storedEnvironment { return stored } else { return .production } } } public static let test = Environment(baseURL: "http://localhost:9042", cocoaHubBaseURL: Self.defaultCocoaHubBaseURL, configPath: "/config.json", sessionsPath: "/contents.json", newsPath: "/news.json", liveVideosPath: "/videos_live.json", featuredSectionsPath: "/_featured.json") public static let production = Environment(baseURL: "https://api2021.wwdc.io", cocoaHubBaseURL: Self.defaultCocoaHubBaseURL, configPath: "/config.json", sessionsPath: "/contents.json", newsPath: "/news.json", liveVideosPath: "/videos_live.json", featuredSectionsPath: "/_featured.json") }
bsd-2-clause
a3821c4cc2b9c873e150ea12b184bb27
35.870968
118
0.558618
5.876607
false
true
false
false
CesarValiente/CursoSwiftUniMonterrey2-UI
week4/PizzasForWatch/PizzasForWatch WatchKit Extension/PizzaData.swift
1
2000
// // PizzaData.swift // pizzas // // Created by Cesar Valiente on 10/01/16. // Copyright © 2016 Cesar Valiente. All rights reserved. // import Foundation enum Size : String { case Small = "Pequeña" case Medium = "Mediana" case Big = "Grande" } func fromStringToSize (rawValue : String?) -> Size { if (rawValue == Size.Small.rawValue) { return Size.Small }else if (rawValue == Size.Medium.rawValue) { return Size.Medium }else { return Size.Big } } enum Body : String { case Thin = "Delgada" case Crunchy = "Crujiente" case Gross = "Gruesa" } func fromStringToBody (rawValue : String?) -> Body { if (rawValue == Body.Thin.rawValue) { return Body.Thin }else if (rawValue == Body.Crunchy.rawValue) { return Body.Crunchy }else { return Body.Gross } } enum Cheese : String { case Mozzarella case Cheddar case Parmesan = "Parmesano" case NoCheese = "Sin queso" } func fromStringToCheese (rawValue : String?) -> Cheese { if (rawValue == Cheese.Mozzarella.rawValue) { return Cheese.Mozzarella }else if (rawValue == Cheese.Cheddar.rawValue) { return Cheese.Cheddar }else if (rawValue == Cheese.Parmesan.rawValue){ return Cheese.Parmesan }else { return Cheese.NoCheese } } enum Ingredients : String { case One = "1 ingrediente" case Two = "2 ingredientes" case Three = "3 ingredientes" case Four = "4 ingredientes" case Five = "5 ingredientes" } func fromStringToIngredients (rawValue : String?) -> Ingredients { if (rawValue == Ingredients.One.rawValue) { return Ingredients.One }else if (rawValue == Ingredients.Two.rawValue) { return Ingredients.Two }else if (rawValue == Ingredients.Three.rawValue){ return Ingredients.Three }else if (rawValue == Ingredients.Four.rawValue){ return Ingredients.Four }else { return Ingredients.Five } }
mit
af41581debb11d7312628180a86e8c99
23.365854
66
0.633634
3.776938
false
false
false
false
ahoppen/swift
test/SILGen/keypaths_resilient_generic.swift
22
1878
// RUN: %empty-directory(%t) // RUN: %target-swift-frontend -emit-module -enable-library-evolution -emit-module-path=%t/resilient_struct.swiftmodule -module-name=resilient_struct %S/../Inputs/resilient_struct.swift // RUN: %target-swift-frontend -emit-module -enable-library-evolution -emit-module-path=%t/resilient_class.swiftmodule -module-name=resilient_class -I %t %S/../Inputs/resilient_class.swift // RUN: %target-swift-emit-silgen %s -I %t -enable-library-evolution | %FileCheck %s import resilient_class open class MySubclass<T> : ResilientOutsideParent { public final var storedProperty: T? = nil } open class ConcreteSubclass : MySubclass<Int> { public final var anotherStoredProperty: Int? = nil } // CHECK-LABEL: sil shared [thunk] [ossa] @$s26keypaths_resilient_generic10MySubclassC14storedPropertyxSgvplACyxGTK : $@convention(thin) <T> (@in_guaranteed MySubclass<T>) -> @out Optional<T> { // CHECK-LABEL: sil shared [thunk] [ossa] @$s26keypaths_resilient_generic10MySubclassC14storedPropertyxSgvplACyxGTk : $@convention(thin) <T> (@in_guaranteed Optional<T>, @in_guaranteed MySubclass<T>) -> () { // CHECK: sil_property #MySubclass.storedProperty<τ_0_0> ( // CHECK-SAME: settable_property $Optional<τ_0_0>, // CHECK-SAME: id ##MySubclass.storedProperty, // CHECK-SAME: getter @$s26keypaths_resilient_generic10MySubclassC14storedPropertyxSgvplACyxGTK : $@convention(thin) <τ_0_0> (@in_guaranteed MySubclass<τ_0_0>) -> @out Optional<τ_0_0>, // CHECK-SAME: setter @$s26keypaths_resilient_generic10MySubclassC14storedPropertyxSgvplACyxGTk : $@convention(thin) <τ_0_0> (@in_guaranteed Optional<τ_0_0>, @in_guaranteed MySubclass<τ_0_0>) -> () // CHECK-SAME: ) // CHECK: sil_property #ConcreteSubclass.anotherStoredProperty ( // CHECK-SAME: stored_property #ConcreteSubclass.anotherStoredProperty : $Optional<Int> // CHECK-SAME: )
apache-2.0
619b71969b403a63422f3b38b3d96b07
61.333333
207
0.74385
3.375451
false
false
false
false
quan118/RSSKit
Sources/GTMString+HTML.swift
1
14117
// // GTMString+HTML.swift // // // Created by Quan Nguyen on 6/22/16. // Copyright © 2016 Niteco, Inc. All rights reserved. // import Foundation typealias HTMLEscapeMap = (escapeSequence:String, uchar:unichar) // Taken from http://www.w3.org/TR/xhtml1/dtds.html#a_dtd_Special_characters // Ordered by uchar lowest to highest for bsearching let gAsciiHTMLEscapeMap:[HTMLEscapeMap] = [ // A.2.2. Special characters ( "&quot;", 34 ), ( "&amp;", 38 ), ( "&apos;", 39 ), ( "&lt;", 60 ), ( "&gt;", 62 ), // A.2.1. Latin-1 characters ( "&nbsp;", 160 ), ( "&iexcl;", 161 ), ( "&cent;", 162 ), ( "&pound;", 163 ), ( "&curren;", 164 ), ( "&yen;", 165 ), ( "&brvbar;", 166 ), ( "&sect;", 167 ), ( "&uml;", 168 ), ( "&copy;", 169 ), ( "&ordf;", 170 ), ( "&laquo;", 171 ), ( "&not;", 172 ), ( "&shy;", 173 ), ( "&reg;", 174 ), ( "&macr;", 175 ), ( "&deg;", 176 ), ( "&plusmn;", 177 ), ( "&sup2;", 178 ), ( "&sup3;", 179 ), ( "&acute;", 180 ), ( "&micro;", 181 ), ( "&para;", 182 ), ( "&middot;", 183 ), ( "&cedil;", 184 ), ( "&sup1;", 185 ), ( "&ordm;", 186 ), ( "&raquo;", 187 ), ( "&frac14;", 188 ), ( "&frac12;", 189 ), ( "&frac34;", 190 ), ( "&iquest;", 191 ), ( "&Agrave;", 192 ), ( "&Aacute;", 193 ), ( "&Acirc;", 194 ), ( "&Atilde;", 195 ), ( "&Auml;", 196 ), ( "&Aring;", 197 ), ( "&AElig;", 198 ), ( "&Ccedil;", 199 ), ( "&Egrave;", 200 ), ( "&Eacute;", 201 ), ( "&Ecirc;", 202 ), ( "&Euml;", 203 ), ( "&Igrave;", 204 ), ( "&Iacute;", 205 ), ( "&Icirc;", 206 ), ( "&Iuml;", 207 ), ( "&ETH;", 208 ), ( "&Ntilde;", 209 ), ( "&Ograve;", 210 ), ( "&Oacute;", 211 ), ( "&Ocirc;", 212 ), ( "&Otilde;", 213 ), ( "&Ouml;", 214 ), ( "&times;", 215 ), ( "&Oslash;", 216 ), ( "&Ugrave;", 217 ), ( "&Uacute;", 218 ), ( "&Ucirc;", 219 ), ( "&Uuml;", 220 ), ( "&Yacute;", 221 ), ( "&THORN;", 222 ), ( "&szlig;", 223 ), ( "&agrave;", 224 ), ( "&aacute;", 225 ), ( "&acirc;", 226 ), ( "&atilde;", 227 ), ( "&auml;", 228 ), ( "&aring;", 229 ), ( "&aelig;", 230 ), ( "&ccedil;", 231 ), ( "&egrave;", 232 ), ( "&eacute;", 233 ), ( "&ecirc;", 234 ), ( "&euml;", 235 ), ( "&igrave;", 236 ), ( "&iacute;", 237 ), ( "&icirc;", 238 ), ( "&iuml;", 239 ), ( "&eth;", 240 ), ( "&ntilde;", 241 ), ( "&ograve;", 242 ), ( "&oacute;", 243 ), ( "&ocirc;", 244 ), ( "&otilde;", 245 ), ( "&ouml;", 246 ), ( "&divide;", 247 ), ( "&oslash;", 248 ), ( "&ugrave;", 249 ), ( "&uacute;", 250 ), ( "&ucirc;", 251 ), ( "&uuml;", 252 ), ( "&yacute;", 253 ), ( "&thorn;", 254 ), ( "&yuml;", 255 ), // A.2.2. Special characters cont'd ( "&OElig;", 338 ), ( "&oelig;", 339 ), ( "&Scaron;", 352 ), ( "&scaron;", 353 ), ( "&Yuml;", 376 ), // A.2.3. Symbols ( "&fnof;", 402 ), // A.2.2. Special characters cont'd ( "&circ;", 710 ), ( "&tilde;", 732 ), // A.2.3. Symbols cont'd ( "&Alpha;", 913 ), ( "&Beta;", 914 ), ( "&Gamma;", 915 ), ( "&Delta;", 916 ), ( "&Epsilon;", 917 ), ( "&Zeta;", 918 ), ( "&Eta;", 919 ), ( "&Theta;", 920 ), ( "&Iota;", 921 ), ( "&Kappa;", 922 ), ( "&Lambda;", 923 ), ( "&Mu;", 924 ), ( "&Nu;", 925 ), ( "&Xi;", 926 ), ( "&Omicron;", 927 ), ( "&Pi;", 928 ), ( "&Rho;", 929 ), ( "&Sigma;", 931 ), ( "&Tau;", 932 ), ( "&Upsilon;", 933 ), ( "&Phi;", 934 ), ( "&Chi;", 935 ), ( "&Psi;", 936 ), ( "&Omega;", 937 ), ( "&alpha;", 945 ), ( "&beta;", 946 ), ( "&gamma;", 947 ), ( "&delta;", 948 ), ( "&epsilon;", 949 ), ( "&zeta;", 950 ), ( "&eta;", 951 ), ( "&theta;", 952 ), ( "&iota;", 953 ), ( "&kappa;", 954 ), ( "&lambda;", 955 ), ( "&mu;", 956 ), ( "&nu;", 957 ), ( "&xi;", 958 ), ( "&omicron;", 959 ), ( "&pi;", 960 ), ( "&rho;", 961 ), ( "&sigmaf;", 962 ), ( "&sigma;", 963 ), ( "&tau;", 964 ), ( "&upsilon;", 965 ), ( "&phi;", 966 ), ( "&chi;", 967 ), ( "&psi;", 968 ), ( "&omega;", 969 ), ( "&thetasym;", 977 ), ( "&upsih;", 978 ), ( "&piv;", 982 ), // A.2.2. Special characters cont'd ( "&ensp;", 8194 ), ( "&emsp;", 8195 ), ( "&thinsp;", 8201 ), ( "&zwnj;", 8204 ), ( "&zwj;", 8205 ), ( "&lrm;", 8206 ), ( "&rlm;", 8207 ), ( "&ndash;", 8211 ), ( "&mdash;", 8212 ), ( "&lsquo;", 8216 ), ( "&rsquo;", 8217 ), ( "&sbquo;", 8218 ), ( "&ldquo;", 8220 ), ( "&rdquo;", 8221 ), ( "&bdquo;", 8222 ), ( "&dagger;", 8224 ), ( "&Dagger;", 8225 ), // A.2.3. Symbols cont'd ( "&bull;", 8226 ), ( "&hellip;", 8230 ), // A.2.2. Special characters cont'd ( "&permil;", 8240 ), // A.2.3. Symbols cont'd ( "&prime;", 8242 ), ( "&Prime;", 8243 ), // A.2.2. Special characters cont'd ( "&lsaquo;", 8249 ), ( "&rsaquo;", 8250 ), // A.2.3. Symbols cont'd ( "&oline;", 8254 ), ( "&frasl;", 8260 ), // A.2.2. Special characters cont'd ( "&euro;", 8364 ), // A.2.3. Symbols cont'd ( "&image;", 8465 ), ( "&weierp;", 8472 ), ( "&real;", 8476 ), ( "&trade;", 8482 ), ( "&alefsym;", 8501 ), ( "&larr;", 8592 ), ( "&uarr;", 8593 ), ( "&rarr;", 8594 ), ( "&darr;", 8595 ), ( "&harr;", 8596 ), ( "&crarr;", 8629 ), ( "&lArr;", 8656 ), ( "&uArr;", 8657 ), ( "&rArr;", 8658 ), ( "&dArr;", 8659 ), ( "&hArr;", 8660 ), ( "&forall;", 8704 ), ( "&part;", 8706 ), ( "&exist;", 8707 ), ( "&empty;", 8709 ), ( "&nabla;", 8711 ), ( "&isin;", 8712 ), ( "&notin;", 8713 ), ( "&ni;", 8715 ), ( "&prod;", 8719 ), ( "&sum;", 8721 ), ( "&minus;", 8722 ), ( "&lowast;", 8727 ), ( "&radic;", 8730 ), ( "&prop;", 8733 ), ( "&infin;", 8734 ), ( "&ang;", 8736 ), ( "&and;", 8743 ), ( "&or;", 8744 ), ( "&cap;", 8745 ), ( "&cup;", 8746 ), ( "&int;", 8747 ), ( "&there4;", 8756 ), ( "&sim;", 8764 ), ( "&cong;", 8773 ), ( "&asymp;", 8776 ), ( "&ne;", 8800 ), ( "&equiv;", 8801 ), ( "&le;", 8804 ), ( "&ge;", 8805 ), ( "&sub;", 8834 ), ( "&sup;", 8835 ), ( "&nsub;", 8836 ), ( "&sube;", 8838 ), ( "&supe;", 8839 ), ( "&oplus;", 8853 ), ( "&otimes;", 8855 ), ( "&perp;", 8869 ), ( "&sdot;", 8901 ), ( "&lceil;", 8968 ), ( "&rceil;", 8969 ), ( "&lfloor;", 8970 ), ( "&rfloor;", 8971 ), ( "&lang;", 9001 ), ( "&rang;", 9002 ), ( "&loz;", 9674 ), ( "&spades;", 9824 ), ( "&clubs;", 9827 ), ( "&hearts;", 9829 ), ( "&diams;", 9830 ) ] // Taken from http://www.w3.org/TR/xhtml1/dtds.html#a_dtd_Special_characters // This is table A.2.2 Special Characters let gUnicodeHTMLEscapeMap:[HTMLEscapeMap] = [ // C0 Controls and Basic Latin ( "&quot;", 34 ), ( "&amp;", 38 ), ( "&apos;", 39 ), ( "&lt;", 60 ), ( "&gt;", 62 ), // Latin Extended-A ( "&OElig;", 338 ), ( "&oelig;", 339 ), ( "&Scaron;", 352 ), ( "&scaron;", 353 ), ( "&Yuml;", 376 ), // Spacing Modifier Letters ( "&circ;", 710 ), ( "&tilde;", 732 ), // General Punctuation ( "&ensp;", 8194 ), ( "&emsp;", 8195 ), ( "&thinsp;", 8201 ), ( "&zwnj;", 8204 ), ( "&zwj;", 8205 ), ( "&lrm;", 8206 ), ( "&rlm;", 8207 ), ( "&ndash;", 8211 ), ( "&mdash;", 8212 ), ( "&lsquo;", 8216 ), ( "&rsquo;", 8217 ), ( "&sbquo;", 8218 ), ( "&ldquo;", 8220 ), ( "&rdquo;", 8221 ), ( "&bdquo;", 8222 ), ( "&dagger;", 8224 ), ( "&Dagger;", 8225 ), ( "&permil;", 8240 ), ( "&lsaquo;", 8249 ), ( "&rsaquo;", 8250 ), ( "&euro;", 8364 ) ] extension String { static private func escapeMapCompare(uchar:unichar, map:HTMLEscapeMap) -> Int { var val = 0 if uchar > map.uchar { val = 1 } else if (uchar < map.uchar) { val = -1 } else { val = 0 } return val } static private func bsearch(codeUnit:unichar, table:[HTMLEscapeMap]) -> HTMLEscapeMap? { var first = 0, last = table.count-1 while first <= last { let mid = (first + last) / 2 if table[mid].uchar == codeUnit { return table[mid] } else if table[mid].uchar < codeUnit { first = mid + 1 } else { last = mid - 1 } } return nil } func gtm_stringByEscapingHTMLUsingTable(table:[HTMLEscapeMap], escapingUnicode:Bool) -> String { // 1. Get length of this string (in utf16). if length == 0 then return self // 2. Create an array of utf16 code unit from content of this string // 3. Iterate through the array, look up code unit in let length = self.utf16.count if length == 0 { return self } var finalString = "" for codeunit in self.utf16 { let val = String.bsearch(codeunit, table: table) if val != nil || (escapingUnicode && codeunit > 127) { if let val = val { finalString += val.escapeSequence } else { finalString += "&#\(codeunit);" } } else { finalString.append(UnicodeScalar(codeunit)) } } return finalString } // From '<span>blah<span>' to '&lt;span&gt;blah&lt;span&gt;' public func gtm_stringByEscapingForHTML() -> String { return gtm_stringByEscapingHTMLUsingTable(gUnicodeHTMLEscapeMap, escapingUnicode: false) } // From '&lt;span&gt;blah&lt;span&gt;' to '<span>blah<span>' public func gtm_stringByUnescapingFromHTML() -> String { var range = self.startIndex..<self.endIndex var subrange = self.rangeOfString("&", options: NSStringCompareOptions.BackwardsSearch, range: range, locale: nil) // if no ampersands, we've got a quick way out if subrange == nil || subrange?.count == 0 { return self } var finalString = String(self) repeat { var semiColonRange:Range<String.Index>? = subrange!.startIndex..<range.endIndex semiColonRange = self.rangeOfString(";", options: NSStringCompareOptions.CaseInsensitiveSearch, range: semiColonRange, locale: nil) range = self.startIndex..<subrange!.startIndex // if we don't find a semicolon in the range, we don't have a sequence if semiColonRange == nil { subrange = self.rangeOfString("&", options: NSStringCompareOptions.BackwardsSearch, range: range, locale: nil) continue } let escapeRange = subrange!.startIndex...semiColonRange!.startIndex let escapeString = self.substringWithRange(escapeRange) let length = escapeString.characters.count // a sequence must be longer than 3 (&lt;) and less than 11 (&thetasym;) if length > 3 && length < 11 { if escapeString[escapeString.startIndex.advancedBy(1)] == "#" { let char2 = escapeString[escapeString.startIndex.advancedBy(2)] if char2 == "x" || char2 == "X" { // Hex escape sequences &#xa3; let subrange2 = escapeString.startIndex.advancedBy(3)..<escapeString.endIndex.predecessor() let hexSequence = escapeString.substringWithRange(subrange2) let scanner = NSScanner(string: hexSequence) var value:CUnsignedInt = 0 if scanner.scanHexInt(&value) && value < UInt32(CUnsignedShort.max) && value > 0 && scanner.scanLocation == length - 4 { let charString = String(Character(UnicodeScalar(value))) finalString.replaceRange(escapeRange, with: charString) } } else { // Decimal Sequences &#123; let subrange2 = escapeString.startIndex.advancedBy(2)..<escapeString.endIndex.predecessor() let numberSequence = escapeString.substringWithRange(subrange2) let scanner = NSScanner(string: numberSequence) var value:Int32 = 0 if scanner.scanInt(&value) && value < Int32(CUnsignedShort.max) && value > 0 && scanner.scanLocation == length - 3 { let charString = String(Character(UnicodeScalar(UInt32(value)))) finalString.replaceRange(escapeRange, with: charString) } } } else { // "standard" sequences for kv in gAsciiHTMLEscapeMap { if escapeString == kv.escapeSequence { finalString.replaceRange(escapeRange, with: String(Character(UnicodeScalar(kv.uchar)))) break } } } } subrange = self.rangeOfString("&", options: NSStringCompareOptions.BackwardsSearch, range: range, locale: nil) } while subrange != nil && subrange?.count != 0 return finalString } public func gtm_stringByEscapingForAsciiHTML() -> String { return gtm_stringByEscapingHTMLUsingTable(gAsciiHTMLEscapeMap, escapingUnicode: true) } }
mit
81699f64c9bcbf036c2f07aaba20819f
28.595388
144
0.442902
3.675085
false
false
false
false
noppoMan/Prorsum
Tests/ProrsumTests/HTTPClientTests.swift
1
2535
// // HTTPClientTests.swift // Prorsum // // Created by Yuki Takei on 2016/12/04. // // #if os(Linux) import Glibc #else import Darwin.C #endif import XCTest import Foundation @testable import Prorsum class HTTPClientTests: XCTestCase { static var allTests : [(String, (HTTPClientTests) -> () throws -> Void)] { return [ ("testConnect", testConnect), ("testHTTPSConnect", testHTTPSConnect), ("testRedirect", testRedirect), ("testRedirectToOtherDomain", testRedirectToOtherDomain), ("testRedirectMaxRedirectionExceeded", testRedirectMaxRedirectionExceeded) ] } func testConnect() { let client = try! HTTPClient(url: URL(string: "http://httpbin.org/get")!) try! client.open() let response = try! client.request() XCTAssertEqual(response.statusCode, 200) } func testHTTPSConnect() { let client = try! HTTPClient(url: URL(string: "https://httpbin.org/get")!) try! client.open() let response = try! client.request() XCTAssertEqual(response.statusCode, 200) } func testRedirect() { let client = try! HTTPClient(url: URL(string: "https://httpbin.org/redirect/2")!) try! client.open() let response = try! client.request() XCTAssertEqual(response.statusCode, 200) } func testRedirectToOtherDomain() { let client = try! HTTPClient(url: URL(string: "https://httpbin.org/redirect-to?url=http%3A%2F%2Fexample.com%2F")!) try! client.open() let response = try! client.request() XCTAssertEqual(response.statusCode, 200) } func testRedirectToOtherDomainWithPort() { let client = try! HTTPClient(url: URL(string: "https://httpbin.org/redirect-to?url=http%3A%2F%2Fexample.com%3A80")!) try! client.open() let response = try! client.request() XCTAssertEqual(response.statusCode, 200) } func testRedirectMaxRedirectionExceeded() { HTTPClient.maxRedirection = 1 defer { HTTPClient.maxRedirection = 10 } let client = try! HTTPClient(url: URL(string: "https://httpbin.org/redirect/1")!) try! client.open() do { _ = try client.request() } catch HTTPClientError.maxRedirectionExceeded(let max) { XCTAssertEqual(max, 1) } catch { XCTFail("\(error)") } } }
mit
7089e98852862c25cc330977a7bce76f
28.137931
124
0.597633
4.28934
false
true
false
false
practicalswift/swift
validation-test/stdlib/CoreGraphics-verifyOnly.swift
36
4335
// RUN: %target-typecheck-verify-swift // REQUIRES: objc_interop import CoreGraphics //===----------------------------------------------------------------------===// // CGColorSpace //===----------------------------------------------------------------------===// // CGColorSpace.colorTable // TODO: has memory issues as a runtime test, so make it verify-only for now let table: [UInt8] = [0,0,0, 255,0,0, 0,0,255, 0,255,0, 255,255,0, 255,0,255, 0,255,255, 255,255,255] let space = CGColorSpace(indexedBaseSpace: CGColorSpaceCreateDeviceRGB(), last: table.count - 1, colorTable: table)! // expectEqual(table, space.colorTable) //===----------------------------------------------------------------------===// // CGContext //===----------------------------------------------------------------------===// func testCGContext(context: CGContext, image: CGImage, glyph: CGGlyph) { context.setLineDash(phase: 0.5, lengths: [0.1, 0.2]) context.move(to: CGPoint.zero) context.addLine(to: CGPoint(x: 0.5, y: 0.5)) context.addCurve(to: CGPoint(x: 1, y: 1), control1: CGPoint(x: 1, y: 0), control2: CGPoint(x: 0, y: 1)) context.addQuadCurve(to: CGPoint(x: 0.5, y: 0.5), control: CGPoint(x: 0.5, y: 0)) context.addRects([CGRect(x: 0, y: 0, width: 100, height: 100)]) context.addLines(between: [CGPoint(x: 0.5, y: 0.5)]) context.addArc(center: CGPoint(x: 0.5, y: 0.5), radius: 1, startAngle: 0, endAngle: .pi, clockwise: false) context.addArc(tangent1End: CGPoint(x: 1, y: 1), tangent2End: CGPoint(x: 0.5, y: 0.5), radius: 0.5) context.fill([CGRect(x: 0, y: 0, width: 100, height: 100)]) context.fillPath() context.fillPath(using: .evenOdd) context.strokeLineSegments(between: [CGPoint(x: 0.5, y: 0.5), CGPoint(x: 0, y: 0.5)]) context.clip(to: [CGRect(x: 0, y: 0, width: 100, height: 100)]) context.clip() context.clip(using: .evenOdd) context.draw(image, in: CGRect(x: 0, y: 0, width: 100, height: 100), byTiling: true) print(context.textPosition) context.showGlyphs([glyph], at: [CGPoint(x: 0.5, y: 0.5)]) } //===----------------------------------------------------------------------===// // CGDirectDisplay //===----------------------------------------------------------------------===// #if os(macOS) let (dx, dy) = CGGetLastMouseDelta() #endif //===----------------------------------------------------------------------===// // CGImage //===----------------------------------------------------------------------===// func testCGImage(image: CGImage) -> CGImage? { return image.copy(maskingColorComponents: [1, 0, 0]) } //===----------------------------------------------------------------------===// // CGLayer //===----------------------------------------------------------------------===// func testDrawLayer(in context: CGContext) { let layer = CGLayer(context, size: CGSize(width: 512, height: 384), auxiliaryInfo: nil)! context.draw(layer, in: CGRect(origin: .zero, size: layer.size)) context.draw(layer, at: CGPoint(x: 20, y: 20)) } func testCGPath(path: CGPath) { let dashed = path.copy(dashingWithPhase: 1, lengths: [0.2, 0.3, 0.5]) let stroked = path.copy(strokingWithWidth: 1, lineCap: .butt, lineJoin: .miter, miterLimit: 0.1) let mutable = stroked.mutableCopy()! // test inferred transform parameter for all below print(path.contains(CGPoint(x: 0.5, y: 0.5))) print(path.contains(CGPoint(x: 0.5, y: 0.5), using: .evenOdd)) mutable.move(to: .zero) mutable.addLine(to: CGPoint(x: 0.5, y: 0.5)) mutable.addCurve(to: CGPoint(x: 1, y: 1), control1: CGPoint(x: 1, y: 0), control2: CGPoint(x: 0, y: 1)) mutable.addQuadCurve(to: CGPoint(x: 0.5, y: 0.5), control: CGPoint(x: 0.5, y: 0)) mutable.addRect(CGRect(x: 0, y: 0, width: 10, height: 10)) mutable.addRects([CGRect(x: 0, y: 0, width: 100, height: 100)]) mutable.addLines(between: [CGPoint(x: 0.5, y: 0.5)]) mutable.addEllipse(in: CGRect(x: 0, y: 0, width: 50, height: 70)) mutable.addArc(center: CGPoint(x: 0.5, y: 0.5), radius: 1, startAngle: 0, endAngle: .pi, clockwise: false) mutable.addArc(tangent1End: CGPoint(x: 1, y: 1), tangent2End: CGPoint(x: 0.5, y: 0.5), radius: 0.5) mutable.addRelativeArc(center: CGPoint(x: 1, y: 1), radius: 0.5, startAngle: .pi, delta: .pi/2) mutable.addPath(dashed) }
apache-2.0
9347ced388a7018872ce7ef4844618e2
33.404762
109
0.535179
3.456938
false
false
false
false
LucyJeong/LearningCS50
Week3/LinearSearch.playground/Contents.swift
1
578
//: Playground - noun: a place where people can play //Equatable: == or != 연산자를 사용하여 값이 동일한지 판단할 수 있는 타입입니다. 이 프로토콜을 채택하면 해당 타입을 위한 == 연산자를 구현해야합니다. 그러면 표준라이브러리에서 != 연산자를 자동으로 구현해줍니다. func linearSearch<T:Equatable>(_ array: [T],_ object: T) -> Int? { for (index, obj) in array.enumerated() where obj == object{ return index } return nil } var a = [1,3,4,5,43,3,34,52,50] linearSearch(a, 50)
mit
95e52bc9650de2e409d2041eadcbd8b1
27
130
0.628571
2.110553
false
false
false
false
kkolli/MathGame
client/Speedy/BoardHeaderController.swift
1
1300
// // BoardHeaderController.swift // Speedy // // Created by Tyler Levine on 3/6/15. // Copyright (c) 2015 Krishna Kolli. All rights reserved. // import Foundation import SpriteKit class BoardHeaderController { let scene: GameScene let frame: CGRect let view: BoardHeader let board: BoardController init(mode: BoardMode, scene s: GameScene, frame f: CGRect, board b: BoardController) { scene = s frame = f board = b if mode == .SINGLE { view = BoardHeader(frame: f, targetNum: b.targetNumber!, time: 600) s.addChild(view) } else { view = BoardHeader(frame: f, targetNum: b.targetNumber!, time: 600, opponentName: "") s.addChild(view) } } func setTargetNumber(num: Int) { view.target = num } func setTimeRemaining(time: Int) { view.timer = time } func setScore(currentScore: Int) { view.score = currentScore } func setOpponentName(opponent: String) { view.opponentName = opponent } func setOpponentScore(opponentScore: Int) { view.opponentScore = opponentScore } func getScorePosition() -> CGPoint { return view.getScoreLabelPosition() } }
gpl-2.0
61abe240e0565952af29c59d81fe4d0b
22.654545
97
0.595385
4.113924
false
false
false
false
osorioabel/my-location-app
My Locations/My Locations/Controllers/LocationDetailsViewController.swift
1
13188
// // LocationDetailsViewController.swift // My Locations // // Created by Abel Osorio on 2/17/16. // Copyright © 2016 Abel Osorio. All rights reserved. // import UIKit import CoreLocation import Dispatch import CoreData private let dateFormatter: NSDateFormatter = { let formatter = NSDateFormatter() formatter.dateStyle = .MediumStyle formatter.timeStyle = .ShortStyle return formatter }() class LocationDetailsViewController: UITableViewController { @IBOutlet weak var descriptionTextView: UITextView! @IBOutlet weak var categoryLabel: UILabel! @IBOutlet weak var latitudeLabel: UILabel! @IBOutlet weak var longitudeLabel: UILabel! @IBOutlet weak var addressLabel: UILabel! @IBOutlet weak var dateLabel: UILabel! @IBOutlet weak var imageView: UIImageView! @IBOutlet weak var addPhotoLabel: UILabel! var coordinate = CLLocationCoordinate2D(latitude: 0, longitude: 0) var placemark: CLPlacemark? var categoryName = "No Category" var descriptionText = "" var managedObjectContext: NSManagedObjectContext! var date = NSDate() var image: UIImage? var observer: AnyObject! var locationToEdit: Location? { didSet { if let location = locationToEdit { descriptionText = location.locationDescription categoryName = location.category date = location.date coordinate = CLLocationCoordinate2DMake(location.latitude, location.longitude) placemark = location.placemark } } } // MARK: - Life Cycle override func viewDidLoad() { super.viewDidLoad() if let location = locationToEdit{ title = "Edit Location" if location.hasPhoto { if let image = location.photoImage{ showImage(image) } } } descriptionTextView.text = descriptionText categoryLabel.text = categoryName latitudeLabel.text = String(format: "%.8f", coordinate.latitude) longitudeLabel.text = String(format: "%.8f", coordinate.longitude) if let placemark = placemark { addressLabel.text = stringFromPlacemark(placemark) } else { addressLabel.text = "No Address Found" } dateLabel.text = formatDate(NSDate()) let gestureRecognizer = UITapGestureRecognizer(target: self,action: Selector("hideKeyboard:")) gestureRecognizer.cancelsTouchesInView = false tableView.addGestureRecognizer(gestureRecognizer) imageView.hidden = true listenForBackgroundNotification() tableView.backgroundColor = UIColor.blackColor() tableView.separatorColor = UIColor(white: 1.0, alpha: 0.2) tableView.indicatorStyle = .White descriptionTextView.textColor = UIColor.whiteColor() descriptionTextView.backgroundColor = UIColor.blackColor() addPhotoLabel.textColor = UIColor.whiteColor() addPhotoLabel.highlightedTextColor = addPhotoLabel.textColor addressLabel.textColor = UIColor(white: 1.0, alpha: 0.4) addressLabel.highlightedTextColor = addressLabel.textColor } deinit { NSNotificationCenter.defaultCenter().removeObserver(observer) } // MARK: - String Related func stringFromPlacemark(placemark: CLPlacemark) -> String { var line = "" line.addText(placemark.subThoroughfare) line.addText(placemark.thoroughfare, withSeparator: " ") line.addText(placemark.locality, withSeparator: ", ") line.addText(placemark.administrativeArea, withSeparator: ", ") line.addText(placemark.postalCode, withSeparator: " ") line.addText(placemark.country, withSeparator: ", ") return line } // MARK: - Date related func formatDate(date: NSDate) -> String { return dateFormatter.stringFromDate(date) } // MARK: - Actions @IBAction func done (){ let hudView = HudView.hubInView(navigationController!.view, animated: true) if let _ = locationToEdit{ hudView.text = "Updated" }else{ hudView.text = "Tagged" } saveLocation() afterDelay(0.6){ self.dismissViewControllerAnimated(true, completion: nil) } } func showImage(image:UIImage){ imageView.image = image imageView.hidden = false imageView.frame = CGRect(x: 10, y: 10, width: 260, height: 260) } @IBAction func cancel(){ dismissViewControllerAnimated(true, completion: nil) } override func tableView(tableView: UITableView,willSelectRowAtIndexPath indexPath: NSIndexPath) -> NSIndexPath? { if indexPath.section == 0 || indexPath.section == 1 { return indexPath } else { return nil } } override func tableView(tableView: UITableView,didSelectRowAtIndexPath indexPath: NSIndexPath) { if indexPath.section == 0 && indexPath.row == 0 { descriptionTextView.becomeFirstResponder() }else if indexPath.section == 1 && indexPath.row == 0{ tableView.deselectRowAtIndexPath(indexPath, animated: true) pickPhoto() } } // MARK: - UITableViewDelegate override func tableView(tableView: UITableView,heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { switch (indexPath.section,indexPath.row){ case (0,0): return 88 case (1,_): return imageView.hidden ? 44:280 case (2,2): addressLabel.frame.size = CGSize(width: view.bounds.size.width - 115, height: 10000) addressLabel.sizeToFit() addressLabel.frame.origin.x = view.bounds.size.width - addressLabel.frame.size.width - 15 return addressLabel.frame.size.height + 20 default: return 44 } } override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell,forRowAtIndexPath indexPath: NSIndexPath) { cell.backgroundColor = UIColor.blackColor() if let textLabel = cell.textLabel { textLabel.textColor = UIColor.whiteColor() textLabel.highlightedTextColor = textLabel.textColor } if let detailLabel = cell.detailTextLabel { detailLabel.textColor = UIColor(white: 1.0, alpha: 0.4) detailLabel.highlightedTextColor = detailLabel.textColor } let selectionView = UIView(frame: CGRect.zero) selectionView.backgroundColor = UIColor(white: 1.0, alpha: 0.2) cell.selectedBackgroundView = selectionView if indexPath.row == 2 { let addressLabel = cell.viewWithTag(100) as! UILabel addressLabel.textColor = UIColor.whiteColor() addressLabel.highlightedTextColor = addressLabel.textColor } } // MARK: - Keyboard func hideKeyboard(gestureRecognizer: UIGestureRecognizer) { let point = gestureRecognizer.locationInView(tableView) let indexPath = tableView.indexPathForRowAtPoint(point) if indexPath != nil && indexPath!.section == 0 && indexPath!.row == 0 { return } descriptionTextView.resignFirstResponder() } func saveLocation(){ let location : Location if let temp = locationToEdit{ location = temp }else{ location = NSEntityDescription.insertNewObjectForEntityForName( "Location", inManagedObjectContext: managedObjectContext) as! Location location.photoID = nil } location.locationDescription = descriptionTextView.text location.category = categoryName location.latitude = coordinate.latitude location.longitude = coordinate.longitude location.date = date location.placemark = placemark if let image = image { if !location.hasPhoto { location.photoID = Location.nextPhotoID() } if let data = UIImageJPEGRepresentation(image, 0.5) { // 3 do { try data.writeToFile(location.photoPath,options: .DataWritingAtomic) }catch {print("Error writing file: \(error)")} } } do { try managedObjectContext.save() } catch { fatalCoreDataError(error) } } // MARK: - Segue Related override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "PickCategory" { let controller = segue.destinationViewController as! CategoryPickerViewController controller.selectedCategoryName = categoryName }else if segue.identifier == ""{ } } @IBAction func categoryPickerDidPickCategory(segue: UIStoryboardSegue) { let controller = segue.sourceViewController as! CategoryPickerViewController categoryName = controller.selectedCategoryName categoryLabel.text = categoryName } func listenForBackgroundNotification() { observer = NSNotificationCenter.defaultCenter().addObserverForName(UIApplicationDidEnterBackgroundNotification, object: nil, queue: NSOperationQueue.mainQueue()) { [weak self ] _ in if let strongSelf = self{ if strongSelf.presentedViewController != nil { strongSelf.dismissViewControllerAnimated(false, completion: nil) } strongSelf.descriptionTextView.resignFirstResponder() } } } } // MARK: - ImagePicker Extension extension LocationDetailsViewController : UIImagePickerControllerDelegate,UINavigationControllerDelegate{ func takePhotoWithCamera() { let imagePicker = UIImagePickerController() imagePicker.sourceType = .Camera imagePicker.delegate = self imagePicker.allowsEditing = true imagePicker.view.tintColor = view.tintColor imagePicker.modalPresentationStyle = UIModalPresentationStyle.OverCurrentContext presentViewController(imagePicker, animated: true, completion: nil) } func choosePhotoFromLibrary() { let imagePicker = MyImagePickerController() imagePicker.sourceType = .PhotoLibrary imagePicker.delegate = self imagePicker.allowsEditing = true imagePicker.modalPresentationStyle = UIModalPresentationStyle.OverCurrentContext presentViewController(imagePicker, animated: true, completion: nil) } func pickPhoto() { if UIImagePickerController.isSourceTypeAvailable(.Camera) { showPhotoMenu() } else { choosePhotoFromLibrary() } } func showPhotoMenu() { let alertController = UIAlertController(title: nil, message: nil,preferredStyle: .ActionSheet) let cancelAction = UIAlertAction(title: "Cancel", style: .Cancel, handler: nil) alertController.addAction(cancelAction) let takePhotoAction = UIAlertAction(title: "Take Photo",style: .Default, handler: { _ in self.takePhotoWithCamera()}) alertController.addAction(takePhotoAction) let chooseFromLibraryAction = UIAlertAction(title:"Choose From Library", style: .Default, handler: { _ in self.choosePhotoFromLibrary()}) alertController.addAction(chooseFromLibraryAction) presentViewController(alertController, animated: true, completion: nil) } func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) { image = info[UIImagePickerControllerEditedImage] as? UIImage if let image = image { showImage(image) } dismissViewControllerAnimated(true, completion: nil) tableView.reloadData() } func imagePickerControllerDidCancel(picker: UIImagePickerController) { dismissViewControllerAnimated(true, completion: nil) } }
mit
fa0b20ebf31f22e94c4bfb8ef2e01e83
35.228022
146
0.600591
6.179475
false
false
false
false
Sol88/GASSwiftExtensions
GASSwiftExtensions/Sources/UIControl+ActionBlock.swift
1
898
// Created by Виктор Заикин on 16.05.16. // Copyright © 2016 Виктор Заикин. All rights reserved. import UIKit public typealias ControlActionBlock = () -> Void var AssociatedObjectHandle: UInt8 = 0 class BlockWrapper: NSObject { var block: ControlActionBlock? init(block: ControlActionBlock?) { self.block = block } func invokeBlock() { if let block = block { block() } } } public extension UIControl { public func addActionBlock(controlEvents: UIControlEvents, actionBlock:ControlActionBlock?) { let wrapper = BlockWrapper(block: actionBlock) self.addTarget(wrapper, action: #selector(BlockWrapper.invokeBlock), for: controlEvents) objc_setAssociatedObject(self, &AssociatedObjectHandle, wrapper, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC) } }
mit
5c733c61d5211d66b0e7644b3ddc399e
27.16129
130
0.687285
4.343284
false
false
false
false
wagnersouz4/replay
Replay/Replay/Helpers/GridHelper.swift
1
1361
// // Grid.swift // Replay // // Created by Wagner Souza on 6/04/17. // Copyright © 2017 Wagner Souza. All rights reserved. // import UIKit public struct GridLayout { let tableViewHeight: CGFloat let orientation: GridOrientation let size: CGSize } public class GridHelper { public var view: UIView init(_ view: UIView) { self.view = view } public var screenHeight: CGFloat { return max(view.frame.height, self.view.frame.width) } public var screenWidth: CGFloat { return min(view.frame.height, view.frame.width) } public var landscapeLayout: GridLayout { let tableHeight = screenWidth * 0.562 let orientation = GridOrientation.landscape let height = tableHeight * 0.9 let size = CGSize(width: height * 1.78, height: height) return GridLayout( tableViewHeight: tableHeight, orientation: orientation, size: size) } public var portraitLayout: GridLayout { let tableHeight = screenHeight * 0.35 let orientation = GridOrientation.portrait let height = tableHeight * 0.9 let size = CGSize(width: height * 0.67, height: height) return GridLayout( tableViewHeight: tableHeight, orientation: orientation, size: size) } }
mit
c8ff04aa377b96b34f9bb2d64331ccf8
23.285714
63
0.625
4.518272
false
false
false
false
tkohout/Genie
GenieTests/GenieTests.swift
1
2495
// // GeneeTests.swift // GeneeTests // // Created by Tomas Kohout on 23/10/2016. // Copyright © 2016 Bouke Haarsma. All rights reserved. // import XCTest import SourceKittenFramework class GeneeTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testThatParentIsFound() { let structure = Structure(file: File(contents: [ " enum TestEnum {", " case Test1", " case Test2", " }", "", " class Whatever: NSObject {", " let test: TestEnum? = nil", " }", "struct User {", "let id: Int", "let email: String", "let name: String?", "let surname: String?", "let latitude: Double?", "}"].joined(separator: "\n"))).dictionary as SourceKitRepresentable let variableStructures = structure.substructures.flatten().filter { $0.kind == SwiftDeclarationKind.varInstance } let parent = variableStructures.first?.parent(root: structure) XCTAssertNotNil(parent, "Parent is nil") XCTAssertNotNil(parent?.name, "Parent name is nil") } func testThatClosureIsFound() { let structure: SourceKitRepresentable = Structure(file: File(contents: [ //"class Some {", " func someFunc(){", " let closure: (String) -> () = { a in", " self.someOtherFunc()", " }", "let i = 5", "if i == 5 {", "i+=1", "}", "", " }", "", " func someOtherFunc(){", "", " }", //"}" ].joined(separator: "\n"))).dictionary print(structure.tree()) XCTAssertNotNil(structure) } } extension SourceKitRepresentable { func tree() -> String { var result = ["\(self.name ?? "??"):\(self.typeName ?? "??")"] result += self.substructures.map { $0.tree() } ?? [] return result.joined(separator: "\n") } }
mit
209d03a2cbfae9d2de716c144f9b76f9
26.108696
122
0.49158
4.714556
false
true
false
false
btanner/Eureka
Source/Core/Validation.swift
3
3344
// RowValidationType.swift // Eureka ( https://github.com/xmartlabs/Eureka ) // // Copyright (c) 2016 Xmartlabs SRL ( http://xmartlabs.com ) // // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation public struct ValidationError: Equatable { public let msg: String public init(msg: String) { self.msg = msg } } public func == (lhs: ValidationError, rhs: ValidationError) -> Bool { return lhs.msg == rhs.msg } public protocol BaseRuleType { var id: String? { get set } var validationError: ValidationError { get set } } public protocol RuleType: BaseRuleType { associatedtype RowValueType func isValid(value: RowValueType?) -> ValidationError? } public struct ValidationOptions: OptionSet { public let rawValue: Int public init(rawValue: Int) { self.rawValue = rawValue } public static let validatesOnDemand = ValidationOptions(rawValue: 1 << 0) public static let validatesOnChange = ValidationOptions(rawValue: 1 << 1) public static let validatesOnBlur = ValidationOptions(rawValue: 1 << 2) public static let validatesOnChangeAfterBlurred = ValidationOptions(rawValue: 1 << 3) public static let validatesAlways: ValidationOptions = [.validatesOnChange, .validatesOnBlur] } public struct ValidationRuleHelper<T> where T: Equatable { let validateFn: ((T?) -> ValidationError?) public let rule: BaseRuleType } public struct RuleSet<T: Equatable> { internal var rules: [ValidationRuleHelper<T>] = [] public init() {} /// Add a validation Rule to a Row /// - Parameter rule: RuleType object typed to the same type of the Row.value public mutating func add<Rule: RuleType>(rule: Rule) where T == Rule.RowValueType { let validFn: ((T?) -> ValidationError?) = { (val: T?) in return rule.isValid(value: val) } rules.append(ValidationRuleHelper(validateFn: validFn, rule: rule)) } public mutating func remove(ruleWithIdentifier identifier: String) { if let index = rules.firstIndex(where: { (validationRuleHelper) -> Bool in return validationRuleHelper.rule.id == identifier }) { rules.remove(at: index) } } public mutating func removeAllRules() { rules.removeAll() } }
mit
c5a706b69438cb41984f6cfb55c421a3
32.777778
97
0.704844
4.464619
false
false
false
false
sjtu-meow/iOS
Meow/ArticleUserPageTableViewCell.swift
1
1170
// // ArticleUserPageTableViewCell.swift // Meow // // Created by 林武威 on 2017/7/20. // Copyright © 2017年 喵喵喵的伙伴. All rights reserved. // import UIKit class ArticleUserPageTableViewCell: UITableViewCell { @IBOutlet weak var likeCountLabel: UILabel! @IBOutlet weak var contentLabel: UILabel! @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var coverImageView: UIImageView! @IBOutlet weak var commentCountLabel: UILabel! func configure(model: ArticleSummary) { if let url = model.cover{ coverImageView.af_setImage(withURL: url) } titleLabel.text = model.title contentLabel.text = model.summary if let likeCount = model.likeCount { likeCountLabel.text = "\(likeCount)" } else { likeCountLabel.text = "0" } if let commentCount = model.commentCount { commentCountLabel.text = "\(commentCount)" } else { commentCountLabel.text = "0" } //likeCountLabel.text = "\(model.likeCount)" //commentCountLabel.text = "\(model.commentCount)" } }
apache-2.0
27a0b74263713f48edb2c96050392ecb
28.461538
58
0.619669
4.523622
false
false
false
false
pawan007/SmartZip
SmartZip/Library/Controls/DesignableTextField.swift
1
4401
// // DesignableTextField.swift // SmartZip // // Created by Pawan Kumar on 02/06/16. // Copyright © 2016 Modi. All rights reserved. // import UIKit @IBDesignable class DesignableTextField: UITextField { var topBorder: UIView? var bottomBorder: UIView? var leftBorder: UIView? var rightBorder: UIView? @IBInspectable var borderColor: UIColor = UIColor.clearColor() { didSet { layer.borderColor = borderColor.CGColor } } @IBInspectable var borderWidth: CGFloat = 0 { didSet { layer.borderWidth = borderWidth } } @IBInspectable var cornerRadius: CGFloat = 0 { didSet { layer.cornerRadius = cornerRadius } } @IBInspectable var placeHolderColor : UIColor = UIColor.lightGrayColor(){ didSet { setValue(placeHolderColor, forKeyPath: "_placeholderLabel.textColor") } } @IBInspectable var bottomLineWidth : CGFloat = 1 { didSet{ let border: CALayer = CALayer() border.borderColor = UIColor.darkGrayColor().CGColor self.frame = CGRectMake(0, self.frame.size.height - bottomLineWidth, self.frame.size.width, self.frame.size.height) border.borderWidth = borderWidth self.layer.addSublayer(border) self.layer.masksToBounds = true } } @IBInspectable var bottomLineColor : UIColor = UIColor.lightGrayColor(){ didSet { let border: CALayer = CALayer() border.borderColor = bottomLineColor.CGColor } } @IBInspectable var leftImage : String = "" { didSet { leftViewMode = UITextFieldViewMode.Always let imageView = UIImageView(); imageView.frame=CGRectMake(self.frame.origin.x+5, self.frame.origin.y+5, 30,self.frame.size.height-4) let image = UIImage(named:leftImage); imageView.image = image; leftView = imageView; } } @IBInspectable var paddingLeft: CGFloat = 0 @IBInspectable var paddingRight: CGFloat = 0 override func textRectForBounds(bounds: CGRect) -> CGRect { return CGRectMake(bounds.origin.x + paddingLeft, bounds.origin.y, bounds.size.width - paddingLeft - paddingRight, bounds.size.height); } override func editingRectForBounds(bounds: CGRect) -> CGRect { return textRectForBounds(bounds) } @IBInspectable var topBorderColor : UIColor = UIColor.clearColor() @IBInspectable var topBorderHeight : CGFloat = 0 { didSet{ if topBorder == nil{ topBorder = UIView() topBorder?.backgroundColor=topBorderColor; topBorder?.frame = CGRectMake(0, 0, self.frame.size.width, topBorderHeight) addSubview(topBorder!) } } } @IBInspectable var bottomBorderColor : UIColor = UIColor.clearColor() @IBInspectable var bottomBorderHeight : CGFloat = 0 { didSet{ if bottomBorder == nil{ bottomBorder = UIView() bottomBorder?.backgroundColor=bottomBorderColor; bottomBorder?.frame = CGRectMake(0, self.frame.size.height - bottomBorderHeight, self.frame.size.width, bottomBorderHeight) addSubview(bottomBorder!) } } } @IBInspectable var leftBorderColor : UIColor = UIColor.clearColor() @IBInspectable var leftBorderHeight : CGFloat = 0 { didSet{ if leftBorder == nil{ leftBorder = UIView() leftBorder?.backgroundColor=leftBorderColor; leftBorder?.frame = CGRectMake(0, 0, leftBorderHeight, self.frame.size.height) addSubview(leftBorder!) } } } @IBInspectable var rightBorderColor : UIColor = UIColor.clearColor() @IBInspectable var rightBorderHeight : CGFloat = 0 { didSet{ if rightBorder == nil{ rightBorder = UIView() rightBorder?.backgroundColor=topBorderColor; rightBorder?.frame = CGRectMake(self.frame.size.width - rightBorderHeight, 0, rightBorderHeight, self.frame.size.height) addSubview(rightBorder!) } } } }
mit
5de3ed0eecf743977e23148f03c895d2
32.59542
139
0.6
5.275779
false
false
false
false
tlax/looper
looper/View/StoreGo/VStoreGoPlusButtons.swift
1
3287
import UIKit class VStoreGoPlusButtons:UIView { private weak var controller:CStoreGoPlus! private let kButtonMargin:CGFloat = 1 private let kButtonWidth:CGFloat = 148 convenience init(controller:CStoreGoPlus) { self.init() clipsToBounds = true translatesAutoresizingMaskIntoConstraints = false backgroundColor = UIColor.genericBackground self.controller = controller let buttonStore:UIButton = UIButton() buttonStore.translatesAutoresizingMaskIntoConstraints = false buttonStore.clipsToBounds = true buttonStore.backgroundColor = UIColor.white buttonStore.setTitle( NSLocalizedString("VStoreGoPlusButtons_buttonStore", comment:""), for:UIControlState.normal) buttonStore.setTitleColor( UIColor.genericLight, for:UIControlState.normal) buttonStore.setTitleColor( UIColor(white:0, alpha:0.1), for:UIControlState.highlighted) buttonStore.titleLabel!.font = UIFont.medium(size:15) buttonStore.addTarget( self, action:#selector(actionStore(sender:)), for:UIControlEvents.touchUpInside) let buttonCancel:UIButton = UIButton() buttonCancel.translatesAutoresizingMaskIntoConstraints = false buttonCancel.clipsToBounds = true buttonCancel.backgroundColor = UIColor.white buttonCancel.setTitle( NSLocalizedString("VStoreGoPlusButtons_buttonCancel", comment:""), for:UIControlState.normal) buttonCancel.setTitleColor( UIColor(white:0.6, alpha:1), for:UIControlState.normal) buttonCancel.setTitleColor( UIColor(white:0, alpha:0.1), for:UIControlState.highlighted) buttonCancel.titleLabel!.font = UIFont.medium(size:15) buttonCancel.addTarget( self, action:#selector(self.actionCancel(sender:)), for:UIControlEvents.touchUpInside) addSubview(buttonStore) addSubview(buttonCancel) NSLayoutConstraint.topToTop( view:buttonCancel, toView:self, constant:kButtonMargin) NSLayoutConstraint.bottomToBottom( view:buttonCancel, toView:self) NSLayoutConstraint.leftToLeft( view:buttonCancel, toView:self, constant:kButtonMargin) NSLayoutConstraint.width( view:buttonCancel, constant:kButtonWidth) NSLayoutConstraint.topToTop( view:buttonStore, toView:self, constant:kButtonMargin) NSLayoutConstraint.bottomToBottom( view:buttonStore, toView:self) NSLayoutConstraint.rightToRight( view:buttonStore, toView:self, constant:-kButtonMargin) NSLayoutConstraint.width( view:buttonStore, constant:kButtonWidth) } //MARK: actions func actionStore(sender button:UIButton) { controller.openStore() } func actionCancel(sender button:UIButton) { controller.close() } }
mit
b7ab7309c15e0c840e4f0ce1c9230e9e
31.87
78
0.622452
5.933213
false
false
false
false
goblinr/omim
iphone/Maps/Core/BackgroundFetchScheduler/BackgroundFetchTask/BackgroundFetchTask.swift
1
884
@objc class BackgroundFetchTask: NSObject { var queue: DispatchQueue { return .global() } var frameworkType: BackgroundFetchTaskFrameworkType { return .none } private var backgroundTaskIdentifier = UIBackgroundTaskInvalid lazy var block = { self.finish(.failed) } var completionHandler: BackgroundFetchScheduler.FetchResultHandler! func start() { backgroundTaskIdentifier = UIApplication.shared.beginBackgroundTask(expirationHandler: { self.finish(.failed) }) if backgroundTaskIdentifier != UIBackgroundTaskInvalid { queue.async(execute: block) } } func finish(_ result: UIBackgroundFetchResult) { guard backgroundTaskIdentifier != UIBackgroundTaskInvalid else { return } UIApplication.shared.endBackgroundTask(backgroundTaskIdentifier) backgroundTaskIdentifier = UIBackgroundTaskInvalid completionHandler(result) } }
apache-2.0
be312976af2daefb11eaf86cce207e82
34.36
92
0.769231
6.013605
false
false
false
false
iAugux/iBBS-Swift
iBBS/IBBSEditingViewController.swift
1
6534
// // IBBSEditingViewController.swift // iBBS // // Created by Augus on 9/15/15. // // http://iAugus.com // https://github.com/iAugux // // Copyright © 2015 iAugus. All rights reserved. // import UIKit import SwiftyJSON let nodeID = "board" let articleTitle = "title" var contentsArrayOfPostArticle: NSMutableDictionary! class IBBSEditingViewController: UIViewController, UITextViewDelegate { var segueId: String! var nodeId: Int! @IBOutlet var avatarImageView: IBBSAvatarImageView! { didSet{ avatarImageView.antiOffScreenRendering = false avatarImageView.backgroundColor = CUSTOM_THEME_COLOR.darkerColor(0.75) IBBSContext.configureCurrentUserAvatar(avatarImageView) } } @IBOutlet var nodesPickerView: UIPickerView! { didSet{ nodesPickerView.showsSelectionIndicator = false } } @IBOutlet var contentTextView: UITextView! { didSet{ contentTextView.layer.cornerRadius = 4.0 contentTextView.backgroundColor = CUSTOM_THEME_COLOR.darkerColor(0.75).colorWithAlphaComponent(0.35) } } private var node: JSON? private let postControllerID = "iBBSPostViewController" private var defaultSelectedRow: Int! private var blurView: UIView! override func viewDidLoad() { super.viewDidLoad() node = IBBSContext.getNodes() navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .Cancel, target: self , action: #selector(cancelAction)) navigationItem.rightBarButtonItem = UIBarButtonItem(title: BUTTON_NEXT, style: .Plain, target: self, action: #selector(okAction(_:))) view.backgroundColor = UIColor(patternImage: BACKGROUNDER_IMAGE!) blurView = UIVisualEffectView(effect: UIBlurEffect(style: .Light)) blurView.alpha = BLUR_VIEW_ALPHA_OF_BG_IMAGE view.insertSubview(blurView, atIndex: 0) blurView.snp_makeConstraints { (make) in make.edges.equalTo(UIEdgeInsetsZero) } configureDefaultSelectedRow() nodesPickerView.delegate = self nodesPickerView.dataSource = self nodesPickerView.selectRow(defaultSelectedRow, inComponent: 0, animated: true) contentTextView.delegate = self contentsArrayOfPostArticle = NSMutableDictionary() // set default node ID contentsArrayOfPostArticle.setObject(defaultSelectedRow + 1, forKey: nodeID) contentTextView.becomeFirstResponder() } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) navigationController?.navigationBar.tintColor = CUSTOM_THEME_COLOR navigationController?.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName: CUSTOM_THEME_COLOR] navigationController?.navigationBar.translucent = true } private func configureDefaultSelectedRow() { if segueId == postSegue { // IBBSViewController called me defaultSelectedRow = 0 } else { // IBBSNodeViewController called me guard nodeId != nil else { defaultSelectedRow = 0 return } defaultSelectedRow = nodeId - 1 } } @objc private func cancelAction(){ // close keyboard first contentTextView.resignFirstResponder() dismissViewControllerAnimated(true , completion: nil) } @IBAction func okAction(sender: AnyObject) { guard let title = contentTextView.text else { return } contentsArrayOfPostArticle.setObject(title, forKey: articleTitle) if let title = contentsArrayOfPostArticle.valueForKey(articleTitle) as? String { let str = title.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()) if str.isEmpty { let alertController = UIAlertController(title: "", message: YOU_HAVENOT_WROTE_ANYTHING, preferredStyle: .Alert) let action = UIAlertAction(title: GOT_IT, style: .Cancel) { (_) -> Void in self.contentTextView.becomeFirstResponder() } alertController.addAction(action) presentViewController(alertController, animated: true, completion: nil) return } } guard let vc = UIStoryboard.Main.instantiateViewControllerWithIdentifier(String(IBBSPostViewController)) as? IBBSPostViewController else { return } navigationController?.pushViewController(vc , animated: true) } override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) { contentTextView.resignFirstResponder() } func textView(textView: UITextView, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool { let str = text as NSString if str.isEqual("\n") { textView.resignFirstResponder() return false } return true } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } // MARK: - UIPickerViewDataSource extension IBBSEditingViewController: UIPickerViewDataSource { func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { return node?.count ?? 0 } func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int { return 1 } func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { guard let node = node?.arrayValue[row] else { return nil } return node["name"].stringValue } } // MARK: - UIPickerViewDelegate extension IBBSEditingViewController: UIPickerViewDelegate { func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { guard let node = node?.arrayValue[row] else { return } let nodeId = node["id"].intValue // save node ID to array contentsArrayOfPostArticle.setObject(nodeId, forKey: nodeID) } }
mit
f932d2e5337d56255a81543e7fee65b5
30.565217
155
0.636002
5.690767
false
false
false
false
auth0/Auth0.swift
Auth0/Handlers.swift
1
3053
import Foundation func plainJson(from response: Response<AuthenticationError>, callback: Request<[String: Any], AuthenticationError>.Callback) { do { if let dictionary = try response.result() as? [String: Any] { callback(.success(dictionary)) } else { callback(.failure(AuthenticationError(from: response))) } } catch let error as AuthenticationError { callback(.failure(error)) } catch { callback(.failure(AuthenticationError(cause: error))) } } func codable<T: Codable>(from response: Response<AuthenticationError>, callback: Request<T, AuthenticationError>.Callback) { do { if let dictionary = try response.result() as? [String: Any] { let data = try JSONSerialization.data(withJSONObject: dictionary) let decoder = JSONDecoder() decoder.dateDecodingStrategy = .secondsSince1970 let decodedObject = try decoder.decode(T.self, from: data) callback(.success(decodedObject)) } else { callback(.failure(AuthenticationError(from: response))) } } catch let error as AuthenticationError { callback(.failure(error)) } catch { callback(.failure(AuthenticationError(cause: error))) } } func authenticationObject<T: JSONObjectPayload>(from response: Response<AuthenticationError>, callback: Request<T, AuthenticationError>.Callback) { do { if let dictionary = try response.result() as? [String: Any], let object = T(json: dictionary) { callback(.success(object)) } else { callback(.failure(AuthenticationError(from: response))) } } catch let error as AuthenticationError { callback(.failure(error)) } catch { callback(.failure(AuthenticationError(cause: error))) } } func databaseUser(from response: Response<AuthenticationError>, callback: Request<DatabaseUser, AuthenticationError>.Callback) { do { if let dictionary = try response.result() as? [String: Any], let email = dictionary["email"] as? String { let username = dictionary["username"] as? String let verified = dictionary["email_verified"] as? Bool ?? false callback(.success((email: email, username: username, verified: verified))) } else { callback(.failure(AuthenticationError(from: response))) } } catch let error as AuthenticationError { callback(.failure(error)) } catch { callback(.failure(AuthenticationError(cause: error))) } } func noBody(from response: Response<AuthenticationError>, callback: Request<Void, AuthenticationError>.Callback) { do { _ = try response.result() callback(.success(())) } catch let error as AuthenticationError where error.code == emptyBodyError { callback(.success(())) } catch let error as AuthenticationError { callback(.failure(error)) } catch { callback(.failure(AuthenticationError(cause: error))) } }
mit
488d4f701d4142b3fcae0e43db99e95e
39.171053
147
0.650508
4.924194
false
false
false
false
soracom/soracom-sdk-ios
Pod/Classes/Subscriber.swift
1
1353
import Foundation public enum TagValueMatchMode: String { case Exact = "exact" case Prefix = "prefix" } public enum SubscriberStatus: String { case Active = "active" case Inactive = "inactive" case Ready = "ready" case InStock = "instock" case Shipped = "shipped" case Suspended = "suspended" case Terminated = "terminated" } public enum SpeedClass: String { case S1Minimum = "s1.minimum" case S1Slow = "s1.slow" case S1Standard = "s1.standard" case S1Fast = "s1.fast" } public class Subscriber { public var IMSI: String public var MSISDN: String public var ipAddress: String? public var APN: String? public var speedClass: SpeedClass? public var status: SubscriberStatus public var tags: [String: String] init(value: [String: AnyObject]) { self.IMSI = value["imsi"] as! String self.MSISDN = value["msisdn"] as! String self.APN = value["apn"] as! String? if let ipAddress = value["ipAddress"] as? String { self.ipAddress = ipAddress } if let speedClass = value["speedClass"] as? String { self.speedClass = SpeedClass(rawValue: speedClass) } self.status = SubscriberStatus(rawValue: value["status"] as! String)! self.tags = value["tags"] as! [String: String] } }
mit
bfe94b86419dcabd1c80addfd075370c
26.612245
77
0.634146
3.747922
false
false
false
false
ianyh/Highball
Highball/Modules/Posts/Dashboard/DashboardModule.swift
1
706
// // DashboardModule.swift // Highball // // Created by Ian Ynda-Hummel on 9/1/16. // Copyright © 2016 ianynda. All rights reserved. // import Foundation public struct DashboardModule { public let viewController: DashboardViewController private let presenter = DashboardPresenter() private let dataManager: PostsDataManager public init(postHeightCache: PostHeightCache) { viewController = DashboardViewController(postHeightCache: postHeightCache) dataManager = PostsDataManager(postHeightCache: postHeightCache, delegate: presenter) viewController.presenter = presenter presenter.view = viewController presenter.dataManager = dataManager } } extension DashboardModule: Module {}
mit
e377cb9e97f2bc6e54d25439466dcf1c
25.111111
87
0.790071
4.433962
false
false
false
false
hooman/swift
test/expr/unary/keypath/keypath.swift
3
45188
// RUN: %target-swift-frontend -typecheck -parse-as-library %s -verify struct Sub: Hashable { static func ==(_: Sub, _: Sub) -> Bool { return true } func hash(into hasher: inout Hasher) {} } struct OptSub: Hashable { static func ==(_: OptSub, _: OptSub) -> Bool { return true } func hash(into hasher: inout Hasher) {} } struct NonHashableSub {} struct Prop { subscript(sub: Sub) -> A { get { return A() } set { } } subscript(optSub: OptSub) -> A? { get { return A() } set { } } subscript(nonHashableSub: NonHashableSub) -> A { get { return A() } set { } } subscript(a: Sub, b: Sub) -> A { get { return A() } set { } } subscript(a: Sub, b: NonHashableSub) -> A { get { return A() } set { } } var nonMutatingProperty: B { get { fatalError() } nonmutating set { fatalError() } } } struct A: Hashable { init() { fatalError() } var property: Prop var optProperty: Prop? let optLetProperty: Prop? subscript(sub: Sub) -> A { get { return self } set { } } static func ==(_: A, _: A) -> Bool { fatalError() } func hash(into hasher: inout Hasher) { fatalError() } } struct B {} struct C<T> { // expected-note 4 {{'T' declared as parameter to type 'C'}} var value: T subscript() -> T { get { return value } } subscript(sub: Sub) -> T { get { return value } set { } } subscript<U: Hashable>(sub: U) -> U { get { return sub } set { } } subscript<X>(noHashableConstraint sub: X) -> X { get { return sub } set { } } } struct Unavailable { @available(*, unavailable) var unavailableProperty: Int // expected-note@-1 {{'unavailableProperty' has been explicitly marked unavailable here}} @available(*, unavailable) subscript(x: Sub) -> Int { get { } set { } } // expected-note@-1 {{'subscript(_:)' has been explicitly marked unavailable here}} } struct Deprecated { @available(*, deprecated) var deprecatedProperty: Int @available(*, deprecated) subscript(x: Sub) -> Int { get { } set { } } } @available(*, deprecated) func getDeprecatedSub() -> Sub { return Sub() } extension Array where Element == A { var property: Prop { fatalError() } } protocol P { var member: String { get } } extension B : P { var member : String { return "Member Value" } } struct Exactly<T> {} func expect<T>(_ x: inout T, toHaveType _: Exactly<T>.Type) {} func testKeyPath(sub: Sub, optSub: OptSub, nonHashableSub: NonHashableSub, x: Int) { var a = \A.property expect(&a, toHaveType: Exactly<WritableKeyPath<A, Prop>>.self) var b = \A.[sub] expect(&b, toHaveType: Exactly<WritableKeyPath<A, A>>.self) var c = \A.[sub].property expect(&c, toHaveType: Exactly<WritableKeyPath<A, Prop>>.self) var d = \A.optProperty? expect(&d, toHaveType: Exactly<KeyPath<A, Prop?>>.self) var e = \A.optProperty?[sub] expect(&e, toHaveType: Exactly<KeyPath<A, A?>>.self) var f = \A.optProperty! expect(&f, toHaveType: Exactly<WritableKeyPath<A, Prop>>.self) var g = \A.property[optSub]?.optProperty![sub] expect(&g, toHaveType: Exactly<KeyPath<A, A?>>.self) var h = \[A].property expect(&h, toHaveType: Exactly<KeyPath<[A], Prop>>.self) var i = \[A].property.nonMutatingProperty expect(&i, toHaveType: Exactly<ReferenceWritableKeyPath<[A], B>>.self) var j = \[A].[x] expect(&j, toHaveType: Exactly<WritableKeyPath<[A], A>>.self) var k = \[A: B].[A()] expect(&k, toHaveType: Exactly<WritableKeyPath<[A: B], B?>>.self) var l = \C<A>.value expect(&l, toHaveType: Exactly<WritableKeyPath<C<A>, A>>.self) // expected-error@+1{{generic parameter 'T' could not be inferred}} _ = \C.value // expected-error@+1{{}} _ = \(() -> ()).noMember let _: (A) -> Prop = \.property let _: PartialKeyPath<A> = \.property let _: KeyPath<A, Prop> = \.property let _: WritableKeyPath<A, Prop> = \.property let _: ReferenceWritableKeyPath<A, Prop> = \.property //expected-error@-1 {{cannot convert value of type 'WritableKeyPath<A, Prop>' to specified type 'ReferenceWritableKeyPath<A, Prop>'}} let _: (A) -> A = \.[sub] let _: PartialKeyPath<A> = \.[sub] let _: KeyPath<A, A> = \.[sub] let _: WritableKeyPath<A, A> = \.[sub] let _: ReferenceWritableKeyPath<A, A> = \.[sub] //expected-error@-1 {{cannot convert value of type 'WritableKeyPath<A, A>' to specified type 'ReferenceWritableKeyPath<A, A>'}} let _: (A) -> Prop? = \.optProperty? let _: PartialKeyPath<A> = \.optProperty? let _: KeyPath<A, Prop?> = \.optProperty? // expected-error@+1{{cannot convert}} let _: WritableKeyPath<A, Prop?> = \.optProperty? // expected-error@+1{{cannot convert}} let _: ReferenceWritableKeyPath<A, Prop?> = \.optProperty? let _: (A) -> A? = \.optProperty?[sub] let _: PartialKeyPath<A> = \.optProperty?[sub] let _: KeyPath<A, A?> = \.optProperty?[sub] // expected-error@+1{{cannot convert}} let _: WritableKeyPath<A, A?> = \.optProperty?[sub] // expected-error@+1{{cannot convert}} let _: ReferenceWritableKeyPath<A, A?> = \.optProperty?[sub] let _: KeyPath<A, Prop> = \.optProperty! let _: KeyPath<A, Prop> = \.optLetProperty! let _: KeyPath<A, Prop?> = \.property[optSub]?.optProperty! let _: KeyPath<A, A?> = \.property[optSub]?.optProperty![sub] let _: (C<A>) -> A = \.value let _: PartialKeyPath<C<A>> = \.value let _: KeyPath<C<A>, A> = \.value let _: WritableKeyPath<C<A>, A> = \.value let _: ReferenceWritableKeyPath<C<A>, A> = \.value // expected-error@-1 {{cannot convert value of type 'WritableKeyPath<C<A>, A>' to specified type 'ReferenceWritableKeyPath<C<A>, A>'}} let _: (C<A>) -> A = \C.value let _: PartialKeyPath<C<A>> = \C.value let _: KeyPath<C<A>, A> = \C.value let _: WritableKeyPath<C<A>, A> = \C.value // expected-error@+1{{cannot convert}} let _: ReferenceWritableKeyPath<C<A>, A> = \C.value let _: (Prop) -> B = \.nonMutatingProperty let _: PartialKeyPath<Prop> = \.nonMutatingProperty let _: KeyPath<Prop, B> = \.nonMutatingProperty let _: WritableKeyPath<Prop, B> = \.nonMutatingProperty let _: ReferenceWritableKeyPath<Prop, B> = \.nonMutatingProperty var m = [\A.property, \A.[sub], \A.optProperty!] expect(&m, toHaveType: Exactly<[PartialKeyPath<A>]>.self) // \.optProperty returns an optional of Prop and `\.[sub]` returns `A`, all this unifies into `[PartialKeyPath<A>]` var n = [\A.property, \.optProperty, \.[sub], \.optProperty!] expect(&n, toHaveType: Exactly<[PartialKeyPath<A>]>.self) let _: [PartialKeyPath<A>] = [\.property, \.optProperty, \.[sub], \.optProperty!] var o = [\A.property, \C<A>.value] expect(&o, toHaveType: Exactly<[AnyKeyPath]>.self) let _: AnyKeyPath = \A.property let _: AnyKeyPath = \C<A>.value let _: AnyKeyPath = \.property // expected-error {{'AnyKeyPath' does not provide enough context for root type to be inferred; consider explicitly specifying a root type}} {{24-24=<#Root#>}} let _: AnyKeyPath = \C.value // expected-error{{generic parameter 'T' could not be inferred}} let _: AnyKeyPath = \.value // expected-error {{'AnyKeyPath' does not provide enough context for root type to be inferred; consider explicitly specifying a root type}} {{24-24=<#Root#>}} let _ = \Prop.[nonHashableSub] // expected-error{{subscript index of type 'NonHashableSub' in a key path must be Hashable}} let _ = \Prop.[sub, sub] let _ = \Prop.[sub, nonHashableSub] // expected-error{{subscript index of type 'NonHashableSub' in a key path must be Hashable}} let _ = \C<Int>.[] let _ = \C<Int>.[sub] let _ = \C<Int>.[noHashableConstraint: sub] let _ = \C<Int>.[noHashableConstraint: nonHashableSub] // expected-error{{subscript index of type 'NonHashableSub' in a key path must be Hashable}} let _ = \Unavailable.unavailableProperty // expected-error {{'unavailableProperty' is unavailable}} let _ = \Unavailable.[sub] // expected-error {{'subscript(_:)' is unavailable}} let _ = \Deprecated.deprecatedProperty // expected-warning {{'deprecatedProperty' is deprecated}} let _ = \Deprecated.[sub] // expected-warning {{'subscript(_:)' is deprecated}} let _ = \A.[getDeprecatedSub()] // expected-warning {{'getDeprecatedSub()' is deprecated}} } func testKeyPathInGenericContext<H: Hashable, X>(hashable: H, anything: X) { let _ = \C<Int>.[hashable] let _ = \C<Int>.[noHashableConstraint: hashable] let _ = \C<Int>.[noHashableConstraint: anything] // expected-error{{subscript index of type 'X' in a key path must be Hashable}} } func testDisembodiedStringInterpolation(x: Int) { \(x) // expected-error{{string interpolation can only appear inside a string literal}} \(x, radix: 16) // expected-error{{string interpolation can only appear inside a string literal}} } func testNoComponents() { let _: KeyPath<A, A> = \A // expected-error{{must have at least one component}} let _: KeyPath<C, A> = \C // expected-error{{must have at least one component}} // expected-error@-1 {{generic parameter 'T' could not be inferred}} let _: KeyPath<A, C> = \A // expected-error{{must have at least one component}} // expected-error@-1 {{generic parameter 'T' could not be inferred}} _ = \A // expected-error {{key path must have at least one component}} } struct TupleStruct { var unlabeled: (Int, String) var labeled: (foo: Int, bar: String) } typealias UnlabeledGenericTuple<T, U> = (T, U) typealias LabeledGenericTuple<T, U> = (a: T, b: U) func tupleComponent<T, U>(_: T, _: U) { let _ = \(Int, String).0 let _ = \(Int, String).1 let _ = \TupleStruct.unlabeled.0 let _ = \TupleStruct.unlabeled.1 let _ = \(foo: Int, bar: String).0 let _ = \(foo: Int, bar: String).1 let _ = \(foo: Int, bar: String).foo let _ = \(foo: Int, bar: String).bar let _ = \TupleStruct.labeled.0 let _ = \TupleStruct.labeled.1 let _ = \TupleStruct.labeled.foo let _ = \TupleStruct.labeled.bar let _ = \(T, U).0 let _ = \(T, U).1 let _ = \UnlabeledGenericTuple<T, U>.0 let _ = \UnlabeledGenericTuple<T, U>.1 let _ = \(a: T, b: U).0 let _ = \(a: T, b: U).1 let _ = \(a: T, b: U).a let _ = \(a: T, b: U).b let _ = \LabeledGenericTuple<T, U>.0 let _ = \LabeledGenericTuple<T, U>.1 let _ = \LabeledGenericTuple<T, U>.a let _ = \LabeledGenericTuple<T, U>.b } func tuple_el_0<T, U>() -> KeyPath<(T, U), T> { return \.0 } func tuple_el_1<T, U>() -> KeyPath<(T, U), U> { return \.1 } func tupleGeneric<T, U>(_ v: (T, U)) { _ = (1, "hello")[keyPath: tuple_el_0()] _ = (1, "hello")[keyPath: tuple_el_1()] _ = v[keyPath: tuple_el_0()] _ = v[keyPath: tuple_el_1()] _ = ("tuple", "too", "big")[keyPath: tuple_el_1()] // expected-note@-12 {{}} // expected-error@-2 {{generic parameter 'T' could not be inferred}} // expected-error@-3 {{generic parameter 'U' could not be inferred}} } struct Z { } func testKeyPathSubscript(readonly: Z, writable: inout Z, kp: KeyPath<Z, Int>, wkp: WritableKeyPath<Z, Int>, rkp: ReferenceWritableKeyPath<Z, Int>) { var sink: Int sink = readonly[keyPath: kp] sink = writable[keyPath: kp] sink = readonly[keyPath: wkp] sink = writable[keyPath: wkp] sink = readonly[keyPath: rkp] sink = writable[keyPath: rkp] readonly[keyPath: kp] = sink // expected-error{{cannot assign through subscript: 'kp' is a read-only key path}} writable[keyPath: kp] = sink // expected-error{{cannot assign through subscript: 'kp' is a read-only key path}} readonly[keyPath: wkp] = sink // expected-error{{cannot assign through subscript: 'readonly' is a 'let' constant}} writable[keyPath: wkp] = sink readonly[keyPath: rkp] = sink writable[keyPath: rkp] = sink let pkp: PartialKeyPath = rkp var anySink1 = readonly[keyPath: pkp] expect(&anySink1, toHaveType: Exactly<Any>.self) var anySink2 = writable[keyPath: pkp] expect(&anySink2, toHaveType: Exactly<Any>.self) readonly[keyPath: pkp] = anySink1 // expected-error{{cannot assign through subscript: 'pkp' is a read-only key path}} writable[keyPath: pkp] = anySink2 // expected-error{{cannot assign through subscript: 'pkp' is a read-only key path}} let akp: AnyKeyPath = pkp var anyqSink1 = readonly[keyPath: akp] expect(&anyqSink1, toHaveType: Exactly<Any?>.self) var anyqSink2 = writable[keyPath: akp] expect(&anyqSink2, toHaveType: Exactly<Any?>.self) readonly[keyPath: akp] = anyqSink1 // expected-error{{cannot assign through subscript: 'readonly' is a 'let' constant}} writable[keyPath: akp] = anyqSink2 // expected-error{{cannot assign through subscript: 'writable' is immutable}} } struct ZwithSubscript { subscript(keyPath kp: KeyPath<ZwithSubscript, Int>) -> Int { return 0 } subscript(keyPath kp: WritableKeyPath<ZwithSubscript, Int>) -> Int { return 0 } subscript(keyPath kp: ReferenceWritableKeyPath<ZwithSubscript, Int>) -> Int { return 0 } subscript(keyPath kp: PartialKeyPath<ZwithSubscript>) -> Any { return 0 } } struct NotZ {} func testKeyPathSubscript(readonly: ZwithSubscript, writable: inout ZwithSubscript, wrongType: inout NotZ, kp: KeyPath<ZwithSubscript, Int>, wkp: WritableKeyPath<ZwithSubscript, Int>, rkp: ReferenceWritableKeyPath<ZwithSubscript, Int>) { var sink: Int sink = readonly[keyPath: kp] sink = writable[keyPath: kp] sink = readonly[keyPath: wkp] sink = writable[keyPath: wkp] sink = readonly[keyPath: rkp] sink = writable[keyPath: rkp] readonly[keyPath: kp] = sink // expected-error {{cannot assign through subscript: subscript is get-only}} writable[keyPath: kp] = sink // expected-error {{cannot assign through subscript: subscript is get-only}} readonly[keyPath: wkp] = sink // expected-error {{cannot assign through subscript: subscript is get-only}} // FIXME: silently falls back to keypath application, which seems inconsistent writable[keyPath: wkp] = sink // FIXME: silently falls back to keypath application, which seems inconsistent readonly[keyPath: rkp] = sink // FIXME: silently falls back to keypath application, which seems inconsistent writable[keyPath: rkp] = sink let pkp: PartialKeyPath = rkp var anySink1 = readonly[keyPath: pkp] expect(&anySink1, toHaveType: Exactly<Any>.self) var anySink2 = writable[keyPath: pkp] expect(&anySink2, toHaveType: Exactly<Any>.self) readonly[keyPath: pkp] = anySink1 // expected-error{{cannot assign through subscript: subscript is get-only}} writable[keyPath: pkp] = anySink2 // expected-error{{cannot assign through subscript: subscript is get-only}} let akp: AnyKeyPath = pkp var anyqSink1 = readonly[keyPath: akp] expect(&anyqSink1, toHaveType: Exactly<Any?>.self) var anyqSink2 = writable[keyPath: akp] expect(&anyqSink2, toHaveType: Exactly<Any?>.self) // FIXME: silently falls back to keypath application, which seems inconsistent readonly[keyPath: akp] = anyqSink1 // expected-error{{cannot assign through subscript: 'readonly' is a 'let' constant}} // FIXME: silently falls back to keypath application, which seems inconsistent writable[keyPath: akp] = anyqSink2 // expected-error{{cannot assign through subscript: 'writable' is immutable}} _ = wrongType[keyPath: kp] // expected-error{{cannot be applied}} _ = wrongType[keyPath: wkp] // expected-error{{cannot be applied}} _ = wrongType[keyPath: rkp] // expected-error{{cannot be applied}} _ = wrongType[keyPath: pkp] // expected-error{{cannot be applied}} _ = wrongType[keyPath: akp] } func testKeyPathSubscriptMetatype(readonly: Z.Type, writable: inout Z.Type, kp: KeyPath<Z.Type, Int>, wkp: WritableKeyPath<Z.Type, Int>, rkp: ReferenceWritableKeyPath<Z.Type, Int>) { var sink: Int sink = readonly[keyPath: kp] sink = writable[keyPath: kp] sink = readonly[keyPath: wkp] sink = writable[keyPath: wkp] sink = readonly[keyPath: rkp] sink = writable[keyPath: rkp] readonly[keyPath: kp] = sink // expected-error{{cannot assign through subscript: 'kp' is a read-only key path}} writable[keyPath: kp] = sink // expected-error{{cannot assign through subscript: 'kp' is a read-only key path}} readonly[keyPath: wkp] = sink // expected-error{{cannot assign through subscript: 'readonly' is a 'let' constant}} writable[keyPath: wkp] = sink readonly[keyPath: rkp] = sink writable[keyPath: rkp] = sink } func testKeyPathSubscriptTuple(readonly: (Z,Z), writable: inout (Z,Z), kp: KeyPath<(Z,Z), Int>, wkp: WritableKeyPath<(Z,Z), Int>, rkp: ReferenceWritableKeyPath<(Z,Z), Int>) { var sink: Int sink = readonly[keyPath: kp] sink = writable[keyPath: kp] sink = readonly[keyPath: wkp] sink = writable[keyPath: wkp] sink = readonly[keyPath: rkp] sink = writable[keyPath: rkp] readonly[keyPath: kp] = sink // expected-error{{cannot assign through subscript: 'kp' is a read-only key path}} writable[keyPath: kp] = sink // expected-error{{cannot assign through subscript: 'kp' is a read-only key path}} readonly[keyPath: wkp] = sink // expected-error{{cannot assign through subscript: 'readonly' is a 'let' constant}} writable[keyPath: wkp] = sink readonly[keyPath: rkp] = sink writable[keyPath: rkp] = sink } func testKeyPathSubscriptLValue(base: Z, kp: inout KeyPath<Z, Z>) { _ = base[keyPath: kp] } func testKeyPathSubscriptExistentialBase(concreteBase: inout B, existentialBase: inout P, kp: KeyPath<P, String>, wkp: WritableKeyPath<P, String>, rkp: ReferenceWritableKeyPath<P, String>, pkp: PartialKeyPath<P>, s: String) { _ = concreteBase[keyPath: kp] _ = concreteBase[keyPath: wkp] _ = concreteBase[keyPath: rkp] _ = concreteBase[keyPath: pkp] concreteBase[keyPath: kp] = s // expected-error {{cannot assign through subscript: 'kp' is a read-only key path}} concreteBase[keyPath: wkp] = s // expected-error {{key path with root type 'P' cannot be applied to a base of type 'B'}} concreteBase[keyPath: rkp] = s concreteBase[keyPath: pkp] = s // expected-error {{cannot assign through subscript: 'pkp' is a read-only key path}} _ = existentialBase[keyPath: kp] _ = existentialBase[keyPath: wkp] _ = existentialBase[keyPath: rkp] _ = existentialBase[keyPath: pkp] existentialBase[keyPath: kp] = s // expected-error {{cannot assign through subscript: 'kp' is a read-only key path}} existentialBase[keyPath: wkp] = s existentialBase[keyPath: rkp] = s existentialBase[keyPath: pkp] = s // expected-error {{cannot assign through subscript: 'pkp' is a read-only key path}} } struct AA { subscript(x: Int) -> Int { return x } subscript(labeled x: Int) -> Int { return x } var c: CC? = CC() } class CC { var i = 0 } func testKeyPathOptional() { _ = \AA.c?.i _ = \AA.c!.i // SR-6198 let path: KeyPath<CC,Int>! = \CC.i let cc = CC() _ = cc[keyPath: path] } func testLiteralInAnyContext() { let _: AnyKeyPath = \A.property let _: AnyObject = \A.property let _: Any = \A.property let _: Any? = \A.property } func testMoreGeneralContext<T, U>(_: KeyPath<T, U>, with: T.Type) {} func testLiteralInMoreGeneralContext() { testMoreGeneralContext(\.property, with: A.self) } func testLabeledSubscript() { let _: KeyPath<AA, Int> = \AA.[labeled: 0] let _: KeyPath<AA, Int> = \.[labeled: 0] let k = \AA.[labeled: 0] // TODO: These ought to work without errors. let _ = \AA.[keyPath: k] // expected-error@-1 {{cannot convert value of type 'KeyPath<AA, Int>' to expected argument type 'Int'}} let _ = \AA.[keyPath: \AA.[labeled: 0]] // expected-error {{extraneous argument label 'keyPath:' in call}} // expected-error@-1 {{cannot convert value of type 'KeyPath<AA, Int>' to expected argument type 'Int'}} } func testInvalidKeyPathComponents() { let _ = \.{return 0} // expected-error* {{}} } class X { class var a: Int { return 1 } static var b = 2 } func testStaticKeyPathComponent() { _ = \X.a // expected-error{{cannot refer to static member}} _ = \X.Type.a // expected-error{{cannot refer to static member}} _ = \X.b // expected-error{{cannot refer to static member}} _ = \X.Type.b // expected-error{{cannot refer to static member}} } class Bass: Hashable { static func ==(_: Bass, _: Bass) -> Bool { return false } func hash(into hasher: inout Hasher) {} } class Treble: Bass { } struct BassSubscript { subscript(_: Bass) -> Int { fatalError() } subscript(_: @autoclosure () -> String) -> Int { fatalError() } } func testImplicitConversionInSubscriptIndex() { _ = \BassSubscript.[Treble()] _ = \BassSubscript.["hello"] // expected-error{{must be Hashable}} } // Crash in diagnostics + SR-11438 struct UnambiguousSubscript { subscript(sub: Sub) -> Int { get { } set { } } subscript(y y: Sub) -> Int { get { } set { } } } func useUnambiguousSubscript(_ sub: Sub) { let _: PartialKeyPath<UnambiguousSubscript> = \.[sub] } struct BothUnavailableSubscript { @available(*, unavailable) subscript(sub: Sub) -> Int { get { } set { } } // expected-note {{'subscript(_:)' has been explicitly marked unavailable here}} @available(*, unavailable) subscript(y y: Sub) -> Int { get { } set { } } } func useBothUnavailableSubscript(_ sub: Sub) { let _: PartialKeyPath<BothUnavailableSubscript> = \.[sub] // expected-error@-1 {{'subscript(_:)' is unavailable}} } // SR-6106 func sr6106() { class B {} class A { var b: B? = nil } class C { var a: A? func myFunc() { let _ = \C.a?.b } } } // SR-6744 func sr6744() { struct ABC { let value: Int func value(adding i: Int) -> Int { return value + i } } let abc = ABC(value: 0) func get<T>(for kp: KeyPath<ABC, T>) -> T { return abc[keyPath: kp] } _ = get(for: \.value) } func sr7380() { _ = ""[keyPath: \.count] _ = ""[keyPath: \String.count] let arr1 = [1] _ = arr1[keyPath: \.[0]] _ = arr1[keyPath: \[Int].[0]] let dic1 = [1:"s"] _ = dic1[keyPath: \.[1]] _ = dic1[keyPath: \[Int: String].[1]] var arr2 = [1] arr2[keyPath: \.[0]] = 2 arr2[keyPath: \[Int].[0]] = 2 var dic2 = [1:"s"] dic2[keyPath: \.[1]] = "" dic2[keyPath: \[Int: String].[1]] = "" _ = [""][keyPath: \.[0]] _ = [""][keyPath: \[String].[0]] _ = ["": ""][keyPath: \.["foo"]] _ = ["": ""][keyPath: \[String: String].["foo"]] class A { var a: String = "" } _ = A()[keyPath: \.a] _ = A()[keyPath: \A.a] A()[keyPath: \.a] = "" A()[keyPath: \A.a] = "" } struct VisibilityTesting { private(set) var x: Int fileprivate(set) var y: Int let z: Int // Key path exprs should not get special dispensation to write to lets // in init contexts init() { var xRef = \VisibilityTesting.x var yRef = \VisibilityTesting.y var zRef = \VisibilityTesting.z expect(&xRef, toHaveType: Exactly<WritableKeyPath<VisibilityTesting, Int>>.self) expect(&yRef, toHaveType: Exactly<WritableKeyPath<VisibilityTesting, Int>>.self) // Allow WritableKeyPath for Swift 3/4 only. expect(&zRef, toHaveType: Exactly<WritableKeyPath<VisibilityTesting, Int>>.self) } func inPrivateContext() { var xRef = \VisibilityTesting.x var yRef = \VisibilityTesting.y var zRef = \VisibilityTesting.z expect(&xRef, toHaveType: Exactly<WritableKeyPath<VisibilityTesting, Int>>.self) expect(&yRef, toHaveType: Exactly<WritableKeyPath<VisibilityTesting, Int>>.self) expect(&zRef, toHaveType: Exactly<KeyPath<VisibilityTesting, Int>>.self) } } struct VisibilityTesting2 { func inFilePrivateContext() { var xRef = \VisibilityTesting.x var yRef = \VisibilityTesting.y var zRef = \VisibilityTesting.z // Allow WritableKeyPath for Swift 3/4 only. expect(&xRef, toHaveType: Exactly<WritableKeyPath<VisibilityTesting, Int>>.self) expect(&yRef, toHaveType: Exactly<WritableKeyPath<VisibilityTesting, Int>>.self) expect(&zRef, toHaveType: Exactly<KeyPath<VisibilityTesting, Int>>.self) } } protocol PP {} class Base : PP { var i: Int = 0 } class Derived : Base {} func testSubtypeKeypathClass(_ keyPath: ReferenceWritableKeyPath<Base, Int>) { testSubtypeKeypathClass(\Derived.i) } func testSubtypeKeypathProtocol(_ keyPath: ReferenceWritableKeyPath<PP, Int>) { testSubtypeKeypathProtocol(\Base.i) // expected-error@-1 {{cannot convert value of type 'ReferenceWritableKeyPath<Base, Int>' to expected argument type 'ReferenceWritableKeyPath<PP, Int>'}} // expected-note@-2 {{arguments to generic parameter 'Root' ('Base' and 'PP') are expected to be equal}} } // rdar://problem/32057712 struct Container { let base: Base? = Base() } var rdar32057712 = \Container.base?.i var identity1 = \Container.self var identity2: WritableKeyPath = \Container.self var identity3: WritableKeyPath<Container, Container> = \Container.self var identity4: WritableKeyPath<Container, Container> = \.self var identity5: KeyPath = \Container.self var identity6: KeyPath<Container, Container> = \Container.self var identity7: KeyPath<Container, Container> = \.self var identity8: PartialKeyPath = \Container.self var identity9: PartialKeyPath<Container> = \Container.self var identity10: PartialKeyPath<Container> = \.self var identity11: AnyKeyPath = \Container.self var identity12: (Container) -> Container = \Container.self var identity13: (Container) -> Container = \.self var interleavedIdentityComponents = \Container.self.base.self?.self.i.self protocol P_With_Static_Members { static var x: Int { get } static var arr: [Int] { get } } func test_keypath_with_static_members(_ p: P_With_Static_Members) { let _ = p[keyPath: \.x] // expected-error@-1 {{key path cannot refer to static member 'x'}} let _: KeyPath<P_With_Static_Members, Int> = \.x // expected-error@-1 {{key path cannot refer to static member 'x'}} let _ = \P_With_Static_Members.arr.count // expected-error@-1 {{key path cannot refer to static member 'arr'}} let _ = p[keyPath: \.arr.count] // expected-error@-1 {{key path cannot refer to static member 'arr'}} struct S { static var foo: String = "Hello" var bar: Bar } struct Bar { static var baz: Int = 42 } func foo(_ s: S) { let _ = \S.Type.foo // expected-error@-1 {{key path cannot refer to static member 'foo'}} let _ = s[keyPath: \.foo] // expected-error@-1 {{key path cannot refer to static member 'foo'}} let _: KeyPath<S, String> = \.foo // expected-error@-1 {{key path cannot refer to static member 'foo'}} let _ = \S.foo // expected-error@-1 {{key path cannot refer to static member 'foo'}} let _ = \S.bar.baz // expected-error@-1 {{key path cannot refer to static member 'baz'}} let _ = s[keyPath: \.bar.baz] // expected-error@-1 {{key path cannot refer to static member 'baz'}} } } func test_keypath_with_mutating_getter() { struct S { var foo: Int { mutating get { return 42 } } subscript(_: Int) -> [Int] { mutating get { return [] } } } _ = \S.foo // expected-error@-1 {{key path cannot refer to 'foo', which has a mutating getter}} let _: KeyPath<S, Int> = \.foo // expected-error@-1 {{key path cannot refer to 'foo', which has a mutating getter}} _ = \S.[0] // expected-error@-1 {{key path cannot refer to 'subscript(_:)', which has a mutating getter}} _ = \S.[0].count // expected-error@-1 {{key path cannot refer to 'subscript(_:)', which has a mutating getter}} func test_via_subscript(_ s: S) { _ = s[keyPath: \.foo] // expected-error@-1 {{key path cannot refer to 'foo', which has a mutating getter}} _ = s[keyPath: \.[0].count] // expected-error@-1 {{key path cannot refer to 'subscript(_:)', which has a mutating getter}} } } func test_keypath_with_method_refs() { struct S { func foo() -> Int { return 42 } static func bar() -> Int { return 0 } } let _: KeyPath<S, Int> = \.foo // expected-error {{key path cannot refer to instance method 'foo()'}} // expected-error@-1 {{key path value type '() -> Int' cannot be converted to contextual type 'Int'}} let _: KeyPath<S, Int> = \.bar // expected-error {{key path cannot refer to static member 'bar()'}} let _ = \S.Type.bar // expected-error {{key path cannot refer to static method 'bar()'}} struct A { func foo() -> B { return B() } static func faz() -> B { return B() } } struct B { var bar: Int = 42 } let _: KeyPath<A, Int> = \.foo.bar // expected-error {{key path cannot refer to instance method 'foo()'}} let _: KeyPath<A, Int> = \.faz.bar // expected-error {{key path cannot refer to static member 'faz()'}} let _ = \A.foo.bar // expected-error {{key path cannot refer to instance method 'foo()'}} let _ = \A.Type.faz.bar // expected-error {{key path cannot refer to static method 'faz()'}} } // SR-12519: Compiler crash on invalid method reference in key path. protocol Zonk { func wargle() } typealias Blatz = (gloop: String, zoop: Zonk?) func sr12519(fleep: [Blatz]) { fleep.compactMap(\.zoop?.wargle) // expected-error {{key path cannot refer to instance method 'wargle()'}} } // SR-10467 - Argument type 'KeyPath<String, Int>' does not conform to expected type 'Any' func test_keypath_in_any_context() { func foo(_: Any) {} foo(\String.count) // Ok } protocol PWithTypeAlias { typealias Key = WritableKeyPath<Self, Int?> static var fooKey: Key? { get } static var barKey: Key! { get } static var fazKey: Key?? { get } static var bazKey: Key?! { get } } func test_keypath_inference_with_optionals() { final class S : PWithTypeAlias { static var fooKey: Key? { return \.foo } static var barKey: Key! { return \.foo } static var fazKey: Key?? { return \.foo } static var bazKey: Key?! { return \.foo } var foo: Int? = nil } } func sr11562() { struct S1 { subscript(x x: Int) -> Int { x } } _ = \S1.[5] // expected-error {{missing argument label 'x:' in call}} {{12-12=x: }} struct S2 { subscript(x x: Int) -> Int { x } // expected-note {{incorrect labels for candidate (have: '(_:)', expected: '(x:)')}} subscript(y y: Int) -> Int { y } // expected-note {{incorrect labels for candidate (have: '(_:)', expected: '(y:)')}} } _ = \S2.[5] // expected-error {{no exact matches in call to subscript}} struct S3 { subscript(x x: Int, y y: Int) -> Int { x } } _ = \S3.[y: 5, x: 5] // expected-error {{argument 'x' must precede argument 'y'}} struct S4 { subscript(x: (Int, Int)) -> Int { x.0 } } _ = \S4.[1, 4] // expected-error {{subscript expects a single parameter of type '(Int, Int)'}} {{12-12=(}} {{16-16=)}} // expected-error@-1 {{subscript index of type '(Int, Int)' in a key path must be Hashable}} } // SR-12290: Ban keypaths with contextual root and without a leading dot struct SR_12290 { let property: [Int] = [] let kp1: KeyPath<SR_12290, Int> = \property.count // expected-error {{a Swift key path with contextual root must begin with a leading dot}}{{38-38=.}} let kp2: KeyPath<SR_12290, Int> = \.property.count // Ok let kp3: KeyPath<SR_12290, Int> = \SR_12290.property.count // Ok func foo1(_: KeyPath<SR_12290, Int> = \property.count) {} // expected-error {{a Swift key path with contextual root must begin with a leading dot}}{{42-42=.}} func foo2(_: KeyPath<SR_12290, Int> = \.property.count) {} // Ok func foo3(_: KeyPath<SR_12290, Int> = \SR_12290.property.count) {} // Ok func foo4<T>(_: KeyPath<SR_12290, T>) {} func useFoo4() { foo4(\property.count) // expected-error {{a Swift key path with contextual root must begin with a leading dot}}{{11-11=.}} foo4(\.property.count) // Ok foo4(\SR_12290.property.count) // Ok } } func testKeyPathHole() { _ = \.x // expected-error {{cannot infer key path type from context; consider explicitly specifying a root type}} {{8-8=<#Root#>}} _ = \.x.y // expected-error {{cannot infer key path type from context; consider explicitly specifying a root type}} {{8-8=<#Root#>}} let _ : AnyKeyPath = \.x // expected-error@-1 {{'AnyKeyPath' does not provide enough context for root type to be inferred; consider explicitly specifying a root type}} {{25-25=<#Root#>}} let _ : AnyKeyPath = \.x.y // expected-error@-1 {{'AnyKeyPath' does not provide enough context for root type to be inferred; consider explicitly specifying a root type}} {{25-25=<#Root#>}} func f(_ i: Int) {} f(\.x) // expected-error {{cannot infer key path type from context; consider explicitly specifying a root type}} {{6-6=<#Root#>}} f(\.x.y) // expected-error {{cannot infer key path type from context; consider explicitly specifying a root type}} {{6-6=<#Root#>}} func provideValueButNotRoot<T>(_ fn: (T) -> String) {} provideValueButNotRoot(\.x) // expected-error {{cannot infer key path type from context; consider explicitly specifying a root type}} provideValueButNotRoot(\.x.y) // expected-error {{cannot infer key path type from context; consider explicitly specifying a root type}} provideValueButNotRoot(\String.foo) // expected-error {{value of type 'String' has no member 'foo'}} func provideKPValueButNotRoot<T>(_ kp: KeyPath<T, String>) {} // expected-note {{in call to function 'provideKPValueButNotRoot'}} provideKPValueButNotRoot(\.x) // expected-error {{cannot infer key path type from context; consider explicitly specifying a root type}} provideKPValueButNotRoot(\.x.y) // expected-error {{cannot infer key path type from context; consider explicitly specifying a root type}} provideKPValueButNotRoot(\String.foo) // expected-error@-1 {{value of type 'String' has no member 'foo'}} // expected-error@-2 {{generic parameter 'T' could not be inferred}} } func testMissingMember() { let _: KeyPath<String, String> = \.foo // expected-error {{value of type 'String' has no member 'foo'}} let _: KeyPath<String, String> = \.foo.bar // expected-error {{value of type 'String' has no member 'foo'}} let _: PartialKeyPath<String> = \.foo // expected-error {{value of type 'String' has no member 'foo'}} let _: PartialKeyPath<String> = \.foo.bar // expected-error {{value of type 'String' has no member 'foo'}} _ = \String.x.y // expected-error {{value of type 'String' has no member 'x'}} } // SR-5688 struct SR5688_A { var b: SR5688_B? } struct SR5688_AA { var b: SR5688_B } struct SR5688_B { var m: Int var c: SR5688_C? } struct SR5688_C { var d: Int } struct SR5688_S { subscript(_ x: Int) -> String? { "" } } struct SR5688_O { struct Nested { var foo = "" } } func SR5688_KP(_ kp: KeyPath<String?, Int>) {} func testMemberAccessOnOptionalKeyPathComponent() { _ = \SR5688_A.b.m // expected-error@-1 {{value of optional type 'SR5688_B?' must be unwrapped to refer to member 'm' of wrapped base type 'SR5688_B'}} // expected-note@-2 {{chain the optional using '?' to access member 'm' only for non-'nil' base values}} {{18-18=?}} // expected-note@-3 {{force-unwrap using '!' to abort execution if the optional value contains 'nil'}} {{18-18=!}} _ = \SR5688_A.b.c.d // expected-error@-1 {{value of optional type 'SR5688_B?' must be unwrapped to refer to member 'c' of wrapped base type 'SR5688_B'}} // expected-note@-2 {{chain the optional using '?' to access member 'c' only for non-'nil' base values}} {{18-18=?}} // expected-error@-3 {{value of optional type 'SR5688_C?' must be unwrapped to refer to member 'd' of wrapped base type 'SR5688_C'}} // expected-note@-4 {{chain the optional using '?' to access member 'd' only for non-'nil' base values}} {{20-20=?}} // expected-note@-5 {{force-unwrap using '!' to abort execution if the optional value contains 'nil'}} {{20-20=!}} _ = \SR5688_A.b?.c.d // expected-error@-1 {{value of optional type 'SR5688_C?' must be unwrapped to refer to member 'd' of wrapped base type 'SR5688_C'}} // expected-note@-2 {{chain the optional using '?' to access member 'd' only for non-'nil' base values}} {{21-21=?}} _ = \SR5688_AA.b.c.d // expected-error@-1 {{value of optional type 'SR5688_C?' must be unwrapped to refer to member 'd' of wrapped base type 'SR5688_C'}} // expected-note@-2 {{chain the optional using '?' to access member 'd' only for non-'nil' base values}} {{21-21=?}} // expected-note@-3 {{force-unwrap using '!' to abort execution if the optional value contains 'nil'}} {{21-21=!}} \String?.count // expected-error@-1 {{value of optional type 'String?' must be unwrapped to refer to member 'count' of wrapped base type 'String'}} // expected-note@-2 {{use unwrapped type 'String' as key path root}} {{4-11=String}} \Optional<String>.count // expected-error@-1 {{value of optional type 'Optional<String>' must be unwrapped to refer to member 'count' of wrapped base type 'String'}} // expected-note@-2 {{use unwrapped type 'String' as key path root}} {{4-20=String}} \SR5688_S.[5].count // expected-error@-1 {{value of optional type 'String?' must be unwrapped to refer to member 'count' of wrapped base type 'String'}} // expected-note@-2 {{chain the optional using '?' to access member 'count' only for non-'nil' base values}}{{16-16=?}} // expected-note@-3 {{force-unwrap using '!' to abort execution if the optional value contains 'nil'}}{{16-16=!}} \SR5688_O.Nested?.foo.count // expected-error@-1 {{value of optional type 'SR5688_O.Nested?' must be unwrapped to refer to member 'foo' of wrapped base type 'SR5688_O.Nested'}} // expected-note@-2 {{use unwrapped type 'SR5688_O.Nested' as key path root}}{{4-20=SR5688_O.Nested}} \(Int, Int)?.0 // expected-error@-1 {{value of optional type '(Int, Int)?' must be unwrapped to refer to member '0' of wrapped base type '(Int, Int)'}} // expected-note@-2 {{use unwrapped type '(Int, Int)' as key path root}}{{4-15=(Int, Int)}} SR5688_KP(\.count) // expected-error {{key path root inferred as optional type 'String?' must be unwrapped to refer to member 'count' of unwrapped type 'String'}} // expected-note@-1 {{chain the optional using '?.' to access unwrapped type member 'count'}} {{15-15=?.}} // expected-note@-2 {{unwrap the optional using '!.' to access unwrapped type member 'count'}} {{15-15=!.}} let _ : KeyPath<String?, Int> = \.count // expected-error {{key path root inferred as optional type 'String?' must be unwrapped to refer to member 'count' of unwrapped type 'String'}} // expected-note@-1 {{chain the optional using '?.' to access unwrapped type member 'count'}} {{37-37=?.}} // expected-note@-2 {{unwrap the optional using '!.' to access unwrapped type member 'count'}} {{37-37=!.}} let _ : KeyPath<String?, Int> = \.utf8.count // expected-error@-1 {{key path root inferred as optional type 'String?' must be unwrapped to refer to member 'utf8' of unwrapped type 'String'}} // expected-note@-2 {{chain the optional using '?.' to access unwrapped type member 'utf8'}} {{37-37=?.}} // expected-note@-3 {{unwrap the optional using '!.' to access unwrapped type member 'utf8'}} {{37-37=!.}} } func testSyntaxErrors() { _ = \. ; // expected-error{{expected member name following '.'}} _ = \.a ; _ = \[a ; _ = \[a]; _ = \? ; _ = \! ; _ = \. ; // expected-error{{expected member name following '.'}} _ = \.a ; _ = \[a ; _ = \[a,; _ = \[a:; _ = \[a]; _ = \.a?; _ = \.a!; _ = \A ; _ = \A, ; _ = \A< ; _ = \A. ; // expected-error{{expected member name following '.'}} _ = \A.a ; _ = \A[a ; _ = \A[a]; _ = \A? ; _ = \A! ; _ = \A. ; // expected-error{{expected member name following '.'}} _ = \A.a ; _ = \A[a ; _ = \A[a,; _ = \A[a:; _ = \A[a]; _ = \A.a?; _ = \A.a!; } // SR-14644 func sr14644() { _ = \Int.byteSwapped.signum() // expected-error {{invalid component of Swift key path}} _ = \Int.byteSwapped.init() // expected-error {{invalid component of Swift key path}} _ = \Int // expected-error {{key path must have at least one component}} _ = \Int? // expected-error {{key path must have at least one component}} _ = \Int. // expected-error {{invalid component of Swift key path}} // expected-error@-1 {{expected member name following '.'}} } // SR-13364 - keypath missing optional crashes compiler: "Inactive constraints left over?" func sr13364() { let _: KeyPath<String?, Int?> = \.utf8.count // expected-error {{no exact matches in reference to property 'count'}} // expected-note@-1 {{found candidate with type 'Int'}} } // rdar://74711236 - crash due to incorrect member access in key path func rdar74711236() { struct S { var arr: [V] = [] } struct V : Equatable { } enum Type { case store } struct Context { func supported() -> [Type] { return [] } } func test(context: Context?) { var s = S() s.arr = { // FIXME: Missing member reference is pattern needs a better diagnostic if let type = context?.store { // expected-error {{type of expression is ambiguous without more context}} // `isSupported` should be an invalid declaration to trigger a crash in `map(\.option)` let isSupported = context!.supported().contains(type) return (isSupported ? [type] : []).map(\.option) // expected-error@-1 {{value of type 'Any' has no member 'option'}} // expected-note@-2 {{cast 'Any' to 'AnyObject' or use 'as!' to force downcast to a more specific type to access members}} } return [] }() } } extension String { var filterOut : (Self) throws -> Bool { { $0.contains("a") } } } func test_kp_as_function_mismatch() { let a : [String] = [ "asd", "bcd", "def" ] let _ : (String) -> Bool = \.filterOut // expected-error{{key path value type '(String) throws -> Bool' cannot be converted to contextual type 'Bool'}} _ = a.filter(\.filterOut) // expected-error{{key path value type '(String) throws -> Bool' cannot be converted to contextual type 'Bool'}} let _ : (String) -> Bool = \String.filterOut // expected-error{{key path value type '(String) throws -> Bool' cannot be converted to contextual type 'Bool'}} _ = a.filter(\String.filterOut) // expected-error{{key path value type '(String) throws -> Bool' cannot be converted to contextual type 'Bool'}} } func test_partial_keypath_inference() { // rdar://problem/34144827 struct S { var i: Int = 0 } enum E { case A(pkp: PartialKeyPath<S>) } _ = E.A(pkp: \.i) // Ok // rdar://problem/36472188 class ThePath { var isWinding:Bool? } func walk<T>(aPath: T, forKey: PartialKeyPath<T>) {} func walkThePath(aPath: ThePath, forKey: PartialKeyPath<ThePath>) {} func test(path: ThePath) { walkThePath(aPath: path, forKey: \.isWinding) // Ok walk(aPath: path, forKey: \.isWinding) // Ok } } // SR-14499 struct SR14499_A { } struct SR14499_B { } func sr14499() { func reproduceA() -> [(SR14499_A, SR14499_B)] { [ (true, .init(), SR14499_B.init()) // expected-error {{cannot infer contextual base in reference to member 'init'}} ] .filter(\.0) // expected-error {{value of type 'Any' has no member '0'}} // expected-note@-1 {{cast 'Any' to 'AnyObject' or use 'as!' to force downcast to a more specific type to access members}} .prefix(3) .map { ($0.1, $0.2) } // expected-error {{value of type 'Any' has no member '1'}} expected-error{{value of type 'Any' has no member '2'}} // expected-note@-1 2 {{cast 'Any' to 'AnyObject' or use 'as!' to force downcast to a more specific type to access members}} } func reproduceB() -> [(SR14499_A, SR14499_B)] { [ (true, SR14499_A.init(), .init()) // expected-error {{cannot infer contextual base in reference to member 'init'}} ] .filter(\.0) // expected-error {{value of type 'Any' has no member '0'}} // expected-note@-1 {{cast 'Any' to 'AnyObject' or use 'as!' to force downcast to a more specific type to access members}} .prefix(3) .map { ($0.1, $0.2) } // expected-error {{value of type 'Any' has no member '1'}} expected-error{{value of type 'Any' has no member '2'}} // expected-note@-1 2 {{cast 'Any' to 'AnyObject' or use 'as!' to force downcast to a more specific type to access members}} } func reproduceC() -> [(SR14499_A, SR14499_B)] { [ (true, .init(), .init()) // expected-error 2 {{cannot infer contextual base in reference to member 'init'}} ] .filter(\.0) // expected-error {{value of type 'Any' has no member '0'}} // expected-note@-1 {{cast 'Any' to 'AnyObject' or use 'as!' to force downcast to a more specific type to access members}} .prefix(3) .map { ($0.1, $0.2) } // expected-error {{value of type 'Any' has no member '1'}} expected-error{{value of type 'Any' has no member '2'}} // expected-note@-1 2 {{cast 'Any' to 'AnyObject' or use 'as!' to force downcast to a more specific type to access members}} } }
apache-2.0
ca233405258d23c593e846f6b088025b
37.262489
191
0.642759
3.648313
false
false
false
false
nathawes/swift
test/Constraints/operator.swift
5
7204
// RUN: %target-typecheck-verify-swift // Test constraint simplification of chains of binary operators. // <https://bugs.swift.org/browse/SR-1122> do { let a: String? = "a" let b: String? = "b" let c: String? = "c" let _: String? = a! + b! + c! let x: Double = 1 _ = x + x + x let sr3483: Double? = 1 _ = sr3483! + sr3483! + sr3483! let sr2636: [String: Double] = ["pizza": 10.99, "ice cream": 4.99, "salad": 7.99] _ = sr2636["pizza"]! _ = sr2636["pizza"]! + sr2636["salad"]! _ = sr2636["pizza"]! + sr2636["salad"]! + sr2636["ice cream"]! } // Use operators defined within a type. struct S0 { static func +(lhs: S0, rhs: S0) -> S0 { return lhs } } func useS0(lhs: S0, rhs: S0) { _ = lhs + rhs } // Use operators defined within a generic type. struct S0b<T> { static func + <U>(lhs: S0b<T>, rhs: U) -> S0b<U> { return S0b<U>() } } func useS0b(s1i: S0b<Int>, s: String) { var s1s = s1i + s s1s = S0b<String>() _ = s1s } // Use operators defined within a protocol extension. infix operator %%% infix operator %%%% protocol P1 { static func %%%(lhs: Self, rhs: Self) -> Bool } extension P1 { static func %%%%(lhs: Self, rhs: Self) -> Bool { return !(lhs %%% rhs) } } func useP1Directly<T : P1>(lhs: T, rhs: T) { _ = lhs %%% rhs _ = lhs %%%% rhs } struct S1 : P1 { static func %%%(lhs: S1, rhs: S1) -> Bool { return false } } func useP1Model(lhs: S1, rhs: S1) { _ = lhs %%% rhs _ = lhs %%%% rhs } struct S1b<T> : P1 { static func %%%(lhs: S1b<T>, rhs: S1b<T>) -> Bool { return false } } func useP1ModelB(lhs: S1b<Int>, rhs: S1b<Int>) { _ = lhs %%% rhs _ = lhs %%%% rhs } func useP1ModelBGeneric<T>(lhs: S1b<T>, rhs: S1b<T>) { _ = lhs %%% rhs _ = lhs %%%% rhs } // Use operators defined within a protocol extension to satisfy a requirement. protocol P2 { static func %%%(lhs: Self, rhs: Self) -> Bool static func %%%%(lhs: Self, rhs: Self) -> Bool } extension P2 { static func %%%%(lhs: Self, rhs: Self) -> Bool { return !(lhs %%% rhs) } } func useP2Directly<T : P2>(lhs: T, rhs: T) { _ = lhs %%% rhs _ = lhs %%%% rhs } struct S2 : P2 { static func %%%(lhs: S2, rhs: S2) -> Bool { return false } } func useP2Model(lhs: S2, rhs: S2) { _ = lhs %%% rhs _ = lhs %%%% rhs } struct S2b<T> : P2 { static func %%%(lhs: S2b<T>, rhs: S2b<T>) -> Bool { return false } } func useP2Model2(lhs: S2b<Int>, rhs: S2b<Int>) { _ = lhs %%% rhs _ = lhs %%%% rhs } func useP2Model2Generic<T>(lhs: S2b<T>, rhs: S2b<T>) { _ = lhs %%% rhs _ = lhs %%%% rhs } // Using an extension of one protocol to satisfy another conformance. protocol P3 { } extension P3 { static func ==(lhs: Self, rhs: Self) -> Bool { return true } } struct S3 : P3, Equatable { } // rdar://problem/30220565 func shrinkTooFar(_ : Double, closure : ()->()) {} func testShrinkTooFar() { shrinkTooFar(0*0*0) {} } // rdar://problem/33759839 enum E_33759839 { case foo case bar(String) } let foo_33759839 = ["a", "b", "c"] let bar_33759839 = ["A", "B", "C"] let _: [E_33759839] = foo_33759839.map { .bar($0) } + bar_33759839.map { .bar($0) } + [E_33759839.foo] // Ok // rdar://problem/28688585 class B_28688585 { var value: Int init(value: Int) { self.value = value } func add(_ other: B_28688585) -> B_28688585 { return B_28688585(value: value + other.value) } } class D_28688585 : B_28688585 { } func + (lhs: B_28688585, rhs: B_28688585) -> B_28688585 { return lhs.add(rhs) } let var_28688585 = D_28688585(value: 1) _ = var_28688585 + var_28688585 + var_28688585 // Ok // rdar://problem/35740653 - Fix `LinkedExprAnalyzer` greedy operator linking struct S_35740653 { var v: Double = 42 static func value(_ value: Double) -> S_35740653 { return S_35740653(v: value) } static func / (lhs: S_35740653, rhs: S_35740653) -> Double { return lhs.v / rhs.v } } func rdar35740653(val: S_35740653) { let _ = 0...Int(val / .value(1.0 / 42.0)) // Ok } protocol P_37290898 {} struct S_37290898: P_37290898 {} func rdar37290898(_ arr: inout [P_37290898], _ element: S_37290898?) { arr += [element].compactMap { $0 } // Ok } // SR-8221 infix operator ??= func ??= <T>(lhs: inout T?, rhs: T?) {} var c: Int = 0 // expected-note {{change variable type to 'Int?' if it doesn't need to be declared as 'Int'}} c ??= 5 // expected-error{{inout argument could be set to a value with a type other than 'Int'; use a value declared as type 'Int?' instead}} func rdar46459603() { enum E { case foo(value: String) } let e = E.foo(value: "String") var arr = ["key": e] // FIXME(rdar://problem/64844584) - on iOS simulator this diagnostic is flaky, // either `referencing operator function '==' on 'Equatable'` or `operator function '==' requires` _ = arr.values == [e] // expected-error@-1 {{requires that 'Dictionary<String, E>.Values' conform to 'Equatable'}} // expected-error@-2 {{cannot convert value of type '[E]' to expected argument type 'Dictionary<String, E>.Values'}} _ = [arr.values] == [[e]] // expected-error@-1 {{requires that 'Dictionary<String, E>.Values' conform to 'Equatable'}} // expected-error@-2 {{cannot convert value of type '[E]' to expected element type 'Dictionary<String, E>.Values'}} } // SR-10843 infix operator ^^^ func ^^^ (lhs: String, rhs: String) {} struct SR10843 { static func ^^^ (lhs: SR10843, rhs: SR10843) {} } func sr10843() { let s = SR10843() (^^^)(s, s) _ = (==)(0, 0) } // SR-10970 precedencegroup PowerPrecedence { lowerThan: BitwiseShiftPrecedence higherThan: AdditionPrecedence associativity: right } infix operator ^^ : PowerPrecedence extension Int { static func ^^ (lhs: Int, rhs: Int) -> Int { var result = 1 for _ in 1...rhs { result *= lhs } return result } } _ = 1 ^^ 2 ^^ 3 * 4 // expected-error {{adjacent operators are in unordered precedence groups 'PowerPrecedence' and 'MultiplicationPrecedence'}} // rdar://problem/60185506 - Ambiguity with Float comparison func rdar_60185506() { struct X { var foo: Float } func test(x: X?) { let _ = (x?.foo ?? 0) <= 0.5 // Ok } } // rdar://problem/60727310 func rdar60727310() { func myAssertion<T>(_ a: T, _ op: ((T,T)->Bool), _ b: T) {} var e: Error? = nil myAssertion(e, ==, nil) // expected-error {{binary operator '==' cannot be applied to two 'Error?' operands}} } // FIXME(SR-12438): Bad diagnostic. func sr12438(_ e: Error) { func foo<T>(_ a: T, _ op: ((T, T) -> Bool)) {} foo(e, ==) // expected-error {{type of expression is ambiguous without more context}} } // rdar://problem/62054241 - Swift compiler crashes when passing < as the sort function in sorted(by:) and the type of the array is not comparable func rdar_62054241() { struct Foo { let a: Int } func test(_ arr: [Foo]) -> [Foo] { return arr.sorted(by: <) // expected-error {{no exact matches in reference to operator function '<'}} // expected-note@-1 {{found candidate with type '(Foo, Foo) -> Bool'}} } } // SR-11399 - Operator returning IUO doesn't implicitly unwrap postfix operator ^^^ postfix func ^^^ (lhs: Int) -> Int! { 0 } let x: Int = 1^^^
apache-2.0
d03196315aeca9b348f918a9da3035de
22.933555
146
0.601749
3.031987
false
false
false
false
nathawes/swift
benchmark/utils/main.swift
2
10749
//===--- main.swift -------------------------------------------*- swift -*-===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // This is just a driver for performance overview tests. import TestsUtils import DriverUtils import Ackermann import AngryPhonebook import AnyHashableWithAClass import Array2D import ArrayAppend import ArrayInClass import ArrayLiteral import ArrayOfGenericPOD import ArrayOfGenericRef import ArrayOfPOD import ArrayOfRef import ArraySetElement import ArraySubscript import BinaryFloatingPointConversionFromBinaryInteger import BinaryFloatingPointProperties import BitCount import Breadcrumbs import BucketSort import ByteSwap import COWTree import COWArrayGuaranteedParameterOverhead import CString import CSVParsing import Calculator import CaptureProp import ChaCha import ChainedFilterMap import CharacterLiteralsLarge import CharacterLiteralsSmall import CharacterProperties import Chars import ClassArrayGetter import Codable import Combos import DataBenchmarks import DeadArray import DevirtualizeProtocolComposition import DictOfArraysToArrayOfDicts import DictTest import DictTest2 import DictTest3 import DictTest4 import DictTest4Legacy import DictionaryBridge import DictionaryBridgeToObjC import DictionaryCompactMapValues import DictionaryCopy import DictionaryGroup import DictionaryKeysContains import DictionaryLiteral import DictionaryOfAnyHashableStrings import DictionaryRemove import DictionarySubscriptDefault import DictionarySwap import Diffing import DiffingMyers import DropFirst import DropLast import DropWhile import ErrorHandling import Exclusivity import ExistentialPerformance import Fibonacci import FindStringNaive import FlattenList import FloatingPointConversion import FloatingPointParsing import FloatingPointPrinting import Hanoi import Hash import Histogram import HTTP2StateMachine import InsertCharacter import IntegerParsing import Integrate import IterateData import Join import LazyFilter import LinkedList import LuhnAlgoEager import LuhnAlgoLazy import MapReduce import Memset import Mirror import MonteCarloE import MonteCarloPi import NibbleSort import NIOChannelPipeline import NSDictionaryCastToSwift import NSError #if canImport(Darwin) import NSStringConversion #endif import NopDeinit import ObjectAllocation #if canImport(Darwin) import ObjectiveCBridging import ObjectiveCBridgingStubs #if !(SWIFT_PACKAGE || Xcode) import ObjectiveCNoBridgingStubs #endif #endif import ObserverClosure import ObserverForwarderStruct import ObserverPartiallyAppliedMethod import ObserverUnappliedMethod import OpaqueConsumingUsers import OpenClose import Phonebook import PointerArithmetics import PolymorphicCalls import PopFront import PopFrontGeneric import Prefix import PrefixWhile import Prims import PrimsNonStrongRef import PrimsSplit import ProtocolConformance import ProtocolDispatch import ProtocolDispatch2 import Queue import RC4 import RGBHistogram import Radix2CooleyTukey import RandomShuffle import RandomTree import RandomValues import RangeAssignment import RangeIteration import RangeOverlaps import RangeReplaceableCollectionPlusDefault import RecursiveOwnedParameter import ReduceInto import RemoveWhere import ReversedCollections import RomanNumbers import SequenceAlgos import SetTests import SevenBoom import Sim2DArray import SortArrayInClass import SortIntPyramids import SortLargeExistentials import SortLettersInPlace import SortStrings import StackPromo import StaticArray import StrComplexWalk import StrToInt import StringBuilder import StringComparison import StringEdits import StringEnum import StringInterpolation import StringMatch import StringRemoveDupes import StringReplaceSubrange import StringTests import StringWalk import Substring import Suffix import SuperChars import TwoSum import TypeFlood import UTF8Decode import Walsh import WordCount import XorLoop @inline(__always) private func registerBenchmark(_ bench: BenchmarkInfo) { registeredBenchmarks.append(bench) } @inline(__always) private func registerBenchmark< S : Sequence >(_ infos: S) where S.Element == BenchmarkInfo { registeredBenchmarks.append(contentsOf: infos) } registerBenchmark(Ackermann) registerBenchmark(AngryPhonebook) registerBenchmark(AnyHashableWithAClass) registerBenchmark(Array2D) registerBenchmark(ArrayAppend) registerBenchmark(ArrayInClass) registerBenchmark(ArrayLiteral) registerBenchmark(ArrayOfGenericPOD) registerBenchmark(ArrayOfGenericRef) registerBenchmark(ArrayOfPOD) registerBenchmark(ArrayOfRef) registerBenchmark(ArraySetElement) registerBenchmark(ArraySubscript) registerBenchmark(BinaryFloatingPointConversionFromBinaryInteger) registerBenchmark(BinaryFloatingPointPropertiesBinade) registerBenchmark(BinaryFloatingPointPropertiesNextUp) registerBenchmark(BinaryFloatingPointPropertiesUlp) registerBenchmark(BitCount) registerBenchmark(Breadcrumbs) registerBenchmark(BucketSort) registerBenchmark(ByteSwap) registerBenchmark(COWTree) registerBenchmark(COWArrayGuaranteedParameterOverhead) registerBenchmark(CString) registerBenchmark(CSVParsing) registerBenchmark(Calculator) registerBenchmark(CaptureProp) registerBenchmark(ChaCha) registerBenchmark(ChainedFilterMap) registerBenchmark(CharacterLiteralsLarge) registerBenchmark(CharacterLiteralsSmall) registerBenchmark(CharacterPropertiesFetch) registerBenchmark(CharacterPropertiesStashed) registerBenchmark(CharacterPropertiesStashedMemo) registerBenchmark(CharacterPropertiesPrecomputed) registerBenchmark(Chars) registerBenchmark(Codable) registerBenchmark(Combos) registerBenchmark(ClassArrayGetter) registerBenchmark(DataBenchmarks) registerBenchmark(DeadArray) registerBenchmark(DevirtualizeProtocolComposition) registerBenchmark(DictOfArraysToArrayOfDicts) registerBenchmark(Dictionary) registerBenchmark(Dictionary2) registerBenchmark(Dictionary3) registerBenchmark(Dictionary4) registerBenchmark(Dictionary4Legacy) registerBenchmark(DictionaryBridge) registerBenchmark(DictionaryBridgeToObjC) registerBenchmark(DictionaryCompactMapValues) registerBenchmark(DictionaryCopy) registerBenchmark(DictionaryGroup) registerBenchmark(DictionaryKeysContains) registerBenchmark(DictionaryLiteral) registerBenchmark(DictionaryOfAnyHashableStrings) registerBenchmark(DictionaryRemove) registerBenchmark(DictionarySubscriptDefault) registerBenchmark(DictionarySwap) registerBenchmark(Diffing) registerBenchmark(DiffingMyers) registerBenchmark(DropFirst) registerBenchmark(DropLast) registerBenchmark(DropWhile) registerBenchmark(ErrorHandling) registerBenchmark(Exclusivity) registerBenchmark(ExistentialPerformance) registerBenchmark(Fibonacci) registerBenchmark(FindStringNaive) registerBenchmark(FlattenListLoop) registerBenchmark(FlattenListFlatMap) registerBenchmark(FloatingPointConversion) registerBenchmark(FloatingPointParsing) registerBenchmark(FloatingPointPrinting) registerBenchmark(Hanoi) registerBenchmark(HashTest) registerBenchmark(Histogram) registerBenchmark(HTTP2StateMachine) registerBenchmark(InsertCharacter) registerBenchmark(IntegerParsing) registerBenchmark(IntegrateTest) registerBenchmark(IterateData) registerBenchmark(Join) registerBenchmark(LazyFilter) registerBenchmark(LinkedList) registerBenchmark(LuhnAlgoEager) registerBenchmark(LuhnAlgoLazy) registerBenchmark(MapReduce) registerBenchmark(Memset) registerBenchmark(MirrorDefault) registerBenchmark(MonteCarloE) registerBenchmark(MonteCarloPi) registerBenchmark(NSDictionaryCastToSwift) registerBenchmark(NSErrorTest) #if canImport(Darwin) registerBenchmark(NSStringConversion) #endif registerBenchmark(NibbleSort) registerBenchmark(NIOChannelPipeline) registerBenchmark(NopDeinit) registerBenchmark(ObjectAllocation) #if canImport(Darwin) registerBenchmark(ObjectiveCBridging) registerBenchmark(ObjectiveCBridgingStubs) #if !(SWIFT_PACKAGE || Xcode) registerBenchmark(ObjectiveCNoBridgingStubs) #endif #endif registerBenchmark(ObserverClosure) registerBenchmark(ObserverForwarderStruct) registerBenchmark(ObserverPartiallyAppliedMethod) registerBenchmark(ObserverUnappliedMethod) registerBenchmark(OpaqueConsumingUsers) registerBenchmark(OpenClose) registerBenchmark(Phonebook) registerBenchmark(PointerArithmetics) registerBenchmark(PolymorphicCalls) registerBenchmark(PopFront) registerBenchmark(PopFrontArrayGeneric) registerBenchmark(Prefix) registerBenchmark(PrefixWhile) registerBenchmark(Prims) registerBenchmark(PrimsNonStrongRef) registerBenchmark(PrimsSplit) registerBenchmark(ProtocolConformance) registerBenchmark(ProtocolDispatch) registerBenchmark(ProtocolDispatch2) registerBenchmark(QueueGeneric) registerBenchmark(QueueConcrete) registerBenchmark(RC4Test) registerBenchmark(RGBHistogram) registerBenchmark(Radix2CooleyTukey) registerBenchmark(RandomShuffle) registerBenchmark(RandomTree) registerBenchmark(RandomValues) registerBenchmark(RangeAssignment) registerBenchmark(RangeIteration) registerBenchmark(RangeOverlaps) registerBenchmark(RangeReplaceableCollectionPlusDefault) registerBenchmark(RecursiveOwnedParameter) registerBenchmark(ReduceInto) registerBenchmark(RemoveWhere) registerBenchmark(ReversedCollections) registerBenchmark(RomanNumbers) registerBenchmark(SequenceAlgos) registerBenchmark(SetTests) registerBenchmark(SevenBoom) registerBenchmark(Sim2DArray) registerBenchmark(SortArrayInClass) registerBenchmark(SortIntPyramids) registerBenchmark(SortLargeExistentials) registerBenchmark(SortLettersInPlace) registerBenchmark(SortStrings) registerBenchmark(StackPromo) registerBenchmark(StaticArrayTest) registerBenchmark(StrComplexWalk) registerBenchmark(StrToInt) registerBenchmark(StringBuilder) registerBenchmark(StringComparison) registerBenchmark(StringEdits) registerBenchmark(StringEnum) registerBenchmark(StringHashing) registerBenchmark(StringInterpolation) registerBenchmark(StringInterpolationSmall) registerBenchmark(StringInterpolationManySmallSegments) registerBenchmark(StringMatch) registerBenchmark(StringNormalization) registerBenchmark(StringRemoveDupes) registerBenchmark(StringReplaceSubrange) registerBenchmark(StringTests) registerBenchmark(StringWalk) registerBenchmark(SubstringTest) registerBenchmark(Suffix) registerBenchmark(SuperChars) registerBenchmark(TwoSum) registerBenchmark(TypeFlood) registerBenchmark(TypeName) registerBenchmark(UTF8Decode) registerBenchmark(Walsh) registerBenchmark(WordCount) registerBenchmark(XorLoop) main()
apache-2.0
c5178b2a254109c733237deb13d620d1
27.212598
80
0.884826
5.535015
false
false
false
false
EurekaCommunity/ImageRow
Sources/ImageCell.swift
1
2154
// ImageCell.swift // ImageRow ( https://github.com/EurekaCommunity/ImageRow ) // // Copyright (c) 2016 Xmartlabs SRL ( http://xmartlabs.com ) // // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Eureka import UIKit public final class ImageCell: PushSelectorCell<UIImage> { public override func setup() { super.setup() accessoryType = .none editingAccessoryView = .none let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 44, height: 44)) imageView.contentMode = .scaleAspectFill imageView.clipsToBounds = true accessoryView = imageView editingAccessoryView = imageView } public override func update() { super.update() selectionStyle = row.isDisabled ? .none : .default (accessoryView as? UIImageView)?.image = row.value ?? (row as? ImageRowProtocol)?.thumbnailImage ?? (row as? ImageRowProtocol)?.placeholderImage (editingAccessoryView as? UIImageView)?.image = row.value ?? (row as? ImageRowProtocol)?.thumbnailImage ?? (row as? ImageRowProtocol)?.placeholderImage } }
mit
0485cbb9de531cf47a9600efddd2782e
42.08
159
0.714485
4.765487
false
false
false
false
hoorace/Swift-Font-Awesome
Source/FontAwesome+UIImage.swift
1
4804
// // FontAwesome+UIImage.swift // Swift-Font-Awesome // // Created by longhao on 15/7/18. // Copyright (c) 2015年 longhao. All rights reserved. // import UIKit public extension UIImage { //https://github.com/melvitax/AFImageHelper/blob/master/AF%2BImage%2BHelper/AF%2BImage%2BExtension.swift //image with circle public convenience init?(faCircle: Fa, imageSize: CGFloat, color: UIColor = UIColor.whiteColor(),circleColor: UIColor = UIColor.grayColor(), backgroundColor: UIColor = UIColor.clearColor(), radius: CGFloat = 5) { FontAwesome.sharedManager.registerFont() let fontSize = imageSize - 2 * radius let font: UIFont = UIFont(name: kFontAwesome, size: fontSize)! let size = CGSizeMake(fontSize + 2 * radius, fontSize + 2 * radius) // circle size UIGraphicsBeginImageContextWithOptions(size, false, 0) let context = UIGraphicsGetCurrentContext() CGContextSetAllowsAntialiasing(context, true) CGContextSetFillColorWithColor(context, backgroundColor.CGColor) CGContextFillRect(context, CGRect(origin: CGPoint(x: 0, y: 0), size: size)) let style = NSMutableParagraphStyle() style.alignment = .Center let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height) let attrCircle = [NSFontAttributeName: UIFont(name: kFontAwesome, size: size.width)!, NSForegroundColorAttributeName:circleColor, NSParagraphStyleAttributeName:style] Fa.Circle.text!.drawInRect(rect, withAttributes: attrCircle) let rectIn = CGRect(x: radius - 1, y: radius, width: fontSize + 2, height: fontSize + 2) let attr = [NSFontAttributeName: font, NSForegroundColorAttributeName:color, NSParagraphStyleAttributeName:style] faCircle.text!.drawInRect(rectIn, withAttributes: attr) self.init(CGImage:UIGraphicsGetImageFromCurrentImageContext().CGImage!) UIGraphicsEndImageContext() } //image with square public convenience init?(faSquare: Fa, imageSize: CGFloat, color: UIColor = UIColor.whiteColor(),circleColor: UIColor = UIColor.grayColor(), backgroundColor: UIColor = UIColor.clearColor(), radius: CGFloat = 8) { FontAwesome.sharedManager.registerFont() let fontSize = imageSize - 2 * radius let font: UIFont = UIFont(name: kFontAwesome, size: fontSize)! let size = CGSizeMake(fontSize + 2 * radius, fontSize + 2 * radius) // circle size UIGraphicsBeginImageContextWithOptions(size, false, 0) let context = UIGraphicsGetCurrentContext() CGContextSetAllowsAntialiasing(context, true) CGContextSetFillColorWithColor(context, backgroundColor.CGColor) CGContextFillRect(context, CGRect(origin: CGPoint(x: 0, y: 0), size: size)) let style = NSMutableParagraphStyle() style.alignment = .Center let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height) let attrCircle = [NSFontAttributeName: UIFont(name: kFontAwesome, size: size.width)!, NSForegroundColorAttributeName:circleColor, NSParagraphStyleAttributeName:style] Fa.SquareO.text!.drawInRect(rect, withAttributes: attrCircle) let rectIn = CGRect(x: radius, y: radius, width: fontSize + 2, height: fontSize + 2) let attr = [NSFontAttributeName: font, NSForegroundColorAttributeName:color, NSParagraphStyleAttributeName:style] faSquare.text!.drawInRect(rectIn, withAttributes: attr) self.init(CGImage:UIGraphicsGetImageFromCurrentImageContext().CGImage!) UIGraphicsEndImageContext() } // MARK: Image with Text public convenience init?(fa: Fa, imageSize: CGFloat, color: UIColor = UIColor.whiteColor(), backgroundColor: UIColor = UIColor.grayColor()) { FontAwesome.sharedManager.registerFont() let font: UIFont = UIFont(name: kFontAwesome, size: imageSize - 2)! let size = CGSizeMake(imageSize, imageSize) // circle size UIGraphicsBeginImageContextWithOptions(size, false, 0) let context = UIGraphicsGetCurrentContext() CGContextSetAllowsAntialiasing(context, true) CGContextSetFillColorWithColor(context, backgroundColor.CGColor) CGContextFillRect(context, CGRect(origin: CGPoint(x: 0, y: 0), size: size)) let style = NSMutableParagraphStyle() style.alignment = .Center let rectIn = CGRect(x: 0, y: 0, width: imageSize, height: imageSize) let attr = [NSFontAttributeName: font, NSForegroundColorAttributeName:color, NSParagraphStyleAttributeName:style] fa.text!.drawInRect(rectIn, withAttributes: attr) self.init(CGImage:UIGraphicsGetImageFromCurrentImageContext().CGImage!) UIGraphicsEndImageContext() } }
mit
cf8b95add0046f191b03f05375f6b60a
52.955056
214
0.70304
5.023013
false
false
false
false
XueSeason/Awesome-CNodeJS
Awesome-CNodeJS/Awesome-CNodeJS/Controllers/Home/HomeViewController.swift
1
5108
// // HomeViewController.swift // Awesome-CNodeJS // // Created by 薛纪杰 on 16/1/1. // Copyright © 2016年 XueSeason. All rights reserved. // import UIKit import Alamofire class HomeViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UINavigationControllerDelegate { @IBOutlet weak var tableView: UITableView! var topics: [Topic] = Array() var page: Int! let cellTransition = CellTransition() // MARK: - life cycle override func viewDidLoad() { super.viewDidLoad() self.navigationController?.navigationBar.translucent = false self.tabBarController?.tabBar.translucent = false self.tableView.addObserver(self, forKeyPath: "contentOffset", options: [.New, .Old], context: nil) page = 1 loadTopicWithPage(page) } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) self.navigationController?.navigationBar.hidden = false self.navigationController?.delegate = self } override func viewWillDisappear(animated: Bool) { super.viewWillAppear(animated) self.navigationController?.delegate = nil } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } deinit { self.tableView.removeObserver(self, forKeyPath: "contentOffset") } // MARK: - methods func reloadTopic() { self.topics.removeAll() page = 1 loadTopicWithPage(page) } func loadTopicWithPage(page: Int) { weak var weakSelf = self Alamofire.request(.GET, "https://cnodejs.org/api/v1/topics", parameters: ["page": page, "limit": 20]) .responseData { (response ) -> Void in if let data = response.data { for item in JSON(data: data)["data"].array! { let topic = Topic(json: item) weakSelf?.topics.append(topic) } weakSelf?.tableView.reloadData() weakSelf?.tableView.scrollToRowAtIndexPath(NSIndexPath(forRow: 20 * (page - 1), inSection: 0), atScrollPosition: .Bottom, animated: true) weakSelf?.tableView.contentInset = UIEdgeInsetsMake(0, 0, 0, 0); self.page!++ } } } // MARK: - UITableViewDelegate func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { self.cellTransition.enterView = tableView.cellForRowAtIndexPath(indexPath) } // MARK: - UITableViewDataSource func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.topics.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("topic", forIndexPath: indexPath) as! TopicTableViewCell cell.selectionStyle = .None let topic = self.topics[indexPath.row] cell.configureCell(Topic: topic) return cell } // MARK: - Transition Animation func navigationController(navigationController: UINavigationController, animationControllerForOperation operation: UINavigationControllerOperation, fromViewController fromVC: UIViewController, toViewController toVC: UIViewController) -> UIViewControllerAnimatedTransitioning? { if operation == .Push { return self.cellTransition } else { return nil } } // MARK: - KVO override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) { loadMoreTopicIfPull() } func loadMoreTopicIfPull() { if self.tableView.contentSize.height <= 0 { return } let defaultRefreshHeight: CGFloat = 50.0 let offset = self.tableView.contentOffset.y + self.tableView.bounds.height - self.tableView.contentSize.height if offset >= defaultRefreshHeight { self.tableView.contentInset = UIEdgeInsetsMake(0, 0, defaultRefreshHeight, 0); } if !self.tableView.dragging && self.tableView.decelerating { if offset == defaultRefreshHeight { loadTopicWithPage(page) } } } // MARK: - Navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.destinationViewController.isKindOfClass(TopicDetailViewController) { let vc = segue.destinationViewController as! TopicDetailViewController let indexPath = self.tableView.indexPathForCell(sender as! UITableViewCell)! vc.topicId = self.topics[indexPath.row].id } } }
mit
51b34ba005ebdcd0df0fa721063ed660
33.452703
157
0.626397
5.453476
false
false
false
false
BjornRuud/HTTPSession
Pods/Swifter/Sources/String+Misc.swift
4
3523
// // String+Misc.swift // Swifter // // Copyright (c) 2014-2016 Damian Kołakowski. All rights reserved. // import Foundation extension String { public func split(_ separator: Character) -> [String] { return self.characters.split { $0 == separator }.map(String.init) } public func split(_ maxSplit: Int = Int.max, separator: Character) -> [String] { return self.characters.split(maxSplits: maxSplit, omittingEmptySubsequences: true) { $0 == separator }.map(String.init) } public func replace(old: Character, _ new: Character) -> String { var buffer = [Character]() self.characters.forEach { buffer.append($0 == old ? new : $0) } return String(buffer) } public func unquote() -> String { var scalars = self.unicodeScalars; if scalars.first == "\"" && scalars.last == "\"" && scalars.count >= 2 { scalars.removeFirst(); scalars.removeLast(); return String(scalars) } return self } public func trim() -> String { var scalars = self.unicodeScalars while let _ = scalars.first?.asWhitespace() { scalars.removeFirst() } while let _ = scalars.last?.asWhitespace() { scalars.removeLast() } return String(scalars) } public static func fromUInt8(_ array: [UInt8]) -> String { // Apple changes the definition of String(data: .... ) every release so let's stay with 'fromUInt8(...)' wrapper. return array.reduce("", { $0.0 + String(UnicodeScalar($0.1)) }) } public func removePercentEncoding() -> String { var scalars = self.unicodeScalars var output = "" var decodeBuffer = [UInt8]() while let scalar = scalars.popFirst() { if scalar == "%" { let first = scalars.popFirst() let secon = scalars.popFirst() if let first = first?.asAlpha(), let secon = secon?.asAlpha() { decodeBuffer.append(first*16+secon) } else { if !decodeBuffer.isEmpty { output.append(String.fromUInt8(decodeBuffer)) decodeBuffer.removeAll() } if let first = first { output.append(Character(first)) } if let secon = secon { output.append(Character(secon)) } } } else { if !decodeBuffer.isEmpty { output.append(String.fromUInt8(decodeBuffer)) decodeBuffer.removeAll() } output.append(Character(scalar)) } } if !decodeBuffer.isEmpty { output.append(String.fromUInt8(decodeBuffer)) decodeBuffer.removeAll() } return output } } extension UnicodeScalar { public func asWhitespace() -> UInt8? { if self.value >= 9 && self.value <= 13 { return UInt8(self.value) } if self.value == 32 { return UInt8(self.value) } return nil } public func asAlpha() -> UInt8? { if self.value >= 48 && self.value <= 57 { return UInt8(self.value) - 48 } if self.value >= 97 && self.value <= 102 { return UInt8(self.value) - 87 } if self.value >= 65 && self.value <= 70 { return UInt8(self.value) - 55 } return nil } }
mit
b4786906a692230f0fdac1c4fc5692b8
31.915888
127
0.53038
4.591917
false
false
false
false
jshultz/ios9-swift2-tic-tac-toe
tic-tac-toe/AppDelegate.swift
1
6108
// // AppDelegate.swift // tic-tac-toe // // Created by Jason Shultz on 10/8/15. // Copyright © 2015 HashRocket. All rights reserved. // import UIKit import CoreData @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. // Saves changes in the application's managed object context before the application terminates. self.saveContext() } // MARK: - Core Data stack lazy var applicationDocumentsDirectory: NSURL = { // The directory the application uses to store the Core Data store file. This code uses a directory named "Open-Sky-Media--LLC.tic_tac_toe" in the application's documents Application Support directory. let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask) return urls[urls.count-1] }() lazy var managedObjectModel: NSManagedObjectModel = { // The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model. let modelURL = NSBundle.mainBundle().URLForResource("tic_tac_toe", withExtension: "momd")! return NSManagedObjectModel(contentsOfURL: modelURL)! }() lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = { // The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. // Create the coordinator and store let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel) let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("SingleViewCoreData.sqlite") var failureReason = "There was an error creating or loading the application's saved data." do { try coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil) } catch { // Report any error we got. var dict = [String: AnyObject]() dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" dict[NSLocalizedFailureReasonErrorKey] = failureReason dict[NSUnderlyingErrorKey] = error as NSError let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict) // Replace this with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)") abort() } return coordinator }() lazy var managedObjectContext: NSManagedObjectContext = { // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail. let coordinator = self.persistentStoreCoordinator var managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType) managedObjectContext.persistentStoreCoordinator = coordinator return managedObjectContext }() // MARK: - Core Data Saving support func saveContext () { if managedObjectContext.hasChanges { do { try managedObjectContext.save() } catch { // Replace this implementation with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. let nserror = error as NSError NSLog("Unresolved error \(nserror), \(nserror.userInfo)") abort() } } } }
mit
778de40aca71886f01e409d0f561f88e
54.018018
291
0.718847
5.821735
false
false
false
false
mbigatti/BMXKeyboardStatus
Framework/BMXKeyboardStatus/KeyboardStatus.swift
1
2760
// // KeyboardStatus.swift // BMXKeyboardStatus // https://github.com/mbigatti/BMXKeyboardStatus // // Copyright (c) 2014 Massimiliano Bigatti. All rights reserved. // import UIKit /** A simple component that provides informations about the keyboard. */ public class KeyboardStatus : NSObject { /// singleton shared instance public class var sharedInstance : KeyboardStatus { struct Static { static let instance : KeyboardStatus = KeyboardStatus() } return Static.instance } override init() { super.init() registerNotifications() } deinit { unregisterNotifications() } /// keyboard is on screen public var keyboardShowed = false /// keyboard frame (animation origin) public var keyboardBeginFrame : CGRect? /// keyboard frame (animation end) public var keyboardEndFrame : CGRect? /// keyboard animation duration public var keyboardAnimationDuration : Float? /// keyboard animation curve public var keyboardAnimationCurve : UIViewAnimationCurve? /** Register notifications about showing / hiding of the on screen keyboard */ func registerNotifications() { let nc = NSNotificationCenter.defaultCenter() nc.addObserver(self, selector: "keyboardDidShow:", name: UIKeyboardDidShowNotification, object: nil) nc.addObserver(self, selector: "keyboardWillHide:", name: UIKeyboardWillHideNotification, object: nil) } /** Unregister notifications */ func unregisterNotifications() { NSNotificationCenter.defaultCenter().removeObserver(self) } /** Keyboard was shown callback function - parameter notification: notification */ func keyboardDidShow(notification : NSNotification) { keyboardShowed = true let userInfo = notification.userInfo! as NSDictionary keyboardBeginFrame = userInfo.objectForKey(UIKeyboardFrameBeginUserInfoKey)!.CGRectValue keyboardEndFrame = userInfo.objectForKey(UIKeyboardFrameEndUserInfoKey)!.CGRectValue keyboardAnimationDuration = userInfo.objectForKey(UIKeyboardAnimationDurationUserInfoKey)!.floatValue keyboardAnimationCurve = UIViewAnimationCurve(rawValue: userInfo.objectForKey(UIKeyboardAnimationCurveUserInfoKey)!.integerValue) } /** Keyboard was hide callback function - parameter notification: notification */ func keyboardWillHide(notification : NSNotification) { keyboardShowed = false keyboardEndFrame = nil keyboardAnimationDuration = nil keyboardAnimationCurve = nil } }
mit
06ef706caf3b8a04a4933ab3736d3811
29
137
0.676812
6.359447
false
false
false
false
ikesyo/Dollar.swift
Dollar/DollarTests/DollarTests.swift
4
21472
// // DollarTests.swift // DollarTests // // Created by Ankur Patel on 6/3/14. // Copyright (c) 2014 Encore Dev Labs LLC. All rights reserved. // import XCTest import Dollar class DollarTests: XCTestCase { override func setUp() { super.setUp() } override func tearDown() { super.tearDown() } func testFirst() { if let result = $.first([1, 2, 3, 4]) { XCTAssertEqual(result, 1, "Return first element") } XCTAssertNil($.first([Int]()), "Returns nil when array is empty") } func testSecond() { if let result = $.second([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) { XCTAssertEqual(result, 2, "Return second element") } XCTAssertNil($.second([Int]()), "Returns nil when array is empty") } func testThird() { if let result = $.third([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) { XCTAssertEqual(result, 3, "Return third element") } XCTAssertNil($.third([Int]()), "Returns nil when array is empty") } func testNoop() { $.noop() } func testCompact() { XCTAssert($.compact([3, nil, 4, 5]) == [3, 4, 5], "Return truth array") XCTAssertEqual($.compact([nil, nil]) as [NSObject], [], "Return truth array") } func testEach() { var arr: [Int] = [] var result = $.each([1, 3, 4, 5], callback: { arr.append($0 * 2) }) XCTAssert(result == [1, 3, 4, 5], "Return the array itself") XCTAssert(arr == [2, 6, 8, 10], "Return array with doubled numbers") } func testEqual() { XCTAssert($.equal(Optional("hello"), Optional("hello")), "optionalString and otherOptionalString should be equal.") XCTAssertFalse($.equal(Optional("hello"), Optional("goodbye")), "optionalString and thirdOptionalString should not be equal.") XCTAssert($.equal(nil as String?, nil as String?), "Nil optionals should be equal.") } func testFlatten() { XCTAssertEqual($.flatten([[3], 4, 5]), [3, 4, 5], "Return flat array") XCTAssertEqual($.flatten([[[3], 4], 5] as [NSObject]), [3, 4, 5], "Return flat array") } func testShuffle() { XCTAssertEqual($.shuffle([1]), [1], "Return shuffled array") XCTAssertEqual($.shuffle([1, 2, 3]).count, 3, "Return shuffled array") XCTAssertEqual($.shuffle([Int]()), [], "Return empty array") } func testIndexOf() { XCTAssertEqual($.indexOf(["A", "B", "C"], value: "B")!, 1, "Return index of value") XCTAssertEqual($.indexOf([3, 4, 5], value: 5)!, 2, "Return index of value") XCTAssertEqual($.indexOf([3, 4, 5], value: 3)!, 0, "Return index of value") XCTAssertNil($.indexOf([3, 4, 5], value: 2), "Return index of value") } func testInitial() { XCTAssertEqual($.initial([3, 4, 5]), [3, 4], "Return all values except for last") XCTAssertEqual($.initial([3, 4, 5], numElements: 2), [3], "Return all values except for last") XCTAssertEqual($.initial([3, 4, 5], numElements: 4), [], "Return all values except for last") } func testRest() { XCTAssertEqual($.rest([3, 4, 5]), [4, 5], "Returns all value except for first") XCTAssertEqual($.rest([3, 4, 5], numElements: 2), [5], "Returns all value except for first") XCTAssertEqual($.rest([3, 4, 5], numElements: 4), [], "Returns all value except for first") } func testLast() { if let result = $.last([3, 4, 5]) { XCTAssertEqual(result, 5, "Returns last element in array") } XCTAssertNil($.last([NSObject]()), "Returns nil when array is empty") } func testFindIndex() { let arr = [["age": 36], ["age": 40], ["age": 1]] XCTAssertEqual($.findIndex(arr) { $0["age"] < 20 }!, 2, "Returns index of element in array") } func testFindLastIndex() { let arr = [["age": 36], ["age": 40], ["age": 1]] XCTAssertEqual($.findLastIndex(arr) { $0["age"] > 30 }!, 1, "Returns last index of element in array") } func testLastIndexOf() { XCTAssertEqual($.lastIndexOf([1, 2, 3, 1, 2, 3], value: 2)!, 4, "Returns last index of element in array") } func testContains() { XCTAssertTrue($.contains([1, 2, 3, 1, 2, 3], value: 2), "Checks if array contains element") XCTAssertFalse($.contains([1, 2, 3, 1, 2, 3], value: 10), "Checks if array contains element") } func testRange() { XCTAssertEqual($.range(4), [0, 1, 2, 3], "Generates range") XCTAssertEqual($.range(from: 1, to: 5), [1, 2, 3, 4], "Generates range") XCTAssertEqual($.range(from: 0, to: 20, incrementBy: 5), [0, 5, 10, 15], "Generates range") XCTAssertEqual($.range(4.0), [0.0, 1.0, 2.0, 3.0], "Generates range of doubles") XCTAssertEqual($.range(from: -2.0, to: 2.0), [-2.0, -1.0, 0.0, 1.0], "Generates range of doubles") XCTAssertEqual($.range(from: -10.0, to: 10.0, incrementBy: 5), [-10.0, -5.0, 0.0, 5.0], "Generates range of doubles") XCTAssertEqual($.range(from: 1, through: 5), [1, 2, 3, 4, 5], "Increments by 1 and includes 5") XCTAssertEqual($.range(from: 0, through: 20, incrementBy: 5), [0, 5, 10, 15, 20], "Includes 20") XCTAssertEqual($.range(from: -10.0, through: 10.0, incrementBy: 5), [-10.0, -5.0, 0.0, 5.0, 10.0], "Includes 10.0") } func testSequence() { XCTAssertEqual($.sequence("abc"), ["a", "b", "c"], "Generates array of characters") } func testRemove() { XCTAssertEqual($.remove([1, 2, 3, 4, 5, 6], callback: { $0 == 2 || $0 == 3 }), [1, 4, 5, 6], "Remove based on callback") } func testRemoveElement() { XCTAssertEqual($.remove(["ant", "bat", "cat", "dog", "egg"], value: "cat"), ["ant", "bat", "dog", "egg"], "Array after removing element") XCTAssertEqual($.remove(["ant", "bat", "cat", "dog", "egg"], value: "fish"), ["ant", "bat", "cat", "dog", "egg"], "Array after removing element that does not exist") } func testSortedIndex() { XCTAssertEqual($.sortedIndex([3, 4, 6, 10], value: 5), 2, "Index to insert element at in a sorted array") XCTAssertEqual($.sortedIndex([10, 20, 30, 50], value: 40), 3, "Index to insert element at in a sorted array") } func testWithout() { XCTAssertEqual($.without([3, 4, 5, 3, 5], values: 3, 5), [4], "Removes elements passed after the array") XCTAssertEqual($.without([3, 4, 5, 3, 5], values: 4), [3, 5, 3, 5], "Removes elements passed after the array") XCTAssertEqual($.without([3, 4, 5, 3, 5], values: 3, 4, 5), [], "Removes elements passed after the array") } func testPull() { XCTAssertEqual($.pull([3, 4, 5, 3, 5], values: 3, 5), [4], "Removes elements passed after the array") XCTAssertEqual($.pull([3, 4, 5, 3, 5], values: 4), [3, 5, 3, 5], "Removes elements passed after the array") XCTAssertEqual($.pull([3, 4, 5, 3, 5], values: 3, 4, 5), [], "Removes elements passed after the array") } func testZip() { XCTAssertTrue($.zip(["fred", "barney"], [30, 40], [true, false]) as [NSObject] == [["fred", 30, true], ["barney", 40, false]], "Zip up arrays") } func testZipObject() { XCTAssertTrue($.zipObject(["fred", "barney"], values: [30, 40]) as [String: Int] == ["fred": 30, "barney": 40], "Zip up array to object") } func testIntersection() { XCTAssertEqual($.intersection([1, 2, 3], [5, 2, 1, 4], [2, 1]).sorted({$0<$1}), [1, 2], "Intersection of arrays") } func testDifference() { XCTAssertEqual($.difference([1, 2, 3, 4, 5], [5, 2, 10]).sorted({$0<$1}), [1, 3, 4], "Difference of arrays") XCTAssertEqual($.difference([1, 1, 1, 2, 2], [], [3]).sorted({$0<$1}), [1, 1, 1, 2, 2], "Difference of arrays") XCTAssertEqual($.difference([1, 1, 1, 2, 2], [1, 1], [3]).sorted({$0<$1}), [2, 2], "Difference of arrays") XCTAssertEqual($.difference([1, 1, 1, 2, 2], [1, 1], [1, 2, 2]), [], "Difference of arrays") XCTAssertEqual($.difference([1, 1, 1, 2, 2], [1, 1, 1], [1, 2, 2]), [], "Difference of arrays") XCTAssertEqual($.difference([1, 1, 1, 2, 2], []).sorted({$0<$1}), [1, 1, 1, 2, 2], "Difference of arrays") } func testUniq() { XCTAssertEqual($.uniq([1, 2, 1, 3, 1]), [1, 2, 3], "Uniq of arrays") XCTAssertEqual($.uniq([1, 2.5, 3, 1.5, 2, 3.5], by: {floor($0)}), [1, 2.5, 3], "Uniq numbers by condition") } func testUnion() { XCTAssertEqual($.union([1, 2, 3], [5, 2, 1, 4], [2, 1]), [1, 2, 3, 5, 4], "Union of arrays") } func testXOR() { XCTAssertEqual($.xor([1, 2, 3], [5, 2, 1, 4]).sorted{$0<$1}, [3, 4, 5], "Xor of arrays") } func testAt() { XCTAssertEqual($.at(["ant", "bat", "cat", "dog", "egg"], indexes: 0, 2, 4), ["ant", "cat", "egg"], "At of arrays") } func testEvery() { XCTAssertTrue($.every([1, 2, 3, 4]) { $0 < 20 }, "All elements in collection are true") XCTAssertFalse($.every([1, 2, 3, 4]) { $0 == 1 }, "All elements in collection are true") } func testFind() { XCTAssertEqual($.find([1, 2, 3, 4], callback: { $0 == 2 })!, 2, "Return element when object is found") XCTAssertNil($.find([1, 2, 3, 4], callback: { $0 as! Int == 10 }), "Return nil when object not found") } func testMax() { XCTAssert($.max([1, 2, 3, 4, 2, 1]) == 4, "Returns maximum element") XCTAssertNil($.max([Int]()), "Returns nil when array is empty") } func testMin() { XCTAssert($.min([2, 1, 2, 3, 4]) == 1, "Returns minumum element") XCTAssertNil($.min([Int]()), "Returns nil when array is empty") } func testSample() { let arr = [2, 1, 2, 3, 4] XCTAssertTrue($.contains(arr, value: $.sample(arr)), "Returns sample which is an element from the array") } func testPluck() { let arr = [["age": 20], ["age": 30], ["age": 40]] XCTAssertEqual($.pluck(arr, value: "age"), [20, 30, 40], "Returns values from the object where they key is the value") } func testFrequencies() { XCTAssertTrue($.frequencies(["a", "a", "b", "c", "a", "b"]) == ["a": 3, "b": 2, "c": 1], "Returns correct frequency dictionary") XCTAssertTrue($.frequencies([1,2,3,4,5]) { $0 % 2 == 0 } == [false: 3, true: 2], "Returns correct frequency dictionary from cond") } func testKeys() { let dict = ["Dog": 1, "Cat": 2] XCTAssertEqual($.keys(dict).sorted({$0<$1}), ["Cat", "Dog"], "Returns correct array with keys") } func testValues() { let dict = ["Dog": 1, "Cat": 2] XCTAssertEqual($.values(dict).sorted({$0<$1}), [1, 2], "Returns correct array with values") } func testMerge() { let dict = ["Dog": 1, "Cat": 2] let dict2 = ["Cow": 3] let dict3 = ["Sheep": 4] XCTAssertTrue($.merge(dict, dict2, dict3) == ["Dog": 1, "Cat": 2, "Cow": 3, "Sheep": 4], "Returns correct merged dictionary") let arr = [1, 5] let arr2 = [2, 4] let arr3 = [5, 6] XCTAssertEqual($.merge(arr, arr2, arr3), [1, 5, 2, 4, 5, 6], "Returns correct merged array") } func testPick() { let dict = ["Dog": 1, "Cat": 2, "Cow": 3] XCTAssertTrue($.pick(dict, keys: "Dog", "Cow") == ["Dog": 1, "Cow": 3], "Returns correct picked dictionary") } func testOmit() { let dict = ["Dog": 1, "Cat": 2, "Cow": 3] XCTAssertTrue($.omit(dict, keys: "Dog") == ["Cat": 2, "Cow": 3], "Returns correct omited dictionary") } func testTap() { var beatle = CarExample(name: "Fusca") $.tap(beatle, function: {$0.name = "Beatle"}).color = "Blue" XCTAssertEqual(beatle.name!, "Beatle", "Set the car name") XCTAssertEqual(beatle.color!, "Blue", "Set the car color") } func testChaining() { var chain = $.chain([1, 2, 3]) XCTAssertEqual(chain.first()!, 1, "Returns first element which ends the chain") chain = $.chain([10, 20, 30, 40, 50]) var elements: [Int] = [] chain.each { elements.append($0 as Int) } chain.value XCTAssertEqual(elements, [10, 20, 30, 40, 50], "Goes through each element in the array") XCTAssertTrue(chain.all({ ($0 as Int) < 100 }), "All elements are less than 100") chain = $.chain([10, 20, 30, 40, 50]) XCTAssertFalse(chain.all({ ($0 as Int) < 40 }), "All elements are not less than 40") chain = $.chain([10, 20, 30, 40, 50]) XCTAssertTrue(chain.any({ ($0 as Int) < 40 }), "At least one element is less than 40") chain = $.chain([10, 20, 30, 40, 50]) elements = [Int]() chain.slice(0, end: 3).each { elements.append($0 as Int) } chain.value XCTAssertEqual(elements, [10, 20, 30], "Chained seld") let testarr = [[[1, 2]], 3, [[4], 5]] let chainA = $.chain(testarr) XCTAssertEqual(chainA.flatten().initial(2).value, [1, 2, 3], "Returns flatten array from chaining") let chainB = $.chain(testarr) XCTAssertEqual(chainB.initial().flatten().first()!, 1, "Returns flatten array from chaining") let chainC = $.chain(testarr) // XCTAssertEqual(chainC.flatten().map({ (elem) in elem as Int * 10 }).value, [10, 20, 30, 40, 50], "Returns mapped values") // XCTAssertEqual(chainC.flatten().map({ (elem) in elem as Int * 10 }).first()!, 100, "Returns first element from mapped value") } func testPartial() { let s = "ABCD" let partialFunc = $.partial({(T: String...) in T[0] + " " + T[1] + " from " + T[2] }, "Hello") XCTAssertEqual(partialFunc("World", "Swift"), "Hello World from Swift", "Returns curry function that is evaluated") } func testBind() { let helloWorldFunc = $.bind({(T: String...) in T[0] + " " + T[1] + " from " + T[2] }, "Hello", "World", "Swift") XCTAssertEqual(helloWorldFunc(), "Hello World from Swift", "Returns curry function that is evaluated") } func testTimes() { let fun = $.bind({ (names: String...) -> String in let people = $.join(names, separator: " from ") return "Hello \(people)" }, "Ankur", "Swift") XCTAssertEqual($.times(3, function: fun) as [String], ["Hello Ankur from Swift", "Hello Ankur from Swift", "Hello Ankur from Swift"], "Call a function 3 times") } func testAfter() { var saves = ["profile", "settings"] let asyncSave = { (function: () -> ()?) in function() } var isDone = false var completeCallback = $.after(saves.count) { isDone = true } for elem in saves { asyncSave(completeCallback) } XCTAssertTrue(isDone, "Should be done") } func testPartition() { var array = [1, 2, 3, 4, 5] XCTAssertEqual($.partition(array, n: 2), [[1, 2], [3, 4]], "Partition uses n for step if not supplied.") XCTAssertTrue($.partition(array, n: 2, step: 1) == [[1, 2], [2, 3], [3, 4], [4, 5]], "Partition allows specifying a custom step.") XCTAssertEqual($.partition(array, n: 2, step: 1, pad: nil), [[1, 2], [2, 3], [3, 4], [4, 5], [5]], "Partition with nil pad allows the last partition to be less than n length") XCTAssertEqual($.partition(array, n: 4, step: 1, pad: nil), [[1, 2, 3, 4], [2, 3, 4, 5], [3, 4, 5]], "Partition with nil pad stops at the first partition less than n length.") XCTAssertEqual($.partition(array, n: 2, step: 1, pad: [6,7,8]), [[1, 2], [2, 3], [3, 4], [4, 5], [5, 6]], "Partition pads the last partition to the right length.") XCTAssertEqual($.partition(array, n: 4, step: 3, pad: [6]), [[1, 2, 3, 4], [4, 5, 6]], "Partition doesn't add more elements than pad has.") XCTAssertEqual($.partition([1, 2, 3, 4, 5], n: 2, pad: [6]), [[1, 2], [3, 4], [5, 6]], "Partition with pad and no step uses n as step.") XCTAssertTrue($.partition([1, 2, 3, 4, 5, 6], n: 2, step: 4) == [[1, 2], [5, 6]], "Partition step length works.") XCTAssertEqual($.partition(array, n: 10), [[]], "Partition without pad returns [[]] if n is longer than array.") } func testPartitionAll() { var array = [1, 2, 3, 4, 5] XCTAssertTrue($.partitionAll(array, n: 2, step: 1) == [[1, 2], [2, 3], [3, 4], [4, 5], [5]], "PartitionAll includes partitions less than n.") XCTAssertTrue($.partitionAll(array, n: 2) == [[1, 2], [3, 4], [5]], "PartitionAll uses n as the step when not supplied.") XCTAssertTrue($.partitionAll(array, n:4, step: 1) == [[1, 2, 3, 4], [2, 3, 4, 5], [3, 4, 5], [4, 5], [5]], "PartitionAll does not stop at the first partition less than n length.") } func testPartitionBy() { XCTAssertTrue($.partitionBy([1, 2, 3, 4, 5]) { $0 > 10 } == [[1, 2, 3, 4, 5]], "PartitionBy doesn't try to split unnecessarily.") XCTAssertTrue($.partitionBy([1, 2, 4, 3, 5, 6]) { $0 % 2 == 0 } == [[1], [2, 4], [3, 5], [6]], "PartitionBy splits appropriately on Bool.") XCTAssertTrue($.partitionBy([1, 7, 3, 6, 10, 12]) { $0 % 3 } == [[1, 7], [3, 6], [10], [12]], "PartitionBy can split on functions other than Bool.") } func testMap() { XCTAssertEqual($.map([1, 2, 3, 4, 5]) { $0 * 2 }, [2, 4, 6, 8, 10], "Map function should double values in the array") } func testFlatMap() { XCTAssertEqual($.flatMap([1, 2, 3]) { [$0, $0] }, [1, 1, 2, 2, 3, 3], "FlatMap should double every item in the array and concatenate them.") let expected: String? = "swift" let actual = $.flatMap(NSURL(string: "https://apple.com/swift/")) { $0.lastPathComponent } XCTAssert($.equal(actual, expected), "FlatMap on optionals should run the function and produce a single-level optional containing the last path component of the url.") } func testReduce() { XCTAssertEqual($.reduce([1, 2, 3, 4, 5], initial: 0) { $0 + $1 } as Int, 15, "Reduce function should sum elements in the array") } func testSlice() { XCTAssertEqual($.slice([1,2,3,4,5], start: 0, end: 2), [1, 2], "Slice subarray 0..2") XCTAssertEqual($.slice([1,2,3,4,5], start: 0), [1, 2, 3, 4, 5], "Slice at 0 is whole array") XCTAssertEqual($.slice([1,2,3,4,5], start: 3), [4, 5], "Slice with start goes till end") XCTAssertEqual($.slice([1,2,3,4,5], start: 8), [], "Slice out of bounds is empty") XCTAssertEqual($.slice([1,2,3,4,5], start: 8, end: 10), [], "Slice out of bounds is empty") XCTAssertEqual($.slice([1,2,3,4,5], start: 8 , end: 2), [], "Slice with end < start is empty") XCTAssertEqual($.slice([1,2,3,4,5], start: 3, end: 3), [], "Slice at x and x is empty") XCTAssertEqual($.slice([1,2,3,4,5], start: 2, end: 5), [3,4,5], "Slice at x and x is subarray") } func testFib() { var times = 0 let fibMemo = $.memoize { (fib: (Int -> Int), val: Int) -> Int in times += 1 return val == 1 || val == 0 ? 1 : fib(val - 1) + fib(val - 2) } let x = fibMemo(5) XCTAssertEqual(times, 6, "Function called 6 times") times = 0 let y = fibMemo(5) XCTAssertEqual(times, 0, "Function called 0 times due to memoize") times = 0 let z = fibMemo(6) XCTAssertEqual(times, 1, "Function called 1 times due to memoize") } func testId() { XCTAssertEqual($.id(1), 1, "Id should return the argument it gets passed") } func testComposeVariadic() { let double = { (params: Int...) -> [Int] in return $.map(params) { $0 * 2 } } let subtractTen = { (params: Int...) -> [Int] in return $.map(params) { $0 - 10 } } let doubleSubtractTen = $.compose(double, subtractTen) XCTAssertEqual(doubleSubtractTen(5, 6, 7), [0, 2, 4], "Should double value and then subtract 10") } func testComposeArray() { let double = { (params: [Int]) -> [Int] in return $.map(params) { $0 * 2 } } let subtractTen = { (params: [Int]) -> [Int] in return $.map(params) { $0 - 10 } } let doubleSubtractTen = $.compose(double, subtractTen) XCTAssertEqual(doubleSubtractTen([5, 6, 7]), [0, 2, 4], "Should double value and then subtract 10") } func testChunk() { XCTAssertEqual($.chunk([1, 2, 3, 4], size: 2), [[1, 2], [3, 4]], "Should chunk with elements in groups of 2") XCTAssertEqual($.chunk([1, 2, 3, 4], size: 3), [[1, 2, 3], [4]], "Should chunk with elements in groups of 2") } func testFill() { var arr = Array<Int>(count: 5, repeatedValue: 1) XCTAssertEqual($.fill(&arr, withElem: 42), [42,42,42,42,42], "Should fill array with 42") $.fill(&arr, withElem: 1, startIndex: 1, endIndex: 3) XCTAssertEqual($.fill(&arr, withElem: 1, startIndex: 1, endIndex: 3), [42,1,1,1,42], "Should fill array with 1") } func testPullAt() { XCTAssertEqual($.pullAt([10, 20, 30, 40, 50], indices: 1, 2, 3), [10, 50], "Remove elements at index") } func testSize() { XCTAssertEqual($.size([10, 20, 30, 40, 50]), 5, "Returns size") } }
mit
d93fe336c3f1464fc6bb94b3b995a692
44.782516
187
0.55109
3.518846
false
true
false
false
ZenMotionLLC/ZMClockSolver
ZMClockSolver/ZMClock.swift
1
3510
// // ZMClock.swift // ClockSolver // // Created by Jason Kirchner on 4/8/16. // Copyright © 2016 Zen Motion LLC. All rights reserved. // import Foundation /// Represents a clock with numbers around the face. @available(iOS 7, *) @available(OSX 10.10, *) @available(watchOS 2, *) struct ZMClock { /// The numbers on the 'Clock' face. /// The positions begin at the top of the clock face and rotate in a clockwise direction. let positions: [Int] /// The solution for the clock. /// * The solution will be calculated on whatever thread this variable is called on. /// /// - returns: The solution to the clock, i.e. the order of positions on the clock that will result in the clock being solved, or nil if the clock is impossible to solve var solution: [Int]? { return ZMClockSolver.solutionForClock(self) } /// The solution for the clock returned to a closure. /// * The solution is calculated on a background thread and will not block the main thread. /// * The closure is executed on the main thread. func calculateSolutionOnComplete( onComplete: ( [Int]?) -> Void ) { dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0)) { let solution = self.solution dispatch_async(dispatch_get_main_queue()) { onComplete(solution) } } } private var numberOfPositions: Int { return positions.count } private func possibleIndexesFromIndex(index: Int) -> [Int] { guard index < numberOfPositions else { return [Int]() } let movement = positions[index] let forwardIndex = abs((index + movement) % numberOfPositions) let reverseIndex = (((index - movement) % numberOfPositions) + numberOfPositions) % numberOfPositions var indexes = [forwardIndex] if reverseIndex != forwardIndex { indexes.append(reverseIndex) } return indexes } private struct ZMClockSolver { static func solutionForClock(clock: ZMClock) -> [Int]? { let numberOfPositions = clock.numberOfPositions guard numberOfPositions > 1 else { return nil } for startingIndex in 0..<numberOfPositions { let moves = [startingIndex] if clockMoves(moves, onClock: clock) == nil { continue } else { return clockMoves(moves, onClock: clock) } } return nil } static private func clockMoves(moves: [Int], onClock clock: ZMClock) -> [Int]? { guard moves.count <= clock.numberOfPositions else { return nil } guard let position = moves.last else { return nil } let possible = clock.possibleIndexesFromIndex(position) for finalPosition in possible { if moves.contains(finalPosition) { continue } else { var final = moves final.append(finalPosition) if final.count == clock.numberOfPositions { return final } if clockMoves(final, onClock: clock) == nil { continue } else { return clockMoves(final, onClock: clock) } } } return nil } } }
gpl-3.0
fb3d7e9be293e481bc0b4af686e24c8e
31.192661
173
0.569108
5.034433
false
false
false
false
ps2/rileylink_ios
MinimedKit/GlucoseEvents/UnknownGlucoseEvent.swift
1
846
// // UnknownGlucoseEvent.swift // RileyLink // // Created by Timothy Mecklem on 10/19/16. // Copyright © 2016 Pete Schwamb. All rights reserved. // import Foundation public struct UnknownGlucoseEvent: GlucoseEvent { public let length: Int public let rawData: Data public let timestamp: DateComponents private let op: String public init?(availableData: Data, relativeTimestamp: DateComponents) { length = 1 guard length <= availableData.count else { return nil } rawData = availableData.subdata(in: 0..<length) op = rawData.hexadecimalString timestamp = relativeTimestamp } public var dictionaryRepresentation: [String: Any] { return [ "name": "Could Not Decode", "op": op ] } }
mit
533d55d9fb30c5cb16fde1e85a669ec7
23.142857
74
0.611834
4.884393
false
false
false
false
CSullivan102/LearnApp
Learn/CreateLearnItemViewController.swift
1
1927
// // CreateLearnItemViewController.swift // Learn // // Created by Christopher Sullivan on 8/20/15. // Copyright © 2015 Christopher Sullivan. All rights reserved. // import UIKit import CoreData import LearnKit class CreateLearnItemViewController: UIViewController, ManagedObjectContextSettable, PocketAPISettable { var managedObjectContext: NSManagedObjectContext! var pocketAPI: PocketAPI! var topic: Topic? @IBOutlet weak var titleTextField: UITextField! @IBOutlet weak var urlTextField: UITextField! override func viewDidLoad() { super.viewDidLoad() titleTextField.becomeFirstResponder() } @IBAction func create(sender: UIBarButtonItem) { createLearnItem() presentingViewController?.dismissViewControllerAnimated(true, completion: nil) } @IBAction func cancel(sender: UIBarButtonItem) { presentingViewController?.dismissViewControllerAnimated(true, completion: nil) } private func createLearnItem() { guard let topic = topic else { fatalError("Tried to create a learn item with no topic") } guard let titleValue = titleTextField.text where titleValue.characters.count > 0, let urlValue = urlTextField.text, url = NSURL(string: urlValue) else { return } managedObjectContext.performChanges { let learnItem: LearnItem = self.managedObjectContext.insertObject() learnItem.title = titleValue learnItem.url = url learnItem.itemType = .Article learnItem.read = false learnItem.dateAdded = NSDate() learnItem.topic = topic if self.pocketAPI.isAuthenticated() { self.pocketAPI.addURLToPocket(url) { (pocketItem) -> () in learnItem.copyDataFromPocketItem(pocketItem) } } } } }
mit
bd4f59e07163edf54ab487147bcb5ab1
32.206897
104
0.657321
5.410112
false
false
false
false
m-alani/contests
hackerrank/Pairs.swift
1
888
// // Pairs.swift // // Practice solution - Marwan Alani - 2017 // // Check the problem (and run the code) on HackerRank @ https://www.hackerrank.com/challenges/pairs // Note: make sure that you select "Swift" from the top-right language menu of the code editor when testing this code // import Foundation // Read N & K as Strings var inputString = String(readLine() ?? "")!.components(separatedBy: " ") // Convert the strings into integers let inputInt: [Int] = inputString.map({Int($0) ?? 0}) let N = inputInt[0] let K = inputInt[1] // Read the N integers as String inputString = String(readLine() ?? "")!.components(separatedBy: " ") // Convert the strings into integers let input = Set(inputString.map({Int($0) ?? 0})) // Process the input var output = 0 for number in input { if input.contains(number - K) { output += 1 } } // Print the output print(output)
mit
c03a8704209e6b9232b6ff0299ccb399
25.909091
118
0.675676
3.509881
false
false
false
false
liushuaikobe/beauties
beauties/BeautyImageEntity.swift
2
1135
// // BeautyImageEntity.swift // beauties // // Created by Shuai Liu on 15/6/30. // Copyright (c) 2015年 Shuai Liu. All rights reserved. // import Foundation class BeautyImageEntity: NSObject, NSCoding { var imageUrl: String? var imageHeight: Int? var imageWidth: Int? override var description: String { return "imageUrl: \(self.imageUrl), imageHeight: \(self.imageHeight), imageWidth: \(self.imageWidth)" } override init() { } required init?(coder aDecoder: NSCoder) { imageUrl = aDecoder.decodeObjectForKey("imageUrl") as? String imageHeight = aDecoder.decodeObjectForKey("imageHeight") as? Int imageWidth = aDecoder.decodeObjectForKey("imageWidth") as? Int } func encodeWithCoder(aCoder: NSCoder) { if imageUrl != nil { aCoder.encodeObject(imageUrl, forKey: "imageUrl") } if imageHeight != nil { aCoder.encodeObject(imageHeight, forKey: "imageHeight") } if imageWidth != nil { aCoder.encodeObject(imageWidth, forKey: "imageWidth") } } }
mit
1f04358ba4fee6a90e53d92cf4e3b044
26.658537
109
0.623124
4.720833
false
false
false
false
leonereveel/Moya
Source/ReactiveCocoa/Moya+ReactiveCocoa.swift
1
4549
import Foundation import ReactiveCocoa /// Subclass of MoyaProvider that returns SignalProducer instances when requests are made. Much better than using completion closures. public class ReactiveCocoaMoyaProvider<Target where Target: TargetType>: MoyaProvider<Target> { private let stubScheduler: DateSchedulerType? /// Initializes a reactive provider. public init(endpointClosure: EndpointClosure = MoyaProvider.DefaultEndpointMapping, requestClosure: RequestClosure = MoyaProvider.DefaultRequestMapping, stubClosure: StubClosure = MoyaProvider.NeverStub, manager: Manager = ReactiveCocoaMoyaProvider<Target>.DefaultAlamofireManager(), plugins: [PluginType] = [], stubScheduler: DateSchedulerType? = nil, trackInflights: Bool = false) { self.stubScheduler = stubScheduler super.init(endpointClosure: endpointClosure, requestClosure: requestClosure, stubClosure: stubClosure, manager: manager, plugins: plugins, trackInflights: trackInflights) } /// Designated request-making method. public func request(token: Target) -> SignalProducer<Response, Error> { // Creates a producer that starts a request each time it's started. return SignalProducer { [weak self] observer, requestDisposable in let cancellableToken = self?.request(token) { result in switch result { case let .Success(response): observer.sendNext(response) observer.sendCompleted() case let .Failure(error): observer.sendFailed(error) } } requestDisposable.addDisposable { // Cancel the request cancellableToken?.cancel() } } } override func stubRequest(target: Target, request: NSURLRequest, completion: Moya.Completion, endpoint: Endpoint<Target>, stubBehavior: Moya.StubBehavior) -> CancellableToken { guard let stubScheduler = self.stubScheduler else { return super.stubRequest(target, request: request, completion: completion, endpoint: endpoint, stubBehavior: stubBehavior) } notifyPluginsOfImpendingStub(request, target: target) var dis: Disposable? = .None let token = CancellableToken { dis?.dispose() } let stub = createStubFunction(token, forTarget: target, withCompletion: completion, endpoint: endpoint, plugins: plugins) switch stubBehavior { case .Immediate: dis = stubScheduler.schedule(stub) case .Delayed(let seconds): let date = NSDate(timeIntervalSinceNow: seconds) dis = stubScheduler.scheduleAfter(date, action: stub) case .Never: fatalError("Attempted to stub request when behavior requested was never stub!") } return token } } public extension ReactiveCocoaMoyaProvider { public func requestWithProgress(token: Target) -> SignalProducer<ProgressResponse, Error> { let progressBlock = { (observer: Signal<ProgressResponse, Error>.Observer) -> (ProgressResponse) -> Void in return { (progress: ProgressResponse) in observer.sendNext(progress) } } let response: SignalProducer<ProgressResponse, Error> = SignalProducer { [weak self] observer, disposable in let cancellableToken = self?.request(token, queue: nil, progress: progressBlock(observer)) { result in switch result { case let .Success(response): observer.sendNext(ProgressResponse(response: response)) observer.sendCompleted() case let .Failure(error): observer.sendFailed(error) } } let cleanUp = ActionDisposable { cancellableToken?.cancel() } disposable.addDisposable(cleanUp) } // Accumulate all progress and combine them when the result comes return response.scan(ProgressResponse()) { (last, progress) in let totalBytes = progress.totalBytes > 0 ? progress.totalBytes : last.totalBytes let bytesExpected = progress.bytesExpected > 0 ? progress.bytesExpected : last.bytesExpected let response = progress.response ?? last.response return ProgressResponse(totalBytes: totalBytes, bytesExpected: bytesExpected, response: response) } } }
mit
a5e4b65ce22d1d8299978eece61f4e49
45.896907
182
0.649813
5.862113
false
false
false
false
Guicai-Li/iOS_Tutorial
Flo/Flo/CounterView.swift
1
2394
// // CounterView.swift // Flo // // Created by 力贵才 on 15/12/2. // Copyright © 2015年 Guicai.Li. All rights reserved. // import Foundation import UIKit let NoOfGlasses = 8 let π:CGFloat = CGFloat(M_PI) @IBDesignable class CounterView: UIView { @IBInspectable var outlineColor: UIColor = UIColor.blueColor() @IBInspectable var counterColor: UIColor = UIColor.orangeColor() @IBInspectable var counter: Int = 5 { didSet{ setNeedsDisplay() } } override func drawRect(rect: CGRect) { // 1 let center = CGPoint(x:bounds.width/2, y: bounds.height/2) // 2 let radius: CGFloat = max(bounds.width, bounds.height) // 3 let arcWidth: CGFloat = 76 // 4 let startAngle: CGFloat = 3 * π / 4 let endAngle: CGFloat = π / 4 // 5 var path = UIBezierPath(arcCenter: center, radius: radius/2 - arcWidth/2, startAngle: startAngle, endAngle: endAngle, clockwise: true) // 6 path.lineWidth = arcWidth counterColor.setStroke() path.stroke() //Draw the outline //1 - first calculate the difference between the two angles //ensuring it is positive let angleDifference: CGFloat = 2 * π - startAngle + endAngle //then calculate the arc for each single glass let arcLengthPerGlass = angleDifference / CGFloat(NoOfGlasses) //then multiply out by the actual glasses drunk let outlineEndAngle = arcLengthPerGlass * CGFloat(counter) + startAngle //2 - draw the outer arc var outlinePath = UIBezierPath(arcCenter: center, radius: bounds.width/2 - 2.5, startAngle: startAngle, endAngle: outlineEndAngle, clockwise: true) //3 - draw the inner arc outlinePath.addArcWithCenter(center, radius: bounds.width/2 - arcWidth + 2.5, startAngle: outlineEndAngle, endAngle: startAngle, clockwise: false) //4 - close the path outlinePath.closePath() outlineColor.setStroke() outlinePath.lineWidth = 5.0 outlinePath.stroke() } }
apache-2.0
2d32f6e6c7b0172aa760b71fc28e04dd
26.056818
79
0.562789
4.819838
false
false
false
false
Yurssoft/QuickFile
QuickFile/Coordinators/YSPlaylistCoordinator.swift
1
980
// // YSPlaylistCoordinator.swift // YSGGP // // Created by Yurii Boiko on 12/7/16. // Copyright © 2016 Yurii Boiko. All rights reserved. // import Foundation import UIKit import AVKit import AVFoundation import SwiftMessages class YSPlaylistCoordinator: YSCoordinatorProtocol { func start(playlistViewController: YSPlaylistViewController) { let viewModel = YSPlaylistViewModel() playlistViewController.viewModel = viewModel YSAppDelegate.appDelegate().playerCoordinator.viewModel.playerDelegate = viewModel YSAppDelegate.appDelegate().playlistDelegate = viewModel viewModel.model = YSPlaylistAndPlayerModel() viewModel.coordinatorDelegate = self } } extension YSPlaylistCoordinator: YSPlaylistViewModelCoordinatorDelegate { func playlistViewModelDidSelectFile(_ viewModel: YSPlaylistViewModelProtocol, file: YSDriveFileProtocol) { YSAppDelegate.appDelegate().playerCoordinator.play(file: file) } }
mit
9155118706bbd10c82d639b32b8e5259
31.633333
110
0.767109
5.235294
false
false
false
false
riteshhgupta/TagCellLayout
TagCellLayout/ViewController.swift
1
2797
// // ViewController.swift // TagCellLayout // // Created by Ritesh-Gupta on 20/11/15. // Copyright © 2015 Ritesh. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var collectionView: UICollectionView? var longString = "start ––– Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. ––– end" var oneLineHeight: CGFloat { return 54.0 } var longTagIndex: Int { return 1 } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) defaultSetup() // THIS IS ALL WHAT IS REQUIRED TO SETUP YOUR TAGS let tagCellLayout = TagCellLayout(alignment: .center, delegate: self) collectionView?.collectionViewLayout = tagCellLayout } //MARK: - Default Methods func defaultSetup() { let nib = UINib(nibName: "TagCollectionViewCell", bundle: nil) collectionView?.register(nib, forCellWithReuseIdentifier: "TagCollectionViewCell") } } extension ViewController: UICollectionViewDelegate, UICollectionViewDataSource { //MARK: - UICollectionView Delegate/Datasource Methods func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let identifier = "TagCollectionViewCell" let cell = collectionView.dequeueReusableCell(withReuseIdentifier: identifier, for: indexPath) as! TagCollectionViewCell if indexPath.row == longTagIndex || indexPath.row == (longTagIndex + 3) { cell.configure(with: longString) } else { cell.configure(with: "Tags") } return cell } func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int { return 1 } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return 10 } } extension ViewController: TagCellLayoutDelegate { func tagCellLayoutTagSize(layout: TagCellLayout, atIndex index: Int) -> CGSize { if index == longTagIndex || index == (longTagIndex + 3) { var s = textSize(text: longString, font: UIFont.systemFont(ofSize: 17.0), collectionView: collectionView!) s.height += 8.0 return s } else { let width = CGFloat(index % 2 == 0 ? 80 : 120) return CGSize(width: width, height: oneLineHeight) } } } extension ViewController { func textSize(text: String, font: UIFont, collectionView: UICollectionView) -> CGSize { var f = collectionView.bounds f.size.height = 9999.0 let label = UILabel() label.numberOfLines = 0 label.text = text label.font = font var s = label.sizeThatFits(f.size) s.height = max(oneLineHeight, s.height) return s } }
mit
5a11438395426078cf4bf5759ed096e2
27.121212
161
0.731681
4.023121
false
false
false
false
tokyovigilante/CesiumKit
CesiumKit/Core/BoundingRectangle.swift
1
8878
// // BoundingRectangle.swift // CesiumKit // // Created by Ryan Walklin on 11/06/14. // Copyright (c) 2014 Test Toast. All rights reserved. // import Foundation /** * A bounding rectangle given by a corner, width and height. * @alias BoundingRectangle * @constructor * * @param {Number} [x=0.0] The x coordinate of the rectangle. * @param {Number} [y=0.0] The y coordinate of the rectangle. * @param {Number} [width=0.0] The width of the rectangle. * @param {Number} [height=0.0] The height of the rectangle. * * @see BoundingSphere */ public struct BoundingRectangle: Equatable { /** * The x coordinate of the rectangle. * @type {Number} * @default 0.0 */ public var x: Double = 0.0 /** * The y coordinate of the rectangle. * @type {Number} * @default 0.0 */ public var y: Double = 0.0 /** * The width of the rectangle. * @type {Number} * @default 0.0 */ public var width: Double = 0.0 /** * The height of the rectangle. * @type {Number} * @default 0.0 */ public var height: Double = 0.0 var projection: MapProjection = GeographicProjection() public init (x: Double = 0.0, y: Double = 0.0, width: Double = 0.0, height: Double = 0.0, projection: MapProjection = GeographicProjection()) { self.x = x self.y = y self.width = width self.height = height self.projection = projection } /** * Computes a bounding rectangle enclosing the list of 2D points. * The rectangle is oriented with the corner at the bottom left. * * @param {Cartesian2[]} positions List of points that the bounding rectangle will enclose. Each point must have <code>x</code> and <code>y</code> properties. * @param {BoundingRectangle} [result] The object onto which to store the result. * @returns {BoundingRectangle} The modified result parameter or a new BoundingRectangle instance if one was not provided. */ init(fromPoints points: [Cartesian2]) { if (points.count == 0) { x = 0 y = 0 width = 0 height = 0 } var minimumX = points[0].x var minimumY = points[0].y var maximumX = points[0].x var maximumY = points[0].y for cartesian2 in points { let x = cartesian2.x let y = cartesian2.y minimumX = min(x, minimumX) maximumX = max(x, maximumX) minimumY = min(y, minimumY) maximumY = max(y, maximumY) } x = minimumX y = minimumY width = maximumX - minimumX height = maximumY - minimumY } /** * Computes a bounding rectangle from an rectangle. * * @param {Rectangle} rectangle The valid rectangle used to create a bounding rectangle. * @param {Object} [projection=GeographicProjection] The projection used to project the rectangle into 2D. * @param {BoundingRectangle} [result] The object onto which to store the result. * @returns {BoundingRectangle} The modified result parameter or a new BoundingRectangle instance if one was not provided. */ init(fromRectangle rectangle: Rectangle, projection: MapProjection = GeographicProjection()) { self.projection = projection let lowerLeft = projection.project(rectangle.southwest) let upperRight = projection.project(rectangle.northeast).subtract(lowerLeft) //upperRight.subtract(lowerLeft) x = lowerLeft.x y = lowerLeft.y width = upperRight.x height = upperRight.y } /** * Computes a bounding rectangle that is the union of the left and right bounding rectangles. * * @param {BoundingRectangle} left A rectangle to enclose in bounding rectangle. * @param {BoundingRectangle} right A rectangle to enclose in a bounding rectangle. * @param {BoundingRectangle} [result] The object onto which to store the result. * @returns {BoundingRectangle} The modified result parameter or a new BoundingRectangle instance if one was not provided. */ func union(_ other: BoundingRectangle) -> BoundingRectangle { let lowerLeftX = min(x, other.x); let lowerLeftY = min(y, other.y); let upperRightX = max(x + width, other.x + other.width); let upperRightY = max(y + height, other.y + other.height); return BoundingRectangle( x: lowerLeftX, y: lowerLeftY, width: upperRightX - lowerLeftX, height: upperRightY - lowerLeftY) } /** * Computes a bounding rectangle by enlarging the provided rectangle until it contains the provided point. * * @param {BoundingRectangle} rectangle A rectangle to expand. * @param {Cartesian2} point A point to enclose in a bounding rectangle. * @param {BoundingRectangle} [result] The object onto which to store the result. * @returns {BoundingRectangle} The modified result parameter or a new BoundingRectangle instance if one was not provided. */ func expand(_ point: Cartesian2) -> BoundingRectangle { var result = self let width = point.x - result.x let height = point.y - result.y if (width > result.width) { result.width = width } else if (width < 0) { result.width -= width; result.x = point.x } if (height > result.height) { result.height = height } else if (height < 0) { result.height -= height; result.y = point.y } return result } /** * Determines if two rectangles intersect. * * @param {BoundingRectangle} left A rectangle to check for intersection. * @param {BoundingRectangle} right The other rectangle to check for intersection. * @returns {Intersect} <code>Intersect.INTESECTING</code> if the rectangles intersect, <code>Intersect.OUTSIDE</code> otherwise. */ func intersect(_ other: BoundingRectangle) -> Intersect { if !(x > other.x + other.width || x + width < other.x || y + height < other.y || y > other.y + other.height) { return Intersect.intersecting } return Intersect.outside; } } extension BoundingRectangle: Packable { init(array: [Double], startingIndex: Int) { self.init() } /** * The number of elements used to pack the object into an array. * @type {Number} */ static func packedLength() -> Int { return 4 } func checkPackedArrayLength(_ array: [Double], startingIndex: Int) -> Bool { return false } /** * Stores the provided instance into the provided array. * * @param {BoundingRectangle} value The value to pack. * @param {Number[]} array The array to pack into. * @param {Number} [startingIndex=0] The index into the array at which to start packing the elements. * * @returns {Number[]} The array that was packed into */ func pack (_ array: inout [Float], startingIndex: Int = 0) { array[startingIndex] = Float(x) array[startingIndex+1] = Float(y) array[startingIndex+2] = Float(width) array[startingIndex+3] = Float(height) } /** * Retrieves an instance from a packed array. * * @param {Number[]} array The packed array. * @param {Number} [startingIndex=0] The starting index of the element to be unpacked. * @param {BoundingRectangle} [result] The object into which to store the result. * @returns {BoundingRectangle} The modified result parameter or a new BoundingRectangle instance if one was not provided. */ static func unpack (array: [Float], startingIndex: Int = 0) -> BoundingRectangle { var result = BoundingRectangle() result.x = Double(array[startingIndex]) result.y = Double(array[startingIndex+1]) result.width = Double(array[startingIndex+2]) result.height = Double(array[startingIndex+3]) return result } } /** * Compares the provided BoundingRectangles componentwise and returns * <code>true</code> if they are equal, <code>false</code> otherwise. * * @param {BoundingRectangle} [left] The first BoundingRectangle. * @param {BoundingRectangle} [right] The second BoundingRectangle. * @returns {Boolean} <code>true</code> if left and right are equal, <code>false</code> otherwise. */ public func ==(left: BoundingRectangle, right: BoundingRectangle) -> Bool { return (left.x == right.x && left.y == right.y && left.width == right.width && left.height == right.height) }
apache-2.0
0f74007f0016352d6aa660770dbd3f8f
33.015326
162
0.616242
4.371246
false
false
false
false
rdhiggins/GoogleURLShortener
GoogleURLShortener/Secrets.swift
1
2302
// // Secrets.swift // MIT License // // Copyright (c) 2016 Spazstik Software, LLC // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. import Foundation struct Secrets { fileprivate let filename: String! /// This property contains the API key to use for accessing a Google API let googleAPIKey: String? init(filename: String) { self.filename = filename // Load the dictionary from the secrets file guard let filePath = Bundle.main.path(forResource: filename, ofType: "plist"), let plist = NSDictionary(contentsOfFile: filePath) else { print("There appears to be no Secrets file, or the Secrets file does not contain a dictionary") fatalError() } // Decode the API Key if let apiKey = plist["GoogleAPIKey"] as? String, !apiKey.isEmpty { self.googleAPIKey = apiKey } else { self.googleAPIKey = nil } } } /// Global Secrets Structure let sharedSecrets = { let s = Secrets(filename: "Secrets") if s.googleAPIKey == nil { fatalError("A Google API Key is required!") } // Initialize what needs to be initialized, like the Google API Key GoogleURLShortenerRouter.apiKey = s.googleAPIKey! }
mit
531420bfe72c88d1c0612f01ea200139
35.539683
107
0.694613
4.62249
false
false
false
false
CodaFi/APL.swift
APLTests/BooleanArithmeticSpec.swift
1
1456
// // BooleanArithmeticSpec.swift // APL // // Created by Robert Widmann on 7/14/14. // Copyright (c) 2014 Robert Widmann. All rights reserved. // import Foundation import XCTest import APL class BooleanArithmeticSpec : XCTestCase { func testDyadMatch() { let x = ["a", "a", "a", "a", "a", "a"] let y = ["a", "a", "a", "a", "a", "a"] let z = ["b", "a", "a", "a", "a", "a"] XCTAssertTrue(x≡y, "") XCTAssertTrue(y≡x, "") XCTAssertFalse(z≡x, "") } func testMonadNot() { let x = true let y = false XCTAssertFalse(~x, "") XCTAssertTrue(~y, "") } func testMonadAND() { let x = true let y = false XCTAssertTrue(x ∧ x, "") XCTAssertFalse(x ∧ y, "") XCTAssertFalse(y ∧ y, "") } func testMonadOR() { let x = true let y = false XCTAssertTrue(x ∨ x, "") XCTAssertTrue(x ∨ y, "") XCTAssertFalse(y ∨ y, "") } func testMonadNAND() { let x = true let y = false XCTAssertFalse(x ⍲ x, "") XCTAssertTrue(x ⍲ y, "") XCTAssertTrue(y ⍲ y, "") } func testMonadNOR() { let x = true let y = false XCTAssertFalse(x ⍱ x, "") XCTAssertFalse(x ⍱ y, "") XCTAssertTrue(y ⍱ y, "") } }
mit
85eca2887cf04c79e24d3ebc5cd7a842
20.283582
59
0.454418
3.723238
false
true
false
false
verticon/VerticonsToolbox
VerticonsToolbox/Geometry.swift
1
10664
// // Geometry.swift // // Created by Luka on 27. 08. 14. // Copyright (c) 2014 lvnyk // // 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 // MARK: - calculations // MARK: CGPoint public func +(lhs: CGPoint, rhs: CGPoint) -> CGPoint { return CGPoint(x: lhs.x+rhs.x, y: lhs.y+rhs.y) } public func +=(lhs: inout CGPoint, rhs: CGPoint) { lhs.x += rhs.x lhs.y += rhs.y } public func -(lhs: CGPoint, rhs: CGPoint) -> CGPoint { return CGPoint(x: lhs.x-rhs.x, y: lhs.y-rhs.y) } public func -=(lhs: inout CGPoint, rhs: CGPoint) { lhs.x -= rhs.x lhs.y -= rhs.y } public func *(lhs: CGPoint, rhs: CGFloat) -> CGPoint { return CGPoint(x: lhs.x*rhs, y: lhs.y*rhs) } public func *=(lhs: inout CGPoint, rhs: CGFloat) { lhs.x *= rhs lhs.y *= rhs } public func *(lhs: CGFloat, rhs: CGPoint) -> CGPoint { return CGPoint(x: rhs.x*lhs, y: rhs.y*lhs) } public func /(lhs: CGPoint, rhs: CGFloat) -> CGPoint { return CGPoint(x: lhs.x/rhs, y: lhs.y/rhs) } public func /=(lhs: inout CGPoint, rhs: CGFloat) { lhs.x /= rhs lhs.y /= rhs } public func +(lhs: CGPoint, rhs: CGVector) -> CGPoint { return CGPoint(x: lhs.x+rhs.dx, y: lhs.y+rhs.dy) } public func -(lhs: CGPoint, rhs: CGVector) -> CGPoint { return CGPoint(x: lhs.x-rhs.dx, y: lhs.y-rhs.dy) } prefix public func -(lhs: CGPoint) -> CGPoint { return CGPoint(x: -lhs.x, y: -lhs.y) } // MARK: CGVector public func +(lhs: CGVector, rhs: CGVector) -> CGVector { return CGVector(dx: lhs.dx+rhs.dx, dy: lhs.dy+rhs.dy) } public func +=(lhs: inout CGVector, rhs: CGVector) { lhs.dx += rhs.dx lhs.dy += rhs.dy } public func -(lhs: CGVector, rhs: CGVector) -> CGVector { return CGVector(dx: lhs.dx-rhs.dx, dy: lhs.dy-rhs.dy) } public func -=(lhs: inout CGVector, rhs: CGVector) { lhs.dx -= rhs.dx lhs.dy -= rhs.dy } public func *(lhs: CGVector, rhs: CGFloat) -> CGVector { return CGVector(dx: lhs.dx*rhs, dy: lhs.dy*rhs) } public func *=(lhs: inout CGVector, rhs: CGFloat) { lhs.dx *= rhs lhs.dy *= rhs } public func *(lhs: CGFloat, rhs: CGVector) -> CGVector { return CGVector(dx: rhs.dx*lhs, dy: rhs.dy*lhs) } public func /(lhs: CGVector, rhs: CGFloat) -> CGVector { return CGVector(dx: lhs.dx/rhs, dy: lhs.dy/rhs) } public func /=(lhs: inout CGVector, rhs: CGFloat) { lhs.dx /= rhs lhs.dy /= rhs } // MARK: CGSize public func +(lhs: CGSize, rhs: CGSize) -> CGSize { return CGSize(width: lhs.width+rhs.width, height: lhs.height+rhs.height) } public func +=(lhs: inout CGSize, rhs: CGSize) { lhs.width += rhs.width lhs.height += rhs.height } public func -(lhs: CGSize, rhs: CGSize) -> CGSize { return CGSize(width: lhs.width-rhs.width, height: lhs.height-rhs.height) } public func -=(lhs: inout CGSize, rhs: CGSize) { lhs.width -= rhs.width lhs.height -= rhs.height } public func *(lhs: CGFloat, rhs: CGSize) -> CGSize { return CGSize(width: rhs.width*lhs, height: rhs.height*lhs) } public func *(lhs: CGSize, rhs: CGFloat) -> CGSize { return CGSize(width: lhs.width*rhs, height: lhs.height*rhs) } public func *=(lhs: inout CGSize, rhs: CGFloat) { lhs.width *= rhs lhs.height *= rhs } public func /(lhs: CGSize, rhs: CGFloat) -> CGSize { return CGSize(width: lhs.width/rhs, height: lhs.height/rhs) } public func /=(lhs: inout CGSize, rhs: CGFloat) { lhs.width /= rhs lhs.height /= rhs } // MARK: CGRect public func *(lhs: CGRect, rhs: CGFloat) -> CGRect { return CGRect(origin: lhs.origin*rhs, size: lhs.size*rhs) } public func *(lhs: CGFloat, rhs: CGRect) -> CGRect { return CGRect(origin: lhs*rhs.origin, size: lhs*rhs.size) } public func *=(lhs: inout CGRect, rhs: CGFloat) { lhs.origin *= rhs lhs.size *= rhs } public func /(lhs: CGRect, rhs: CGFloat) -> CGRect { return CGRect(origin: lhs.origin/rhs, size: lhs.size/rhs) } public func /=(lhs: inout CGRect, rhs: CGFloat) { lhs.origin /= rhs lhs.size /= rhs } public func +(lhs: CGRect, rhs: CGPoint) -> CGRect { return lhs.offsetBy(dx: rhs.x, dy: rhs.y) } public func -(lhs: CGRect, rhs: CGPoint) -> CGRect { return lhs.offsetBy(dx: -rhs.x, dy: -rhs.y) } public func +(lhs: CGRect, rhs: CGSize) -> CGRect { return CGRect(origin: lhs.origin, size: lhs.size+rhs) } public func -(lhs: CGRect, rhs: CGSize) -> CGRect { return CGRect(origin: lhs.origin, size: lhs.size-rhs) } // MARK: - helpers /// Determines whether the second vector is above > 0 or below < 0 the first one public func *(lhs: CGPoint, rhs: CGPoint ) -> CGFloat { return lhs.x*rhs.y - lhs.y*rhs.x } /// smallest angle between 2 angles public func arcFi( _ fi1: CGFloat, fi2: CGFloat ) -> CGFloat { let p = CGPoint(x: cos(fi1)-cos(fi2), y: sin(fi1)-sin(fi2)) let dSqr = p.x*p.x + p.y*p.y let fi = acos(1-dSqr/2) return fi } /// whether fi2 is larger than fi1 in reference to the ref angle public func compareAngles( _ ref: CGFloat, fi1: CGFloat, fi2: CGFloat ) -> CGFloat { return -arcFi(ref, fi2: fi1)+arcFi(ref, fi2: fi2) } /// intersection public func lineIntersection( segmentStart p1:CGPoint, segmentEnd p2:CGPoint, lineStart p3:CGPoint, lineEnd p4:CGPoint, insideSegment: Bool = true, lineIsSegment: Bool = false, hardUpperLimit: Bool = false ) -> CGPoint? { let parallel = CGFloat(p1.x-p2.x)*CGFloat(p3.y-p4.y) - CGFloat(p1.y-p2.y)*CGFloat(p3.x-p4.x) == 0 if parallel == false { let x: CGFloat = CGFloat(CGFloat(CGFloat(p1.x*p2.y) - CGFloat(p1.y*p2.x))*CGFloat(p3.x-p4.x) - CGFloat(p1.x-p2.x)*CGFloat(CGFloat(p3.x*p4.y) - CGFloat(p3.y*p4.x))) / CGFloat(CGFloat(p1.x-p2.x)*CGFloat(p3.y-p4.y) - CGFloat(p1.y - p2.y)*CGFloat(p3.x-p4.x)) let y: CGFloat = CGFloat(CGFloat(CGFloat(p1.x*p2.y) - CGFloat(p1.y*p2.x))*CGFloat(p3.y-p4.y) - CGFloat(p1.y-p2.y)*CGFloat(CGFloat(p3.x*p4.y) - CGFloat(p3.y*p4.x))) / CGFloat(CGFloat(p1.x-p2.x)*CGFloat(p3.y-p4.y) - CGFloat(p1.y - p2.y)*CGFloat(p3.x-p4.x)) let intersection = CGPoint( x: x, y: y ) if insideSegment { let u = p2.x == p1.x ? 0 : (intersection.x - p1.x) / (p2.x - p1.x) let v = p2.y == p1.y ? 0 : (intersection.y - p1.y) / (p2.y - p1.y) if u<0 || v<0 || v>1 || u>1 || hardUpperLimit && (v>=1 || u>=1) { return nil } if lineIsSegment { let w = p4.x == p3.x ? 0 : (intersection.y - p3.x) / (p4.x - p3.x) let x = p4.y == p3.y ? 0 : (intersection.y - p3.y) / (p4.y - p3.y) if w<0 || x<0 || w>1 || x>1 || hardUpperLimit && (w>=1 || x>=1) { return nil } } } return intersection } return nil } public func segmentsIntersection(_ segment1: (CGPoint, CGPoint), _ segment2: (CGPoint, CGPoint)) -> CGPoint? { return lineIntersection(segmentStart: segment1.0, segmentEnd: segment1.1, lineStart: segment2.0, lineEnd: segment2.1, insideSegment: true, lineIsSegment: true, hardUpperLimit: true) } /// center of circle through points public func circleCenter(_ p0: CGPoint, p1: CGPoint, p2: CGPoint) -> CGPoint? { let p01 = (p0+p1)/2 // midpoint let p12 = (p1+p2)/2 let t01 = p1-p0 // parallel -> tangent let t12 = p2-p1 return lineIntersection( segmentStart: p01, segmentEnd: p01 + CGPoint(x: -t01.y, y: t01.x), lineStart: p12, lineEnd: p12 + CGPoint(x: -t12.y, y: t12.x), insideSegment: false) } // MARK: - extensions extension CGFloat { static let Pi = CGFloat(Double.pi) static let Pi2 = CGFloat(Double.pi)/2 static let Phi = CGFloat(1.618033988749894848204586834) static public func random(_ d:CGFloat = 1) -> CGFloat { return CGFloat(arc4random())/CGFloat(UInt32.max) * d } } extension CGRect { var topLeft: CGPoint { return CGPoint(x: self.minX, y: self.minY) } var topRight: CGPoint { return CGPoint(x: self.maxX, y: self.minY) } var bottomLeft: CGPoint { return CGPoint(x: self.minX, y: self.maxY) } var bottomRight: CGPoint { return CGPoint(x: self.maxX, y: self.maxY) } var topMiddle: CGPoint { return CGPoint(x: self.midX, y: self.minY) } var bottomMiddle: CGPoint { return CGPoint(x: self.midX, y: self.maxY) } var middleLeft: CGPoint { return CGPoint(x: self.minX, y: self.midY) } var middleRight: CGPoint { return CGPoint(x: self.maxX, y: self.midY) } var center: CGPoint { return CGPoint(x: self.midX, y: self.midY) } public func transformed(_ t: CGAffineTransform) -> CGRect { return self.applying(t) } public func insetWith(_ insets: UIEdgeInsets) -> CGRect { return self.inset(by: insets) } } extension CGPoint { /// distance to another point public func distanceTo(_ point: CGPoint) -> CGFloat { return sqrt(pow(self.x-point.x, 2) + pow(self.y-point.y, 2)) } public func integral() -> CGPoint { return CGPoint(x: round(self.x), y: round(self.y)) } mutating public func integrate() { self.x = round(self.x) self.y = round(self.y) } public func transformed(_ t: CGAffineTransform) -> CGPoint { return self.applying(t) } public func normalized() -> CGPoint { if self == .zero { return CGPoint(x: 1, y: 0) } return self/self.distanceTo(.zero) } } extension CGVector { init(point: CGPoint) { self.init() self.dx = point.x self.dy = point.y } init(size: CGSize) { self.init() self.dx = size.width self.dy = size.height } var length: CGFloat { return sqrt(self.dx*self.dx+self.dy*self.dy) } } extension CGPoint { init(vector: CGVector) { self.init() self.x = vector.dx self.y = vector.dy } } extension CGSize { public func integral() -> CGSize { var s = self s.integrate() return s } mutating public func integrate() { self.width = round(self.width) self.height = round(self.height) } }
mit
430631d2ec51be51e6d09aab9b2d54ef
24.150943
256
0.651257
2.829398
false
false
false
false
ontouchstart/swift3-playground
Learn to Code 2.playgroundbook/Contents/Chapters/Document11.playgroundchapter/Pages/Challenge2.playgroundpage/Sources/SetUp.swift
1
2704
// // SetUp.swift // // Copyright (c) 2016 Apple Inc. All Rights Reserved. // import Foundation // MARK: Globals //public let world = GridWorld(columns: 9, rows: 5) public let world = loadGridWorld(named: "11.5") public func playgroundPrologue() { placeItems() placeLocks() placeMissingStairs() // Must be called in `playgroundPrologue()` to update with the current page contents. registerAssessment(world, assessment: assessmentPoint) //// ---- // Any items added or removed after this call will be animated. finalizeWorldBuilding(for: world) //// ---- } // Called from LiveView.swift to initially set the LiveView. public func presentWorld() { setUpLiveViewWith(world) } // MARK: Epilogue public func playgroundEpilogue() { sendCommands(for: world) } // MARK: Placement func placeMissingStairs() { world.place(Stair(), facing: south, at: Coordinate(column: 7, row: 1)) world.place(Stair(), facing: north, at: Coordinate(column: 7, row: 3)) } func placeBlocks() { world.removeNodes(at: world.coordinates(inColumns: 2...6, intersectingRows: [1,3])) world.removeNodes(at: world.coordinates(inColumns: [3,5], intersectingRows: [2])) world.placeWater(at: world.coordinates(inColumns: 2...6, intersectingRows: [1,3])) world.placeWater(at: world.coordinates(inColumns: [3,5], intersectingRows: [2])) world.placeBlocks(at: world.coordinates(inColumns:[1,7])) world.placeBlocks(at: world.coordinates(inColumns: [0,1,7,8], intersectingRows: [2])) world.placeBlocks(at: world.coordinates(inColumns: [0,8], intersectingRows: [2])) world.place(Stair(), facing: south, at: Coordinate(column: 1, row: 1)) world.place(Stair(), facing: north, at: Coordinate(column: 1, row: 3)) world.place(nodeOfType: Stair.self, facing: east, at: world.coordinates(inColumns: [2], intersectingRows: [0,4])) world.place(nodeOfType: Stair.self, facing: west, at: world.coordinates(inColumns: [6], intersectingRows: [0,4])) } func placeItems() { world.placeGems(at: [Coordinate(column: 4, row: 2)]) world.place(nodeOfType: Switch.self, at: [Coordinate(column: 2, row: 2)]) } func placeLocks() { let lock = PlatformLock(color: .pink) world.place(lock, facing: east, at: Coordinate(column: 0, row: 2)) let lock1 = PlatformLock(color: .green) world.place(lock1, facing: west, at: Coordinate(column: 8, row: 2)) let platform1 = Platform(onLevel: 1, controlledBy: lock1) world.place(platform1, at: Coordinate(column: 3, row: 2)) let platform2 = Platform(onLevel: 4, controlledBy: lock) world.place(platform2, at: Coordinate(column: 5, row: 2)) }
mit
4ed01a69a22387ce25ae4792a8f718c1
31.578313
117
0.678994
3.480051
false
false
false
false
watson-developer-cloud/ios-sdk
Sources/DiscoveryV1/Models/Conversions.swift
1
3628
/** * (C) Copyright IBM Corp. 2018, 2020. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. **/ import Foundation /** Document conversion settings. */ public struct Conversions: Codable, Equatable { /** A list of PDF conversion settings. */ public var pdf: PDFSettings? /** A list of Word conversion settings. */ public var word: WordSettings? /** A list of HTML conversion settings. */ public var html: HTMLSettings? /** A list of Document Segmentation settings. */ public var segment: SegmentSettings? /** Defines operations that can be used to transform the final output JSON into a normalized form. Operations are executed in the order that they appear in the array. */ public var jsonNormalizations: [NormalizationOperation]? /** When `true`, automatic text extraction from images (this includes images embedded in supported document formats, for example PDF, and suppported image formats, for example TIFF) is performed on documents uploaded to the collection. This field is supported on **Advanced** and higher plans only. **Lite** plans do not support image text recognition. */ public var imageTextRecognition: Bool? // Map each property name to the key that shall be used for encoding/decoding. private enum CodingKeys: String, CodingKey { case pdf = "pdf" case word = "word" case html = "html" case segment = "segment" case jsonNormalizations = "json_normalizations" case imageTextRecognition = "image_text_recognition" } /** Initialize a `Conversions` with member variables. - parameter pdf: A list of PDF conversion settings. - parameter word: A list of Word conversion settings. - parameter html: A list of HTML conversion settings. - parameter segment: A list of Document Segmentation settings. - parameter jsonNormalizations: Defines operations that can be used to transform the final output JSON into a normalized form. Operations are executed in the order that they appear in the array. - parameter imageTextRecognition: When `true`, automatic text extraction from images (this includes images embedded in supported document formats, for example PDF, and suppported image formats, for example TIFF) is performed on documents uploaded to the collection. This field is supported on **Advanced** and higher plans only. **Lite** plans do not support image text recognition. - returns: An initialized `Conversions`. */ public init( pdf: PDFSettings? = nil, word: WordSettings? = nil, html: HTMLSettings? = nil, segment: SegmentSettings? = nil, jsonNormalizations: [NormalizationOperation]? = nil, imageTextRecognition: Bool? = nil ) { self.pdf = pdf self.word = word self.html = html self.segment = segment self.jsonNormalizations = jsonNormalizations self.imageTextRecognition = imageTextRecognition } }
apache-2.0
ef78e47c2f77734b70d0eb1612d0ea8a
34.920792
121
0.68495
4.843792
false
false
false
false
Xiomara7/cv
Xiomara-Figueroa/ExtraViewController.swift
1
4344
// // ExtraViewController.swift // Xiomara-Figueroa // // Created by Xiomara on 4/25/15. // Copyright (c) 2015 UPRRP. All rights reserved. // import UIKit class ExtraViewController: UIViewController, UICollectionViewDelegateFlowLayout, UICollectionViewDataSource { var collectionView: UICollectionView! var screenWidth: CGFloat! var screenHeight: CGFloat! init() { super.init(nibName: nil, bundle: nil) self.title = "Outreach" } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() self.navigationController?.navigationBar.tintColor = UIColor.blackColor() self.navigationItem.leftBarButtonItem = UIBarButtonItem(image: UIImage(named:"cancel"), style:.Done, target:self, action:Selector("dismissAction:")) screenWidth = UIScreen.mainScreen().bounds.width screenHeight = UIScreen.mainScreen().bounds.height let imgSize = UIImage(named: "extra_1")?.size let layout = UICollectionViewFlowLayout() layout.sectionInset = UIEdgeInsets(top: 20.0, left: 20.0, bottom: 20.0, right: 20.0) layout.itemSize = imgSize! layout.scrollDirection = .Horizontal collectionView = UICollectionView(frame: CGRectMake(0.0, 0.0, screenWidth, screenHeight), collectionViewLayout: layout) collectionView.delegate = self collectionView.dataSource = self collectionView!.registerClass(UICollectionViewCell.self, forCellWithReuseIdentifier: "Cell") collectionView?.pagingEnabled = false collectionView?.backgroundColor = UIColor.whiteColor() self.view.addSubview(collectionView!) } class addImage: UIImageView { init(frame:CGRect, imageName: String) { super.init(frame:frame) self.image = UIImage(named:imageName) self.contentMode = .ScaleToFill } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } // Mark: - Selector Methods func dismissAction(sender: AnyObject?) { self.dismissViewControllerAnimated(true, completion: nil) } // Mark: - Collection View DataSource Methods func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return 1 } func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int { return DataManager.shared.extraImages.count } // Mark: - Collection View Delegate Methods func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCellWithReuseIdentifier("Cell", forIndexPath: indexPath) as! UICollectionViewCell let img = DataManager.shared.extraImages[indexPath.section] as! String cell.backgroundView = addImage(frame: cell.bounds, imageName: img) return cell } func collectionView(collectionView: UICollectionView, didHighlightItemAtIndexPath indexPath: NSIndexPath) { let cell = collectionView.cellForItemAtIndexPath(indexPath) let img = DataManager.shared.extraImagesInfo[indexPath.section] as! String let imgView = addImage(frame: cell!.bounds, imageName: img) cell?.backgroundView?.addSubview(imgView) collectionView.selectItemAtIndexPath(indexPath, animated: true, scrollPosition:.CenteredHorizontally) } func collectionView(collectionView: UICollectionView, didUnhighlightItemAtIndexPath indexPath: NSIndexPath) { let cell = collectionView.cellForItemAtIndexPath(indexPath) let img = DataManager.shared.extraImages[indexPath.section] as! String cell!.backgroundView = addImage(frame:cell!.bounds, imageName:img) } }
mit
fc3065c40629a892bfe8100ac642a1a7
34.909091
130
0.638812
5.807487
false
false
false
false
Popdeem/Popdeem-SDK-iOS
Carthage/Checkouts/facebook-ios-sdk/samples/HelloTV/HelloTV/FirstViewController.swift
1
4240
// Copyright (c) 2014-present, Facebook, Inc. All rights reserved. // // You are hereby granted a non-exclusive, worldwide, royalty-free license to use, // copy, modify, and distribute this software in source code or binary form for use // in connection with the web services and APIs provided by Facebook. // // As with any software that integrates with the Facebook platform, your use of // this software is subject to the Facebook Developer Principles and Policies // [http://developers.facebook.com/policy/]. This copyright notice shall be // included in all copies or substantial portions of the software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS // FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR // COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER // IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN // CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. import UIKit import FBSDKShareKit import FBSDKTVOSKit class FirstViewController: UIViewController { @IBOutlet private weak var imageView: UIImageView? @IBOutlet private weak var loginButton: FBSDKDeviceLoginButton? @IBOutlet private weak var shareButton: FBSDKDeviceShareButton? private var blankImage: UIImage? override func viewDidLoad() { super.viewDidLoad() loginButton?.delegate = self blankImage = imageView?.image // Subscribe to FB session changes (in case they logged in or out in the second tab) NSNotificationCenter.defaultCenter().addObserverForName( FBSDKAccessTokenDidChangeNotification, object: nil, queue: NSOperationQueue.mainQueue()) { (notification) -> Void in self.updateContent() } // If the user is already logged in. if FBSDKAccessToken.currentAccessToken() != nil { updateContent() } let linkContent = FBSDKShareLinkContent() linkContent.contentURL = NSURL(string: "https://developers.facebook.com/docs/tvos") linkContent.contentDescription = "Let's build a tvOS app with Facebook!" shareButton?.shareContent = linkContent } private func flipImageViewToImage(image: UIImage?) { guard let imageView = imageView else { return } UIView.transitionWithView(imageView, duration: 1, options:.TransitionCrossDissolve, animations: { () -> Void in self.imageView?.image = image }, completion: nil) } private func updateContent() { guard let imageView = imageView else { return } guard FBSDKAccessToken.currentAccessToken() != nil else { imageView.image = blankImage return } // Download the user's profile image. Usually Facebook Graph API // should be accessed via `FBSDKGraphRequest` except for binary data (like the image). let urlString = String( format: "https://graph.facebook.com/v2.5/me/picture?type=square&width=%d&height=%d&access_token=%@", Int(imageView.bounds.size.width), Int(imageView.bounds.size.height), FBSDKAccessToken.currentAccessToken().tokenString) let url = NSURL(string: urlString) let userImage = UIImage(data: NSData(contentsOfURL: url!)!) flipImageViewToImage(userImage!) } } extension FirstViewController: FBSDKDeviceLoginButtonDelegate { func deviceLoginButtonDidCancel(button: FBSDKDeviceLoginButton) { print("Login cancelled") } func deviceLoginButtonDidLogIn(button: FBSDKDeviceLoginButton) { print("Login complete") updateContent() } func deviceLoginButtonDidLogOut(button: FBSDKDeviceLoginButton) { print("Logout complete") flipImageViewToImage(blankImage) } func deviceLoginButtonDidFail(button: FBSDKDeviceLoginButton, error: NSError) { print("Login error : ", error) } } extension FirstViewController: FBSDKDeviceShareViewControllerDelegate { func deviceShareViewControllerDidComplete(viewController: FBSDKDeviceShareViewController, error: NSError?) { print("Device share finished with error?", error) } }
mit
cdcf415390604f498a20be614108335f
36.192982
110
0.721226
5.139394
false
false
false
false
steelwheels/Canary
Source/CNPathExpression.swift
1
652
/** * @file CNPathExpression.swift * @brief Define CNPathExpression class * @par Copyright * Copyright (C) 2017 Steel Wheels Project */ import Foundation public class CNPathExpression { public var pathElements: Array<String> public init(){ pathElements = [] } public init(pathElements elms: Array<String>){ pathElements = elms } public var description: String { get { var result = "" var is1st = true for elm in pathElements { if is1st { is1st = false } else { result += "." } result += elm } return result } } public func append(path str:String){ pathElements.append(str) } }
gpl-2.0
174b1532d6e615ae040a902a002cbc79
14.52381
47
0.642638
3.134615
false
false
false
false