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
ShauryaS/Brain-Stimulator
ios/Brain Stimulator/Brain Stimulator/Profile.swift
1
2405
// // Profile.swift // Brain Stimulator // // Created by Shaurya Srivastava on 6/12/17. // Copyright © 2017 Shaurya Srivastava. All rights reserved. // import Foundation import UIKit import Firebase class Profile: UIViewController{ @IBOutlet var userLab: UILabel! @IBOutlet var typeLab: UILabel! @IBOutlet var pointsLab: UILabel! @IBOutlet var gamesPlayedLab: UILabel! @IBOutlet var daysLab: UILabel! @IBOutlet var burstLab: UILabel! @IBOutlet var burstTF: UITextField! override func viewDidLoad() { super.viewDidLoad() userLab.text = username if isTherapist == true{ typeLab.text = "Account Type: Therapist" } else{ typeLab.text = "Account Type: Client" } pointsLab.text = "Points: " + String(points) gamesPlayedLab.text = "Games Played: " + String(gamesPlayed) //daysLab.text = "Days Played: " + String(days) burstLab.text = "Burst: " self.view.backgroundColor = bgColor navigationItem.title = "Profile" let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(LogIn.dismissKeyboard)) view.addGestureRecognizer(tap) } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) userLab.textColor = fontColor typeLab.textColor = fontColor pointsLab.textColor = fontColor gamesPlayedLab.textColor = fontColor daysLab.textColor = fontColor burstLab.textColor = fontColor burstTF.textColor = fontColor burstTF.attributedPlaceholder = NSAttributedString(string:String(gameburst), attributes:[NSForegroundColorAttributeName: fontColor]) } //Calls this function when the tap is recognized. func dismissKeyboard() { //Causes the view (or one of its embedded text fields) to resign the first responder status. view.endEditing(true) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "settomainseg" { firebaseRef.child("users").child(uid).updateChildValues(["gameBurst": Int(burstTF.text!) ?? gameburst]) } } }
apache-2.0
3bb9bf7736cc598a81591d5a18a54d71
32.388889
140
0.656822
4.55303
false
false
false
false
t089/sajson
swift/sajson/Decodable/_Decodable.swift
1
129401
// // Decodable.swift // // Created by Tobias Haeberle on 05.07.17. // Copyright © 2017 Tobias Haeberle. All rights reserved. // import Foundation #if !swift(>=3.2) // The decodable protocol is available in Swift 3.2. /// A type that can decode itself from an external representation. public protocol Decodable { /// Creates a new instance by decoding from the given decoder. /// /// This initializer throws an error if reading from the decoder fails, or /// if the data read is corrupted or otherwise invalid. /// /// - Parameter decoder: The decoder to read data from. init(from decoder: Decoder) throws } /// A type that can be used as a key for encoding and decoding. public protocol CodingKey { /// The string to use in a named collection (e.g. a string-keyed dictionary). var stringValue: String { get } /// Initializes `self` from a string. /// /// - parameter stringValue: The string value of the desired key. /// - returns: An instance of `Self` from the given string, or `nil` if the given string does not correspond to any instance of `Self`. init?(stringValue: String) /// The int to use in an indexed collection (e.g. an int-keyed dictionary). var intValue: Int? { get } /// Initializes `self` from an integer. /// /// - parameter intValue: The integer value of the desired key. /// - returns: An instance of `Self` from the given integer, or `nil` if the given integer does not correspond to any instance of `Self`. init?(intValue: Int) } /// A type that can decode values from a native format into in-memory representations. public protocol Decoder { /// The path of coding keys taken to get to this point in decoding. /// A `nil` value indicates an unkeyed container. var codingPath: [CodingKey] { get } /// Any contextual information set by the user for decoding. var userInfo: [CodingUserInfoKey : Any] { get } /// Returns the data stored in `self` as represented in a container keyed by the given key type. /// /// - parameter type: The key type to use for the container. /// - returns: A keyed decoding container view into `self`. /// - throws: `DecodingError.typeMismatch` if the encountered stored value is not a keyed container. func container<Key>(keyedBy type: Key.Type) throws -> KeyedDecodingContainer<Key> /// Returns the data stored in `self` as represented in a container appropriate for holding values with no keys. /// /// - returns: An unkeyed container view into `self`. /// - throws: `DecodingError.typeMismatch` if the encountered stored value is not an unkeyed container. func unkeyedContainer() throws -> UnkeyedDecodingContainer /// Returns the data stored in `self` as represented in a container appropriate for holding a single primitive value. /// /// - returns: A single value container view into `self`. /// - throws: `DecodingError.typeMismatch` if the encountered stored value is not a single value container. func singleValueContainer() throws -> SingleValueDecodingContainer } /// A type that provides a view into a decoder's storage and is used to hold /// the encoded properties of a decodable type in a keyed manner. /// /// Decoders should provide types conforming to `UnkeyedDecodingContainer` for /// their format. public protocol KeyedDecodingContainerProtocol { associatedtype Key : CodingKey /// The path of coding keys taken to get to this point in decoding. /// A `nil` value indicates an unkeyed container. var codingPath: [CodingKey] { get } /// All the keys the `Decoder` has for this container. /// /// Different keyed containers from the same `Decoder` may return different keys here; it is possible to encode with multiple key types which are not convertible to one another. This should report all keys present which are convertible to the requested type. var allKeys: [Key] { get } /// Returns whether the `Decoder` contains a value associated with the given key. /// /// The value associated with the given key may be a null value as appropriate for the data format. /// /// - parameter key: The key to search for. /// - returns: Whether the `Decoder` has an entry for the given key. func contains(_ key: Key) -> Bool /// Decodes a null value for the given key. /// /// - parameter key: The key that the decoded value is associated with. /// - returns: Whether the encountered value was null. /// - throws: `DecodingError.keyNotFound` if `self` does not have an entry for the given key. func decodeNil(forKey key: Key) throws -> Bool /// Decodes a value of the given type for the given key. /// /// - parameter type: The type of value to decode. /// - parameter key: The key that the decoded value is associated with. /// - returns: A value of the requested type, if present for the given key and convertible to the requested type. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value is not convertible to the requested type. /// - throws: `DecodingError.keyNotFound` if `self` does not have an entry for the given key. /// - throws: `DecodingError.valueNotFound` if `self` has a null entry for the given key. func decode(_ type: Bool.Type, forKey key: Key) throws -> Bool /// Decodes a value of the given type for the given key. /// /// - parameter type: The type of value to decode. /// - parameter key: The key that the decoded value is associated with. /// - returns: A value of the requested type, if present for the given key and convertible to the requested type. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value is not convertible to the requested type. /// - throws: `DecodingError.keyNotFound` if `self` does not have an entry for the given key. /// - throws: `DecodingError.valueNotFound` if `self` has a null entry for the given key. func decode(_ type: Int.Type, forKey key: Key) throws -> Int /// Decodes a value of the given type for the given key. /// /// - parameter type: The type of value to decode. /// - parameter key: The key that the decoded value is associated with. /// - returns: A value of the requested type, if present for the given key and convertible to the requested type. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value is not convertible to the requested type. /// - throws: `DecodingError.keyNotFound` if `self` does not have an entry for the given key. /// - throws: `DecodingError.valueNotFound` if `self` has a null entry for the given key. func decode(_ type: Int8.Type, forKey key: Key) throws -> Int8 /// Decodes a value of the given type for the given key. /// /// - parameter type: The type of value to decode. /// - parameter key: The key that the decoded value is associated with. /// - returns: A value of the requested type, if present for the given key and convertible to the requested type. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value is not convertible to the requested type. /// - throws: `DecodingError.keyNotFound` if `self` does not have an entry for the given key. /// - throws: `DecodingError.valueNotFound` if `self` has a null entry for the given key. func decode(_ type: Int16.Type, forKey key: Key) throws -> Int16 /// Decodes a value of the given type for the given key. /// /// - parameter type: The type of value to decode. /// - parameter key: The key that the decoded value is associated with. /// - returns: A value of the requested type, if present for the given key and convertible to the requested type. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value is not convertible to the requested type. /// - throws: `DecodingError.keyNotFound` if `self` does not have an entry for the given key. /// - throws: `DecodingError.valueNotFound` if `self` has a null entry for the given key. func decode(_ type: Int32.Type, forKey key: Key) throws -> Int32 /// Decodes a value of the given type for the given key. /// /// - parameter type: The type of value to decode. /// - parameter key: The key that the decoded value is associated with. /// - returns: A value of the requested type, if present for the given key and convertible to the requested type. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value is not convertible to the requested type. /// - throws: `DecodingError.keyNotFound` if `self` does not have an entry for the given key. /// - throws: `DecodingError.valueNotFound` if `self` has a null entry for the given key. func decode(_ type: Int64.Type, forKey key: Key) throws -> Int64 /// Decodes a value of the given type for the given key. /// /// - parameter type: The type of value to decode. /// - parameter key: The key that the decoded value is associated with. /// - returns: A value of the requested type, if present for the given key and convertible to the requested type. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value is not convertible to the requested type. /// - throws: `DecodingError.keyNotFound` if `self` does not have an entry for the given key. /// - throws: `DecodingError.valueNotFound` if `self` has a null entry for the given key. func decode(_ type: UInt.Type, forKey key: Key) throws -> UInt /// Decodes a value of the given type for the given key. /// /// - parameter type: The type of value to decode. /// - parameter key: The key that the decoded value is associated with. /// - returns: A value of the requested type, if present for the given key and convertible to the requested type. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value is not convertible to the requested type. /// - throws: `DecodingError.keyNotFound` if `self` does not have an entry for the given key. /// - throws: `DecodingError.valueNotFound` if `self` has a null entry for the given key. func decode(_ type: UInt8.Type, forKey key: Key) throws -> UInt8 /// Decodes a value of the given type for the given key. /// /// - parameter type: The type of value to decode. /// - parameter key: The key that the decoded value is associated with. /// - returns: A value of the requested type, if present for the given key and convertible to the requested type. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value is not convertible to the requested type. /// - throws: `DecodingError.keyNotFound` if `self` does not have an entry for the given key. /// - throws: `DecodingError.valueNotFound` if `self` has a null entry for the given key. func decode(_ type: UInt16.Type, forKey key: Key) throws -> UInt16 /// Decodes a value of the given type for the given key. /// /// - parameter type: The type of value to decode. /// - parameter key: The key that the decoded value is associated with. /// - returns: A value of the requested type, if present for the given key and convertible to the requested type. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value is not convertible to the requested type. /// - throws: `DecodingError.keyNotFound` if `self` does not have an entry for the given key. /// - throws: `DecodingError.valueNotFound` if `self` has a null entry for the given key. func decode(_ type: UInt32.Type, forKey key: Key) throws -> UInt32 /// Decodes a value of the given type for the given key. /// /// - parameter type: The type of value to decode. /// - parameter key: The key that the decoded value is associated with. /// - returns: A value of the requested type, if present for the given key and convertible to the requested type. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value is not convertible to the requested type. /// - throws: `DecodingError.keyNotFound` if `self` does not have an entry for the given key. /// - throws: `DecodingError.valueNotFound` if `self` has a null entry for the given key. func decode(_ type: UInt64.Type, forKey key: Key) throws -> UInt64 /// Decodes a value of the given type for the given key. /// /// - parameter type: The type of value to decode. /// - parameter key: The key that the decoded value is associated with. /// - returns: A value of the requested type, if present for the given key and convertible to the requested type. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value is not convertible to the requested type. /// - throws: `DecodingError.keyNotFound` if `self` does not have an entry for the given key. /// - throws: `DecodingError.valueNotFound` if `self` has a null entry for the given key. func decode(_ type: Float.Type, forKey key: Key) throws -> Float /// Decodes a value of the given type for the given key. /// /// - parameter type: The type of value to decode. /// - parameter key: The key that the decoded value is associated with. /// - returns: A value of the requested type, if present for the given key and convertible to the requested type. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value is not convertible to the requested type. /// - throws: `DecodingError.keyNotFound` if `self` does not have an entry for the given key. /// - throws: `DecodingError.valueNotFound` if `self` has a null entry for the given key. func decode(_ type: Double.Type, forKey key: Key) throws -> Double /// Decodes a value of the given type for the given key. /// /// - parameter type: The type of value to decode. /// - parameter key: The key that the decoded value is associated with. /// - returns: A value of the requested type, if present for the given key and convertible to the requested type. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value is not convertible to the requested type. /// - throws: `DecodingError.keyNotFound` if `self` does not have an entry for the given key. /// - throws: `DecodingError.valueNotFound` if `self` has a null entry for the given key. func decode(_ type: String.Type, forKey key: Key) throws -> String /// Decodes a value of the given type for the given key. /// /// - parameter type: The type of value to decode. /// - parameter key: The key that the decoded value is associated with. /// - returns: A value of the requested type, if present for the given key and convertible to the requested type. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value is not convertible to the requested type. /// - throws: `DecodingError.keyNotFound` if `self` does not have an entry for the given key. /// - throws: `DecodingError.valueNotFound` if `self` has a null entry for the given key. func decode<T : Decodable>(_ type: T.Type, forKey key: Key) throws -> T /// Decodes a value of the given type for the given key, if present. /// /// This method returns `nil` if the container does not have a value associated with `key`, or if the value is null. The difference between these states can be distinguished with a `contains(_:)` call. /// /// - parameter type: The type of value to decode. /// - parameter key: The key that the decoded value is associated with. /// - returns: A decoded value of the requested type, or `nil` if the `Decoder` does not have an entry associated with the given key, or if the value is a null value. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value is not convertible to the requested type. func decodeIfPresent(_ type: Bool.Type, forKey key: Key) throws -> Bool? /// Decodes a value of the given type for the given key, if present. /// /// This method returns `nil` if the container does not have a value associated with `key`, or if the value is null. The difference between these states can be distinguished with a `contains(_:)` call. /// /// - parameter type: The type of value to decode. /// - parameter key: The key that the decoded value is associated with. /// - returns: A decoded value of the requested type, or `nil` if the `Decoder` does not have an entry associated with the given key, or if the value is a null value. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value is not convertible to the requested type. func decodeIfPresent(_ type: Int.Type, forKey key: Key) throws -> Int? /// Decodes a value of the given type for the given key, if present. /// /// This method returns `nil` if the container does not have a value associated with `key`, or if the value is null. The difference between these states can be distinguished with a `contains(_:)` call. /// /// - parameter type: The type of value to decode. /// - parameter key: The key that the decoded value is associated with. /// - returns: A decoded value of the requested type, or `nil` if the `Decoder` does not have an entry associated with the given key, or if the value is a null value. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value is not convertible to the requested type. func decodeIfPresent(_ type: Int8.Type, forKey key: Key) throws -> Int8? /// Decodes a value of the given type for the given key, if present. /// /// This method returns `nil` if the container does not have a value associated with `key`, or if the value is null. The difference between these states can be distinguished with a `contains(_:)` call. /// /// - parameter type: The type of value to decode. /// - parameter key: The key that the decoded value is associated with. /// - returns: A decoded value of the requested type, or `nil` if the `Decoder` does not have an entry associated with the given key, or if the value is a null value. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value is not convertible to the requested type. func decodeIfPresent(_ type: Int16.Type, forKey key: Key) throws -> Int16? /// Decodes a value of the given type for the given key, if present. /// /// This method returns `nil` if the container does not have a value associated with `key`, or if the value is null. The difference between these states can be distinguished with a `contains(_:)` call. /// /// - parameter type: The type of value to decode. /// - parameter key: The key that the decoded value is associated with. /// - returns: A decoded value of the requested type, or `nil` if the `Decoder` does not have an entry associated with the given key, or if the value is a null value. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value is not convertible to the requested type. func decodeIfPresent(_ type: Int32.Type, forKey key: Key) throws -> Int32? /// Decodes a value of the given type for the given key, if present. /// /// This method returns `nil` if the container does not have a value associated with `key`, or if the value is null. The difference between these states can be distinguished with a `contains(_:)` call. /// /// - parameter type: The type of value to decode. /// - parameter key: The key that the decoded value is associated with. /// - returns: A decoded value of the requested type, or `nil` if the `Decoder` does not have an entry associated with the given key, or if the value is a null value. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value is not convertible to the requested type. func decodeIfPresent(_ type: Int64.Type, forKey key: Key) throws -> Int64? /// Decodes a value of the given type for the given key, if present. /// /// This method returns `nil` if the container does not have a value associated with `key`, or if the value is null. The difference between these states can be distinguished with a `contains(_:)` call. /// /// - parameter type: The type of value to decode. /// - parameter key: The key that the decoded value is associated with. /// - returns: A decoded value of the requested type, or `nil` if the `Decoder` does not have an entry associated with the given key, or if the value is a null value. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value is not convertible to the requested type. func decodeIfPresent(_ type: UInt.Type, forKey key: Key) throws -> UInt? /// Decodes a value of the given type for the given key, if present. /// /// This method returns `nil` if the container does not have a value associated with `key`, or if the value is null. The difference between these states can be distinguished with a `contains(_:)` call. /// /// - parameter type: The type of value to decode. /// - parameter key: The key that the decoded value is associated with. /// - returns: A decoded value of the requested type, or `nil` if the `Decoder` does not have an entry associated with the given key, or if the value is a null value. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value is not convertible to the requested type. func decodeIfPresent(_ type: UInt8.Type, forKey key: Key) throws -> UInt8? /// Decodes a value of the given type for the given key, if present. /// /// This method returns `nil` if the container does not have a value associated with `key`, or if the value is null. The difference between these states can be distinguished with a `contains(_:)` call. /// /// - parameter type: The type of value to decode. /// - parameter key: The key that the decoded value is associated with. /// - returns: A decoded value of the requested type, or `nil` if the `Decoder` does not have an entry associated with the given key, or if the value is a null value. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value is not convertible to the requested type. func decodeIfPresent(_ type: UInt16.Type, forKey key: Key) throws -> UInt16? /// Decodes a value of the given type for the given key, if present. /// /// This method returns `nil` if the container does not have a value associated with `key`, or if the value is null. The difference between these states can be distinguished with a `contains(_:)` call. /// /// - parameter type: The type of value to decode. /// - parameter key: The key that the decoded value is associated with. /// - returns: A decoded value of the requested type, or `nil` if the `Decoder` does not have an entry associated with the given key, or if the value is a null value. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value is not convertible to the requested type. func decodeIfPresent(_ type: UInt32.Type, forKey key: Key) throws -> UInt32? /// Decodes a value of the given type for the given key, if present. /// /// This method returns `nil` if the container does not have a value associated with `key`, or if the value is null. The difference between these states can be distinguished with a `contains(_:)` call. /// /// - parameter type: The type of value to decode. /// - parameter key: The key that the decoded value is associated with. /// - returns: A decoded value of the requested type, or `nil` if the `Decoder` does not have an entry associated with the given key, or if the value is a null value. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value is not convertible to the requested type. func decodeIfPresent(_ type: UInt64.Type, forKey key: Key) throws -> UInt64? /// Decodes a value of the given type for the given key, if present. /// /// This method returns `nil` if the container does not have a value associated with `key`, or if the value is null. The difference between these states can be distinguished with a `contains(_:)` call. /// /// - parameter type: The type of value to decode. /// - parameter key: The key that the decoded value is associated with. /// - returns: A decoded value of the requested type, or `nil` if the `Decoder` does not have an entry associated with the given key, or if the value is a null value. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value is not convertible to the requested type. func decodeIfPresent(_ type: Float.Type, forKey key: Key) throws -> Float? /// Decodes a value of the given type for the given key, if present. /// /// This method returns `nil` if the container does not have a value associated with `key`, or if the value is null. The difference between these states can be distinguished with a `contains(_:)` call. /// /// - parameter type: The type of value to decode. /// - parameter key: The key that the decoded value is associated with. /// - returns: A decoded value of the requested type, or `nil` if the `Decoder` does not have an entry associated with the given key, or if the value is a null value. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value is not convertible to the requested type. func decodeIfPresent(_ type: Double.Type, forKey key: Key) throws -> Double? /// Decodes a value of the given type for the given key, if present. /// /// This method returns `nil` if the container does not have a value associated with `key`, or if the value is null. The difference between these states can be distinguished with a `contains(_:)` call. /// /// - parameter type: The type of value to decode. /// - parameter key: The key that the decoded value is associated with. /// - returns: A decoded value of the requested type, or `nil` if the `Decoder` does not have an entry associated with the given key, or if the value is a null value. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value is not convertible to the requested type. func decodeIfPresent(_ type: String.Type, forKey key: Key) throws -> String? /// Decodes a value of the given type for the given key, if present. /// /// This method returns `nil` if the container does not have a value associated with `key`, or if the value is null. The difference between these states can be distinguished with a `contains(_:)` call. /// /// - parameter type: The type of value to decode. /// - parameter key: The key that the decoded value is associated with. /// - returns: A decoded value of the requested type, or `nil` if the `Decoder` does not have an entry associated with the given key, or if the value is a null value. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value is not convertible to the requested type. func decodeIfPresent<T : Decodable>(_ type: T.Type, forKey key: Key) throws -> T? /// Returns the data stored for the given key as represented in a container keyed by the given key type. /// /// - parameter type: The key type to use for the container. /// - parameter key: The key that the nested container is associated with. /// - returns: A keyed decoding container view into `self`. /// - throws: `DecodingError.typeMismatch` if the encountered stored value is not a keyed container. func nestedContainer<NestedKey>(keyedBy type: NestedKey.Type, forKey key: Key) throws -> KeyedDecodingContainer<NestedKey> /// Returns the data stored for the given key as represented in an unkeyed container. /// /// - parameter key: The key that the nested container is associated with. /// - returns: An unkeyed decoding container view into `self`. /// - throws: `DecodingError.typeMismatch` if the encountered stored value is not an unkeyed container. func nestedUnkeyedContainer(forKey key: Key) throws -> UnkeyedDecodingContainer /// Returns a `Decoder` instance for decoding `super` from the container associated with the default `super` key. /// /// Equivalent to calling `superDecoder(forKey:)` with `Key(stringValue: "super", intValue: 0)`. /// /// - returns: A new `Decoder` to pass to `super.init(from:)`. /// - throws: `DecodingError.keyNotFound` if `self` does not have an entry for the default `super` key. /// - throws: `DecodingError.valueNotFound` if `self` has a null entry for the default `super` key. func superDecoder() throws -> Decoder /// Returns a `Decoder` instance for decoding `super` from the container associated with the given key. /// /// - parameter key: The key to decode `super` for. /// - returns: A new `Decoder` to pass to `super.init(from:)`. /// - throws: `DecodingError.keyNotFound` if `self` does not have an entry for the given key. /// - throws: `DecodingError.valueNotFound` if `self` has a null entry for the given key. func superDecoder(forKey key: Key) throws -> Decoder } // An implementation of _KeyedDecodingContainerBase and _KeyedDecodingContainerBox are given at the bottom of this file. /// A concrete container that provides a view into an decoder's storage, making /// the encoded properties of an decodable type accessible by keys. public struct KeyedDecodingContainer<K : CodingKey> : KeyedDecodingContainerProtocol { public typealias Key = K /// The container for the concrete decoder. The type is _*Base so that it's generic on the key type. @_versioned internal var _box: _KeyedDecodingContainerBase<Key> /// Initializes `self` with the given container. /// /// - parameter container: The container to hold. public init<Container : KeyedDecodingContainerProtocol>(_ container: Container) where Container.Key == Key { _box = _KeyedDecodingContainerBox(container) } /// The path of coding keys taken to get to this point in decoding. /// A `nil` value indicates an unkeyed container. public var codingPath: [CodingKey] { return _box.codingPath } /// All the keys the `Decoder` has for this container. /// /// Different keyed containers from the same `Decoder` may return different keys here; it is possible to encode with multiple key types which are not convertible to one another. This should report all keys present which are convertible to the requested type. public var allKeys: [Key] { return _box.allKeys } /// Returns whether the `Decoder` contains a value associated with the given key. /// /// The value associated with the given key may be a null value as appropriate for the data format. /// /// - parameter key: The key to search for. /// - returns: Whether the `Decoder` has an entry for the given key. public func contains(_ key: Key) -> Bool { return _box.contains(key) } /// Decodes a null value for the given key. /// /// - parameter key: The key that the decoded value is associated with. /// - returns: Whether the encountered value was null. /// - throws: `DecodingError.keyNotFound` if `self` does not have an entry for the given key. public func decodeNil(forKey key: Key) throws -> Bool { return try _box.decodeNil(forKey: key) } /// Decodes a value of the given type for the given key. /// /// - parameter type: The type of value to decode. /// - parameter key: The key that the decoded value is associated with. /// - returns: A value of the requested type, if present for the given key and convertible to the requested type. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value is not convertible to the requested type. /// - throws: `DecodingError.keyNotFound` if `self` does not have an entry for the given key. /// - throws: `DecodingError.valueNotFound` if `self` has a null entry for the given key. public func decode(_ type: Bool.Type, forKey key: Key) throws -> Bool { return try _box.decode(Bool.self, forKey: key) } /// Decodes a value of the given type for the given key. /// /// - parameter type: The type of value to decode. /// - parameter key: The key that the decoded value is associated with. /// - returns: A value of the requested type, if present for the given key and convertible to the requested type. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value is not convertible to the requested type. /// - throws: `DecodingError.keyNotFound` if `self` does not have an entry for the given key. /// - throws: `DecodingError.valueNotFound` if `self` has a null entry for the given key. public func decode(_ type: Int.Type, forKey key: Key) throws -> Int { return try _box.decode(Int.self, forKey: key) } /// Decodes a value of the given type for the given key. /// /// - parameter type: The type of value to decode. /// - parameter key: The key that the decoded value is associated with. /// - returns: A value of the requested type, if present for the given key and convertible to the requested type. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value is not convertible to the requested type. /// - throws: `DecodingError.keyNotFound` if `self` does not have an entry for the given key. /// - throws: `DecodingError.valueNotFound` if `self` has a null entry for the given key. public func decode(_ type: Int8.Type, forKey key: Key) throws -> Int8 { return try _box.decode(Int8.self, forKey: key) } /// Decodes a value of the given type for the given key. /// /// - parameter type: The type of value to decode. /// - parameter key: The key that the decoded value is associated with. /// - returns: A value of the requested type, if present for the given key and convertible to the requested type. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value is not convertible to the requested type. /// - throws: `DecodingError.keyNotFound` if `self` does not have an entry for the given key. /// - throws: `DecodingError.valueNotFound` if `self` has a null entry for the given key. public func decode(_ type: Int16.Type, forKey key: Key) throws -> Int16 { return try _box.decode(Int16.self, forKey: key) } /// Decodes a value of the given type for the given key. /// /// - parameter type: The type of value to decode. /// - parameter key: The key that the decoded value is associated with. /// - returns: A value of the requested type, if present for the given key and convertible to the requested type. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value is not convertible to the requested type. /// - throws: `DecodingError.keyNotFound` if `self` does not have an entry for the given key. /// - throws: `DecodingError.valueNotFound` if `self` has a null entry for the given key. public func decode(_ type: Int32.Type, forKey key: Key) throws -> Int32 { return try _box.decode(Int32.self, forKey: key) } /// Decodes a value of the given type for the given key. /// /// - parameter type: The type of value to decode. /// - parameter key: The key that the decoded value is associated with. /// - returns: A value of the requested type, if present for the given key and convertible to the requested type. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value is not convertible to the requested type. /// - throws: `DecodingError.keyNotFound` if `self` does not have an entry for the given key. /// - throws: `DecodingError.valueNotFound` if `self` has a null entry for the given key. public func decode(_ type: Int64.Type, forKey key: Key) throws -> Int64 { return try _box.decode(Int64.self, forKey: key) } /// Decodes a value of the given type for the given key. /// /// - parameter type: The type of value to decode. /// - parameter key: The key that the decoded value is associated with. /// - returns: A value of the requested type, if present for the given key and convertible to the requested type. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value is not convertible to the requested type. /// - throws: `DecodingError.keyNotFound` if `self` does not have an entry for the given key. /// - throws: `DecodingError.valueNotFound` if `self` has a null entry for the given key. public func decode(_ type: UInt.Type, forKey key: Key) throws -> UInt { return try _box.decode(UInt.self, forKey: key) } /// Decodes a value of the given type for the given key. /// /// - parameter type: The type of value to decode. /// - parameter key: The key that the decoded value is associated with. /// - returns: A value of the requested type, if present for the given key and convertible to the requested type. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value is not convertible to the requested type. /// - throws: `DecodingError.keyNotFound` if `self` does not have an entry for the given key. /// - throws: `DecodingError.valueNotFound` if `self` has a null entry for the given key. public func decode(_ type: UInt8.Type, forKey key: Key) throws -> UInt8 { return try _box.decode(UInt8.self, forKey: key) } /// Decodes a value of the given type for the given key. /// /// - parameter type: The type of value to decode. /// - parameter key: The key that the decoded value is associated with. /// - returns: A value of the requested type, if present for the given key and convertible to the requested type. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value is not convertible to the requested type. /// - throws: `DecodingError.keyNotFound` if `self` does not have an entry for the given key. /// - throws: `DecodingError.valueNotFound` if `self` has a null entry for the given key. public func decode(_ type: UInt16.Type, forKey key: Key) throws -> UInt16 { return try _box.decode(UInt16.self, forKey: key) } /// Decodes a value of the given type for the given key. /// /// - parameter type: The type of value to decode. /// - parameter key: The key that the decoded value is associated with. /// - returns: A value of the requested type, if present for the given key and convertible to the requested type. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value is not convertible to the requested type. /// - throws: `DecodingError.keyNotFound` if `self` does not have an entry for the given key. /// - throws: `DecodingError.valueNotFound` if `self` has a null entry for the given key. public func decode(_ type: UInt32.Type, forKey key: Key) throws -> UInt32 { return try _box.decode(UInt32.self, forKey: key) } /// Decodes a value of the given type for the given key. /// /// - parameter type: The type of value to decode. /// - parameter key: The key that the decoded value is associated with. /// - returns: A value of the requested type, if present for the given key and convertible to the requested type. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value is not convertible to the requested type. /// - throws: `DecodingError.keyNotFound` if `self` does not have an entry for the given key. /// - throws: `DecodingError.valueNotFound` if `self` has a null entry for the given key. public func decode(_ type: UInt64.Type, forKey key: Key) throws -> UInt64 { return try _box.decode(UInt64.self, forKey: key) } /// Decodes a value of the given type for the given key. /// /// - parameter type: The type of value to decode. /// - parameter key: The key that the decoded value is associated with. /// - returns: A value of the requested type, if present for the given key and convertible to the requested type. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value is not convertible to the requested type. /// - throws: `DecodingError.keyNotFound` if `self` does not have an entry for the given key. /// - throws: `DecodingError.valueNotFound` if `self` has a null entry for the given key. public func decode(_ type: Float.Type, forKey key: Key) throws -> Float { return try _box.decode(Float.self, forKey: key) } /// Decodes a value of the given type for the given key. /// /// - parameter type: The type of value to decode. /// - parameter key: The key that the decoded value is associated with. /// - returns: A value of the requested type, if present for the given key and convertible to the requested type. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value is not convertible to the requested type. /// - throws: `DecodingError.keyNotFound` if `self` does not have an entry for the given key. /// - throws: `DecodingError.valueNotFound` if `self` has a null entry for the given key. public func decode(_ type: Double.Type, forKey key: Key) throws -> Double { return try _box.decode(Double.self, forKey: key) } /// Decodes a value of the given type for the given key. /// /// - parameter type: The type of value to decode. /// - parameter key: The key that the decoded value is associated with. /// - returns: A value of the requested type, if present for the given key and convertible to the requested type. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value is not convertible to the requested type. /// - throws: `DecodingError.keyNotFound` if `self` does not have an entry for the given key. /// - throws: `DecodingError.valueNotFound` if `self` has a null entry for the given key. public func decode(_ type: String.Type, forKey key: Key) throws -> String { return try _box.decode(String.self, forKey: key) } /// Decodes a value of the given type for the given key. /// /// - parameter type: The type of value to decode. /// - parameter key: The key that the decoded value is associated with. /// - returns: A value of the requested type, if present for the given key and convertible to the requested type. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value is not convertible to the requested type. /// - throws: `DecodingError.keyNotFound` if `self` does not have an entry for the given key. /// - throws: `DecodingError.valueNotFound` if `self` has a null entry for the given key. public func decode<T : Decodable>(_ type: T.Type, forKey key: Key) throws -> T { return try _box.decode(T.self, forKey: key) } /// Decodes a value of the given type for the given key, if present. /// /// This method returns `nil` if the container does not have a value associated with `key`, or if the value is null. The difference between these states can be distinguished with a `contains(_:)` call. /// /// - parameter type: The type of value to decode. /// - parameter key: The key that the decoded value is associated with. /// - returns: A decoded value of the requested type, or `nil` if the `Decoder` does not have an entry associated with the given key, or if the value is a null value. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value is not convertible to the requested type. public func decodeIfPresent(_ type: Bool.Type, forKey key: Key) throws -> Bool? { return try _box.decodeIfPresent(Bool.self, forKey: key) } /// Decodes a value of the given type for the given key, if present. /// /// This method returns `nil` if the container does not have a value associated with `key`, or if the value is null. The difference between these states can be distinguished with a `contains(_:)` call. /// /// - parameter type: The type of value to decode. /// - parameter key: The key that the decoded value is associated with. /// - returns: A decoded value of the requested type, or `nil` if the `Decoder` does not have an entry associated with the given key, or if the value is a null value. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value is not convertible to the requested type. public func decodeIfPresent(_ type: Int.Type, forKey key: Key) throws -> Int? { return try _box.decodeIfPresent(Int.self, forKey: key) } /// Decodes a value of the given type for the given key, if present. /// /// This method returns `nil` if the container does not have a value associated with `key`, or if the value is null. The difference between these states can be distinguished with a `contains(_:)` call. /// /// - parameter type: The type of value to decode. /// - parameter key: The key that the decoded value is associated with. /// - returns: A decoded value of the requested type, or `nil` if the `Decoder` does not have an entry associated with the given key, or if the value is a null value. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value is not convertible to the requested type. public func decodeIfPresent(_ type: Int8.Type, forKey key: Key) throws -> Int8? { return try _box.decodeIfPresent(Int8.self, forKey: key) } /// Decodes a value of the given type for the given key, if present. /// /// This method returns `nil` if the container does not have a value associated with `key`, or if the value is null. The difference between these states can be distinguished with a `contains(_:)` call. /// /// - parameter type: The type of value to decode. /// - parameter key: The key that the decoded value is associated with. /// - returns: A decoded value of the requested type, or `nil` if the `Decoder` does not have an entry associated with the given key, or if the value is a null value. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value is not convertible to the requested type. public func decodeIfPresent(_ type: Int16.Type, forKey key: Key) throws -> Int16? { return try _box.decodeIfPresent(Int16.self, forKey: key) } /// Decodes a value of the given type for the given key, if present. /// /// This method returns `nil` if the container does not have a value associated with `key`, or if the value is null. The difference between these states can be distinguished with a `contains(_:)` call. /// /// - parameter type: The type of value to decode. /// - parameter key: The key that the decoded value is associated with. /// - returns: A decoded value of the requested type, or `nil` if the `Decoder` does not have an entry associated with the given key, or if the value is a null value. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value is not convertible to the requested type. public func decodeIfPresent(_ type: Int32.Type, forKey key: Key) throws -> Int32? { return try _box.decodeIfPresent(Int32.self, forKey: key) } /// Decodes a value of the given type for the given key, if present. /// /// This method returns `nil` if the container does not have a value associated with `key`, or if the value is null. The difference between these states can be distinguished with a `contains(_:)` call. /// /// - parameter type: The type of value to decode. /// - parameter key: The key that the decoded value is associated with. /// - returns: A decoded value of the requested type, or `nil` if the `Decoder` does not have an entry associated with the given key, or if the value is a null value. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value is not convertible to the requested type. public func decodeIfPresent(_ type: Int64.Type, forKey key: Key) throws -> Int64? { return try _box.decodeIfPresent(Int64.self, forKey: key) } /// Decodes a value of the given type for the given key, if present. /// /// This method returns `nil` if the container does not have a value associated with `key`, or if the value is null. The difference between these states can be distinguished with a `contains(_:)` call. /// /// - parameter type: The type of value to decode. /// - parameter key: The key that the decoded value is associated with. /// - returns: A decoded value of the requested type, or `nil` if the `Decoder` does not have an entry associated with the given key, or if the value is a null value. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value is not convertible to the requested type. public func decodeIfPresent(_ type: UInt.Type, forKey key: Key) throws -> UInt? { return try _box.decodeIfPresent(UInt.self, forKey: key) } /// Decodes a value of the given type for the given key, if present. /// /// This method returns `nil` if the container does not have a value associated with `key`, or if the value is null. The difference between these states can be distinguished with a `contains(_:)` call. /// /// - parameter type: The type of value to decode. /// - parameter key: The key that the decoded value is associated with. /// - returns: A decoded value of the requested type, or `nil` if the `Decoder` does not have an entry associated with the given key, or if the value is a null value. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value is not convertible to the requested type. public func decodeIfPresent(_ type: UInt8.Type, forKey key: Key) throws -> UInt8? { return try _box.decodeIfPresent(UInt8.self, forKey: key) } /// Decodes a value of the given type for the given key, if present. /// /// This method returns `nil` if the container does not have a value associated with `key`, or if the value is null. The difference between these states can be distinguished with a `contains(_:)` call. /// /// - parameter type: The type of value to decode. /// - parameter key: The key that the decoded value is associated with. /// - returns: A decoded value of the requested type, or `nil` if the `Decoder` does not have an entry associated with the given key, or if the value is a null value. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value is not convertible to the requested type. public func decodeIfPresent(_ type: UInt16.Type, forKey key: Key) throws -> UInt16? { return try _box.decodeIfPresent(UInt16.self, forKey: key) } /// Decodes a value of the given type for the given key, if present. /// /// This method returns `nil` if the container does not have a value associated with `key`, or if the value is null. The difference between these states can be distinguished with a `contains(_:)` call. /// /// - parameter type: The type of value to decode. /// - parameter key: The key that the decoded value is associated with. /// - returns: A decoded value of the requested type, or `nil` if the `Decoder` does not have an entry associated with the given key, or if the value is a null value. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value is not convertible to the requested type. public func decodeIfPresent(_ type: UInt32.Type, forKey key: Key) throws -> UInt32? { return try _box.decodeIfPresent(UInt32.self, forKey: key) } /// Decodes a value of the given type for the given key, if present. /// /// This method returns `nil` if the container does not have a value associated with `key`, or if the value is null. The difference between these states can be distinguished with a `contains(_:)` call. /// /// - parameter type: The type of value to decode. /// - parameter key: The key that the decoded value is associated with. /// - returns: A decoded value of the requested type, or `nil` if the `Decoder` does not have an entry associated with the given key, or if the value is a null value. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value is not convertible to the requested type. public func decodeIfPresent(_ type: UInt64.Type, forKey key: Key) throws -> UInt64? { return try _box.decodeIfPresent(UInt64.self, forKey: key) } /// Decodes a value of the given type for the given key, if present. /// /// This method returns `nil` if the container does not have a value associated with `key`, or if the value is null. The difference between these states can be distinguished with a `contains(_:)` call. /// /// - parameter type: The type of value to decode. /// - parameter key: The key that the decoded value is associated with. /// - returns: A decoded value of the requested type, or `nil` if the `Decoder` does not have an entry associated with the given key, or if the value is a null value. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value is not convertible to the requested type. public func decodeIfPresent(_ type: Float.Type, forKey key: Key) throws -> Float? { return try _box.decodeIfPresent(Float.self, forKey: key) } /// Decodes a value of the given type for the given key, if present. /// /// This method returns `nil` if the container does not have a value associated with `key`, or if the value is null. The difference between these states can be distinguished with a `contains(_:)` call. /// /// - parameter type: The type of value to decode. /// - parameter key: The key that the decoded value is associated with. /// - returns: A decoded value of the requested type, or `nil` if the `Decoder` does not have an entry associated with the given key, or if the value is a null value. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value is not convertible to the requested type. public func decodeIfPresent(_ type: Double.Type, forKey key: Key) throws -> Double? { return try _box.decodeIfPresent(Double.self, forKey: key) } /// Decodes a value of the given type for the given key, if present. /// /// This method returns `nil` if the container does not have a value associated with `key`, or if the value is null. The difference between these states can be distinguished with a `contains(_:)` call. /// /// - parameter type: The type of value to decode. /// - parameter key: The key that the decoded value is associated with. /// - returns: A decoded value of the requested type, or `nil` if the `Decoder` does not have an entry associated with the given key, or if the value is a null value. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value is not convertible to the requested type. public func decodeIfPresent(_ type: String.Type, forKey key: Key) throws -> String? { return try _box.decodeIfPresent(String.self, forKey: key) } /// Decodes a value of the given type for the given key, if present. /// /// This method returns `nil` if the container does not have a value associated with `key`, or if the value is null. The difference between these states can be distinguished with a `contains(_:)` call. /// /// - parameter type: The type of value to decode. /// - parameter key: The key that the decoded value is associated with. /// - returns: A decoded value of the requested type, or `nil` if the `Decoder` does not have an entry associated with the given key, or if the value is a null value. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value is not convertible to the requested type. public func decodeIfPresent<T : Decodable>(_ type: T.Type, forKey key: Key) throws -> T? { return try _box.decodeIfPresent(T.self, forKey: key) } /// Returns the data stored for the given key as represented in a container keyed by the given key type. /// /// - parameter type: The key type to use for the container. /// - parameter key: The key that the nested container is associated with. /// - returns: A keyed decoding container view into `self`. /// - throws: `DecodingError.typeMismatch` if the encountered stored value is not a keyed container. public func nestedContainer<NestedKey>(keyedBy type: NestedKey.Type, forKey key: Key) throws -> KeyedDecodingContainer<NestedKey> { return try _box.nestedContainer(keyedBy: NestedKey.self, forKey: key) } /// Returns the data stored for the given key as represented in an unkeyed container. /// /// - parameter key: The key that the nested container is associated with. /// - returns: An unkeyed decoding container view into `self`. /// - throws: `DecodingError.typeMismatch` if the encountered stored value is not an unkeyed container. public func nestedUnkeyedContainer(forKey key: Key) throws -> UnkeyedDecodingContainer { return try _box.nestedUnkeyedContainer(forKey: key) } /// Returns a `Decoder` instance for decoding `super` from the container associated with the default `super` key. /// /// Equivalent to calling `superDecoder(forKey:)` with `Key(stringValue: "super", intValue: 0)`. /// /// - throws: `DecodingError.keyNotFound` if `self` does not have an entry for the default `super` key. /// - throws: `DecodingError.valueNotFound` if `self` has a null entry for the default `super` key. public func superDecoder() throws -> Decoder { return try _box.superDecoder() } /// Returns a `Decoder` instance for decoding `super` from the container associated with the given key. /// /// - parameter key: The key to decode `super` for. /// - returns: A new `Decoder` to pass to `super.init(from:)`. /// - throws: `DecodingError.keyNotFound` if `self` does not have an entry for the given key. /// - throws: `DecodingError.valueNotFound` if `self` has a null entry for the given key. public func superDecoder(forKey key: Key) throws -> Decoder { return try _box.superDecoder(forKey: key) } } /// A type that provides a view into a decoder's storage and is used to hold /// the encoded properties of a decodable type sequentially, without keys. /// /// Decoders should provide types conforming to `UnkeyedDecodingContainer` for /// their format. public protocol UnkeyedDecodingContainer { /// The path of coding keys taken to get to this point in decoding. /// A `nil` value indicates an unkeyed container. var codingPath: [CodingKey] { get } /// Returns the number of elements (if known) contained within this container. var count: Int? { get } /// Returns whether there are no more elements left to be decoded in the container. var isAtEnd: Bool { get } /// The current decoding index of the container (i.e. the index of the next element to be decoded.) /// Incremented after every successful decode call. var currentIndex: Int { get } /// Decodes a null value. /// /// If the value is not null, does not increment currentIndex. /// /// - returns: Whether the encountered value was null. /// - throws: `DecodingError.valueNotFound` if there are no more values to decode. mutating func decodeNil() throws -> Bool /// Decodes a value of the given type. /// /// - parameter type: The type of value to decode. /// - returns: A value of the requested type, if present for the given key and convertible to the requested type. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value is not convertible to the requested type. /// - throws: `DecodingError.valueNotFound` if the encountered encoded value is null, or of there are no more values to decode. mutating func decode(_ type: Bool.Type) throws -> Bool /// Decodes a value of the given type. /// /// - parameter type: The type of value to decode. /// - returns: A value of the requested type, if present for the given key and convertible to the requested type. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value is not convertible to the requested type. /// - throws: `DecodingError.valueNotFound` if the encountered encoded value is null, or of there are no more values to decode. mutating func decode(_ type: Int.Type) throws -> Int /// Decodes a value of the given type. /// /// - parameter type: The type of value to decode. /// - returns: A value of the requested type, if present for the given key and convertible to the requested type. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value is not convertible to the requested type. /// - throws: `DecodingError.valueNotFound` if the encountered encoded value is null, or of there are no more values to decode. mutating func decode(_ type: Int8.Type) throws -> Int8 /// Decodes a value of the given type. /// /// - parameter type: The type of value to decode. /// - returns: A value of the requested type, if present for the given key and convertible to the requested type. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value is not convertible to the requested type. /// - throws: `DecodingError.valueNotFound` if the encountered encoded value is null, or of there are no more values to decode. mutating func decode(_ type: Int16.Type) throws -> Int16 /// Decodes a value of the given type. /// /// - parameter type: The type of value to decode. /// - returns: A value of the requested type, if present for the given key and convertible to the requested type. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value is not convertible to the requested type. /// - throws: `DecodingError.valueNotFound` if the encountered encoded value is null, or of there are no more values to decode. mutating func decode(_ type: Int32.Type) throws -> Int32 /// Decodes a value of the given type. /// /// - parameter type: The type of value to decode. /// - returns: A value of the requested type, if present for the given key and convertible to the requested type. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value is not convertible to the requested type. /// - throws: `DecodingError.valueNotFound` if the encountered encoded value is null, or of there are no more values to decode. mutating func decode(_ type: Int64.Type) throws -> Int64 /// Decodes a value of the given type. /// /// - parameter type: The type of value to decode. /// - returns: A value of the requested type, if present for the given key and convertible to the requested type. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value is not convertible to the requested type. /// - throws: `DecodingError.valueNotFound` if the encountered encoded value is null, or of there are no more values to decode. mutating func decode(_ type: UInt.Type) throws -> UInt /// Decodes a value of the given type. /// /// - parameter type: The type of value to decode. /// - returns: A value of the requested type, if present for the given key and convertible to the requested type. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value is not convertible to the requested type. /// - throws: `DecodingError.valueNotFound` if the encountered encoded value is null, or of there are no more values to decode. mutating func decode(_ type: UInt8.Type) throws -> UInt8 /// Decodes a value of the given type. /// /// - parameter type: The type of value to decode. /// - returns: A value of the requested type, if present for the given key and convertible to the requested type. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value is not convertible to the requested type. /// - throws: `DecodingError.valueNotFound` if the encountered encoded value is null, or of there are no more values to decode. mutating func decode(_ type: UInt16.Type) throws -> UInt16 /// Decodes a value of the given type. /// /// - parameter type: The type of value to decode. /// - returns: A value of the requested type, if present for the given key and convertible to the requested type. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value is not convertible to the requested type. /// - throws: `DecodingError.valueNotFound` if the encountered encoded value is null, or of there are no more values to decode. mutating func decode(_ type: UInt32.Type) throws -> UInt32 /// Decodes a value of the given type. /// /// - parameter type: The type of value to decode. /// - returns: A value of the requested type, if present for the given key and convertible to the requested type. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value is not convertible to the requested type. /// - throws: `DecodingError.valueNotFound` if the encountered encoded value is null, or of there are no more values to decode. mutating func decode(_ type: UInt64.Type) throws -> UInt64 /// Decodes a value of the given type. /// /// - parameter type: The type of value to decode. /// - returns: A value of the requested type, if present for the given key and convertible to the requested type. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value is not convertible to the requested type. /// - throws: `DecodingError.valueNotFound` if the encountered encoded value is null, or of there are no more values to decode. mutating func decode(_ type: Float.Type) throws -> Float /// Decodes a value of the given type. /// /// - parameter type: The type of value to decode. /// - returns: A value of the requested type, if present for the given key and convertible to the requested type. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value is not convertible to the requested type. /// - throws: `DecodingError.valueNotFound` if the encountered encoded value is null, or of there are no more values to decode. mutating func decode(_ type: Double.Type) throws -> Double /// Decodes a value of the given type. /// /// - parameter type: The type of value to decode. /// - returns: A value of the requested type, if present for the given key and convertible to the requested type. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value is not convertible to the requested type. /// - throws: `DecodingError.valueNotFound` if the encountered encoded value is null, or of there are no more values to decode. mutating func decode(_ type: String.Type) throws -> String /// Decodes a value of the given type. /// /// - parameter type: The type of value to decode. /// - returns: A value of the requested type, if present for the given key and convertible to the requested type. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value is not convertible to the requested type. /// - throws: `DecodingError.valueNotFound` if the encountered encoded value is null, or of there are no more values to decode. mutating func decode<T : Decodable>(_ type: T.Type) throws -> T /// Decodes a value of the given type, if present. /// /// This method returns `nil` if the container has no elements left to decode, or if the value is null. The difference between these states can be distinguished by checking `isAtEnd`. /// /// - parameter type: The type of value to decode. /// - returns: A decoded value of the requested type, or `nil` if the value is a null value, or if there are no more elements to decode. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value is not convertible to the requested type. mutating func decodeIfPresent(_ type: Bool.Type) throws -> Bool? /// Decodes a value of the given type, if present. /// /// This method returns `nil` if the container has no elements left to decode, or if the value is null. The difference between these states can be distinguished by checking `isAtEnd`. /// /// - parameter type: The type of value to decode. /// - returns: A decoded value of the requested type, or `nil` if the value is a null value, or if there are no more elements to decode. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value is not convertible to the requested type. mutating func decodeIfPresent(_ type: Int.Type) throws -> Int? /// Decodes a value of the given type, if present. /// /// This method returns `nil` if the container has no elements left to decode, or if the value is null. The difference between these states can be distinguished by checking `isAtEnd`. /// /// - parameter type: The type of value to decode. /// - returns: A decoded value of the requested type, or `nil` if the value is a null value, or if there are no more elements to decode. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value is not convertible to the requested type. mutating func decodeIfPresent(_ type: Int8.Type) throws -> Int8? /// Decodes a value of the given type, if present. /// /// This method returns `nil` if the container has no elements left to decode, or if the value is null. The difference between these states can be distinguished by checking `isAtEnd`. /// /// - parameter type: The type of value to decode. /// - returns: A decoded value of the requested type, or `nil` if the value is a null value, or if there are no more elements to decode. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value is not convertible to the requested type. mutating func decodeIfPresent(_ type: Int16.Type) throws -> Int16? /// Decodes a value of the given type, if present. /// /// This method returns `nil` if the container has no elements left to decode, or if the value is null. The difference between these states can be distinguished by checking `isAtEnd`. /// /// - parameter type: The type of value to decode. /// - returns: A decoded value of the requested type, or `nil` if the value is a null value, or if there are no more elements to decode. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value is not convertible to the requested type. mutating func decodeIfPresent(_ type: Int32.Type) throws -> Int32? /// Decodes a value of the given type, if present. /// /// This method returns `nil` if the container has no elements left to decode, or if the value is null. The difference between these states can be distinguished by checking `isAtEnd`. /// /// - parameter type: The type of value to decode. /// - returns: A decoded value of the requested type, or `nil` if the value is a null value, or if there are no more elements to decode. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value is not convertible to the requested type. mutating func decodeIfPresent(_ type: Int64.Type) throws -> Int64? /// Decodes a value of the given type, if present. /// /// This method returns `nil` if the container has no elements left to decode, or if the value is null. The difference between these states can be distinguished by checking `isAtEnd`. /// /// - parameter type: The type of value to decode. /// - returns: A decoded value of the requested type, or `nil` if the value is a null value, or if there are no more elements to decode. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value is not convertible to the requested type. mutating func decodeIfPresent(_ type: UInt.Type) throws -> UInt? /// Decodes a value of the given type, if present. /// /// This method returns `nil` if the container has no elements left to decode, or if the value is null. The difference between these states can be distinguished by checking `isAtEnd`. /// /// - parameter type: The type of value to decode. /// - returns: A decoded value of the requested type, or `nil` if the value is a null value, or if there are no more elements to decode. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value is not convertible to the requested type. mutating func decodeIfPresent(_ type: UInt8.Type) throws -> UInt8? /// Decodes a value of the given type, if present. /// /// This method returns `nil` if the container has no elements left to decode, or if the value is null. The difference between these states can be distinguished by checking `isAtEnd`. /// /// - parameter type: The type of value to decode. /// - returns: A decoded value of the requested type, or `nil` if the value is a null value, or if there are no more elements to decode. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value is not convertible to the requested type. mutating func decodeIfPresent(_ type: UInt16.Type) throws -> UInt16? /// Decodes a value of the given type, if present. /// /// This method returns `nil` if the container has no elements left to decode, or if the value is null. The difference between these states can be distinguished by checking `isAtEnd`. /// /// - parameter type: The type of value to decode. /// - returns: A decoded value of the requested type, or `nil` if the value is a null value, or if there are no more elements to decode. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value is not convertible to the requested type. mutating func decodeIfPresent(_ type: UInt32.Type) throws -> UInt32? /// Decodes a value of the given type, if present. /// /// This method returns `nil` if the container has no elements left to decode, or if the value is null. The difference between these states can be distinguished by checking `isAtEnd`. /// /// - parameter type: The type of value to decode. /// - returns: A decoded value of the requested type, or `nil` if the value is a null value, or if there are no more elements to decode. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value is not convertible to the requested type. mutating func decodeIfPresent(_ type: UInt64.Type) throws -> UInt64? /// Decodes a value of the given type, if present. /// /// This method returns `nil` if the container has no elements left to decode, or if the value is null. The difference between these states can be distinguished by checking `isAtEnd`. /// /// - parameter type: The type of value to decode. /// - returns: A decoded value of the requested type, or `nil` if the value is a null value, or if there are no more elements to decode. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value is not convertible to the requested type. mutating func decodeIfPresent(_ type: Float.Type) throws -> Float? /// Decodes a value of the given type, if present. /// /// This method returns `nil` if the container has no elements left to decode, or if the value is null. The difference between these states can be distinguished by checking `isAtEnd`. /// /// - parameter type: The type of value to decode. /// - returns: A decoded value of the requested type, or `nil` if the value is a null value, or if there are no more elements to decode. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value is not convertible to the requested type. mutating func decodeIfPresent(_ type: Double.Type) throws -> Double? /// Decodes a value of the given type, if present. /// /// This method returns `nil` if the container has no elements left to decode, or if the value is null. The difference between these states can be distinguished by checking `isAtEnd`. /// /// - parameter type: The type of value to decode. /// - returns: A decoded value of the requested type, or `nil` if the value is a null value, or if there are no more elements to decode. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value is not convertible to the requested type. mutating func decodeIfPresent(_ type: String.Type) throws -> String? /// Decodes a value of the given type, if present. /// /// This method returns `nil` if the container has no elements left to decode, or if the value is null. The difference between these states can be distinguished by checking `isAtEnd`. /// /// - parameter type: The type of value to decode. /// - returns: A decoded value of the requested type, or `nil` if the value is a null value, or if there are no more elements to decode. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value is not convertible to the requested type. mutating func decodeIfPresent<T : Decodable>(_ type: T.Type) throws -> T? /// Decodes a nested container keyed by the given type. /// /// - parameter type: The key type to use for the container. /// - returns: A keyed decoding container view into `self`. /// - throws: `DecodingError.typeMismatch` if the encountered stored value is not a keyed container. mutating func nestedContainer<NestedKey>(keyedBy type: NestedKey.Type) throws -> KeyedDecodingContainer<NestedKey> /// Decodes an unkeyed nested container. /// /// - returns: An unkeyed decoding container view into `self`. /// - throws: `DecodingError.typeMismatch` if the encountered stored value is not an unkeyed container. mutating func nestedUnkeyedContainer() throws -> UnkeyedDecodingContainer /// Decodes a nested container and returns a `Decoder` instance for decoding `super` from that container. /// /// - returns: A new `Decoder` to pass to `super.init(from:)`. /// - throws: `DecodingError.valueNotFound` if the encountered encoded value is null, or of there are no more values to decode. mutating func superDecoder() throws -> Decoder } /// A `SingleValueDecodingContainer` is a container which can support the storage and direct decoding of a single non-keyed value. public protocol SingleValueDecodingContainer { /// The path of coding keys taken to get to this point in encoding. /// A `nil` value indicates an unkeyed container. var codingPath: [CodingKey] { get } /// Decodes a null value. /// /// - returns: Whether the encountered value was null. func decodeNil() -> Bool /// Decodes a single value of the given type. /// /// - parameter type: The type to decode as. /// - returns: A value of the requested type. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value cannot be converted to the requested type. /// - throws: `DecodingError.valueNotFound` if the encountered encoded value is null. func decode(_ type: Bool.Type) throws -> Bool /// Decodes a single value of the given type. /// /// - parameter type: The type to decode as. /// - returns: A value of the requested type. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value cannot be converted to the requested type. /// - throws: `DecodingError.valueNotFound` if the encountered encoded value is null. func decode(_ type: Int.Type) throws -> Int /// Decodes a single value of the given type. /// /// - parameter type: The type to decode as. /// - returns: A value of the requested type. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value cannot be converted to the requested type. /// - throws: `DecodingError.valueNotFound` if the encountered encoded value is null. func decode(_ type: Int8.Type) throws -> Int8 /// Decodes a single value of the given type. /// /// - parameter type: The type to decode as. /// - returns: A value of the requested type. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value cannot be converted to the requested type. /// - throws: `DecodingError.valueNotFound` if the encountered encoded value is null. func decode(_ type: Int16.Type) throws -> Int16 /// Decodes a single value of the given type. /// /// - parameter type: The type to decode as. /// - returns: A value of the requested type. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value cannot be converted to the requested type. /// - throws: `DecodingError.valueNotFound` if the encountered encoded value is null. func decode(_ type: Int32.Type) throws -> Int32 /// Decodes a single value of the given type. /// /// - parameter type: The type to decode as. /// - returns: A value of the requested type. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value cannot be converted to the requested type. /// - throws: `DecodingError.valueNotFound` if the encountered encoded value is null. func decode(_ type: Int64.Type) throws -> Int64 /// Decodes a single value of the given type. /// /// - parameter type: The type to decode as. /// - returns: A value of the requested type. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value cannot be converted to the requested type. /// - throws: `DecodingError.valueNotFound` if the encountered encoded value is null. func decode(_ type: UInt.Type) throws -> UInt /// Decodes a single value of the given type. /// /// - parameter type: The type to decode as. /// - returns: A value of the requested type. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value cannot be converted to the requested type. /// - throws: `DecodingError.valueNotFound` if the encountered encoded value is null. func decode(_ type: UInt8.Type) throws -> UInt8 /// Decodes a single value of the given type. /// /// - parameter type: The type to decode as. /// - returns: A value of the requested type. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value cannot be converted to the requested type. /// - throws: `DecodingError.valueNotFound` if the encountered encoded value is null. func decode(_ type: UInt16.Type) throws -> UInt16 /// Decodes a single value of the given type. /// /// - parameter type: The type to decode as. /// - returns: A value of the requested type. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value cannot be converted to the requested type. /// - throws: `DecodingError.valueNotFound` if the encountered encoded value is null. func decode(_ type: UInt32.Type) throws -> UInt32 /// Decodes a single value of the given type. /// /// - parameter type: The type to decode as. /// - returns: A value of the requested type. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value cannot be converted to the requested type. /// - throws: `DecodingError.valueNotFound` if the encountered encoded value is null. func decode(_ type: UInt64.Type) throws -> UInt64 /// Decodes a single value of the given type. /// /// - parameter type: The type to decode as. /// - returns: A value of the requested type. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value cannot be converted to the requested type. /// - throws: `DecodingError.valueNotFound` if the encountered encoded value is null. func decode(_ type: Float.Type) throws -> Float /// Decodes a single value of the given type. /// /// - parameter type: The type to decode as. /// - returns: A value of the requested type. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value cannot be converted to the requested type. /// - throws: `DecodingError.valueNotFound` if the encountered encoded value is null. func decode(_ type: Double.Type) throws -> Double /// Decodes a single value of the given type. /// /// - parameter type: The type to decode as. /// - returns: A value of the requested type. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value cannot be converted to the requested type. /// - throws: `DecodingError.valueNotFound` if the encountered encoded value is null. func decode(_ type: String.Type) throws -> String /// Decodes a single value of the given type. /// /// - parameter type: The type to decode as. /// - returns: A value of the requested type. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value cannot be converted to the requested type. /// - throws: `DecodingError.valueNotFound` if the encountered encoded value is null. func decode<T : Decodable>(_ type: T.Type) throws -> T } //===----------------------------------------------------------------------===// // User Info //===----------------------------------------------------------------------===// /// A user-defined key for providing context during encoding and decoding. public struct CodingUserInfoKey : RawRepresentable, Equatable, Hashable { public typealias RawValue = String /// The key's string value. public let rawValue: String /// Initializes `self` with the given raw value. /// /// - parameter rawValue: The value of the key. public init?(rawValue: String) { self.rawValue = rawValue } /// Returns whether the given keys are equal. /// /// - parameter lhs: The key to compare against. /// - parameter rhs: The key to compare with. public static func ==(_ lhs: CodingUserInfoKey, _ rhs: CodingUserInfoKey) -> Bool { return lhs.rawValue == rhs.rawValue } /// The key's hash value. public var hashValue: Int { return self.rawValue.hashValue } } /// An error that occurs during the decoding of a value. public enum DecodingError : Error { /// The context in which the error occurred. public struct Context { /// The path of `CodingKey`s taken to get to the point of the failing decode call. public let codingPath: [CodingKey] /// A description of what went wrong, for debugging purposes. public let debugDescription: String /// The underlying error which caused this error, if any. public let underlyingError: Error? /// Initializes `self` with the given path of `CodingKey`s and a description of what went wrong. /// /// - parameter codingPath: The path of `CodingKey`s taken to get to the point of the failing decode call. /// - parameter debugDescription: A description of what went wrong, for debugging purposes. /// - parameter underlyingError: The underlying error which caused this error, if any. public init(codingPath: [CodingKey], debugDescription: String, underlyingError: Error? = nil) { self.codingPath = codingPath self.debugDescription = debugDescription self.underlyingError = underlyingError } } /// `.typeMismatch` indicates that a value of the given type could not be decoded because it did not match the type of what was found in the encoded payload. /// /// Contains the attempted type, along with context for debugging. case typeMismatch(Any.Type, Context) /// `.valueNotFound` indicates that a non-optional value of the given type was expected, but a null value was found. /// /// Contains the attempted type, along with context for debugging. case valueNotFound(Any.Type, Context) /// `.keyNotFound` indicates that a `KeyedDecodingContainer` was asked for an entry for the given key, but did not contain one. /// /// Contains the attempted key, along with context for debugging. case keyNotFound(CodingKey, Context) /// `.dataCorrupted` indicates that the data is corrupted or otherwise invalid. /// /// Contains context for debugging. case dataCorrupted(Context) // MARK: - NSError Bridging // CustomNSError bridging applies only when the CustomNSError conformance is applied in the same module as the declared error type. // Since we cannot access CustomNSError (which is defined in Foundation) from here, we can use the "hidden" entry points. public var _domain: String { return "NSCocoaErrorDomain" } public var _code: Int { switch self { case .keyNotFound(_, _): fallthrough case .valueNotFound(_, _): return 4865 case .typeMismatch(_, _): fallthrough case .dataCorrupted(_): return 4864 } } public var _userInfo: AnyObject? { // The error dictionary must be returned as an AnyObject. We can do this only on platforms with bridging, unfortunately. #if os(OSX) || os(iOS) || os(watchOS) || os(tvOS) let context: Context switch self { case .keyNotFound(_, let c): context = c case .valueNotFound(_, let c): context = c case .typeMismatch(_, let c): context = c case .dataCorrupted( let c): context = c } var userInfo: [String : Any] = [ "NSCodingPath": context.codingPath, "NSDebugDescription": context.debugDescription ] if let underlyingError = context.underlyingError { userInfo["NSUnderlyingError"] = underlyingError } return userInfo as AnyObject #else return nil #endif } } // The following extensions allow for easier error construction. internal struct _GenericIndexKey : CodingKey { var stringValue: String var intValue: Int? init?(stringValue: String) { return nil } init?(intValue: Int) { self.stringValue = "Index \(intValue)" self.intValue = intValue } } public extension DecodingError { /// A convenience method which creates a new .dataCorrupted error using a constructed coding path and the given debug description. /// /// Constructs a coding path by appending the given key to the given container's coding path. /// /// - param key: The key which caused the failure. /// - param container: The container in which the corrupted data was accessed. /// - param debugDescription: A description of the error to aid in debugging. static func dataCorruptedError<C : KeyedDecodingContainerProtocol>(forKey key: C.Key, in container: C, debugDescription: String) -> DecodingError { let context = DecodingError.Context(codingPath: container.codingPath + [key], debugDescription: debugDescription) return .dataCorrupted(context) } /// A convenience method which creates a new .dataCorrupted error using a constructed coding path and the given debug description. /// /// Constructs a coding path by appending a nil key to the given container's coding path. /// /// - param container: The container in which the corrupted data was accessed. /// - param debugDescription: A description of the error to aid in debugging. static func dataCorruptedError(in container: UnkeyedDecodingContainer, debugDescription: String) -> DecodingError { let context = DecodingError.Context(codingPath: container.codingPath + [_GenericIndexKey(intValue: container.currentIndex)!], debugDescription: debugDescription) return .dataCorrupted(context) } /// A convenience method which creates a new .dataCorrupted error using a constructed coding path and the given debug description. /// /// Uses the given container's coding path as the constructed path. /// /// - param container: The container in which the corrupted data was accessed. /// - param debugDescription: A description of the error to aid in debugging. static func dataCorruptedError(in container: SingleValueDecodingContainer, debugDescription: String) -> DecodingError { let context = DecodingError.Context(codingPath: container.codingPath, debugDescription: debugDescription) return .dataCorrupted(context) } } @_fixed_layout @_versioned internal class _KeyedDecodingContainerBase<Key : CodingKey> { @_inlineable @_versioned internal var codingPath: [CodingKey] { fatalError("_KeyedDecodingContainerBase cannot be used directly.") } @_inlineable @_versioned internal var allKeys: [Key] { fatalError("_KeyedDecodingContainerBase cannot be used directly.") } @_inlineable @_versioned internal func contains(_ key: Key) -> Bool { fatalError("_KeyedDecodingContainerBase cannot be used directly.") } @_inlineable @_versioned internal func decodeNil(forKey key: Key) throws -> Bool { fatalError("_KeyedDecodingContainerBase cannot be used directly.") } @_inlineable @_versioned internal func decode(_ type: Bool.Type, forKey key: Key) throws -> Bool { fatalError("_KeyedDecodingContainerBase cannot be used directly.") } @_inlineable @_versioned internal func decode(_ type: Int.Type, forKey key: Key) throws -> Int { fatalError("_KeyedDecodingContainerBase cannot be used directly.") } @_inlineable @_versioned internal func decode(_ type: Int8.Type, forKey key: Key) throws -> Int8 { fatalError("_KeyedDecodingContainerBase cannot be used directly.") } @_inlineable @_versioned internal func decode(_ type: Int16.Type, forKey key: Key) throws -> Int16 { fatalError("_KeyedDecodingContainerBase cannot be used directly.") } @_inlineable @_versioned internal func decode(_ type: Int32.Type, forKey key: Key) throws -> Int32 { fatalError("_KeyedDecodingContainerBase cannot be used directly.") } @_inlineable @_versioned internal func decode(_ type: Int64.Type, forKey key: Key) throws -> Int64 { fatalError("_KeyedDecodingContainerBase cannot be used directly.") } @_inlineable @_versioned internal func decode(_ type: UInt.Type, forKey key: Key) throws -> UInt { fatalError("_KeyedDecodingContainerBase cannot be used directly.") } @_inlineable @_versioned internal func decode(_ type: UInt8.Type, forKey key: Key) throws -> UInt8 { fatalError("_KeyedDecodingContainerBase cannot be used directly.") } @_inlineable @_versioned internal func decode(_ type: UInt16.Type, forKey key: Key) throws -> UInt16 { fatalError("_KeyedDecodingContainerBase cannot be used directly.") } @_inlineable @_versioned internal func decode(_ type: UInt32.Type, forKey key: Key) throws -> UInt32 { fatalError("_KeyedDecodingContainerBase cannot be used directly.") } @_inlineable @_versioned internal func decode(_ type: UInt64.Type, forKey key: Key) throws -> UInt64 { fatalError("_KeyedDecodingContainerBase cannot be used directly.") } @_inlineable @_versioned internal func decode(_ type: Float.Type, forKey key: Key) throws -> Float { fatalError("_KeyedDecodingContainerBase cannot be used directly.") } @_inlineable @_versioned internal func decode(_ type: Double.Type, forKey key: Key) throws -> Double { fatalError("_KeyedDecodingContainerBase cannot be used directly.") } @_inlineable @_versioned internal func decode(_ type: String.Type, forKey key: Key) throws -> String { fatalError("_KeyedDecodingContainerBase cannot be used directly.") } @_inlineable @_versioned internal func decode<T : Decodable>(_ type: T.Type, forKey key: Key) throws -> T { fatalError("_KeyedDecodingContainerBase cannot be used directly.") } @_inlineable @_versioned internal func decodeIfPresent(_ type: Bool.Type, forKey key: Key) throws -> Bool? { fatalError("_KeyedDecodingContainerBase cannot be used directly.") } @_inlineable @_versioned internal func decodeIfPresent(_ type: Int.Type, forKey key: Key) throws -> Int? { fatalError("_KeyedDecodingContainerBase cannot be used directly.") } @_inlineable @_versioned internal func decodeIfPresent(_ type: Int8.Type, forKey key: Key) throws -> Int8? { fatalError("_KeyedDecodingContainerBase cannot be used directly.") } @_inlineable @_versioned internal func decodeIfPresent(_ type: Int16.Type, forKey key: Key) throws -> Int16? { fatalError("_KeyedDecodingContainerBase cannot be used directly.") } @_inlineable @_versioned internal func decodeIfPresent(_ type: Int32.Type, forKey key: Key) throws -> Int32? { fatalError("_KeyedDecodingContainerBase cannot be used directly.") } @_inlineable @_versioned internal func decodeIfPresent(_ type: Int64.Type, forKey key: Key) throws -> Int64? { fatalError("_KeyedDecodingContainerBase cannot be used directly.") } @_inlineable @_versioned internal func decodeIfPresent(_ type: UInt.Type, forKey key: Key) throws -> UInt? { fatalError("_KeyedDecodingContainerBase cannot be used directly.") } @_inlineable @_versioned internal func decodeIfPresent(_ type: UInt8.Type, forKey key: Key) throws -> UInt8? { fatalError("_KeyedDecodingContainerBase cannot be used directly.") } @_inlineable @_versioned internal func decodeIfPresent(_ type: UInt16.Type, forKey key: Key) throws -> UInt16? { fatalError("_KeyedDecodingContainerBase cannot be used directly.") } @_inlineable @_versioned internal func decodeIfPresent(_ type: UInt32.Type, forKey key: Key) throws -> UInt32? { fatalError("_KeyedDecodingContainerBase cannot be used directly.") } @_inlineable @_versioned internal func decodeIfPresent(_ type: UInt64.Type, forKey key: Key) throws -> UInt64? { fatalError("_KeyedDecodingContainerBase cannot be used directly.") } @_inlineable @_versioned internal func decodeIfPresent(_ type: Float.Type, forKey key: Key) throws -> Float? { fatalError("_KeyedDecodingContainerBase cannot be used directly.") } @_inlineable @_versioned internal func decodeIfPresent(_ type: Double.Type, forKey key: Key) throws -> Double? { fatalError("_KeyedDecodingContainerBase cannot be used directly.") } @_inlineable @_versioned internal func decodeIfPresent(_ type: String.Type, forKey key: Key) throws -> String? { fatalError("_KeyedDecodingContainerBase cannot be used directly.") } @_inlineable @_versioned internal func decodeIfPresent<T : Decodable>(_ type: T.Type, forKey key: Key) throws -> T? { fatalError("_KeyedDecodingContainerBase cannot be used directly.") } @_inlineable @_versioned internal func nestedContainer<NestedKey>(keyedBy type: NestedKey.Type, forKey key: Key) throws -> KeyedDecodingContainer<NestedKey> { fatalError("_KeyedDecodingContainerBase cannot be used directly.") } @_inlineable @_versioned internal func nestedUnkeyedContainer(forKey key: Key) throws -> UnkeyedDecodingContainer { fatalError("_KeyedDecodingContainerBase cannot be used directly.") } @_inlineable @_versioned internal func superDecoder() throws -> Decoder { fatalError("_KeyedDecodingContainerBase cannot be used directly.") } @_inlineable @_versioned internal func superDecoder(forKey key: Key) throws -> Decoder { fatalError("_KeyedDecodingContainerBase cannot be used directly.") } } @_fixed_layout @_versioned internal final class _KeyedDecodingContainerBox<Concrete : KeyedDecodingContainerProtocol> : _KeyedDecodingContainerBase<Concrete.Key> { typealias Key = Concrete.Key @_versioned internal var concrete: Concrete @_inlineable @_versioned internal init(_ container: Concrete) { concrete = container } @_inlineable @_versioned override var codingPath: [CodingKey] { return concrete.codingPath } @_inlineable @_versioned override var allKeys: [Key] { return concrete.allKeys } @_inlineable @_versioned override internal func contains(_ key: Key) -> Bool { return concrete.contains(key) } @_inlineable @_versioned override internal func decodeNil(forKey key: Key) throws -> Bool { return try concrete.decodeNil(forKey: key) } @_inlineable @_versioned override internal func decode(_ type: Bool.Type, forKey key: Key) throws -> Bool { return try concrete.decode(Bool.self, forKey: key) } @_inlineable @_versioned override internal func decode(_ type: Int.Type, forKey key: Key) throws -> Int { return try concrete.decode(Int.self, forKey: key) } @_inlineable @_versioned override internal func decode(_ type: Int8.Type, forKey key: Key) throws -> Int8 { return try concrete.decode(Int8.self, forKey: key) } @_inlineable @_versioned override internal func decode(_ type: Int16.Type, forKey key: Key) throws -> Int16 { return try concrete.decode(Int16.self, forKey: key) } @_inlineable @_versioned override internal func decode(_ type: Int32.Type, forKey key: Key) throws -> Int32 { return try concrete.decode(Int32.self, forKey: key) } @_inlineable @_versioned override internal func decode(_ type: Int64.Type, forKey key: Key) throws -> Int64 { return try concrete.decode(Int64.self, forKey: key) } @_inlineable @_versioned override internal func decode(_ type: UInt.Type, forKey key: Key) throws -> UInt { return try concrete.decode(UInt.self, forKey: key) } @_inlineable @_versioned override internal func decode(_ type: UInt8.Type, forKey key: Key) throws -> UInt8 { return try concrete.decode(UInt8.self, forKey: key) } @_inlineable @_versioned override internal func decode(_ type: UInt16.Type, forKey key: Key) throws -> UInt16 { return try concrete.decode(UInt16.self, forKey: key) } @_inlineable @_versioned override internal func decode(_ type: UInt32.Type, forKey key: Key) throws -> UInt32 { return try concrete.decode(UInt32.self, forKey: key) } @_inlineable @_versioned override internal func decode(_ type: UInt64.Type, forKey key: Key) throws -> UInt64 { return try concrete.decode(UInt64.self, forKey: key) } @_inlineable @_versioned override internal func decode(_ type: Float.Type, forKey key: Key) throws -> Float { return try concrete.decode(Float.self, forKey: key) } @_inlineable @_versioned override internal func decode(_ type: Double.Type, forKey key: Key) throws -> Double { return try concrete.decode(Double.self, forKey: key) } @_inlineable @_versioned override internal func decode(_ type: String.Type, forKey key: Key) throws -> String { return try concrete.decode(String.self, forKey: key) } @_inlineable @_versioned override internal func decode<T : Decodable>(_ type: T.Type, forKey key: Key) throws -> T { return try concrete.decode(T.self, forKey: key) } @_inlineable @_versioned override internal func decodeIfPresent(_ type: Bool.Type, forKey key: Key) throws -> Bool? { return try concrete.decodeIfPresent(Bool.self, forKey: key) } @_inlineable @_versioned override internal func decodeIfPresent(_ type: Int.Type, forKey key: Key) throws -> Int? { return try concrete.decodeIfPresent(Int.self, forKey: key) } @_inlineable @_versioned override internal func decodeIfPresent(_ type: Int8.Type, forKey key: Key) throws -> Int8? { return try concrete.decodeIfPresent(Int8.self, forKey: key) } @_inlineable @_versioned override internal func decodeIfPresent(_ type: Int16.Type, forKey key: Key) throws -> Int16? { return try concrete.decodeIfPresent(Int16.self, forKey: key) } @_inlineable @_versioned override internal func decodeIfPresent(_ type: Int32.Type, forKey key: Key) throws -> Int32? { return try concrete.decodeIfPresent(Int32.self, forKey: key) } @_inlineable @_versioned override internal func decodeIfPresent(_ type: Int64.Type, forKey key: Key) throws -> Int64? { return try concrete.decodeIfPresent(Int64.self, forKey: key) } @_inlineable @_versioned override internal func decodeIfPresent(_ type: UInt.Type, forKey key: Key) throws -> UInt? { return try concrete.decodeIfPresent(UInt.self, forKey: key) } @_inlineable @_versioned override internal func decodeIfPresent(_ type: UInt8.Type, forKey key: Key) throws -> UInt8? { return try concrete.decodeIfPresent(UInt8.self, forKey: key) } @_inlineable @_versioned override internal func decodeIfPresent(_ type: UInt16.Type, forKey key: Key) throws -> UInt16? { return try concrete.decodeIfPresent(UInt16.self, forKey: key) } @_inlineable @_versioned override internal func decodeIfPresent(_ type: UInt32.Type, forKey key: Key) throws -> UInt32? { return try concrete.decodeIfPresent(UInt32.self, forKey: key) } @_inlineable @_versioned override internal func decodeIfPresent(_ type: UInt64.Type, forKey key: Key) throws -> UInt64? { return try concrete.decodeIfPresent(UInt64.self, forKey: key) } @_inlineable @_versioned override internal func decodeIfPresent(_ type: Float.Type, forKey key: Key) throws -> Float? { return try concrete.decodeIfPresent(Float.self, forKey: key) } @_inlineable @_versioned override internal func decodeIfPresent(_ type: Double.Type, forKey key: Key) throws -> Double? { return try concrete.decodeIfPresent(Double.self, forKey: key) } @_inlineable @_versioned override internal func decodeIfPresent(_ type: String.Type, forKey key: Key) throws -> String? { return try concrete.decodeIfPresent(String.self, forKey: key) } @_inlineable @_versioned override internal func decodeIfPresent<T : Decodable>(_ type: T.Type, forKey key: Key) throws -> T? { return try concrete.decodeIfPresent(T.self, forKey: key) } @_inlineable @_versioned override internal func nestedContainer<NestedKey>(keyedBy type: NestedKey.Type, forKey key: Key) throws -> KeyedDecodingContainer<NestedKey> { return try concrete.nestedContainer(keyedBy: NestedKey.self, forKey: key) } @_inlineable @_versioned override internal func nestedUnkeyedContainer(forKey key: Key) throws -> UnkeyedDecodingContainer { return try concrete.nestedUnkeyedContainer(forKey: key) } @_inlineable @_versioned override internal func superDecoder() throws -> Decoder { return try concrete.superDecoder() } @_inlineable @_versioned override internal func superDecoder(forKey key: Key) throws -> Decoder { return try concrete.superDecoder(forKey: key) } } //===----------------------------------------------------------------------===// // Primitive and RawRepresentable Extensions //===----------------------------------------------------------------------===// extension Bool : Decodable { public init(from decoder: Decoder) throws { self = try decoder.singleValueContainer().decode(Bool.self) } } extension Int : Decodable { public init(from decoder: Decoder) throws { self = try decoder.singleValueContainer().decode(Int.self) } } extension Int8 : Decodable { public init(from decoder: Decoder) throws { self = try decoder.singleValueContainer().decode(Int8.self) } } extension Int16 : Decodable { public init(from decoder: Decoder) throws { self = try decoder.singleValueContainer().decode(Int16.self) } } extension Int32 : Decodable { public init(from decoder: Decoder) throws { self = try decoder.singleValueContainer().decode(Int32.self) } } extension Int64 : Decodable { public init(from decoder: Decoder) throws { self = try decoder.singleValueContainer().decode(Int64.self) } } extension UInt : Decodable { public init(from decoder: Decoder) throws { self = try decoder.singleValueContainer().decode(UInt.self) } } extension UInt8 : Decodable { public init(from decoder: Decoder) throws { self = try decoder.singleValueContainer().decode(UInt8.self) } } extension UInt16 : Decodable { public init(from decoder: Decoder) throws { self = try decoder.singleValueContainer().decode(UInt16.self) } } extension UInt32 : Decodable { public init(from decoder: Decoder) throws { self = try decoder.singleValueContainer().decode(UInt32.self) } } extension UInt64 : Decodable { public init(from decoder: Decoder) throws { self = try decoder.singleValueContainer().decode(UInt64.self) } } extension Float : Decodable { public init(from decoder: Decoder) throws { self = try decoder.singleValueContainer().decode(Float.self) } } extension Double : Decodable { public init(from decoder: Decoder) throws { self = try decoder.singleValueContainer().decode(Double.self) } } extension String : Decodable { public init(from decoder: Decoder) throws { self = try decoder.singleValueContainer().decode(String.self) } } public extension RawRepresentable where RawValue == Bool, Self : Decodable { public init(from decoder: Decoder) throws { let decoded = try decoder.singleValueContainer().decode(RawValue.self) guard let value = Self(rawValue: decoded) else { throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: decoder.codingPath, debugDescription: "Cannot initialize \(Self.self) from invalid \(RawValue.self) value \(decoded)")) } self = value } } public extension RawRepresentable where RawValue == Int, Self : Decodable { public init(from decoder: Decoder) throws { let decoded = try decoder.singleValueContainer().decode(RawValue.self) guard let value = Self(rawValue: decoded) else { throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: decoder.codingPath, debugDescription: "Cannot initialize \(Self.self) from invalid \(RawValue.self) value \(decoded)")) } self = value } } public extension RawRepresentable where RawValue == Int8, Self : Decodable { public init(from decoder: Decoder) throws { let decoded = try decoder.singleValueContainer().decode(RawValue.self) guard let value = Self(rawValue: decoded) else { throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: decoder.codingPath, debugDescription: "Cannot initialize \(Self.self) from invalid \(RawValue.self) value \(decoded)")) } self = value } } public extension RawRepresentable where RawValue == Int16, Self : Decodable { public init(from decoder: Decoder) throws { let decoded = try decoder.singleValueContainer().decode(RawValue.self) guard let value = Self(rawValue: decoded) else { throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: decoder.codingPath, debugDescription: "Cannot initialize \(Self.self) from invalid \(RawValue.self) value \(decoded)")) } self = value } } public extension RawRepresentable where RawValue == Int32, Self : Decodable { public init(from decoder: Decoder) throws { let decoded = try decoder.singleValueContainer().decode(RawValue.self) guard let value = Self(rawValue: decoded) else { throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: decoder.codingPath, debugDescription: "Cannot initialize \(Self.self) from invalid \(RawValue.self) value \(decoded)")) } self = value } } public extension RawRepresentable where RawValue == Int64, Self : Decodable { public init(from decoder: Decoder) throws { let decoded = try decoder.singleValueContainer().decode(RawValue.self) guard let value = Self(rawValue: decoded) else { throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: decoder.codingPath, debugDescription: "Cannot initialize \(Self.self) from invalid \(RawValue.self) value \(decoded)")) } self = value } } public extension RawRepresentable where RawValue == UInt, Self : Decodable { public init(from decoder: Decoder) throws { let decoded = try decoder.singleValueContainer().decode(RawValue.self) guard let value = Self(rawValue: decoded) else { throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: decoder.codingPath, debugDescription: "Cannot initialize \(Self.self) from invalid \(RawValue.self) value \(decoded)")) } self = value } } public extension RawRepresentable where RawValue == UInt8, Self : Decodable { public init(from decoder: Decoder) throws { let decoded = try decoder.singleValueContainer().decode(RawValue.self) guard let value = Self(rawValue: decoded) else { throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: decoder.codingPath, debugDescription: "Cannot initialize \(Self.self) from invalid \(RawValue.self) value \(decoded)")) } self = value } } public extension RawRepresentable where RawValue == UInt16, Self : Decodable { public init(from decoder: Decoder) throws { let decoded = try decoder.singleValueContainer().decode(RawValue.self) guard let value = Self(rawValue: decoded) else { throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: decoder.codingPath, debugDescription: "Cannot initialize \(Self.self) from invalid \(RawValue.self) value \(decoded)")) } self = value } } public extension RawRepresentable where RawValue == UInt32, Self : Decodable { public init(from decoder: Decoder) throws { let decoded = try decoder.singleValueContainer().decode(RawValue.self) guard let value = Self(rawValue: decoded) else { throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: decoder.codingPath, debugDescription: "Cannot initialize \(Self.self) from invalid \(RawValue.self) value \(decoded)")) } self = value } } public extension RawRepresentable where RawValue == UInt64, Self : Decodable { public init(from decoder: Decoder) throws { let decoded = try decoder.singleValueContainer().decode(RawValue.self) guard let value = Self(rawValue: decoded) else { throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: decoder.codingPath, debugDescription: "Cannot initialize \(Self.self) from invalid \(RawValue.self) value \(decoded)")) } self = value } } public extension RawRepresentable where RawValue == Float, Self : Decodable { public init(from decoder: Decoder) throws { let decoded = try decoder.singleValueContainer().decode(RawValue.self) guard let value = Self(rawValue: decoded) else { throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: decoder.codingPath, debugDescription: "Cannot initialize \(Self.self) from invalid \(RawValue.self) value \(decoded)")) } self = value } } public extension RawRepresentable where RawValue == Double, Self : Decodable { public init(from decoder: Decoder) throws { let decoded = try decoder.singleValueContainer().decode(RawValue.self) guard let value = Self(rawValue: decoded) else { throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: decoder.codingPath, debugDescription: "Cannot initialize \(Self.self) from invalid \(RawValue.self) value \(decoded)")) } self = value } } public extension RawRepresentable where RawValue == String, Self : Decodable { public init(from decoder: Decoder) throws { let decoded = try decoder.singleValueContainer().decode(RawValue.self) guard let value = Self(rawValue: decoded) else { throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: decoder.codingPath, debugDescription: "Cannot initialize \(Self.self) from invalid \(RawValue.self) value \(decoded)")) } self = value } } /// MARK: - RawRepresentable CodingKey extension RawRepresentable where Self.RawValue == String, Self: CodingKey { public var stringValue: String { return self.rawValue } public var intValue: Int? { return Int(stringValue) } public init?(stringValue: String) { self.init(rawValue: stringValue) } public init?(intValue: Int) { self.init(rawValue: String(intValue)) } } extension RawRepresentable where Self.RawValue == Int, Self: CodingKey { public var stringValue: String { return "\(rawValue)" } public var intValue: Int? { return rawValue } public init?(stringValue: String) { guard let intValue = Int(stringValue) else { return nil } self.init(rawValue: intValue) } public init?(intValue: Int) { self.init(rawValue: intValue) } } //===----------------------------------------------------------------------===// // Optional/Collection Type Conformances //===----------------------------------------------------------------------===// fileprivate func assertTypeIsDecodable<T>(_ type: T.Type, in wrappingType: Any.Type) { guard T.self is Decodable.Type else { if T.self == Decodable.self { preconditionFailure("\(wrappingType) does not conform to Decodable because Decodable does not conform to itself. You must use a concrete type to encode or decode.") } else { preconditionFailure("\(wrappingType) does not conform to Decodable because \(T.self) does not conform to Decodable.") } } } extension Optional : Decodable /* where Wrapped : Decodable */ { public init(from decoder: Decoder) throws { // Initialize self here so we can get type(of: self). self = .none assertTypeIsDecodable(Wrapped.self, in: type(of: self)) let container = try decoder.singleValueContainer() if !container.decodeNil() { let metaType = (Wrapped.self as! Decodable.Type) let element = try metaType.init(from: decoder) self = .some(element as! Wrapped) } } } extension Array : Decodable /* where Element : Decodable */ { public init(from decoder: Decoder) throws { // Initialize self here so we can get type(of: self). self.init() assertTypeIsDecodable(Element.self, in: type(of: self)) let metaType = (Element.self as! Decodable.Type) var container = try decoder.unkeyedContainer() while !container.isAtEnd { // superDecoder fetches the next element as a container and wraps a Decoder around it. // This is normally appropriate for decoding super, but this is really what we want to do. let subdecoder = try container.superDecoder() let element = try metaType.init(from: subdecoder) self.append(element as! Element) } } } extension Set : Decodable /* where Element : Decodable */ { public init(from decoder: Decoder) throws { // Initialize self here so we can get type(of: self). self.init() assertTypeIsDecodable(Element.self, in: type(of: self)) let metaType = (Element.self as! Decodable.Type) var container = try decoder.unkeyedContainer() while !container.isAtEnd { // superDecoder fetches the next element as a container and wraps a Decoder around it. // This is normally appropriate for decoding super, but this is really what we want to do. let subdecoder = try container.superDecoder() let element = try metaType.init(from: subdecoder) self.insert(element as! Element) } } } /// A wrapper for dictionary keys which are Strings or Ints. internal struct _DictionaryCodingKey : CodingKey { let stringValue: String let intValue: Int? init?(stringValue: String) { self.stringValue = stringValue self.intValue = Int(stringValue) } init?(intValue: Int) { self.stringValue = "\(intValue)" self.intValue = intValue } } extension Dictionary : Decodable /* where Key : Decodable, Value : Decodable */ { public init(from decoder: Decoder) throws { // Initialize self here so we can print type(of: self). self.init() assertTypeIsDecodable(Key.self, in: type(of: self)) assertTypeIsDecodable(Value.self, in: type(of: self)) if Key.self == String.self { // The keys are Strings, so we should be able to expect a keyed container. let container = try decoder.container(keyedBy: _DictionaryCodingKey.self) let valueMetaType = Value.self as! Decodable.Type for key in container.allKeys { let valueDecoder = try container.superDecoder(forKey: key) let value = try valueMetaType.init(from: valueDecoder) self[key.stringValue as! Key] = (value as! Value) } } else if Key.self == Int.self { // The keys are Ints, so we should be able to expect a keyed container. let valueMetaType = Value.self as! Decodable.Type let container = try decoder.container(keyedBy: _DictionaryCodingKey.self) for key in container.allKeys { guard key.intValue != nil else { // We provide stringValues for Int keys; if an encoder chooses not to use the actual intValues, we've encoded string keys. // So on init, _DictionaryCodingKey tries to parse string keys as Ints. If that succeeds, then we would have had an intValue here. // We don't, so this isn't a valid Int key. var codingPath = decoder.codingPath codingPath.append(key) throw DecodingError.typeMismatch(Int.self, DecodingError.Context(codingPath: codingPath, debugDescription: "Expected Int key but found String key instead.")) } let valueDecoder = try container.superDecoder(forKey: key) let value = try valueMetaType.init(from: valueDecoder) self[key.intValue! as! Key] = (value as! Value) } } else { // We should have encoded as an array of alternating key-value pairs. var container = try decoder.unkeyedContainer() // We're expecting to get pairs. If the container has a known count, it had better be even; no point in doing work if not. if let count = container.count { guard count % 2 == 0 else { throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: decoder.codingPath, debugDescription: "Expected collection of key-value pairs; encountered odd-length array instead.")) } } let keyMetaType = (Key.self as! Decodable.Type) let valueMetaType = (Value.self as! Decodable.Type) while !container.isAtEnd { // superDecoder fetches the next element as a container and wraps a Decoder around it. // This is normally appropriate for decoding super, but this is really what we want to do. let keyDecoder = try container.superDecoder() let key = try keyMetaType.init(from: keyDecoder) guard !container.isAtEnd else { throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: decoder.codingPath, debugDescription: "Unkeyed container reached end before value in key-value pair.")) } let valueDecoder = try container.superDecoder() let value = try valueMetaType.init(from: valueDecoder) self[key as! Key] = (value as! Value) } } } } // Default implementation of decodeIfPresent(_:forKey:) in terms of decode(_:forKey:) and decodeNil(forKey:) public extension KeyedDecodingContainerProtocol { public func decodeIfPresent(_ type: Bool.Type, forKey key: Key) throws -> Bool? { guard try self.contains(key) && !self.decodeNil(forKey: key) else { return nil } return try self.decode(Bool.self, forKey: key) } public func decodeIfPresent(_ type: Int.Type, forKey key: Key) throws -> Int? { guard try self.contains(key) && !self.decodeNil(forKey: key) else { return nil } return try self.decode(Int.self, forKey: key) } public func decodeIfPresent(_ type: Int8.Type, forKey key: Key) throws -> Int8? { guard try self.contains(key) && !self.decodeNil(forKey: key) else { return nil } return try self.decode(Int8.self, forKey: key) } public func decodeIfPresent(_ type: Int16.Type, forKey key: Key) throws -> Int16? { guard try self.contains(key) && !self.decodeNil(forKey: key) else { return nil } return try self.decode(Int16.self, forKey: key) } public func decodeIfPresent(_ type: Int32.Type, forKey key: Key) throws -> Int32? { guard try self.contains(key) && !self.decodeNil(forKey: key) else { return nil } return try self.decode(Int32.self, forKey: key) } public func decodeIfPresent(_ type: Int64.Type, forKey key: Key) throws -> Int64? { guard try self.contains(key) && !self.decodeNil(forKey: key) else { return nil } return try self.decode(Int64.self, forKey: key) } public func decodeIfPresent(_ type: UInt.Type, forKey key: Key) throws -> UInt? { guard try self.contains(key) && !self.decodeNil(forKey: key) else { return nil } return try self.decode(UInt.self, forKey: key) } public func decodeIfPresent(_ type: UInt8.Type, forKey key: Key) throws -> UInt8? { guard try self.contains(key) && !self.decodeNil(forKey: key) else { return nil } return try self.decode(UInt8.self, forKey: key) } public func decodeIfPresent(_ type: UInt16.Type, forKey key: Key) throws -> UInt16? { guard try self.contains(key) && !self.decodeNil(forKey: key) else { return nil } return try self.decode(UInt16.self, forKey: key) } public func decodeIfPresent(_ type: UInt32.Type, forKey key: Key) throws -> UInt32? { guard try self.contains(key) && !self.decodeNil(forKey: key) else { return nil } return try self.decode(UInt32.self, forKey: key) } public func decodeIfPresent(_ type: UInt64.Type, forKey key: Key) throws -> UInt64? { guard try self.contains(key) && !self.decodeNil(forKey: key) else { return nil } return try self.decode(UInt64.self, forKey: key) } public func decodeIfPresent(_ type: Float.Type, forKey key: Key) throws -> Float? { guard try self.contains(key) && !self.decodeNil(forKey: key) else { return nil } return try self.decode(Float.self, forKey: key) } public func decodeIfPresent(_ type: Double.Type, forKey key: Key) throws -> Double? { guard try self.contains(key) && !self.decodeNil(forKey: key) else { return nil } return try self.decode(Double.self, forKey: key) } public func decodeIfPresent(_ type: String.Type, forKey key: Key) throws -> String? { guard try self.contains(key) && !self.decodeNil(forKey: key) else { return nil } return try self.decode(String.self, forKey: key) } public func decodeIfPresent<T : Decodable>(_ type: T.Type, forKey key: Key) throws -> T? { guard try self.contains(key) && !self.decodeNil(forKey: key) else { return nil } return try self.decode(T.self, forKey: key) } } // Default implementation of decodeIfPresent(_:) in terms of decode(_:) and decodeNil() public extension UnkeyedDecodingContainer { mutating func decodeIfPresent(_ type: Bool.Type) throws -> Bool? { guard try !self.isAtEnd && !self.decodeNil() else { return nil } return try self.decode(Bool.self) } mutating func decodeIfPresent(_ type: Int.Type) throws -> Int? { guard try !self.isAtEnd && !self.decodeNil() else { return nil } return try self.decode(Int.self) } mutating func decodeIfPresent(_ type: Int8.Type) throws -> Int8? { guard try !self.isAtEnd && !self.decodeNil() else { return nil } return try self.decode(Int8.self) } mutating func decodeIfPresent(_ type: Int16.Type) throws -> Int16? { guard try !self.isAtEnd && !self.decodeNil() else { return nil } return try self.decode(Int16.self) } mutating func decodeIfPresent(_ type: Int32.Type) throws -> Int32? { guard try !self.isAtEnd && !self.decodeNil() else { return nil } return try self.decode(Int32.self) } mutating func decodeIfPresent(_ type: Int64.Type) throws -> Int64? { guard try !self.isAtEnd && !self.decodeNil() else { return nil } return try self.decode(Int64.self) } mutating func decodeIfPresent(_ type: UInt.Type) throws -> UInt? { guard try !self.isAtEnd && !self.decodeNil() else { return nil } return try self.decode(UInt.self) } mutating func decodeIfPresent(_ type: UInt8.Type) throws -> UInt8? { guard try !self.isAtEnd && !self.decodeNil() else { return nil } return try self.decode(UInt8.self) } mutating func decodeIfPresent(_ type: UInt16.Type) throws -> UInt16? { guard try !self.isAtEnd && !self.decodeNil() else { return nil } return try self.decode(UInt16.self) } mutating func decodeIfPresent(_ type: UInt32.Type) throws -> UInt32? { guard try !self.isAtEnd && !self.decodeNil() else { return nil } return try self.decode(UInt32.self) } mutating func decodeIfPresent(_ type: UInt64.Type) throws -> UInt64? { guard try !self.isAtEnd && !self.decodeNil() else { return nil } return try self.decode(UInt64.self) } mutating func decodeIfPresent(_ type: Float.Type) throws -> Float? { guard try !self.isAtEnd && !self.decodeNil() else { return nil } return try self.decode(Float.self) } mutating func decodeIfPresent(_ type: Double.Type) throws -> Double? { guard try !self.isAtEnd && !self.decodeNil() else { return nil } return try self.decode(Double.self) } mutating func decodeIfPresent(_ type: String.Type) throws -> String? { guard try !self.isAtEnd && !self.decodeNil() else { return nil } return try self.decode(String.self) } mutating func decodeIfPresent<T : Decodable>(_ type: T.Type) throws -> T? { guard try !self.isAtEnd && !self.decodeNil() else { return nil } return try self.decode(T.self) } } #endif
mit
2cd8faac603a1f05730cd18c57b89db3
48.865125
260
0.696182
4.483404
false
false
false
false
jjacobson93/RethinkDBSwift
Sources/RethinkDB/SCRAM.swift
1
5824
import Foundation import Cryptor func ^(_ a: [UInt8], _ b: [UInt8]) -> [UInt8] { return zip(a, b).map { (x, y) in return x ^ y } } let CLIENT_KEY = [UInt8]("Client Key".utf8) let SERVER_KEY = [UInt8]("Server Key".utf8) final public class SCRAMClient { let gs2BindFlag = "n,," let algorithm: HMAC.Algorithm public init(algorithm: HMAC.Algorithm) { self.algorithm = algorithm } private func fixUsername(username user: String) -> String { return user.replacingOccurrences(of: "=", with: "=3D").replacingOccurrences(of: ",", with: "=2C") } private func parse(challenge response: String) throws -> (nonce: String, salt: String, iterations: Int) { var nonce: String? = nil var iterations: Int? = nil var salt: String? = nil for part in response.characters.split(separator: ",") where String(part).characters.count >= 3 { let part = String(part) if let first = part.characters.first { let data = part[part.index(part.startIndex, offsetBy: 2)..<part.endIndex] switch first { case "r": nonce = data case "i": iterations = Int(data) case "s": salt = data default: break } } } if let nonce = nonce, let iterations = iterations, let salt = salt { return (nonce: nonce, salt: salt, iterations: iterations) } throw SCRAMError.challengeParseError(challenge: response) } private func parse(finalResponse response: String) throws -> [UInt8] { var signature: [UInt8]? = nil for part in response.characters.split(separator: ",") where String(part).characters.count >= 3 { let part = String(part) if let first = part.characters.first { let data = part[part.index(part.startIndex, offsetBy: 2)..<part.endIndex] switch first { case "v": signature = Data(base64Encoded: data)?.byteArray default: break } } } if let signature = signature { return signature } throw SCRAMError.responseParseError(response: response) } private static func hmac(key: [UInt8], message: [UInt8]) throws -> [UInt8] { guard let bytes = HMAC(using: .sha256, key: key).update(byteArray: message)?.final() else { throw SCRAMError.digestFailure(key, message) } return bytes } // public public func authenticate(_ username: String, usingNonce nonce: String) throws -> String { return "\(gs2BindFlag)n=\(fixUsername(username: username)),r=\(nonce)" } public func process(_ challenge: String, with details: (username: String, password: String), usingNonce nonce: String) throws -> (proof: String, serverSignature: [UInt8]) { let encodedHeader = Data(gs2BindFlag.utf8).base64EncodedString() let parsedResponse = try parse(challenge: challenge) let remoteNonce = parsedResponse.nonce guard String(remoteNonce[remoteNonce.startIndex..<remoteNonce.index(remoteNonce.startIndex, offsetBy: 24)]) == nonce else { throw SCRAMError.invalidNonce(nonce: parsedResponse.nonce) } let noProof = "c=\(encodedHeader),r=\(parsedResponse.nonce)" guard let salt = Data(base64Encoded: parsedResponse.salt)?.byteArray else { throw SCRAMError.base64Failure(original: parsedResponse.salt) } //let saltedPassword = try PBKDF2.calculate(details.password, usingSalt: salt, iterating: parsedResponse.iterations, algorithm: self.algorithm) let saltedPassword = PBKDF.deriveKey(fromPassword: details.password, salt: salt, prf: .sha256, rounds: UInt32(parsedResponse.iterations), derivedKeyLength: UInt(Cryptor.Algorithm.aes256.defaultKeySize)) let clientKey = try SCRAMClient.hmac(key: saltedPassword, message: CLIENT_KEY) let serverKey = try SCRAMClient.hmac(key: saltedPassword, message: SERVER_KEY) guard let storedKey = Digest(using: .sha256).update(byteArray: clientKey)?.final() else { throw SCRAMError.digestFailure(clientKey, []) } let authMessage = "n=\(fixUsername(username: details.username)),r=\(nonce),\(challenge),\(noProof)" let authMessageBytes = [UInt8](authMessage.utf8) let clientSignature = try SCRAMClient.hmac(key: storedKey, message: authMessageBytes) let clientProof = zip(clientKey, clientSignature).map({ $0 ^ $1 }) let serverSignature = try SCRAMClient.hmac(key: serverKey, message: authMessageBytes) let proof = Data(bytes: clientProof).base64EncodedString() return (proof: "\(noProof),p=\(proof)", serverSignature: serverSignature) } public func complete(fromResponse response: String, verifying signature: [UInt8]) throws -> String { let sig = try parse(finalResponse: response) if sig != signature { throw SCRAMError.invalidSignature(signature: sig) } return "" } } public enum SCRAMError: Error { case invalidSignature(signature: [UInt8]) case base64Failure(original: String) case challengeParseError(challenge: String) case responseParseError(response: String) case invalidNonce(nonce: String) case digestFailure([UInt8], [UInt8]) }
mit
2144259abf7beba322644a486408b453
37.315789
210
0.59375
4.490362
false
false
false
false
tanbiao/TitleLabelView
TitleLabelView/TitleLabelView/LabelStyle.swift
1
1035
// // LabelStyle.swift // test1 // // Created by 西乡流水 on 17/5/12. // Copyright © 2017年 西乡流水. All rights reserved. // import UIKit struct LabelStyle { //labelView内间距 var labelViewInsert = UIEdgeInsets(top: 10, left: 0, bottom: 10, right: 0) /**item之间的水平间距*/ var itemMargin : CGFloat = 5 /// item之间的上下间距 var lineMargin : CGFloat = 20 /// labelView的背景颜色 var labelViewBackGroundColor : UIColor = UIColor.white /// item的文字颜色 var textColor : UIColor = UIColor.gray /// item的背景颜色 var itemBackGroundColor : UIColor = UIColor.green /// item的圆角半径 var itemCornerRadius : CGFloat = 5 /// item的文字字体 var textFont :UIFont = UIFont.systemFont(ofSize: 14) /// 是否可以滚动 var LabelViewIsScroll : Bool = true /// 在选择item的时候是否删除当前item,false : 表示 var selectItemIsDelete : Bool = true }
gpl-3.0
d699f940014f77d6ea15e933aeff96df
19.744186
78
0.625561
3.828326
false
false
false
false
ambas/ExpandableTransition
Demo/Demo/Models/Movie.swift
1
837
// // Movie.swift // Demo // // Created by Ambas Chobsanti on 8/20/2558 BE. // Copyright (c) 2558 Ambas. All rights reserved. // import Foundation struct Movie { var movieTitle : String var photoPath : String var tagline : String var overview : String var rating : Float var director : String var budget : String var studio : String init(movieDict : [String : AnyObject]) { movieTitle = movieDict["movieTitle"] as! String photoPath = movieDict["posterPath"] as! String tagline = movieDict["tagline"] as! String overview = movieDict["overview"] as! String rating = movieDict["rating"] as! Float budget = movieDict["budget"] as! String director = movieDict["director"] as! String studio = movieDict["studio"] as! String } }
mit
cc924ffd3316bdedc58a04839131364b
26
55
0.628435
3.985714
false
false
false
false
blinksh/blink
Settings/Model/Archive.swift
1
10467
////////////////////////////////////////////////////////////////////////////////// // // B L I N K // // Copyright (C) 2016-2019 Blink Mobile Shell Project // // This file is part of Blink. // // Blink is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // Blink is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Blink. If not, see <http://www.gnu.org/licenses/>. // // In addition, Blink is also subject to certain additional terms under // GNU GPL version 3 section 7. // // You should have received a copy of these additional terms immediately // following the terms and conditions of the GNU General Public License // which accompanied the Blink Source Code. If not, see // <http://www.github.com/blinksh/blink>. // //////////////////////////////////////////////////////////////////////////////// import Foundation import System import AppleArchive import CryptoKit import BlinkConfig import SSH struct Archive { struct Error: Swift.Error { let description: String init(_ description: String) { self.description = description } } let tmpDirectoryURL: URL private init() throws { let fm = FileManager.default try self.tmpDirectoryURL = fm.url(for: .itemReplacementDirectory, in: .userDomainMask, appropriateFor: BlinkPaths.blinkURL(), create: true) } static func export(to archiveURL: URL, password: String) throws { #if targetEnvironment(simulator) throw Error("Simulator") #else // Copy everything to the temporary directory // Import keys there let arch = try Archive() try arch.copyAllDataToTmpDirectory() guard let context = arch.createEncryptionContext(password) else { throw Error("Could not create encryption for given password") } guard let sourcePath = FilePath(arch.tmpDirectoryURL) else { throw Error("Bad source for archive") } guard let destinationPath = FilePath(archiveURL) else { throw Error("Bad destination for archive") } guard let archiveFileStream = ArchiveByteStream.fileStream( path: destinationPath, mode: .writeOnly, options: [.create, .truncate], permissions: FilePermissions(rawValue: 0o644) ) else { throw Error("Could not create File Stream") } guard let encryptionStream = ArchiveByteStream.encryptionStream( writingTo: archiveFileStream, encryptionContext: context), let encoderStream = AppleArchive.ArchiveStream.encodeStream(writingTo: encryptionStream) else { throw Error("Could not create encryption streams for archive") } let fm = FileManager.default defer { try? encoderStream.close() try? encryptionStream.close() try? archiveFileStream.close() try? fm.removeItem(at: arch.tmpDirectoryURL) } // Archive do { try encoderStream.writeDirectoryContents(archiveFrom: sourcePath, keySet: .defaultForArchive)// (archiveFrom: source, path: .FieldKeySet("*")) } catch { throw Error("Writing directory contents - \(error)") } #endif // TODO Open on the other side, the activateFileViewerSelecting } // Recover from an archive file. This operation may overwrite current configuration. static func recover(from archiveURL: URL, password: String) throws { // Extract let homeURL = URL(fileURLWithPath: BlinkPaths.homePath()) try extract(from: archiveURL, password: password, to: homeURL) // Import information (keys) try recoverKeys(from: homeURL) BKHosts.loadHosts() BKHosts.resetHostsiCloudInformation() } static func extract(from archiveURL: URL, password: String, to destinationURL: URL) throws { #if targetEnvironment(simulator) throw Error("Simulator") #else guard let sourcePath = FilePath(archiveURL) else { throw Error("Wrong source path.") } guard let destinationPath = FilePath(destinationURL) else { throw Error("Wrong destination path.") } guard let archiveFileStream = ArchiveByteStream.fileStream( path: sourcePath, mode: .readOnly, options: [], permissions: []), let context = ArchiveEncryptionContext(from: archiveFileStream) else { throw Error("Invalid archive file") } guard let sKey = SymmetricKey(fromPassword: password) else { throw Error("Invalid password for key") } do { try context.setSymmetricKey(sKey) } catch { throw Error("Invalid password for key") } guard let decryptionStream = ArchiveByteStream.decryptionStream( readingFrom: archiveFileStream, encryptionContext: context), let decoderStream = ArchiveStream.decodeStream(readingFrom: decryptionStream) else { throw Error("Error on decryption streams. Bad password?") } guard let extractStream = ArchiveStream.extractStream(extractingTo: destinationPath) else { throw Error("Error creating extraction stream.") } defer { try? archiveFileStream.close() try? decryptionStream.close() try? decoderStream.close() try? extractStream.close() } do { try ArchiveStream.process(readingFrom: decoderStream, writingTo: extractStream) } catch { throw Error("Error extracting archive elements. \(error)") } #endif } static func recoverKeys(from homeURL: URL) throws { let fm = FileManager.default let keysDirectoryURL = homeURL.appendingPathComponent(".keys", isDirectory: true) let keyNames = try fm.contentsOfDirectory(at: keysDirectoryURL, includingPropertiesForKeys: nil) .filter { $0.lastPathComponent.split(separator: ".").count == 1 } .map { $0.lastPathComponent } defer { try? fm.removeItem(at: keysDirectoryURL) } var failedKeys = [String]() keyNames.forEach { keyName in do { if BKPubKey.withID(keyName) != nil { throw Error("Key already exists \(keyName)") } // Import and store let keyURL = keysDirectoryURL.appendingPathComponent(keyName) let keyBlob = try Data(contentsOf: keyURL) //try Data(contentsOf: keyURL.appendingPathExtension("pub")) let certBlob = try? Data(contentsOf: keysDirectoryURL.appendingPathComponent("\(keyName)-cert.pub")) let pubkeyComponents = try String(contentsOf: keyURL.appendingPathExtension("pub")).split(separator: " ") var pubkeyComment = "" if pubkeyComponents.count >= 3 { pubkeyComment = pubkeyComponents[2...].joined(separator: " ") } let key = try SSHKey(fromFileBlob: keyBlob, passphrase: "", withPublicFileCertBlob: certBlob) if let comment = key.comment, !comment.isEmpty { try BKPubKey.addKeychainKey(id: keyName, key: key, comment: comment) } else { try BKPubKey.addKeychainKey(id: keyName, key: key, comment: pubkeyComment) } } catch { failedKeys.append(keyName) } } if !failedKeys.isEmpty { throw Error("The following keys failed to migrate, please move them manually: \(failedKeys.joined(separator: ", "))") } } private func copyAllDataToTmpDirectory() throws { let fm = FileManager.default // Copy everything let blinkURL = BlinkPaths.blinkURL()! let sshURL = BlinkPaths.sshURL()! // .blink folder try fm.copyItem(at: blinkURL, to: tmpDirectoryURL.appendingPathComponent(".blink")) try fm.copyItem(at: sshURL, to: tmpDirectoryURL.appendingPathComponent(".ssh")) try? fm.removeItem(at: tmpDirectoryURL.appendingPathComponent(".blink/keys")) // TODO Remove the keys file, as keys cannot be imported to other app. Not sure this is true // within the same version of the app, even across devices, something to test. let keysDirectory = tmpDirectoryURL.appendingPathComponent(".keys") try fm.createDirectory(at: keysDirectory, withIntermediateDirectories: false, attributes: nil) // Read each key and store it within the FS // For each identity, get the Privatekey, Publickey and Certificate try BKPubKey.all().forEach { card in if card.storageType == BKPubKeyStorageTypeSecureEnclave { return } guard let privateKey = card.loadPrivateKey() else { throw Error("Could not read private key for \(card.id)") } let publicKey = card.publicKey let cert = card.loadCertificate() try privateKey .write(to: keysDirectory.appendingPathComponent("\(card.id)"), atomically: true, encoding: .utf8) try publicKey .write(to: keysDirectory.appendingPathComponent("\(card.id).pub"), atomically: true, encoding: .utf8) try cert? .write(to: keysDirectory.appendingPathComponent("\(card.id)-cert.pub"), atomically: true, encoding: .utf8) } } // static func import(from path: URL, password: String) {} #if !targetEnvironment(simulator) private func createEncryptionContext(_ password: String) -> ArchiveEncryptionContext? { // Configure encryption // let sKey = SymmetricKey(size: .bits256) guard let sKey = SymmetricKey(fromPassword: password) else { return nil } let context = ArchiveEncryptionContext( profile: .hkdf_sha256_aesctr_hmac__symmetric__none, compressionAlgorithm: .lzfse ) do { try context.setSymmetricKey(sKey) return context } catch { return nil } } #endif } extension SymmetricKey { init?(fromPassword password: String) { guard let passwordData = password.data(using: .utf8), let passwordHash = String( // 256-bit hash SHA256.hash(data: passwordData).map({ String(format: "%02hhx", $0) }).joined().prefix(32) ).data(using: .utf8) else { return nil } self = SymmetricKey(data: passwordHash) } }
gpl-3.0
2386c66e452324ad43e8c71bb225c8eb
32.228571
148
0.658068
4.560784
false
false
false
false
xedin/swift
test/DebugInfo/struct_resilience.swift
3
1474
// RUN: %empty-directory(%t) // // Compile the external swift module. // RUN: %target-swift-frontend -g -emit-module -enable-library-evolution \ // RUN: -emit-module-path=%t/resilient_struct.swiftmodule \ // RUN: -module-name=resilient_struct %S/../Inputs/resilient_struct.swift // // RUN: %target-swift-frontend -g -I %t -emit-ir -enable-library-evolution %s \ // RUN: -o - | %FileCheck %s // import resilient_struct // CHECK-LABEL: define{{.*}} swiftcc void @"$s17struct_resilience9takesSizeyy010resilient_A00D0VF"(%swift.opaque* noalias nocapture) // CHECK-LLDB-LABEL: define{{.*}} swiftcc void @"$s17struct_resilience9takesSizeyy010resilient_A00D0VF"(%T16resilient_struct4SizeV* noalias nocapture dereferenceable({{8|16}})) public func takesSize(_ s: Size) {} // CHECK-LABEL: define{{.*}} swiftcc void @"$s17struct_resilience1fyyF"() // CHECK-LLDB-LABEL: define{{.*}} swiftcc void @"$s17struct_resilience1fyyF"() func f() { let s1 = Size(w: 1, h: 2) takesSize(s1) // CHECK: %[[ADDR:.*]] = alloca i8* // CHECK: call void @llvm.dbg.declare(metadata i8** %[[ADDR]], // CHECK-SAME: metadata ![[V1:[0-9]+]], // CHECK-SAME: metadata !DIExpression(DW_OP_deref)) // CHECK: %[[S1:.*]] = alloca i8, // CHECK: store i8* %[[S1]], i8** %[[ADDR]] } f() // CHECK: ![[TY:[0-9]+]] = !DICompositeType(tag: DW_TAG_structure_type, name: "Size", // CHECK: ![[V1]] = !DILocalVariable(name: "s1", {{.*}}type: ![[TY]])
apache-2.0
de804211bac25f11ee1ca2db783db415
41.114286
176
0.632293
3.176724
false
false
false
false
Bizzi-Body/Bizzi-Body-ParseTutorialPart6-Complete-Solution
SignUpInViewController.swift
1
4352
// // SignUpInViewController.swift // ParseTutorial // // Created by Ian Bradbury on 10/02/2015. // Copyright (c) 2015 bizzi-body. All rights reserved. // import UIKit class SignUpInViewController: UIViewController { @IBOutlet weak var activityIndicator: UIActivityIndicatorView! @IBOutlet weak var message: UILabel! @IBOutlet weak var emailAddress: UITextField! @IBOutlet weak var password: UITextField! @IBAction func signUp(sender: AnyObject) { // Build the terms and conditions alert let alertController = UIAlertController(title: "Agree to terms and conditions", message: "Click I AGREE to signal that you agree to the End User Licence Agreement.", preferredStyle: UIAlertControllerStyle.Alert ) alertController.addAction(UIAlertAction(title: "I AGREE", style: UIAlertActionStyle.Default, handler: { alertController in self.processSignUp()}) ) alertController.addAction(UIAlertAction(title: "I do NOT agree", style: UIAlertActionStyle.Default, handler: nil) ) // Display alert self.presentViewController(alertController, animated: true, completion: nil) } @IBAction func signIn(sender: AnyObject) { activityIndicator.hidden = false activityIndicator.startAnimating() var userEmailAddress = emailAddress.text userEmailAddress = userEmailAddress.lowercaseString var userPassword = password.text PFUser.logInWithUsernameInBackground(userEmailAddress, password:userPassword) { (user: PFUser?, error: NSError?) -> Void in if user!["emailVerified"] as! Bool == true { dispatch_async(dispatch_get_main_queue()) { self.performSegueWithIdentifier( "signInToNavigation", sender: self ) } } else { // User needs to verify email address before continuing let alertController = UIAlertController( title: "Email address verification", message: "We have sent you an email that contains a link - you must click this link before you can continue.", preferredStyle: UIAlertControllerStyle.Alert ) alertController.addAction(UIAlertAction(title: "OKAY", style: UIAlertActionStyle.Default, handler: { alertController in self.processSignOut()}) ) // Display alert self.presentViewController( alertController, animated: true, completion: nil ) } } } // Main viewDidLoad method override func viewDidLoad() { super.viewDidLoad() activityIndicator.hidden = true activityIndicator.hidesWhenStopped = true } // Sign the current user OUT of the app func processSignOut() { // // Sign out PFUser.logOut() // Display sign in / up view controller let storyboard = UIStoryboard(name: "Main", bundle: nil) let vc = storyboard.instantiateViewControllerWithIdentifier("SignUpInViewController") as! UIViewController self.presentViewController(vc, animated: true, completion: nil) } // Sign UP method that is called when once a user has accepted the terms and conditions func processSignUp() { var userEmailAddress = emailAddress.text var userPassword = password.text // Ensure username is lowercase userEmailAddress = userEmailAddress.lowercaseString // Add email address validation // Start activity indicator activityIndicator.hidden = false activityIndicator.startAnimating() // Create the user var user = PFUser() user.username = userEmailAddress user.password = userPassword user.email = userEmailAddress user.signUpInBackgroundWithBlock { (succeeded: Bool, error: NSError?) -> Void in if error == nil { // User needs to verify email address before continuing let alertController = UIAlertController(title: "Email address verification", message: "We have sent you an email that contains a link - you must click this link before you can continue.", preferredStyle: UIAlertControllerStyle.Alert ) alertController.addAction(UIAlertAction(title: "OKAY", style: UIAlertActionStyle.Default, handler: { alertController in self.processSignOut()}) ) // Display alert self.presentViewController(alertController, animated: true, completion: nil) } else { self.activityIndicator.stopAnimating() if let message: AnyObject = error!.userInfo!["error"] { self.message.text = "\(message)" } } } } }
mit
c0928e1c98417fb5797769439d9d21a4
28.208054
115
0.720129
4.431772
false
false
false
false
playstones/NEKit
GenerateCommonCryptoModule.swift
2
3810
import Foundation let verbose = true // MARK: - Exception Handling let handler: @convention(c) (NSException) -> Void = { exception in print("FATAL EXCEPTION: \(exception)") exit(1) } NSSetUncaughtExceptionHandler(handler) // MARK: - Task Utilities func runShellCommand(command: String) -> String? { let args: [String] = command.split { $0 == " " }.map(String.init) let other = args[1..<args.count] let outputPipe = Pipe() let task = Process() task.launchPath = args[0] task.arguments = other.map { $0 } task.standardOutput = outputPipe task.launch() task.waitUntilExit() guard task.terminationStatus == 0 else { return nil } let outputData = outputPipe.fileHandleForReading.readDataToEndOfFile() return String(data:outputData, encoding: String.Encoding.utf8) } // MARK: - File System Utilities func fileExists(filePath: String) -> Bool { return FileManager.default.fileExists(atPath: filePath) } func mkdir(path: String) -> Bool { do { try FileManager.default.createDirectory(atPath: path, withIntermediateDirectories: true, attributes: nil) return true } catch { return false } } // MARK: - String Utilities func trim(_ s: String) -> String { return ((s as NSString).trimmingCharacters(in: NSCharacterSet.whitespacesAndNewlines) as String) } func trim(_ s: String?) -> String? { return (s == nil) ? nil : (trim(s!) as String) } func reportError(message: String) -> Never { print("ERROR: \(message)") exit(1) } // MARK: GenerateCommonCryptoModule enum SDK: String { case iOS = "iphoneos", iOSSimulator = "iphonesimulator", watchOS = "watchos", watchSimulator = "watchsimulator", tvOS = "appletvos", tvOSSimulator = "appletvsimulator", MacOSX = "macosx" static let all = [iOS, iOSSimulator, watchOS, watchSimulator, tvOS, tvOSSimulator, MacOSX] } guard let sdk = SDK(rawValue: CommandLine.arguments[1])?.rawValue else { reportError(message: "SDK must be one of \(SDK.all.map { $0.rawValue })") } guard let sdkVersion = trim(runShellCommand(command: "/usr/bin/xcrun --sdk \(sdk) --show-sdk-version")) else { reportError(message: "ERROR: Failed to determine SDK version for \(sdk)") } guard let sdkPath = trim(runShellCommand(command: "/usr/bin/xcrun --sdk \(sdk) --show-sdk-path")) else { reportError(message: "ERROR: Failed to determine SDK path for \(sdk)") } if verbose { print("SDK: \(sdk)") print("SDK Version: \(sdkVersion)") print("SDK Path: \(sdkPath)") } let moduleDirectory: String let moduleFileName: String if CommandLine.arguments.count > 2 { moduleDirectory = "\(CommandLine.arguments[2])/Frameworks/\(sdk)/CommonCrypto.framework" moduleFileName = "module.map" } else { moduleDirectory = "\(sdkPath)/System/Library/Frameworks/CommonCrypto.framework" moduleFileName = "module.map" if fileExists(filePath: moduleDirectory) { reportError(message: "Module directory already exists at \(moduleDirectory).") } } if !mkdir(path: moduleDirectory) { reportError(message: "Failed to create module directory \(moduleDirectory)") } let headerDir = "\(sdkPath)/usr/include/CommonCrypto/" let headerFile1 = "\(headerDir)/CommonCrypto.h" let headerFile2 = "\(headerDir)/CommonRandom.h" let moduleMapFile = "module CommonCrypto [system] {\n" + " header \"\(headerFile1)\"\n" + " header \"\(headerFile2)\"\n" + " export *\n" + "}\n" let moduleMapPath = "\(moduleDirectory)/\(moduleFileName)" do { try moduleMapFile.write(toFile: moduleMapPath, atomically: true, encoding:String.Encoding.utf8) print("Successfully created module \(moduleMapPath)") exit(0) } catch { reportError(message: "Failed to write module map file to \(moduleMapPath)") }
bsd-3-clause
e9389a85ace0a10faa21d0917f8aff68
30.229508
148
0.681627
3.860182
false
false
false
false
justindarc/focus
ScreenshotTests/MarketingTests.swift
5
816
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import XCTest class MarketingTests: XCTestCase { override func setUp() { super.setUp() continueAfterFailure = false let app = XCUIApplication() setupSnapshot(app) app.launch() } func testMarketingScreenshots() { let app = XCUIApplication() if UIDevice.current.userInterfaceIdiom == .pad { XCUIDevice.shared().orientation = .landscapeLeft } app.buttons["FirstRunViewController.button"].tap() snapshot("01Home") app.buttons["HomeView.settingsButton"].tap() snapshot("02Settings") } }
mpl-2.0
4ccb493d7e02802557932bffc66d941a
28.142857
70
0.636029
4.58427
false
true
false
false
austinzmchen/guildOfWarWorldBosses
GoWWorldBosses/ViewControllers/Drawers/WBDrawerMasterViewController.swift
1
4724
// // WBDrawerMasterViewController.swift // GoWWorldBosses // // Created by Austin Chen on 2016-11-27. // Copyright © 2016 Austin Chen. All rights reserved. // import UIKit import KYDrawerController protocol WBDrawerItemViewControllerType: class { var viewDelegate: WBDrawerMasterViewControllerDelegate? {get set} } protocol WBDrawerMasterViewControllerDelegate: class { func didTriggerToggleButton() func drawerItemVCShouldChange() } enum DrawerOpeningState { case closed case open } class WBDrawerMasterViewController: UINavigationController { fileprivate var selectedDrawerItem: WBDrawerItem? let drawerVC = WBStoryboardFactory.drawerStoryboard.instantiateViewController(withIdentifier: "drawerVC") as! WBDrawerViewController fileprivate var drawerOpeningState: DrawerOpeningState = .closed func setDrawerOpeningState(_ state: DrawerOpeningState, animated: Bool = true, completion: ((_ stateChange: Bool) -> ())? = nil) { guard state != self.drawerOpeningState else { if let c = completion { c(false) } return } switch state { case .open: self.present(drawerVC, animated: false, completion: { if let c = completion { c(true) } }) // if using animated true, there will be a glitch where two phase, first phase fading in, second phase blurring case .closed: if animated { drawerVC.dismiss(animated: animated, completion: { if let c = completion { c(true) } }) } else { if let c = completion { c(true) } } break } self.drawerOpeningState = state } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. drawerVC.delegate = self drawerVC.viewDelegate = self // set up main let timerNavVC = WBStoryboardFactory.timerStoryboard.instantiateViewController(withIdentifier: "timerNavVC") as! UINavigationController let timerVC = timerNavVC.viewControllers.first as! WBMainViewController timerVC.viewDelegate = self self.viewControllers = [timerVC] } func presentDrawerItemViewController(drawerItem: WBDrawerItem) { let vc = WBStoryboardFactory.storyboard(byFileName: drawerItem.storyboardFileName)?.instantiateViewController(withIdentifier: drawerItem.storyboardID) if let navVC = vc as? UINavigationController, let rootVC = navVC.viewControllers.first, let drawerItemVC = rootVC as? WBDrawerItemViewControllerType { drawerItemVC.viewDelegate = self self.viewControllers = [rootVC] } } func presentAPIKeyEntryViewController() { let navVC = WBStoryboardFactory.apiKeyEntryStoryboard.instantiateInitialViewController() as! UINavigationController if let rootVC = navVC.viewControllers.first as? WBAPIKeyEntryViewController { rootVC.isShownFullscreen = false rootVC.viewDelegate = self self.viewControllers = [rootVC] } } } extension WBDrawerMasterViewController: WBDrawerViewControllerDelegate { func didSelect(drawerItem: WBDrawerItem, atIndex index: Int) { selectedDrawerItem = drawerItem // set drawer selected state // let drawerVC = (self.drawerViewController as! UINavigationController).viewControllers.first as! WBDrawerViewController drawerVC.selectedDrawerItem = self.selectedDrawerItem drawerVC.tableView?.reloadData() if !WBKeyStore.isAccountAvailable && drawerItem.title != "Boss Timers" { self.presentAPIKeyEntryViewController() } else { self.presentDrawerItemViewController(drawerItem: drawerItem) } self.setDrawerOpeningState(.closed) } } extension WBDrawerMasterViewController: WBDrawerMasterViewControllerDelegate { func didTriggerToggleButton() { switch drawerOpeningState { // current state case .closed: self.setDrawerOpeningState(.open) case .open: if !WBKeyStore.isAccountAvailable { self.presentAPIKeyEntryViewController() } self.setDrawerOpeningState(.closed) } } func drawerItemVCShouldChange() { guard let drawerItem = selectedDrawerItem else { return } self.presentDrawerItemViewController(drawerItem: drawerItem) } }
mit
0165f71eb90addd11c05cab16272e1c3
32.978417
158
0.650434
5.218785
false
false
false
false
ustwo/formvalidator-swift
Example/macOS/AppDelegate.swift
1
1598
// // AppDelegate.swift // FormValidatorSwift // // Created by Aaron McTavish on 06/01/2017. // Copyright © 2017 ustwo Fampany Ltd. All rights reserved. // import Cocoa @NSApplicationMain class AppDelegate: NSObject, NSApplicationDelegate { // MARK: - Properties lazy var window: NSWindow = { let result = NSWindow(contentRect: NSRect(x: 0, y: 0, width: NSScreen.main!.frame.width / 2.0, height: NSScreen.main!.frame.height / 2.0), styleMask: [NSWindow.StyleMask.titled, NSWindow.StyleMask.miniaturizable, NSWindow.StyleMask.resizable, NSWindow.StyleMask.closable], backing: .buffered, defer: false) result.title = "New Window" result.isOpaque = false result.center() result.isMovableByWindowBackground = true result.backgroundColor = NSColor.white return result }() // MARK: - NSApplicationDelegate func applicationWillFinishLaunching(_ notification: Notification) { if #available(macOS 10.14, *) { NSApp.appearance = NSAppearance(named: .aqua) } } func applicationDidFinishLaunching(_ notification: Notification) { let viewController = FormViewController() window.contentViewController = viewController window.makeKeyAndOrderFront(self) } }
mit
c1b327bce10ad44ee97a80cf8b864644
29.711538
163
0.557921
5.663121
false
false
false
false
krevis/MIDIApps
Frameworks/SnoizeMIDI/Source.swift
1
3054
/* Copyright (c) 2021, Kurt Revis. All rights reserved. This source code is licensed under the BSD-style license found in the LICENSE file in the root directory of this source tree. */ import Foundation import CoreMIDI public class Source: Endpoint, CoreMIDIObjectListable { // MARK: CoreMIDIObjectListable static let midiObjectType = MIDIObjectType.source static func midiObjectCount(_ context: CoreMIDIContext) -> Int { context.interface.getNumberOfSources() } static func midiObjectSubscript(_ context: CoreMIDIContext, _ index: Int) -> MIDIObjectRef { context.interface.getSource(index) } override func midiPropertyChanged(_ property: CFString) { super.midiPropertyChanged(property) if property == kMIDIPropertyConnectionUniqueID || property == kMIDIPropertyName { // This may affect our displayName midiContext.forcePropertyChanged(Self.midiObjectType, midiObjectRef, kMIDIPropertyDisplayName) } if property == kMIDIPropertyDisplayName { // FUTURE: Something more targeted would be nice. midiContext.postObjectListChangedNotification(Self.midiObjectType) } } // MARK: Additional API public func remove() { // Only possible for virtual endpoints owned by this process guard midiObjectRef != 0 && isOwnedByThisProcess else { return } _ = midiContext.interface.endpointDispose(endpointRef) // This object continues to live in the endpoint list until CoreMIDI notifies us, at which time we remove it. // There is no need for us to remove it immediately. (In fact, it's better that we don't; // it's possible that CoreMIDI has enqueued notifications to us about the endpoint, including the notification // that it was added in the first place. If we get that AFTER we remove it from the list, we'll add it again.) } } extension CoreMIDIContext { public func createVirtualSource(name: String, uniqueID: MIDIUniqueID) -> Source? { // If newUniqueID is 0, we'll use the unique ID that CoreMIDI generates for us var newEndpointRef: MIDIEndpointRef = 0 guard interface.sourceCreate(client, name as CFString, &newEndpointRef) == noErr else { return nil } // We want to get at the Source immediately, to configure it. // CoreMIDI will send us a notification that something was added, // but that won't arrive until later. So manually add the new Source, // trusting that we won't add it again later. guard let source = addedVirtualSource(midiObjectRef: newEndpointRef) else { return nil } if uniqueID != 0 { source.uniqueID = uniqueID } while source.uniqueID == 0 { // CoreMIDI didn't assign a unique ID to this endpoint, so we should generate one ourself source.uniqueID = generateNewUniqueID() } source.manufacturer = "Snoize" source.model = name return source } }
bsd-3-clause
8c8ac3d0ad83e806336ec989a9b3b72e
36.703704
118
0.683039
4.801887
false
false
false
false
Mikelulu/BaiSiBuDeQiJie
LKBS/Pods/BMPlayer/Source/BMPlayerProtocols.swift
1
589
// // BMPlayerProtocols.swift // Pods // // Created by BrikerMan on 16/4/30. // // import UIKit extension BMPlayerControlView { public enum ButtonType: Int { case play = 101 case pause = 102 case back = 103 case fullscreen = 105 case replay = 106 } } extension BMPlayer { static func formatSecondsToString(_ secounds: TimeInterval) -> String { let Min = Int(secounds / 60) let Sec = Int(secounds.truncatingRemainder(dividingBy: 60)) return String(format: "%02d:%02d", Min, Sec) } }
mit
d8cad7470b48c9f00f4ee9c4ee62ba2c
20.814815
75
0.590832
3.8
false
false
false
false
crspybits/SyncServerII
Sources/Server/Account Specifics/Google/GoogleCreds+CloudStorage.swift
1
29134
// // GoogleCreds.swift // Server // // Created by Christopher Prince on 12/22/16. // // import LoggerAPI import KituraNet import Foundation import SyncServerShared // TODO: *0* Need automatic refreshing of the access token-- this should make client side testing easier: There should be no need to create a new access token every hour. // TODO: *5* It looks like if we give the user a reader-only role on a file, then they will not be able to modify it. Which will help in terms of users potentially modifying SyncServer files and messing things up. See https://developers.google.com/drive/v3/reference/permissions QUESTION: Will the user then be able to delete the file? private let folderMimeType = "application/vnd.google-apps.folder" extension GoogleCreds : CloudStorage { enum ListFilesError : Swift.Error { case badStatusCode(HTTPStatusCode?) case nilAPIResult case badJSONResult case expiredOrRevokedToken } private static let md5ChecksumKey = "md5Checksum" private func revokedOrExpiredToken(result: APICallResult?) -> Bool { if let result = result { switch result { case .dictionary(let dict): if dict["error"] as? String == self.tokenRevokedOrExpired { return true } default: break } } return false } /* If this isn't working for you, try: curl -H "Authorization: Bearer YourAccessToken" https://www.googleapis.com/drive/v3/files at the command line. */ /* For query parameter, see https://developers.google.com/drive/v3/web/search-parameters fieldsReturned parameter indicates the collection of fields to be returned in the, scoped over the entire response (not just the files resources). See https://developers.google.com/drive/v3/web/performance#partial E.g., "files/id,files/size" See also see http://stackoverflow.com/questions/35143283/google-drive-api-v3-migration */ // Not marked private for testing purposes. Don't call this directly outside of this class otherwise. func listFiles(query:String? = nil, fieldsReturned:String? = nil, completion:@escaping (_ fileListing:[String: Any]?, Swift.Error?)->()) { var urlParameters = "" if fieldsReturned != nil { urlParameters = "fields=" + fieldsReturned! } if query != nil { if urlParameters.count != 0 { urlParameters += "&" } urlParameters += "q=" + query! } var urlParams:String? = urlParameters if urlParameters.count == 0 { urlParams = nil } self.apiCall(method: "GET", path: "/drive/v3/files", urlParameters:urlParams) {[unowned self] (apiResult, statusCode, responseHeaders) in if self.revokedOrExpiredToken(result: apiResult) { completion(nil, ListFilesError.expiredOrRevokedToken) return } var error:ListFilesError? if statusCode != HTTPStatusCode.OK { error = .badStatusCode(statusCode) } guard apiResult != nil else { completion(nil, ListFilesError.nilAPIResult) return } guard case .dictionary(let dictionary) = apiResult! else { completion(nil, ListFilesError.badJSONResult) return } completion(dictionary, error) } } enum SearchError : Swift.Error { case noIdInResultingJSON case moreThanOneItemWithName case noJSONDictionaryResult case expiredOrRevokedToken } enum SearchType { case folder // If parentFolderId is nil, the root folder is assumed. case file(mimeType:String, parentFolderId:String?) case any // folders or files } struct SearchResult { let itemId:String // Google specific result-- a partial files resource for the file. // Contains fields: size, and id let dictionary:[String: Any] // Non-nil for files. let checkSum: String? } // Considers it an error for there to be more than one item with the given name. // Not marked private for testing purposes. Don't call this directly outside of this class otherwise. func searchFor(_ searchType: SearchType, itemName:String, completion:@escaping (_ result:SearchResult?, Swift.Error?)->()) { var query:String = "" switch searchType { case .folder: query = "mimeType='\(folderMimeType)' and " case .file(mimeType: let mimeType, parentFolderId: let parentFolderId): query += "mimeType='\(mimeType)' and " // See https://developers.google.com/drive/v3/web/folder var folderId = "root" if parentFolderId != nil { folderId = parentFolderId! } query += "'\(folderId)' in parents and " case .any: break } query += "name='\(itemName)' and trashed=false" // The structure of this wasn't obvious to me-- it's scoped over the entire response object, not just within the files resource. See also http://stackoverflow.com/questions/38853938/google-drive-api-v3-invalid-field-selection // And see https://developers.google.com/drive/api/v3/performance#partial let fieldsReturned = "files/id,files/\(GoogleCreds.md5ChecksumKey)" self.listFiles(query:query, fieldsReturned:fieldsReturned) { (dictionary, error) in // For the response structure, see https://developers.google.com/drive/v3/reference/files/list var result:SearchResult? var resultError:Swift.Error? = error if error != nil || dictionary == nil { if error == nil { resultError = SearchError.noJSONDictionaryResult } else { switch error! { case ListFilesError.expiredOrRevokedToken: resultError = SearchError.expiredOrRevokedToken default: break } } } else { if let filesArray = dictionary!["files"] as? [Any] { switch filesArray.count { case 0: // resultError will be nil as will result. break case 1: if let fileDict = filesArray[0] as? [String: Any], let id = fileDict["id"] as? String { // See https://developers.google.com/drive/api/v3/reference/files let checkSum = fileDict[GoogleCreds.md5ChecksumKey] as? String result = SearchResult(itemId: id, dictionary: fileDict, checkSum: checkSum) } else { resultError = SearchError.noIdInResultingJSON } default: resultError = SearchError.moreThanOneItemWithName } } } completion(result, resultError) } } enum CreateFolderError : Swift.Error { case badStatusCode(HTTPStatusCode?) case couldNotConvertJSONToString case badJSONResult case noJSONDictionaryResult case noIdInResultingJSON case nilAPIResult case expiredOrRevokedToken } // Create a folder-- assumes it doesn't yet exist. This won't fail if you use it more than once with the same folder name, you just get multiple instances of a folder with the same name. // Not marked private for testing purposes. Don't call this directly outside of this class otherwise. func createFolder(rootFolderName folderName:String, completion:@escaping (_ folderId:String?, Swift.Error?)->()) { // It's not obvious from the docs, but you use the /drive/v3/files endpoint (metadata only) for creating folders. Also not clear from the docs, you need to give the Content-Type in the headers. See https://developers.google.com/drive/v3/web/manage-uploads let additionalHeaders = [ "Content-Type": "application/json; charset=UTF-8" ] let bodyDict = [ "name" : folderName, "mimeType" : "\(folderMimeType)" ] guard let jsonString = JSONExtras.toJSONString(dict: bodyDict) else { completion(nil, CreateFolderError.couldNotConvertJSONToString) return } self.apiCall(method: "POST", path: "/drive/v3/files", additionalHeaders:additionalHeaders, body: .string(jsonString)) { (apiResult, statusCode, responseHeaders) in var resultId:String? var resultError:Swift.Error? if self.revokedOrExpiredToken(result: apiResult) { completion(nil, CreateFolderError.expiredOrRevokedToken) return } guard apiResult != nil else { completion(nil, CreateFolderError.nilAPIResult) return } guard case .dictionary(let dictionary) = apiResult! else { completion(nil, CreateFolderError.badJSONResult) return } if statusCode != HTTPStatusCode.OK { resultError = CreateFolderError.badStatusCode(statusCode) } else { if let id = dictionary["id"] as? String { resultId = id } else { resultError = CreateFolderError.noIdInResultingJSON } } completion(resultId, resultError) } } // Creates a root level folder if it doesn't exist. Returns the folderId in the completion if no error. // Not marked private for testing purposes. Don't call this directly outside of this class otherwise. // CreateFolderError.expiredOrRevokedToken or SearchError.expiredOrRevokedToken for expiry. func createFolderIfDoesNotExist(rootFolderName folderName:String, completion:@escaping (_ folderId:String?, Swift.Error?)->()) { self.searchFor(.folder, itemName: folderName) { (result, error) in if error == nil { if result == nil { // Folder doesn't exist. self.createFolder(rootFolderName: folderName) { (folderId, error) in completion(folderId, error) } } else { // Folder does exist. completion(result!.itemId, nil) } } else { completion(nil, error) } } } enum TrashFileError: Swift.Error { case couldNotConvertJSONToString } /* I've been unable to get this to work. The HTTP PATCH request is less than a year old in Kitura. Wonder if it could be having problems... It doesn't give an error, it gives the file's resource just like when in fact it does work, ie., with curl below. The following curl statement *did* do the job: curl -H "Content-Type: application/json; charset=UTF-8" -H "Authorization: Bearer ya29.CjDNA5hr2sKmWeNq8HzStIje4aaqDuocgpteKS5NYTvGKRIxCZKAHyNFB7ky_s7eyC8" -X PATCH -d '{"trashed":"true"}' https://www.googleapis.com/drive/v3/files/0B3xI3Shw5ptROTA2M1dfby1OVEk */ #if false // Move a file or folder to the trash on Google Drive. func trashFile(fileId:String, completion:@escaping (Swift.Error?)->()) { let bodyDict = [ "trashed": "true" ] guard let jsonString = dictionaryToJSONString(dict: bodyDict) else { completion(TrashFileError.couldNotConvertJSONToString) return } let additionalHeaders = [ "Content-Type": "application/json; charset=UTF-8", ] self.googleAPICall(method: "PATCH", path: "/drive/v3/files/\(fileId)", additionalHeaders:additionalHeaders, body: jsonString) { (json, error) in if error != nil { Log.error("\(error)") } completion(error) } } #endif enum DeleteFileError :Swift.Error { case badStatusCode(HTTPStatusCode?) case expiredOrRevokedToken } // Permanently delete a file or folder // Not marked private for testing purposes. Don't call this directly outside of this class otherwise. func deleteFile(fileId:String, completion:@escaping (Swift.Error?)->()) { // See https://developers.google.com/drive/v3/reference/files/delete let additionalHeaders = [ "Content-Type": "application/json; charset=UTF-8", ] self.apiCall(method: "DELETE", path: "/drive/v3/files/\(fileId)", additionalHeaders:additionalHeaders) { (apiResult, statusCode, responseHeaders) in if self.revokedOrExpiredToken(result: apiResult) { completion(DeleteFileError.expiredOrRevokedToken) return } // The "noContent" correct result was not apparent from the docs-- figured this out by experimentation. if statusCode == HTTPStatusCode.noContent { completion(nil) } else { completion(DeleteFileError.badStatusCode(statusCode)) } } } enum UploadError : Swift.Error { case badStatusCode(HTTPStatusCode?) case couldNotObtainCheckSum case noCloudFolderName case noOptions case missingCloudFolderNameOrMimeType case expiredOrRevokedToken } // TODO: *1* It would be good to put some retry logic in here. With a timed fallback as well. e.g., if an upload fails the first time around, retry after a period of time. OR, do this when I generalize this scheme to use other cloud storage services-- thus the retry logic could work across each scheme. // For relatively small files-- e.g., <= 5MB, where the entire upload can be retried if it fails. func uploadFile(cloudFileName:String, data:Data, options:CloudStorageFileNameOptions?, completion:@escaping (Result<String>)->()) { // See https://developers.google.com/drive/v3/web/manage-uploads guard let options = options else { completion(.failure(UploadError.noOptions)) return } let mimeType = options.mimeType guard let cloudFolderName = options.cloudFolderName else { completion(.failure(UploadError.missingCloudFolderNameOrMimeType)) return } self.createFolderIfDoesNotExist(rootFolderName: cloudFolderName) { (folderId, error) in if let error = error { switch error { case CreateFolderError.expiredOrRevokedToken, SearchError.expiredOrRevokedToken: completion(.accessTokenRevokedOrExpired) default: completion(.failure(error)) } return } let searchType = SearchType.file(mimeType: mimeType, parentFolderId: folderId) // I'm going to do this before I attempt the upload-- because I don't want to upload the same file twice. This results in google drive doing odd things with the file names. E.g., 5200B98F-8CD8-4248-B41E-4DA44087AC3C.950DBB91-B152-4D5C-B344-9BAFF49021B7 (1).0 self.searchFor(searchType, itemName: cloudFileName) { (result, error) in if error == nil { if result == nil { self.completeSmallFileUpload(folderId: folderId!, searchType:searchType, cloudFileName: cloudFileName, data: data, mimeType: mimeType, completion: completion) } else { completion(.failure(CloudStorageError.alreadyUploaded)) } } else { switch error! { case SearchError.expiredOrRevokedToken: completion(.accessTokenRevokedOrExpired) default: Log.error("Error in searchFor: \(String(describing: error))") completion(.failure(error!)) } } } } } // See https://developers.google.com/drive/api/v3/multipart-upload private func completeSmallFileUpload(folderId:String, searchType:SearchType, cloudFileName: String, data: Data, mimeType:String, completion:@escaping (Result<String>)->()) { let boundary = Foundation.UUID().uuidString let additionalHeaders = [ "Content-Type" : "multipart/related; boundary=\(boundary)" ] var urlParameters = "uploadType=multipart" urlParameters += "&fields=" + GoogleCreds.md5ChecksumKey let firstPart = "--\(boundary)\r\n" + "Content-Type: application/json; charset=UTF-8\r\n" + "\r\n" + "{\r\n" + "\"name\": \"\(cloudFileName)\",\r\n" + "\"parents\": [\r\n" + "\"\(folderId)\"\r\n" + "]\r\n" + "}\r\n" + "\r\n" + "--\(boundary)\r\n" + "Content-Type: \(mimeType)\r\n" + "\r\n" var multiPartData = firstPart.data(using: .utf8)! multiPartData.append(data) let endBoundary = "\r\n--\(boundary)--".data(using: .utf8)! multiPartData.append(endBoundary) self.apiCall(method: "POST", path: "/upload/drive/v3/files", additionalHeaders:additionalHeaders, urlParameters:urlParameters, body: .data(multiPartData)) { (json, statusCode, responseHeaders) in if self.revokedOrExpiredToken(result: json) { completion(.accessTokenRevokedOrExpired) return } if statusCode == HTTPStatusCode.OK { guard let json = json, case .dictionary(let dict) = json, let checkSum = dict[GoogleCreds.md5ChecksumKey] as? String else { completion(.failure(UploadError.couldNotObtainCheckSum)) return } completion(.success(checkSum)) } else { // Error case Log.error("Error in completeSmallFileUpload: statusCode=\(String(describing: statusCode))") completion(.failure(UploadError.badStatusCode(statusCode))) } } } enum SearchForFileError : Swift.Error { case cloudFolderDoesNotExist case cloudFileDoesNotExist(cloudFileName:String) case expiredOrRevokedToken } enum LookupFileError: Swift.Error { case noOptions case noCloudFolderName } func lookupFile(cloudFileName:String, options:CloudStorageFileNameOptions?, completion:@escaping (Result<Bool>)->()) { guard let options = options else { completion(.failure(LookupFileError.noOptions)) return } guard let cloudFolderName = options.cloudFolderName else { completion(.failure(LookupFileError.noCloudFolderName)) return } searchFor(cloudFileName: cloudFileName, inCloudFolder: cloudFolderName, fileMimeType: options.mimeType) { (cloudFileId, checkSum, error) in switch error { case .none: completion(.success(true)) case .some(SearchForFileError.cloudFileDoesNotExist): completion(.success(false)) case .some(SearchForFileError.expiredOrRevokedToken): completion(.accessTokenRevokedOrExpired) default: completion(.failure(error!)) } } } func searchFor(cloudFileName:String, inCloudFolder cloudFolderName:String, fileMimeType mimeType:String, completion:@escaping (_ cloudFileId: String?, _ checkSum: String?, Swift.Error?) -> ()) { self.searchFor(.folder, itemName: cloudFolderName) { (result, error) in if let error = error { switch error { case SearchError.expiredOrRevokedToken: completion(nil, nil, SearchForFileError.expiredOrRevokedToken) return default: break } } if result == nil { // Folder doesn't exist. Yikes! completion(nil, nil, SearchForFileError.cloudFolderDoesNotExist) } else { // Folder exists. Next need to find the id of our file within this folder. let searchType = SearchType.file(mimeType: mimeType, parentFolderId: result!.itemId) self.searchFor(searchType, itemName: cloudFileName) { (result, error) in if let error = error { switch error { case SearchError.expiredOrRevokedToken: completion(nil, nil, SearchForFileError.expiredOrRevokedToken) default: break } } if result == nil { completion(nil, nil, SearchForFileError.cloudFileDoesNotExist(cloudFileName: cloudFileName)) } else { completion(result!.itemId, result!.checkSum, nil) } } } } } enum DownloadSmallFileError : Swift.Error { case badStatusCode(HTTPStatusCode?) case nilAPIResult case noDataInAPIResult case noOptions case noCloudFolderName case fileNotFound case expiredOrRevokedToken } func downloadFile(cloudFileName:String, options:CloudStorageFileNameOptions?, completion:@escaping (DownloadResult)->()) { guard let options = options else { completion(.failure(DownloadSmallFileError.noOptions)) return } guard let cloudFolderName = options.cloudFolderName else { completion(.failure(DownloadSmallFileError.noCloudFolderName)) return } searchFor(cloudFileName: cloudFileName, inCloudFolder: cloudFolderName, fileMimeType: options.mimeType) { (cloudFileId, checkSum, error) in if error == nil { // File was found! Need to download it now. self.completeSmallFileDownload(fileId: cloudFileId!) { (data, error) in if error == nil { let downloadResult:DownloadResult = .success(data: data!, checkSum: checkSum!) completion(downloadResult) } else { switch error! { case DownloadSmallFileError.fileNotFound: completion(.fileNotFound) case DownloadSmallFileError.expiredOrRevokedToken: completion(.accessTokenRevokedOrExpired) default: completion(.failure(error!)) } } } } else { switch error! { case SearchForFileError.cloudFileDoesNotExist: completion(.fileNotFound) case SearchForFileError.expiredOrRevokedToken: completion(.accessTokenRevokedOrExpired) default: completion(.failure(error!)) } } } } // Not `private` because of some testing. func completeSmallFileDownload(fileId:String, completion:@escaping (_ data:Data?, Swift.Error?)->()) { // See https://developers.google.com/drive/v3/web/manage-downloads /* GET https://www.googleapis.com/drive/v3/files/0B9jNhSvVjoIVM3dKcGRKRmVIOVU?alt=media Authorization: Bearer <ACCESS_TOKEN> */ let path = "/drive/v3/files/\(fileId)?alt=media" self.apiCall(method: "GET", path: path, expectedSuccessBody: .data, expectedFailureBody: .json) { (apiResult, statusCode, responseHeaders) in if self.revokedOrExpiredToken(result: apiResult) { completion(nil, DownloadSmallFileError.expiredOrRevokedToken) return } /* When the fileId doesn't exist, apiResult from body as JSON is: apiResult: Optional(Server.APICallResult.dictionary( ["error": ["code": 404, "errors": [ ["locationType": "parameter", "reason": "notFound", "location": "fileId", "message": "File not found: foobar.", "domain": "global" ] ], "message": "File not found: foobar."] ])) */ if statusCode == HTTPStatusCode.notFound, case .dictionary(let dict)? = apiResult, let error = dict["error"] as? [String: Any], let errors = error["errors"] as? [[String: Any]], errors.count == 1, let reason = errors[0]["reason"] as? String, reason == "notFound" { completion(nil, DownloadSmallFileError.fileNotFound) return } if statusCode != HTTPStatusCode.OK { completion(nil, DownloadSmallFileError.badStatusCode(statusCode)) return } guard apiResult != nil else { completion(nil, DownloadSmallFileError.nilAPIResult) return } guard case .data(let data) = apiResult! else { completion(nil, DownloadSmallFileError.noDataInAPIResult) return } completion(data, nil) } } enum DeletionError : Swift.Error { case noOptions case noCloudFolderName } func deleteFile(cloudFileName:String, options:CloudStorageFileNameOptions?, completion:@escaping (Result<()>)->()) { guard let options = options else { completion(.failure(DeletionError.noOptions)) return } guard let cloudFolderName = options.cloudFolderName else { completion(.failure(DeletionError.noCloudFolderName)) return } searchFor(cloudFileName: cloudFileName, inCloudFolder: cloudFolderName, fileMimeType: options.mimeType) { (cloudFileId, checkSum, error) in if error == nil { // File was found! Need to delete it now. self.deleteFile(fileId: cloudFileId!) { error in if error == nil { completion(.success(())) } else { switch error! { case DeleteFileError.expiredOrRevokedToken: completion(.accessTokenRevokedOrExpired) default: completion(.failure(error!)) } } } } else { switch error! { case SearchForFileError.expiredOrRevokedToken: completion(.accessTokenRevokedOrExpired) default: completion(.failure(error!)) } } } } }
mit
066885ccac1a12d4ad55b407653a3e7b
38.476965
335
0.54953
5.241814
false
false
false
false
russbishop/swift
test/attr/attr_availability.swift
1
49112
// RUN: %target-parse-verify-swift @available(*, unavailable) func unavailable_func() {} @available(*, unavailable, message: "message") func unavailable_func_with_message() {} @available(tvOS, unavailable) @available(watchOS, unavailable) @available(iOS, unavailable) @available(OSX, unavailable) func unavailable_multiple_platforms() {} @available // expected-error {{expected '(' in 'available' attribute}} func noArgs() {} @available(*) // expected-error {{expected ',' in 'available' attribute}} func noKind() {} @available(badPlatform, unavailable) // expected-warning {{unknown platform 'badPlatform' for attribute 'available'}} func unavailable_bad_platform() {} // Handle unknown platform. @available(HAL9000, unavailable) // expected-warning {{unknown platform 'HAL9000'}} func availabilityUnknownPlatform() {} // <rdar://problem/17669805> Availability can't appear on a typealias @available(*, unavailable, message: "oh no you don't") typealias int = Int // expected-note {{'int' has been explicitly marked unavailable here}} @available(*, unavailable, renamed: "Float") typealias float = Float // expected-note {{'float' has been explicitly marked unavailable here}} struct MyCollection<Element> { @available(*, unavailable, renamed: "Element") typealias T = Element // expected-note 2{{'T' has been explicitly marked unavailable here}} func foo(x: T) { } // expected-error {{'T' has been renamed to 'Element'}} {{15-16=Element}} } extension MyCollection { func append(element: T) { } // expected-error {{'T' has been renamed to 'Element'}} {{24-25=Element}} } @available(*, unavailable, renamed: "MyCollection") typealias YourCollection<Element> = MyCollection<Element> // expected-note {{'YourCollection' has been explicitly marked unavailable here}} var x : YourCollection<Int> // expected-error {{'YourCollection' has been renamed to 'MyCollection'}}{{9-23=MyCollection}} var x : int // expected-error {{'int' is unavailable: oh no you don't}} var y : float // expected-error {{'float' has been renamed to 'Float'}}{{9-14=Float}} // Encoded message @available(*, unavailable, message: "This message has a double quote \"") func unavailableWithDoubleQuoteInMessage() {} // expected-note {{'unavailableWithDoubleQuoteInMessage()' has been explicitly marked unavailable here}} func useWithEscapedMessage() { unavailableWithDoubleQuoteInMessage() // expected-error {{'unavailableWithDoubleQuoteInMessage()' is unavailable: This message has a double quote \"}} } // More complicated parsing. @available(OSX, message: "x", unavailable) let _: Int @available(OSX, introduced: 1, deprecated: 2.0, obsoleted: 3.0.0) let _: Int @available(OSX, introduced: 1.0.0, deprecated: 2.0, obsoleted: 3, unavailable, renamed: "x") let _: Int // Meaningless but accepted. @available(OSX, message: "x") let _: Int // Parse errors. @available() // expected-error{{expected platform name or '*' for 'available' attribute}} let _: Int @available(OSX,) // expected-error{{expected 'available' option such as 'unavailable', 'introduced', 'deprecated', 'obsoleted', 'message', or 'renamed'}} let _: Int @available(OSX, message) // expected-error{{expected ':' after 'message' in 'available' attribute}} let _: Int @available(OSX, message: ) // expected-error{{expected string literal in 'available' attribute}} let _: Int @available(OSX, message: x) // expected-error{{expected string literal in 'available' attribute}} let _: Int @available(OSX, unavailable:) // expected-error{{expected ')' in 'available' attribute}} expected-error{{expected declaration}} let _: Int @available(OSX, introduced) // expected-error{{expected ':' after 'introduced' in 'available' attribute}} let _: Int @available(OSX, introduced: ) // expected-error{{expected version number in 'available' attribute}} let _: Int @available(OSX, introduced: x) // expected-error{{expected version number in 'available' attribute}} let _: Int @available(OSX, introduced: 1.x) // expected-error{{expected ')' in 'available' attribute}} expected-error {{expected declaration}} let _: Int @available(OSX, introduced: 1.0.x) // expected-error{{expected version number in 'available' attribute}} let _: Int @available(OSX, introduced: 0x1) // expected-error{{expected version number in 'available' attribute}} let _: Int @available(OSX, introduced: 1.0e4) // expected-error{{expected version number in 'available' attribute}} let _: Int @available(OSX, introduced: -1) // expected-error{{expected version number in 'available' attribute}} expected-error{{expected declaration}} let _: Int @available(OSX, introduced: 1.0.1e4) // expected-error{{expected version number in 'available' attribute}} let _: Int @available(OSX, introduced: 1.0.0x4) // expected-error{{expected version number in 'available' attribute}} let _: Int @available(*, renamed: "bad name") // expected-error{{'renamed' argument of 'available' attribute must be an operator, identifier, or full function name, optionally prefixed by a type name}} let _: Int @available(*, renamed: "_") // expected-error{{'renamed' argument of 'available' attribute must be an operator, identifier, or full function name, optionally prefixed by a type name}} let _: Int @available(*, renamed: "a+b") // expected-error{{'renamed' argument of 'available' attribute must be an operator, identifier, or full function name, optionally prefixed by a type name}} let _: Int @available(*, renamed: "a(") // expected-error{{'renamed' argument of 'available' attribute must be an operator, identifier, or full function name, optionally prefixed by a type name}} let _: Int @available(*, renamed: "a(:)") // expected-error{{'renamed' argument of 'available' attribute must be an operator, identifier, or full function name, optionally prefixed by a type name}} let _: Int @available(*, renamed: "a(:b:)") // expected-error{{'renamed' argument of 'available' attribute must be an operator, identifier, or full function name, optionally prefixed by a type name}} let _: Int @available(*, deprecated, unavailable, message: "message") // expected-error{{'available' attribute cannot be both unconditionally 'unavailable' and 'deprecated'}} struct BadUnconditionalAvailability { }; @available(*, unavailable, message="oh no you don't") // expected-error {{'=' has been replaced with ':' in attribute arguments}} {{35-36=: }} typealias EqualFixIt1 = Int @available(*, unavailable, message = "oh no you don't") // expected-error {{'=' has been replaced with ':' in attribute arguments}} {{36-37=:}} typealias EqualFixIt2 = Int // Encoding in messages @available(*, deprecated, message: "Say \"Hi\"") func deprecated_func_with_message() {} // 'PANDA FACE' (U+1F43C) @available(*, deprecated, message: "Pandas \u{1F43C} are cute") struct DeprecatedTypeWithMessage { } func use_deprecated_with_message() { deprecated_func_with_message() // expected-warning{{'deprecated_func_with_message()' is deprecated: Say \"Hi\"}} var _: DeprecatedTypeWithMessage // expected-warning{{'DeprecatedTypeWithMessage' is deprecated: Pandas \u{1F43C} are cute}} } @available(*, deprecated, message: "message") func use_deprecated_func_with_message2() { deprecated_func_with_message() // no diagnostic } @available(*, deprecated, renamed: "blarg") func deprecated_func_with_renamed() {} @available(*, deprecated, message: "blarg is your friend", renamed: "blarg") func deprecated_func_with_message_renamed() {} @available(*, deprecated, renamed: "wobble") struct DeprecatedTypeWithRename { } func use_deprecated_with_renamed() { deprecated_func_with_renamed() // expected-warning{{'deprecated_func_with_renamed()' is deprecated: renamed to 'blarg'}} // expected-note@-1{{use 'blarg'}}{{3-31=blarg}} deprecated_func_with_message_renamed() //expected-warning{{'deprecated_func_with_message_renamed()' is deprecated: blarg is your friend}} // expected-note@-1{{use 'blarg'}}{{3-39=blarg}} var _: DeprecatedTypeWithRename // expected-warning{{'DeprecatedTypeWithRename' is deprecated: renamed to 'wobble'}} // expected-note@-1{{use 'wobble'}}{{10-34=wobble}} } // Short form of @available() @available(iOS 8.0, *) func functionWithShortFormIOSAvailable() {} @available(iOS 8, *) func functionWithShortFormIOSVersionNoPointAvailable() {} @available(iOS 8.0, OSX 10.10.3, *) func functionWithShortFormIOSOSXAvailable() {} @available(iOS 8.0 // expected-error {{must handle potential future platforms with '*'}} {{19-19=, *}} func shortFormMissingParen() { // expected-error {{expected ')' in 'available' attribute}} } @available(iOS 8.0, // expected-error {{expected platform name}} func shortFormMissingPlatform() { } @available(iOS 8.0, * func shortFormMissingParenAfterWildcard() { // expected-error {{expected ')' in 'available' attribute}} } @available(*) // expected-error {{expected ',' in 'available' attribute}} func onlyWildcardInAvailable() {} @available(iOS 8.0, *, OSX 10.10.3) func shortFormWithWildcardInMiddle() {} @available(iOS 8.0, OSX 10.10.3) // expected-error {{must handle potential future platforms with '*'}} {{32-32=, *}} func shortFormMissingWildcard() {} @availability(OSX, introduced: 10.10) // expected-error {{@availability has been renamed to @available}} {{2-14=available}} func someFuncUsingOldAttribute() { } // <rdar://problem/23853709> Compiler crash on call to unavailable "print" func OutputStreamTest(message: String, to: inout OutputStream) { print(message, &to) // expected-error {{'print' is unavailable: Please use the 'to' label for the target stream: 'print((...), to: &...)'}} } // expected-note@+1{{'T' has been explicitly marked unavailable here}} struct UnavailableGenericParam<@available(*, unavailable, message: "nope") T> { func f(t: T) { } // expected-error{{'T' is unavailable: nope}} } struct DummyType {} @available(*, unavailable, renamed: "&+") func +(x: DummyType, y: DummyType) {} // expected-note {{here}} @available(*, deprecated, renamed: "&-") func -(x: DummyType, y: DummyType) {} func testOperators(x: DummyType, y: DummyType) { x + y // expected-error {{'+' has been renamed to '&+'}} {{5-6=&+}} x - y // expected-warning {{'-' is deprecated: renamed to '&-'}} expected-note {{use '&-' instead}} {{5-6=&-}} } @available(*, unavailable, renamed: "DummyType.foo") func unavailableMember() {} // expected-note {{here}} @available(*, deprecated, renamed: "DummyType.bar") func deprecatedMember() {} @available(*, unavailable, renamed: "DummyType.Inner.foo") func unavailableNestedMember() {} // expected-note {{here}} @available(*, unavailable, renamed: "DummyType.Foo") struct UnavailableType {} // expected-note {{here}} @available(*, deprecated, renamed: "DummyType.Bar") typealias DeprecatedType = Int func testGlobalToMembers() { unavailableMember() // expected-error {{'unavailableMember()' has been renamed to 'DummyType.foo'}} {{3-20=DummyType.foo}} deprecatedMember() // expected-warning {{'deprecatedMember()' is deprecated: renamed to 'DummyType.bar'}} expected-note {{use 'DummyType.bar' instead}} {{3-19=DummyType.bar}} unavailableNestedMember() // expected-error {{'unavailableNestedMember()' has been renamed to 'DummyType.Inner.foo'}} {{3-26=DummyType.Inner.foo}} let x: UnavailableType? = nil // expected-error {{'UnavailableType' has been renamed to 'DummyType.Foo'}} {{10-25=DummyType.Foo}} _ = x let y: DeprecatedType? = nil // expected-warning {{'DeprecatedType' is deprecated: renamed to 'DummyType.Bar'}} expected-note {{use 'DummyType.Bar' instead}} {{10-24=DummyType.Bar}} _ = y } @available(*, unavailable, renamed: "shinyLabeledArguments(example:)") func unavailableArgNames(a: Int) {} // expected-note {{here}} @available(*, deprecated, renamed: "moreShinyLabeledArguments(example:)") func deprecatedArgNames(b: Int) {} @available(*, unavailable, renamed: "DummyType.shinyLabeledArguments(example:)") func unavailableMemberArgNames(a: Int) {} // expected-note {{here}} @available(*, deprecated, renamed: "DummyType.moreShinyLabeledArguments(example:)") func deprecatedMemberArgNames(b: Int) {} @available(*, unavailable, renamed: "DummyType.shinyLabeledArguments(example:)", message: "ha") func unavailableMemberArgNamesMsg(a: Int) {} // expected-note {{here}} @available(*, deprecated, renamed: "DummyType.moreShinyLabeledArguments(example:)", message: "ha") func deprecatedMemberArgNamesMsg(b: Int) {} @available(*, unavailable, renamed: "shinyLabeledArguments()") func unavailableNoArgs() {} // expected-note {{here}} @available(*, unavailable, renamed: "shinyLabeledArguments(a:)") func unavailableSame(a: Int) {} // expected-note {{here}} @available(*, unavailable, renamed: "shinyLabeledArguments(example:)") func unavailableUnnamed(_ a: Int) {} // expected-note {{here}} @available(*, unavailable, renamed: "shinyLabeledArguments(_:)") func unavailableUnnamedSame(_ a: Int) {} // expected-note {{here}} @available(*, unavailable, renamed: "shinyLabeledArguments(_:)") func unavailableNewlyUnnamed(a: Int) {} // expected-note {{here}} @available(*, unavailable, renamed: "shinyLabeledArguments(veryLongNameToOverflowASmallStringABCDEFGHIJKLMNOPQRSTUVWXYZ:)") func unavailableVeryLongArgNames(a: Int) {} // expected-note {{here}} @available(*, unavailable, renamed: "shinyLabeledArguments(a:b:)") func unavailableMultiSame(a: Int, b: Int) {} // expected-note {{here}} @available(*, unavailable, renamed: "shinyLabeledArguments(example:another:)") func unavailableMultiUnnamed(_ a: Int, _ b: Int) {} // expected-note {{here}} @available(*, unavailable, renamed: "shinyLabeledArguments(_:_:)") func unavailableMultiUnnamedSame(_ a: Int, _ b: Int) {} // expected-note {{here}} @available(*, unavailable, renamed: "shinyLabeledArguments(_:_:)") func unavailableMultiNewlyUnnamed(a: Int, b: Int) {} // expected-note {{here}} @available(*, unavailable, renamed: "Int.init(other:)") func unavailableInit(a: Int) {} // expected-note 2 {{here}} @available(*, unavailable, renamed: "Foo.Bar.init(other:)") func unavailableNestedInit(a: Int) {} // expected-note 2 {{here}} func testArgNames() { unavailableArgNames(a: 0) // expected-error {{'unavailableArgNames(a:)' has been renamed to 'shinyLabeledArguments(example:)'}} {{3-22=shinyLabeledArguments}} {{23-24=example}} deprecatedArgNames(b: 1) // expected-warning {{'deprecatedArgNames(b:)' is deprecated: renamed to 'moreShinyLabeledArguments(example:)'}} expected-note {{use 'moreShinyLabeledArguments(example:)' instead}} {{3-21=moreShinyLabeledArguments}} {{22-23=example}} unavailableMemberArgNames(a: 0) // expected-error {{'unavailableMemberArgNames(a:)' has been replaced by 'DummyType.shinyLabeledArguments(example:)'}} {{3-28=DummyType.shinyLabeledArguments}} {{29-30=example}} deprecatedMemberArgNames(b: 1) // expected-warning {{'deprecatedMemberArgNames(b:)' is deprecated: replaced by 'DummyType.moreShinyLabeledArguments(example:)'}} expected-note {{use 'DummyType.moreShinyLabeledArguments(example:)' instead}} {{3-27=DummyType.moreShinyLabeledArguments}} {{28-29=example}} unavailableMemberArgNamesMsg(a: 0) // expected-error {{'unavailableMemberArgNamesMsg(a:)' has been replaced by 'DummyType.shinyLabeledArguments(example:)': ha}} {{3-31=DummyType.shinyLabeledArguments}} {{32-33=example}} deprecatedMemberArgNamesMsg(b: 1) // expected-warning {{'deprecatedMemberArgNamesMsg(b:)' is deprecated: ha}} expected-note {{use 'DummyType.moreShinyLabeledArguments(example:)' instead}} {{3-30=DummyType.moreShinyLabeledArguments}} {{31-32=example}} unavailableNoArgs() // expected-error {{'unavailableNoArgs()' has been renamed to 'shinyLabeledArguments()'}} {{3-20=shinyLabeledArguments}} unavailableSame(a: 0) // expected-error {{'unavailableSame(a:)' has been renamed to 'shinyLabeledArguments(a:)'}} {{3-18=shinyLabeledArguments}} unavailableUnnamed(0) // expected-error {{'unavailableUnnamed' has been renamed to 'shinyLabeledArguments(example:)'}} {{3-21=shinyLabeledArguments}} {{22-22=example: }} unavailableUnnamedSame(0) // expected-error {{'unavailableUnnamedSame' has been renamed to 'shinyLabeledArguments(_:)'}} {{3-25=shinyLabeledArguments}} unavailableNewlyUnnamed(a: 0) // expected-error {{'unavailableNewlyUnnamed(a:)' has been renamed to 'shinyLabeledArguments(_:)'}} {{3-26=shinyLabeledArguments}} {{27-30=}} unavailableVeryLongArgNames(a: 0) // expected-error {{'unavailableVeryLongArgNames(a:)' has been renamed to 'shinyLabeledArguments(veryLongNameToOverflowASmallStringABCDEFGHIJKLMNOPQRSTUVWXYZ:)'}} {{3-30=shinyLabeledArguments}} {{31-32=veryLongNameToOverflowASmallStringABCDEFGHIJKLMNOPQRSTUVWXYZ}} unavailableMultiSame(a: 0, b: 1) // expected-error {{'unavailableMultiSame(a:b:)' has been renamed to 'shinyLabeledArguments(a:b:)'}} {{3-23=shinyLabeledArguments}} unavailableMultiUnnamed(0, 1) // expected-error {{'unavailableMultiUnnamed' has been renamed to 'shinyLabeledArguments(example:another:)'}} {{3-26=shinyLabeledArguments}} {{27-27=example: }} {{30-30=another: }} unavailableMultiUnnamedSame(0, 1) // expected-error {{'unavailableMultiUnnamedSame' has been renamed to 'shinyLabeledArguments(_:_:)'}} {{3-30=shinyLabeledArguments}} unavailableMultiNewlyUnnamed(a: 0, b: 1) // expected-error {{'unavailableMultiNewlyUnnamed(a:b:)' has been renamed to 'shinyLabeledArguments(_:_:)'}} {{3-31=shinyLabeledArguments}} {{32-35=}} {{38-41=}} unavailableInit(a: 0) // expected-error {{'unavailableInit(a:)' has been replaced by 'Int.init(other:)'}} {{3-18=Int}} {{19-20=other}} let fn = unavailableInit // expected-error {{'unavailableInit(a:)' has been replaced by 'Int.init(other:)'}} {{12-27=Int.init}} fn(a: 1) unavailableNestedInit(a: 0) // expected-error {{'unavailableNestedInit(a:)' has been replaced by 'Foo.Bar.init(other:)'}} {{3-24=Foo.Bar}} {{25-26=other}} let fn2 = unavailableNestedInit // expected-error {{'unavailableNestedInit(a:)' has been replaced by 'Foo.Bar.init(other:)'}} {{13-34=Foo.Bar.init}} fn2(a: 1) } @available(*, unavailable, renamed: "shinyLabeledArguments()") func unavailableTooFew(a: Int) {} // expected-note {{here}} @available(*, unavailable, renamed: "shinyLabeledArguments()") func unavailableTooFewUnnamed(_ a: Int) {} // expected-note {{here}} @available(*, unavailable, renamed: "shinyLabeledArguments(a:b:)") func unavailableTooMany(a: Int) {} // expected-note {{here}} @available(*, unavailable, renamed: "shinyLabeledArguments(a:b:)") func unavailableTooManyUnnamed(_ a: Int) {} // expected-note {{here}} @available(*, unavailable, renamed: "shinyLabeledArguments(a:)") func unavailableNoArgsTooMany() {} // expected-note {{here}} func testRenameArgMismatch() { unavailableTooFew(a: 0) // expected-error{{'unavailableTooFew(a:)' has been renamed to 'shinyLabeledArguments()'}} {{3-20=shinyLabeledArguments}} unavailableTooFewUnnamed(0) // expected-error{{'unavailableTooFewUnnamed' has been renamed to 'shinyLabeledArguments()'}} {{3-27=shinyLabeledArguments}} unavailableTooMany(a: 0) // expected-error{{'unavailableTooMany(a:)' has been renamed to 'shinyLabeledArguments(a:b:)'}} {{3-21=shinyLabeledArguments}} unavailableTooManyUnnamed(0) // expected-error{{'unavailableTooManyUnnamed' has been renamed to 'shinyLabeledArguments(a:b:)'}} {{3-28=shinyLabeledArguments}} unavailableNoArgsTooMany() // expected-error{{'unavailableNoArgsTooMany()' has been renamed to 'shinyLabeledArguments(a:)'}} {{3-27=shinyLabeledArguments}} } @available(*, unavailable, renamed: "Int.foo(self:)") func unavailableInstance(a: Int) {} // expected-note 2 {{here}} @available(*, unavailable, renamed: "Int.foo(self:)") func unavailableInstanceUnlabeled(_ a: Int) {} // expected-note {{here}} @available(*, unavailable, renamed: "Int.foo(self:other:)") func unavailableInstanceFirst(a: Int, b: Int) {} // expected-note {{here}} @available(*, unavailable, renamed: "Int.foo(other:self:)") func unavailableInstanceSecond(a: Int, b: Int) {} // expected-note {{here}} @available(*, unavailable, renamed: "Int.foo(_:self:c:)") func unavailableInstanceSecondOfThree(a: Int, b: Int, c: Int) {} // expected-note {{here}} @available(*, unavailable, renamed: "Int.foo(self:)", message: "blah") func unavailableInstanceMessage(a: Int) {} // expected-note {{here}} @available(*, deprecated, renamed: "Int.foo(self:)") func deprecatedInstance(a: Int) {} @available(*, deprecated, renamed: "Int.foo(self:)", message: "blah") func deprecatedInstanceMessage(a: Int) {} @available(*, unavailable, renamed: "Foo.Bar.foo(self:)") func unavailableNestedInstance(a: Int) {} // expected-note {{here}} func testRenameInstance() { unavailableInstance(a: 0) // expected-error{{'unavailableInstance(a:)' has been replaced by instance method 'Int.foo()'}} {{3-22=0.foo}} {{23-27=}} unavailableInstanceUnlabeled(0) // expected-error{{'unavailableInstanceUnlabeled' has been replaced by instance method 'Int.foo()'}} {{3-31=0.foo}} {{32-33=}} unavailableInstanceFirst(a: 0, b: 1) // expected-error{{'unavailableInstanceFirst(a:b:)' has been replaced by instance method 'Int.foo(other:)'}} {{3-27=0.foo}} {{28-34=}} {{34-35=other}} unavailableInstanceSecond(a: 0, b: 1) // expected-error{{'unavailableInstanceSecond(a:b:)' has been replaced by instance method 'Int.foo(other:)'}} {{3-28=1.foo}} {{29-30=other}} {{33-39=}} unavailableInstanceSecondOfThree(a: 0, b: 1, c: 2) // expected-error{{'unavailableInstanceSecondOfThree(a:b:c:)' has been replaced by instance method 'Int.foo(_:c:)'}} {{3-35=1.foo}} {{36-39=}} {{42-48=}} unavailableInstance(a: 0 + 0) // expected-error{{'unavailableInstance(a:)' has been replaced by instance method 'Int.foo()'}} {{3-22=(0 + 0).foo}} {{23-31=}} unavailableInstanceMessage(a: 0) // expected-error{{'unavailableInstanceMessage(a:)' has been replaced by instance method 'Int.foo()': blah}} {{3-29=0.foo}} {{30-34=}} deprecatedInstance(a: 0) // expected-warning{{'deprecatedInstance(a:)' is deprecated: replaced by instance method 'Int.foo()'}} expected-note{{use 'Int.foo()' instead}} {{3-21=0.foo}} {{22-26=}} deprecatedInstanceMessage(a: 0) // expected-warning{{'deprecatedInstanceMessage(a:)' is deprecated: blah}} expected-note{{use 'Int.foo()' instead}} {{3-28=0.foo}} {{29-33=}} unavailableNestedInstance(a: 0) // expected-error{{'unavailableNestedInstance(a:)' has been replaced by instance method 'Foo.Bar.foo()'}} {{3-28=0.foo}} {{29-33=}} } @available(*, unavailable, renamed: "Int.shinyLabeledArguments(self:)") func unavailableInstanceTooFew(a: Int, b: Int) {} // expected-note {{here}} @available(*, unavailable, renamed: "Int.shinyLabeledArguments(self:)") func unavailableInstanceTooFewUnnamed(_ a: Int, _ b: Int) {} // expected-note {{here}} @available(*, unavailable, renamed: "Int.shinyLabeledArguments(self:b:)") func unavailableInstanceTooMany(a: Int) {} // expected-note {{here}} @available(*, unavailable, renamed: "Int.shinyLabeledArguments(self:b:)") func unavailableInstanceTooManyUnnamed(_ a: Int) {} // expected-note {{here}} @available(*, unavailable, renamed: "Int.shinyLabeledArguments(self:)") func unavailableInstanceNoArgsTooMany() {} // expected-note {{here}} func testRenameInstanceArgMismatch() { unavailableInstanceTooFew(a: 0, b: 1) // expected-error{{'unavailableInstanceTooFew(a:b:)' has been replaced by instance method 'Int.shinyLabeledArguments()'}} {{none}} unavailableInstanceTooFewUnnamed(0, 1) // expected-error{{'unavailableInstanceTooFewUnnamed' has been replaced by instance method 'Int.shinyLabeledArguments()'}} {{none}} unavailableInstanceTooMany(a: 0) // expected-error{{'unavailableInstanceTooMany(a:)' has been replaced by instance method 'Int.shinyLabeledArguments(b:)'}} {{none}} unavailableInstanceTooManyUnnamed(0) // expected-error{{'unavailableInstanceTooManyUnnamed' has been replaced by instance method 'Int.shinyLabeledArguments(b:)'}} {{none}} unavailableInstanceNoArgsTooMany() // expected-error{{'unavailableInstanceNoArgsTooMany()' has been replaced by instance method 'Int.shinyLabeledArguments()'}} {{none}} } @available(*, unavailable, renamed: "getter:Int.prop(self:)") func unavailableInstanceProperty(a: Int) {} // expected-note 2 {{here}} @available(*, unavailable, renamed: "getter:Int.prop(self:)") func unavailableInstancePropertyUnlabeled(_ a: Int) {} // expected-note 2 {{here}} @available(*, unavailable, renamed: "getter:Int.prop()") func unavailableClassProperty() {} // expected-note {{here}} @available(*, unavailable, renamed: "getter:global()") func unavailableGlobalProperty() {} // expected-note {{here}} @available(*, unavailable, renamed: "getter:Int.prop(self:)", message: "blah") func unavailableInstancePropertyMessage(a: Int) {} // expected-note {{here}} @available(*, unavailable, renamed: "getter:Int.prop()", message: "blah") func unavailableClassPropertyMessage() {} // expected-note {{here}} @available(*, unavailable, renamed: "getter:global()", message: "blah") func unavailableGlobalPropertyMessage() {} // expected-note {{here}} @available(*, deprecated, renamed: "getter:Int.prop(self:)") func deprecatedInstanceProperty(a: Int) {} @available(*, deprecated, renamed: "getter:Int.prop()") func deprecatedClassProperty() {} @available(*, deprecated, renamed: "getter:global()") func deprecatedGlobalProperty() {} @available(*, deprecated, renamed: "getter:Int.prop(self:)", message: "blah") func deprecatedInstancePropertyMessage(a: Int) {} @available(*, deprecated, renamed: "getter:Int.prop()", message: "blah") func deprecatedClassPropertyMessage() {} @available(*, deprecated, renamed: "getter:global()", message: "blah") func deprecatedGlobalPropertyMessage() {} func testRenameGetters() { unavailableInstanceProperty(a: 1) // expected-error{{'unavailableInstanceProperty(a:)' has been replaced by property 'Int.prop'}} {{3-30=1.prop}} {{30-36=}} unavailableInstancePropertyUnlabeled(1) // expected-error{{'unavailableInstancePropertyUnlabeled' has been replaced by property 'Int.prop'}} {{3-39=1.prop}} {{39-42=}} unavailableInstanceProperty(a: 1 + 1) // expected-error{{'unavailableInstanceProperty(a:)' has been replaced by property 'Int.prop'}} {{3-30=(1 + 1).prop}} {{30-40=}} unavailableInstancePropertyUnlabeled(1 + 1) // expected-error{{'unavailableInstancePropertyUnlabeled' has been replaced by property 'Int.prop'}} {{3-39=(1 + 1).prop}} {{39-46=}} unavailableClassProperty() // expected-error{{'unavailableClassProperty()' has been replaced by property 'Int.prop'}} {{3-27=Int.prop}} {{27-29=}} unavailableGlobalProperty() // expected-error{{'unavailableGlobalProperty()' has been replaced by 'global'}} {{3-28=global}} {{28-30=}} unavailableInstancePropertyMessage(a: 1) // expected-error{{'unavailableInstancePropertyMessage(a:)' has been replaced by property 'Int.prop': blah}} {{3-37=1.prop}} {{37-43=}} unavailableClassPropertyMessage() // expected-error{{'unavailableClassPropertyMessage()' has been replaced by property 'Int.prop': blah}} {{3-34=Int.prop}} {{34-36=}} unavailableGlobalPropertyMessage() // expected-error{{'unavailableGlobalPropertyMessage()' has been replaced by 'global': blah}} {{3-35=global}} {{35-37=}} deprecatedInstanceProperty(a: 1) // expected-warning {{'deprecatedInstanceProperty(a:)' is deprecated: replaced by property 'Int.prop'}} expected-note{{use 'Int.prop' instead}} {{3-29=1.prop}} {{29-35=}} deprecatedClassProperty() // expected-warning {{'deprecatedClassProperty()' is deprecated: replaced by property 'Int.prop'}} expected-note{{use 'Int.prop' instead}} {{3-26=Int.prop}} {{26-28=}} deprecatedGlobalProperty() // expected-warning {{'deprecatedGlobalProperty()' is deprecated: replaced by 'global'}} expected-note{{use 'global' instead}} {{3-27=global}} {{27-29=}} deprecatedInstancePropertyMessage(a: 1) // expected-warning {{'deprecatedInstancePropertyMessage(a:)' is deprecated: blah}} expected-note{{use 'Int.prop' instead}} {{3-36=1.prop}} {{36-42=}} deprecatedClassPropertyMessage() // expected-warning {{'deprecatedClassPropertyMessage()' is deprecated: blah}} expected-note{{use 'Int.prop' instead}} {{3-33=Int.prop}} {{33-35=}} deprecatedGlobalPropertyMessage() // expected-warning {{'deprecatedGlobalPropertyMessage()' is deprecated: blah}} expected-note{{use 'global' instead}} {{3-34=global}} {{34-36=}} } @available(*, unavailable, renamed: "setter:Int.prop(self:_:)") func unavailableSetInstanceProperty(a: Int, b: Int) {} // expected-note 2 {{here}} @available(*, unavailable, renamed: "setter:Int.prop(_:self:)") func unavailableSetInstancePropertyReverse(a: Int, b: Int) {} // expected-note 2 {{here}} @available(*, unavailable, renamed: "setter:Int.prop(self:newValue:)") func unavailableSetInstancePropertyUnlabeled(_ a: Int, _ b: Int) {} // expected-note 2 {{here}} @available(*, unavailable, renamed: "setter:Int.prop(newValue:self:)") func unavailableSetInstancePropertyUnlabeledReverse(_ a: Int, _ b: Int) {} // expected-note 2 {{here}} @available(*, unavailable, renamed: "setter:Int.prop(x:)") func unavailableSetClassProperty(a: Int) {} // expected-note {{here}} @available(*, unavailable, renamed: "setter:global(_:)") func unavailableSetGlobalProperty(_ a: Int) {} // expected-note {{here}} @available(*, unavailable, renamed: "setter:Int.prop(self:_:)") func unavailableSetInstancePropertyInout(a: inout Int, b: Int) {} // expected-note {{here}} func testRenameSetters() { unavailableSetInstanceProperty(a: 1, b: 2) // expected-error{{'unavailableSetInstanceProperty(a:b:)' has been replaced by property 'Int.prop'}} {{3-33=1.prop}} {{33-43= = }} {{44-45=}} unavailableSetInstancePropertyUnlabeled(1, 2) // expected-error{{'unavailableSetInstancePropertyUnlabeled' has been replaced by property 'Int.prop'}} {{3-42=1.prop}} {{42-46= = }} {{47-48=}} unavailableSetInstancePropertyReverse(a: 1, b: 2) // expected-error{{'unavailableSetInstancePropertyReverse(a:b:)' has been replaced by property 'Int.prop'}} {{3-40=2.prop}} {{40-44= = }} {{45-52=}} unavailableSetInstancePropertyUnlabeledReverse(1, 2) // expected-error{{'unavailableSetInstancePropertyUnlabeledReverse' has been replaced by property 'Int.prop'}} {{3-49=2.prop}} {{49-50= = }} {{51-55=}} unavailableSetInstanceProperty(a: 1 + 1, b: 2 + 2) // expected-error{{'unavailableSetInstanceProperty(a:b:)' has been replaced by property 'Int.prop'}} {{3-33=(1 + 1).prop}} {{33-47= = }} {{52-53=}} unavailableSetInstancePropertyUnlabeled(1 + 1, 2 + 2) // expected-error{{'unavailableSetInstancePropertyUnlabeled' has been replaced by property 'Int.prop'}} {{3-42=(1 + 1).prop}} {{42-50= = }} {{55-56=}} unavailableSetInstancePropertyReverse(a: 1 + 1, b: 2 + 2) // expected-error{{'unavailableSetInstancePropertyReverse(a:b:)' has been replaced by property 'Int.prop'}} {{3-40=(2 + 2).prop}} {{40-44= = }} {{49-60=}} unavailableSetInstancePropertyUnlabeledReverse(1 + 1, 2 + 2) // expected-error{{'unavailableSetInstancePropertyUnlabeledReverse' has been replaced by property 'Int.prop'}} {{3-49=(2 + 2).prop}} {{49-50= = }} {{55-63=}} unavailableSetClassProperty(a: 1) // expected-error{{'unavailableSetClassProperty(a:)' has been replaced by property 'Int.prop'}} {{3-30=Int.prop}} {{30-34= = }} {{35-36=}} unavailableSetGlobalProperty(1) // expected-error{{'unavailableSetGlobalProperty' has been replaced by 'global'}} {{3-31=global}} {{31-32= = }} {{33-34=}} var x = 0 unavailableSetInstancePropertyInout(a: &x, b: 2) // expected-error{{'unavailableSetInstancePropertyInout(a:b:)' has been replaced by property 'Int.prop'}} {{3-38=x.prop}} {{38-49= = }} {{50-51=}} } @available(*, unavailable, renamed: "Int.foo(self:execute:)") func trailingClosure(_ value: Int, fn: () -> Void) {} // expected-note {{here}} @available(*, unavailable, renamed: "Int.foo(self:bar:execute:)") func trailingClosureArg(_ value: Int, _ other: Int, fn: () -> Void) {} // expected-note {{here}} @available(*, unavailable, renamed: "Int.foo(bar:self:execute:)") func trailingClosureArg2(_ value: Int, _ other: Int, fn: () -> Void) {} // expected-note {{here}} func testInstanceTrailingClosure() { trailingClosure(0) {} // expected-error {{'trailingClosure(_:fn:)' has been replaced by instance method 'Int.foo(execute:)'}} {{3-18=0.foo}} {{19-20=}} trailingClosureArg(0, 1) {} // expected-error {{'trailingClosureArg(_:_:fn:)' has been replaced by instance method 'Int.foo(bar:execute:)'}} {{3-21=0.foo}} {{22-25=}} {{25-25=bar: }} trailingClosureArg2(0, 1) {} // expected-error {{'trailingClosureArg2(_:_:fn:)' has been replaced by instance method 'Int.foo(bar:execute:)'}} {{3-22=1.foo}} {{23-23=bar: }} {{24-27=}} } @available(*, unavailable, renamed: "+") func add(_ value: Int, _ other: Int) {} // expected-note {{here}} infix operator *** {} @available(*, unavailable, renamed: "add") func ***(value: (), other: ()) {} // expected-note {{here}} @available(*, unavailable, renamed: "Int.foo(self:_:)") func ***(value: Int, other: Int) {} // expected-note {{here}} prefix operator *** {} @available(*, unavailable, renamed: "add") prefix func ***(value: Int?) {} // expected-note {{here}} @available(*, unavailable, renamed: "Int.foo(self:)") prefix func ***(value: Int) {} // expected-note {{here}} postfix operator *** {} @available(*, unavailable, renamed: "add") postfix func ***(value: Int?) {} // expected-note {{here}} @available(*, unavailable, renamed: "Int.foo(self:)") postfix func ***(value: Int) {} // expected-note {{here}} func testOperators() { add(0, 1) // expected-error {{'add' has been renamed to '+'}} {{none}} () *** () // expected-error {{'***' has been renamed to 'add'}} {{none}} 0 *** 1 // expected-error {{'***' has been replaced by instance method 'Int.foo(_:)'}} {{none}} ***nil // expected-error {{'***' has been renamed to 'add'}} {{none}} ***0 // expected-error {{'***' has been replaced by instance method 'Int.foo()'}} {{none}} nil*** // expected-error {{'***' has been renamed to 'add'}} {{none}} 0*** // expected-error {{'***' has been replaced by instance method 'Int.foo()'}} {{none}} } extension Int { @available(*, unavailable, renamed: "init(other:)") @discardableResult static func factory(other: Int) -> Int { return other } // expected-note 2 {{here}} @available(*, unavailable, renamed: "Int.init(other:)") @discardableResult static func factory2(other: Int) -> Int { return other } // expected-note 2 {{here}} static func testFactoryMethods() { factory(other: 1) // expected-error {{'factory(other:)' has been replaced by 'init(other:)'}} {{none}} factory2(other: 1) // expected-error {{'factory2(other:)' has been replaced by 'Int.init(other:)'}} {{5-13=Int}} } } func testFactoryMethods() { Int.factory(other: 1) // expected-error {{'factory(other:)' has been replaced by 'init(other:)'}} {{6-14=}} Int.factory2(other: 1) // expected-error {{'factory2(other:)' has been replaced by 'Int.init(other:)'}} {{3-15=Int}} } class Base { @available(*, unavailable) func bad() {} // expected-note {{here}} @available(*, unavailable, message: "it was smelly") func smelly() {} // expected-note {{here}} @available(*, unavailable, renamed: "new") func old() {} // expected-note {{here}} @available(*, unavailable, renamed: "new", message: "it was smelly") func oldAndSmelly() {} // expected-note {{here}} @available(*, unavailable) var badProp: Int { return 0 } // expected-note {{here}} @available(*, unavailable, message: "it was smelly") var smellyProp: Int { return 0 } // expected-note {{here}} @available(*, unavailable, renamed: "new") var oldProp: Int { return 0 } // expected-note {{here}} @available(*, unavailable, renamed: "new", message: "it was smelly") var oldAndSmellyProp: Int { return 0 } // expected-note {{here}} @available(*, unavailable, renamed: "init") func nowAnInitializer() {} // expected-note {{here}} @available(*, unavailable, renamed: "init()") func nowAnInitializer2() {} // expected-note {{here}} @available(*, unavailable, renamed: "foo") init(nowAFunction: Int) {} // expected-note {{here}} @available(*, unavailable, renamed: "foo(_:)") init(nowAFunction2: Int) {} // expected-note {{here}} @available(*, unavailable, renamed: "shinyLabeledArguments(example:)") func unavailableArgNames(a: Int) {} // expected-note {{here}} @available(*, unavailable, renamed: "shinyLabeledArguments(example:)") func unavailableArgRenamed(a: Int) {} // expected-note {{here}} @available(*, unavailable, renamed: "shinyLabeledArguments()") func unavailableNoArgs() {} // expected-note {{here}} @available(*, unavailable, renamed: "shinyLabeledArguments(a:)") func unavailableSame(a: Int) {} // expected-note {{here}} @available(*, unavailable, renamed: "shinyLabeledArguments(example:)") func unavailableUnnamed(_ a: Int) {} // expected-note {{here}} @available(*, unavailable, renamed: "shinyLabeledArguments(_:)") func unavailableUnnamedSame(_ a: Int) {} // expected-note {{here}} @available(*, unavailable, renamed: "shinyLabeledArguments(_:)") func unavailableNewlyUnnamed(a: Int) {} // expected-note {{here}} @available(*, unavailable, renamed: "shinyLabeledArguments(a:b:)") func unavailableMultiSame(a: Int, b: Int) {} // expected-note {{here}} @available(*, unavailable, renamed: "shinyLabeledArguments(example:another:)") func unavailableMultiUnnamed(_ a: Int, _ b: Int) {} // expected-note {{here}} @available(*, unavailable, renamed: "shinyLabeledArguments(_:_:)") func unavailableMultiUnnamedSame(_ a: Int, _ b: Int) {} // expected-note {{here}} @available(*, unavailable, renamed: "shinyLabeledArguments(_:_:)") func unavailableMultiNewlyUnnamed(a: Int, b: Int) {} // expected-note {{here}} @available(*, unavailable, renamed: "init(shinyNewName:)") init(unavailableArgNames: Int) {} // expected-note{{here}} @available(*, unavailable, renamed: "init(a:)") init(_ unavailableUnnamed: Int) {} // expected-note{{here}} @available(*, unavailable, renamed: "init(_:)") init(unavailableNewlyUnnamed: Int) {} // expected-note{{here}} @available(*, unavailable, renamed: "init(a:b:)") init(_ unavailableMultiUnnamed: Int, _ b: Int) {} // expected-note{{here}} @available(*, unavailable, renamed: "init(_:_:)") init(unavailableMultiNewlyUnnamed a: Int, b: Int) {} // expected-note{{here}} @available(*, unavailable, renamed: "shinyLabeledArguments(x:)") func unavailableTooFew(a: Int, b: Int) {} // expected-note {{here}} @available(*, unavailable, renamed: "shinyLabeledArguments(x:b:)") func unavailableTooMany(a: Int) {} // expected-note {{here}} @available(*, unavailable, renamed: "shinyLabeledArguments(x:)") func unavailableNoArgsTooMany() {} // expected-note {{here}} @available(*, unavailable, renamed: "Base.shinyLabeledArguments()") func unavailableHasType() {} // expected-note {{here}} } class Sub : Base { override func bad() {} // expected-error {{cannot override 'bad' which has been marked unavailable}} {{none}} override func smelly() {} // expected-error {{cannot override 'smelly' which has been marked unavailable: it was smelly}} {{none}} override func old() {} // expected-error {{'old()' has been renamed to 'new'}} {{17-20=new}} override func oldAndSmelly() {} // expected-error {{'oldAndSmelly()' has been renamed to 'new': it was smelly}} {{17-29=new}} override var badProp: Int { return 0 } // expected-error {{cannot override 'badProp' which has been marked unavailable}} {{none}} override var smellyProp: Int { return 0 } // expected-error {{cannot override 'smellyProp' which has been marked unavailable: it was smelly}} {{none}} override var oldProp: Int { return 0 } // expected-error {{'oldProp' has been renamed to 'new'}} {{16-23=new}} override var oldAndSmellyProp: Int { return 0 } // expected-error {{'oldAndSmellyProp' has been renamed to 'new': it was smelly}} {{16-32=new}} override func nowAnInitializer() {} // expected-error {{'nowAnInitializer()' has been replaced by 'init'}} {{none}} override func nowAnInitializer2() {} // expected-error {{'nowAnInitializer2()' has been replaced by 'init()'}} {{none}} override init(nowAFunction: Int) {} // expected-error {{'init(nowAFunction:)' has been renamed to 'foo'}} {{none}} override init(nowAFunction2: Int) {} // expected-error {{'init(nowAFunction2:)' has been renamed to 'foo(_:)'}} {{none}} override func unavailableArgNames(a: Int) {} // expected-error {{'unavailableArgNames(a:)' has been renamed to 'shinyLabeledArguments(example:)'}} {{17-36=shinyLabeledArguments}} {{37-37=example }} override func unavailableArgRenamed(a param: Int) {} // expected-error {{'unavailableArgRenamed(a:)' has been renamed to 'shinyLabeledArguments(example:)'}} {{17-38=shinyLabeledArguments}} {{39-40=example}} override func unavailableNoArgs() {} // expected-error {{'unavailableNoArgs()' has been renamed to 'shinyLabeledArguments()'}} {{17-34=shinyLabeledArguments}} override func unavailableSame(a: Int) {} // expected-error {{'unavailableSame(a:)' has been renamed to 'shinyLabeledArguments(a:)'}} {{17-32=shinyLabeledArguments}} override func unavailableUnnamed(_ a: Int) {} // expected-error {{'unavailableUnnamed' has been renamed to 'shinyLabeledArguments(example:)'}} {{17-35=shinyLabeledArguments}} {{36-37=example}} override func unavailableUnnamedSame(_ a: Int) {} // expected-error {{'unavailableUnnamedSame' has been renamed to 'shinyLabeledArguments(_:)'}} {{17-39=shinyLabeledArguments}} override func unavailableNewlyUnnamed(a: Int) {} // expected-error {{'unavailableNewlyUnnamed(a:)' has been renamed to 'shinyLabeledArguments(_:)'}} {{17-40=shinyLabeledArguments}} {{41-41=_ }} override func unavailableMultiSame(a: Int, b: Int) {} // expected-error {{'unavailableMultiSame(a:b:)' has been renamed to 'shinyLabeledArguments(a:b:)'}} {{17-37=shinyLabeledArguments}} override func unavailableMultiUnnamed(_ a: Int, _ b: Int) {} // expected-error {{'unavailableMultiUnnamed' has been renamed to 'shinyLabeledArguments(example:another:)'}} {{17-40=shinyLabeledArguments}} {{41-42=example}} {{51-52=another}} override func unavailableMultiUnnamedSame(_ a: Int, _ b: Int) {} // expected-error {{'unavailableMultiUnnamedSame' has been renamed to 'shinyLabeledArguments(_:_:)'}} {{17-44=shinyLabeledArguments}} override func unavailableMultiNewlyUnnamed(a: Int, b: Int) {} // expected-error {{'unavailableMultiNewlyUnnamed(a:b:)' has been renamed to 'shinyLabeledArguments(_:_:)'}} {{17-45=shinyLabeledArguments}} {{46-46=_ }} {{54-54=_ }} override init(unavailableArgNames: Int) {} // expected-error {{'init(unavailableArgNames:)' has been renamed to 'init(shinyNewName:)'}} {{17-17=shinyNewName }} override init(_ unavailableUnnamed: Int) {} // expected-error {{'init' has been renamed to 'init(a:)'}} {{17-18=a}} override init(unavailableNewlyUnnamed: Int) {} // expected-error {{'init(unavailableNewlyUnnamed:)' has been renamed to 'init(_:)'}} {{17-17=_ }} override init(_ unavailableMultiUnnamed: Int, _ b: Int) {} // expected-error {{'init' has been renamed to 'init(a:b:)'}} {{17-18=a}} {{49-51=}} override init(unavailableMultiNewlyUnnamed a: Int, b: Int) {} // expected-error {{'init(unavailableMultiNewlyUnnamed:b:)' has been renamed to 'init(_:_:)'}} {{17-45=_}} {{54-54=_ }} override func unavailableTooFew(a: Int, b: Int) {} // expected-error {{'unavailableTooFew(a:b:)' has been renamed to 'shinyLabeledArguments(x:)'}} {{none}} override func unavailableTooMany(a: Int) {} // expected-error {{'unavailableTooMany(a:)' has been renamed to 'shinyLabeledArguments(x:b:)'}} {{none}} override func unavailableNoArgsTooMany() {} // expected-error {{'unavailableNoArgsTooMany()' has been renamed to 'shinyLabeledArguments(x:)'}} {{none}} override func unavailableHasType() {} // expected-error {{'unavailableHasType()' has been replaced by 'Base.shinyLabeledArguments()'}} {{none}} } // U: Unnamed, L: Labeled @available(*, unavailable, renamed: "after(fn:)") func closure_U_L(_ x: () -> Int) {} // expected-note 3 {{here}} @available(*, unavailable, renamed: "after(fn:)") func closure_L_L(x: () -> Int) {} // expected-note 3 {{here}} @available(*, unavailable, renamed: "after(_:)") func closure_L_U(x: () -> Int) {} // expected-note 3 {{here}} @available(*, unavailable, renamed: "after(arg:fn:)") func closure_UU_LL(_ x: Int, _ y: () -> Int) {} // expected-note 2 {{here}} @available(*, unavailable, renamed: "after(arg:fn:)") func closure_LU_LL(x: Int, _ y: () -> Int) {} // expected-note 2 {{here}} @available(*, unavailable, renamed: "after(arg:fn:)") func closure_LL_LL(x: Int, y: () -> Int) {} // expected-note 2 {{here}} @available(*, unavailable, renamed: "after(arg:fn:)") func closure_UU_LL_ne(_ x: Int, _ y: @noescape () -> Int) {} // expected-note 2 {{here}} @available(*, unavailable, renamed: "after(arg:_:)") func closure_UU_LU(_ x: Int, _ closure: () -> Int) {} // expected-note 2 {{here}} @available(*, unavailable, renamed: "after(arg:_:)") func closure_LU_LU(x: Int, _ closure: () -> Int) {} // expected-note 2 {{here}} @available(*, unavailable, renamed: "after(arg:_:)") func closure_LL_LU(x: Int, y: () -> Int) {} // expected-note 2 {{here}} @available(*, unavailable, renamed: "after(arg:_:)") func closure_UU_LU_ne(_ x: Int, _ y: @noescape () -> Int) {} // expected-note 2 {{here}} func testTrailingClosure() { closure_U_L { 0 } // expected-error {{'closure_U_L' has been renamed to 'after(fn:)'}} {{3-14=after}} {{none}} closure_U_L() { 0 } // expected-error {{'closure_U_L' has been renamed to 'after(fn:)'}} {{3-14=after}} {{none}} closure_U_L({ 0 }) // expected-error {{'closure_U_L' has been renamed to 'after(fn:)'}} {{3-14=after}} {{15-15=fn: }} {{none}} closure_L_L { 0 } // expected-error {{'closure_L_L(x:)' has been renamed to 'after(fn:)'}} {{3-14=after}} {{none}} closure_L_L() { 0 } // expected-error {{'closure_L_L(x:)' has been renamed to 'after(fn:)'}} {{3-14=after}} {{none}} closure_L_L(x: { 0 }) // expected-error {{'closure_L_L(x:)' has been renamed to 'after(fn:)'}} {{3-14=after}} {{15-16=fn}} {{none}} closure_L_U { 0 } // expected-error {{'closure_L_U(x:)' has been renamed to 'after(_:)'}} {{3-14=after}} {{none}} closure_L_U() { 0 } // expected-error {{'closure_L_U(x:)' has been renamed to 'after(_:)'}} {{3-14=after}} {{none}} closure_L_U(x: { 0 }) // expected-error {{'closure_L_U(x:)' has been renamed to 'after(_:)'}} {{3-14=after}} {{15-18=}} {{none}} closure_UU_LL(0) { 0 } // expected-error {{'closure_UU_LL' has been renamed to 'after(arg:fn:)'}} {{3-16=after}} {{17-17=arg: }} {{none}} closure_UU_LL(0, { 0 }) // expected-error {{'closure_UU_LL' has been renamed to 'after(arg:fn:)'}} {{3-16=after}} {{17-17=arg: }} {{20-20=fn: }} {{none}} closure_LU_LL(x: 0) { 0 } // expected-error {{'closure_LU_LL(x:_:)' has been renamed to 'after(arg:fn:)'}} {{3-16=after}} {{17-18=arg}} {{none}} closure_LU_LL(x: 0, { 0 }) // expected-error {{'closure_LU_LL(x:_:)' has been renamed to 'after(arg:fn:)'}} {{3-16=after}} {{17-18=arg}} {{23-23=fn: }} {{none}} closure_LL_LL(x: 1) { 1 } // expected-error {{'closure_LL_LL(x:y:)' has been renamed to 'after(arg:fn:)'}} {{3-16=after}} {{17-18=arg}} {{none}} closure_LL_LL(x: 1, y: { 0 }) // expected-error {{'closure_LL_LL(x:y:)' has been renamed to 'after(arg:fn:)'}} {{3-16=after}} {{17-18=arg}} {{23-24=fn}} {{none}} closure_UU_LL_ne(1) { 1 } // expected-error {{'closure_UU_LL_ne' has been renamed to 'after(arg:fn:)'}} {{3-19=after}} {{20-20=arg: }} {{none}} closure_UU_LL_ne(1, { 0 }) // expected-error {{'closure_UU_LL_ne' has been renamed to 'after(arg:fn:)'}} {{3-19=after}} {{20-20=arg: }} {{23-23=fn: }} {{none}} closure_UU_LU(0) { 0 } // expected-error {{'closure_UU_LU' has been renamed to 'after(arg:_:)'}} {{3-16=after}} {{17-17=arg: }} {{none}} closure_UU_LU(0, { 0 }) // expected-error {{'closure_UU_LU' has been renamed to 'after(arg:_:)'}} {{3-16=after}} {{17-17=arg: }} {{none}} closure_LU_LU(x: 0) { 0 } // expected-error {{'closure_LU_LU(x:_:)' has been renamed to 'after(arg:_:)'}} {{3-16=after}} {{17-18=arg}} {{none}} closure_LU_LU(x: 0, { 0 }) // expected-error {{'closure_LU_LU(x:_:)' has been renamed to 'after(arg:_:)'}} {{3-16=after}} {{17-18=arg}} {{none}} closure_LL_LU(x: 1) { 1 } // expected-error {{'closure_LL_LU(x:y:)' has been renamed to 'after(arg:_:)'}} {{3-16=after}} {{17-18=arg}} {{none}} closure_LL_LU(x: 1, y: { 0 }) // expected-error {{'closure_LL_LU(x:y:)' has been renamed to 'after(arg:_:)'}} {{3-16=after}} {{17-18=arg}} {{23-26=}} {{none}} closure_UU_LU_ne(1) { 1 } // expected-error {{'closure_UU_LU_ne' has been renamed to 'after(arg:_:)'}} {{3-19=after}} {{20-20=arg: }} {{none}} closure_UU_LU_ne(1, { 0 }) // expected-error {{'closure_UU_LU_ne' has been renamed to 'after(arg:_:)'}} {{3-19=after}} {{20-20=arg: }} {{none}} } @available(*, unavailable, renamed: "after(x:y:)") func variadic1(a: Int ..., b: Int = 0) {} // expected-note {{here}} func testVariadic() { // FIXME: fix-it should be: {{1-9=newFn7}} {{10-11=x}} {{none}} variadic1(a: 1, 1) // expected-error {{'variadic1(a:b:)' has been renamed to 'after(x:y:)'}} {{3-12=after}} {{none}} }
apache-2.0
dee8cc8ea0cc856f536740fc133706c3
64.135279
303
0.696103
3.898397
false
false
false
false
longitachi/ZLPhotoBrowser
Example/Example/Kingfisher/Extensions/NSTextAttachment+Kingfisher.swift
1
11078
// // NSTextAttachment+Kingfisher.swift // Kingfisher // // Created by Benjamin Briggs on 22/07/2019. // // Copyright (c) 2019 Wei Wang <[email protected]> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. #if !os(watchOS) #if os(macOS) import AppKit #else import UIKit #endif extension KingfisherWrapper where Base: NSTextAttachment { // MARK: Setting Image /// Sets an image to the text attachment with a source. /// /// - Parameters: /// - source: The `Source` object defines data information from network or a data provider. /// - attributedView: The owner of the attributed string which this `NSTextAttachment` is added. /// - placeholder: A placeholder to show while retrieving the image from the given `resource`. /// - options: An options set to define image setting behaviors. See `KingfisherOptionsInfo` for more. /// - progressBlock: Called when the image downloading progress gets updated. If the response does not contain an /// `expectedContentLength`, this block will not be called. /// - completionHandler: Called when the image retrieved and set finished. /// - Returns: A task represents the image downloading. /// /// - Note: /// /// Internally, this method will use `KingfisherManager` to get the requested source /// Since this method will perform UI changes, you must call it from the main thread. /// /// The retrieved image will be set to `NSTextAttachment.image` property. Because it is not an image view based /// rendering, options related to view, such as `.transition`, are not supported. /// /// Kingfisher will call `setNeedsDisplay` on the `attributedView` when the image task done. It gives the view a /// chance to render the attributed string again for displaying the downloaded image. For example, if you set an /// attributed with this `NSTextAttachment` to a `UILabel` object, pass it as the `attributedView` parameter. /// /// Here is a typical use case: /// /// ```swift /// let attributedText = NSMutableAttributedString(string: "Hello World") /// let textAttachment = NSTextAttachment() /// /// textAttachment.kf.setImage( /// with: URL(string: "https://onevcat.com/assets/images/avatar.jpg")!, /// attributedView: label, /// options: [ /// .processor( /// ResizingImageProcessor(referenceSize: .init(width: 30, height: 30)) /// |> RoundCornerImageProcessor(cornerRadius: 15)) /// ] /// ) /// attributedText.replaceCharacters(in: NSRange(), with: NSAttributedString(attachment: textAttachment)) /// label.attributedText = attributedText /// ``` /// @discardableResult public func setImage( with source: Source?, attributedView: KFCrossPlatformView, placeholder: KFCrossPlatformImage? = nil, options: KingfisherOptionsInfo? = nil, progressBlock: DownloadProgressBlock? = nil, completionHandler: ((Result<RetrieveImageResult, KingfisherError>) -> Void)? = nil) -> DownloadTask? { var mutatingSelf = self guard let source = source else { base.image = placeholder mutatingSelf.taskIdentifier = nil completionHandler?(.failure(KingfisherError.imageSettingError(reason: .emptySource))) return nil } var options = KingfisherParsedOptionsInfo(KingfisherManager.shared.defaultOptions + (options ?? .empty)) if !options.keepCurrentImageWhileLoading { base.image = placeholder } let issuedIdentifier = Source.Identifier.next() mutatingSelf.taskIdentifier = issuedIdentifier if let block = progressBlock { options.onDataReceived = (options.onDataReceived ?? []) + [ImageLoadingProgressSideEffect(block)] } if let provider = ImageProgressiveProvider(options, refresh: { image in self.base.image = image }) { options.onDataReceived = (options.onDataReceived ?? []) + [provider] } options.onDataReceived?.forEach { $0.onShouldApply = { issuedIdentifier == self.taskIdentifier } } let task = KingfisherManager.shared.retrieveImage( with: source, options: options, completionHandler: { result in CallbackQueue.mainCurrentOrAsync.execute { guard issuedIdentifier == self.taskIdentifier else { let reason: KingfisherError.ImageSettingErrorReason do { let value = try result.get() reason = .notCurrentSourceTask(result: value, error: nil, source: source) } catch { reason = .notCurrentSourceTask(result: nil, error: error, source: source) } let error = KingfisherError.imageSettingError(reason: reason) completionHandler?(.failure(error)) return } mutatingSelf.imageTask = nil mutatingSelf.taskIdentifier = nil switch result { case .success(let value): self.base.image = value.image #if canImport(UIKit) attributedView.setNeedsDisplay() #else attributedView.setNeedsDisplay(attributedView.bounds) #endif case .failure: if let image = options.onFailureImage { self.base.image = image } } completionHandler?(result) } } ) mutatingSelf.imageTask = task return task } /// Sets an image to the text attachment with a source. /// /// - Parameters: /// - resource: The `Resource` object contains information about the resource. /// - attributedView: The owner of the attributed string which this `NSTextAttachment` is added. /// - placeholder: A placeholder to show while retrieving the image from the given `resource`. /// - options: An options set to define image setting behaviors. See `KingfisherOptionsInfo` for more. /// - progressBlock: Called when the image downloading progress gets updated. If the response does not contain an /// `expectedContentLength`, this block will not be called. /// - completionHandler: Called when the image retrieved and set finished. /// - Returns: A task represents the image downloading. /// /// - Note: /// /// Internally, this method will use `KingfisherManager` to get the requested source /// Since this method will perform UI changes, you must call it from the main thread. /// /// The retrieved image will be set to `NSTextAttachment.image` property. Because it is not an image view based /// rendering, options related to view, such as `.transition`, are not supported. /// /// Kingfisher will call `setNeedsDisplay` on the `attributedView` when the image task done. It gives the view a /// chance to render the attributed string again for displaying the downloaded image. For example, if you set an /// attributed with this `NSTextAttachment` to a `UILabel` object, pass it as the `attributedView` parameter. /// /// Here is a typical use case: /// /// ```swift /// let attributedText = NSMutableAttributedString(string: "Hello World") /// let textAttachment = NSTextAttachment() /// /// textAttachment.kf.setImage( /// with: URL(string: "https://onevcat.com/assets/images/avatar.jpg")!, /// attributedView: label, /// options: [ /// .processor( /// ResizingImageProcessor(referenceSize: .init(width: 30, height: 30)) /// |> RoundCornerImageProcessor(cornerRadius: 15)) /// ] /// ) /// attributedText.replaceCharacters(in: NSRange(), with: NSAttributedString(attachment: textAttachment)) /// label.attributedText = attributedText /// ``` /// @discardableResult public func setImage( with resource: Resource?, attributedView: KFCrossPlatformView, placeholder: KFCrossPlatformImage? = nil, options: KingfisherOptionsInfo? = nil, progressBlock: DownloadProgressBlock? = nil, completionHandler: ((Result<RetrieveImageResult, KingfisherError>) -> Void)? = nil) -> DownloadTask? { return setImage( with: resource.map { .network($0) }, attributedView: attributedView, placeholder: placeholder, options: options, progressBlock: progressBlock, completionHandler: completionHandler) } // MARK: Cancelling Image /// Cancel the image download task bounded to the text attachment if it is running. /// Nothing will happen if the downloading has already finished. public func cancelDownloadTask() { imageTask?.cancel() } } private var taskIdentifierKey: Void? private var imageTaskKey: Void? // MARK: Properties extension KingfisherWrapper where Base: NSTextAttachment { public private(set) var taskIdentifier: Source.Identifier.Value? { get { let box: Box<Source.Identifier.Value>? = getAssociatedObject(base, &taskIdentifierKey) return box?.value } set { let box = newValue.map { Box($0) } setRetainedAssociatedObject(base, &taskIdentifierKey, box) } } private var imageTask: DownloadTask? { get { return getAssociatedObject(base, &imageTaskKey) } set { setRetainedAssociatedObject(base, &imageTaskKey, newValue)} } } #endif
mit
c317f4a08f2135c8911a6919572708e6
42.105058
119
0.630168
5.203382
false
false
false
false
gilserrap/Bigotes
Pods/GRMustache.swift/Mustache/Rendering/RenderingEngine.swift
2
14318
// The MIT License // // Copyright (c) 2015 Gwendal Roué // // 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 final class RenderingEngine { init(templateAST: TemplateAST, context: Context) { self.templateAST = templateAST self.baseContext = context buffer = "" } func render() throws -> Rendering { buffer = "" try renderTemplateAST(templateAST, inContext: baseContext) return Rendering(buffer, templateAST.contentType) } // MARK: - Rendering private let templateAST: TemplateAST private let baseContext: Context private var buffer: String private func renderTemplateAST(templateAST: TemplateAST, inContext context: Context) throws { // We must take care of eventual content-type mismatch between the // currently rendered AST (defined by init), and the argument. // // For example, the partial loaded by the HTML template `{{>partial}}` // may be a text one. In this case, we must render the partial as text, // and then HTML-encode its rendering. See the "Partial containing // CONTENT_TYPE:TEXT pragma is HTML-escaped when embedded." test in // the text_rendering.json test suite. // // So let's check for a content-type mismatch: let targetContentType = self.templateAST.contentType! if templateAST.contentType == targetContentType { // Content-type match for node in templateAST.nodes { try renderNode(node, inContext: context) } } else { // Content-type mismatch // // Render separately, so that we can HTML-escape the rendering of // the templateAST before appending to our buffer. let renderingEngine = RenderingEngine(templateAST: templateAST, context: context) let rendering = try renderingEngine.render() switch (targetContentType, rendering.contentType) { case (.HTML, .Text): buffer.appendContentsOf(escapeHTML(rendering.string)) default: buffer.appendContentsOf(rendering.string) } } } private func renderNode(node: TemplateASTNode, inContext context: Context) throws { switch node { case .BlockNode(let block): // {{$ name }}...{{/ name }} // // Render the inner content of the resolved block. let resolvedBlock = resolveBlock(block, inContext: context) return try renderTemplateAST(resolvedBlock.innerTemplateAST, inContext: context) case .PartialOverrideNode(let partialOverride): // {{< name }}...{{/ name }} // // Extend the inheritance stack, and render the content of the parent partial let context = context.extendedContext(partialOverride: partialOverride) return try renderTemplateAST(partialOverride.parentPartial.templateAST, inContext: context) case .PartialNode(let partial): // {{> name }} // // Render the content of the partial return try renderTemplateAST(partial.templateAST, inContext: context) case .SectionNode(let section): // {{# name }}...{{/ name }} // {{^ name }}...{{/ name }} // // We have common rendering for sections and variable tags, yet with // a few specific flags: return try renderTag(section.tag, escapesHTML: true, inverted: section.inverted, expression: section.expression, inContext: context) case .TextNode(let text): // text is the trivial case: buffer.appendContentsOf(text) case .VariableNode(let variable): // {{ name }} // {{{ name }}} // {{& name }} // // We have common rendering for sections and variable tags, yet with // a few specific flags: return try renderTag(variable.tag, escapesHTML: variable.escapesHTML, inverted: false, expression: variable.expression, inContext: context) } } private func renderTag(tag: LocatedTag, escapesHTML: Bool, inverted: Bool, expression: Expression, inContext context: Context) throws { // 1. Evaluate expression var box: MustacheBox do { box = try ExpressionInvocation(expression: expression).invokeWithContext(context) } catch let error as MustacheError { let newMessage: String if let oldMessage = error.message { newMessage = "Could not evaluate \(tag): \(oldMessage)" } else { newMessage = "Could not evaluate \(tag)" } throw error.errorWith(message: newMessage, templateID: tag.templateID, lineNumber: tag.lineNumber) } catch { throw MustacheError(kind: .RenderError, message: "Could not evaluate \(tag)", templateID: tag.templateID, lineNumber: tag.lineNumber, underlyingError: error) } // 2. Let willRender functions alter the box for willRender in context.willRenderStack { box = willRender(tag: tag, box: box) } // 3. Render the box let rendering: Rendering do { switch tag.type { case .Variable: let info = RenderingInfo(tag: tag, context: context, enumerationItem: false) rendering = try box.render(info: info) case .Section: switch (inverted, box.boolValue) { case (false, true): // {{# true }}...{{/ true }} // Only case where we trigger the RenderFunction of the Box let info = RenderingInfo(tag: tag, context: context, enumerationItem: false) rendering = try box.render(info: info) case (true, false): // {{^ false }}...{{/ false }} rendering = try tag.render(context) default: // {{^ true }}...{{/ true }} // {{# false }}...{{/ false }} rendering = Rendering("") } } } catch { for didRender in context.didRenderStack { didRender(tag: tag, box: box, string: nil) } // TODO? Inject location in error throw error } // 4. Extend buffer with the rendering, HTML-escaped if needed. let string: String switch (templateAST.contentType!, rendering.contentType, escapesHTML) { case (.HTML, .Text, true): string = escapeHTML(rendering.string) default: string = rendering.string } buffer.appendContentsOf(string) // 5. Let didRender functions do their job for didRender in context.didRenderStack { didRender(tag: tag, box: box, string: string) } } // MARK: - Template inheritance private func resolveBlock(block: TemplateASTNode.Block, inContext context: Context) -> TemplateASTNode.Block { // As we iterate partial overrides, block becomes the deepest overriden // block. context.partialOverrideStack has been built in // renderNode(node:inContext:). // // We also update an array of used parent template AST in order to // support nested partial overrides. var usedParentTemplateASTs: [TemplateAST] = [] return context.partialOverrideStack.reduce(block) { (block, partialOverride) in // Don't apply already used partial // // Relevant test: // { // "name": "com.github.mustachejava.ExtensionTest.testNested", // "template": "{{<box}}{{$box_content}}{{<main}}{{$main_content}}{{<box}}{{$box_content}}{{<tweetbox}}{{$tweetbox_classes}}tweetbox-largetweetbox-user-styled{{/tweetbox_classes}}{{$tweetbox_attrs}}data-rich-text{{/tweetbox_attrs}}{{/tweetbox}}{{/box_content}}{{/box}}{{/main_content}}{{/main}}{{/box_content}}{{/box}}", // "partials": { // "box": "<box>{{$box_content}}{{/box_content}}</box>", // "main": "<main>{{$main_content}}{{/main_content}}</main>", // "tweetbox": "<tweetbox classes=\"{{$tweetbox_classes}}{{/tweetbox_classes}}\" attrs=\"{{$tweetbox_attrs}}{{/tweetbox_attrs}}\"></tweetbox>" // }, // "expected": "<box><main><box><tweetbox classes=\"tweetbox-largetweetbox-user-styled\" attrs=\"data-rich-text\"></tweetbox></box></main></box>" // } let parentTemplateAST = partialOverride.parentPartial.templateAST if (usedParentTemplateASTs.contains { $0 === parentTemplateAST }) { return block } else { let (resolvedBlock, modified) = resolveBlock(block, inChildTemplateAST: partialOverride.childTemplateAST) if modified { usedParentTemplateASTs.append(parentTemplateAST) } return resolvedBlock } } } // Looks for an override for the block argument in a TemplateAST. // Returns the resolvedBlock, and a boolean that tells whether the block was // actually overriden. private func resolveBlock(block: TemplateASTNode.Block, inChildTemplateAST childTemplateAST: TemplateAST) -> (TemplateASTNode.Block, Bool) { // As we iterate template AST nodes, block becomes the last inherited // block in the template AST. // // The boolean turns to true once the block has been actually overriden. return childTemplateAST.nodes.reduce((block, false)) { (step, node) in let (block, modified) = step switch node { case .BlockNode(let resolvedBlock) where resolvedBlock.name == block.name: // {{$ name }}...{{/ name }} // // A block is overriden by another block with the same name. return (resolvedBlock, true) case .PartialOverrideNode(let partialOverride): // {{< partial }}...{{/ partial }} // // Partial overrides have two opprtunities to override the // block: their parent partial, and their overriding blocks. // // Relevant tests: // // { // "name": "Two levels of inheritance: parent partial with overriding content containing another parent partial", // "data": { }, // "template": "{{<partial}}{{<partial2}}{{/partial2}}{{/partial}}", // "partials": { // "partial": "{{$block}}ignored{{/block}}", // "partial2": "{{$block}}inherited{{/block}}" }, // "expected": "inherited" // }, // { // "name": "Two levels of inheritance: parent partial with overriding content containing another parent partial with overriding content containing a block", // "data": { }, // "template": "{{<partial}}{{<partial2}}{{$block}}inherited{{/block}}{{/partial2}}{{/partial}}", // "partials": { // "partial": "{{$block}}ignored{{/block}}", // "partial2": "{{$block}}ignored{{/block}}" }, // "expected": "inherited" // } let (resolvedBlock1, modified1) = resolveBlock(block, inChildTemplateAST: partialOverride.parentPartial.templateAST) let (resolvedBlock2, modified2) = resolveBlock(resolvedBlock1, inChildTemplateAST: partialOverride.childTemplateAST) return (resolvedBlock2, modified || modified1 || modified2) case .PartialNode(let partial): // {{> partial }} // // Relevant test: // // { // "name": "Partials in parent partials can override blocks", // "data": { }, // "template": "{{<partial2}}{{>partial1}}{{/partial2}}", // "partials": { // "partial1": "{{$block}}partial1{{/block}}", // "partial2": "{{$block}}ignored{{/block}}" }, // "expected": "partial1" // }, let (resolvedBlock1, modified1) = resolveBlock(block, inChildTemplateAST: partial.templateAST) return (resolvedBlock1, modified || modified1) default: // Other nodes can't override the block. return (block, modified) } } } }
mit
9c7c0cd8c5df35009f8c220d661e883e
43.740625
334
0.558567
5.177939
false
false
false
false
wireapp/wire-ios
Wire-iOS/Sources/UserInterface/CustomAppLock/WipeDatabase/WipeDatabaseWireframe.swift
1
1225
// Wire // Copyright (C) 2020 Wire Swiss GmbH // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see http://www.gnu.org/licenses/. // import UIKit final class WipeDatabaseWireframe { func createWipeDatabaseModule() -> WipeDatabaseViewController { let interactor = WipeDatabaseInteractor() let presenter = WipeDatabasePresenter() let viewController = WipeDatabaseViewController() viewController.presenter = presenter presenter.userInterface = viewController presenter.interactorInput = interactor interactor.output = presenter presenter.wireframe = self return viewController } }
gpl-3.0
b0f59440b17f6f2ee634939d98fdb5a3
33.027778
71
0.72898
4.9
false
false
false
false
firebase/firebase-ios-sdk
FirebaseDatabase/Tests/Unit/Swift/DatabaseAPITests.swift
1
25466
// // Copyright 2021 Google LLC // // 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. // // MARK: This file is used to evaluate the experience of using the Firebase Database APIs in Swift. import Foundation import FirebaseCore import FirebaseDatabase final class DatabaseAPITests { func usage() { // MARK: - Database var url = "url" let path = "path" let host = "host" let port = 0 let yes = true // Retrieve Database Instance var database = Database.database() database = Database.database(url: url) if let app = FirebaseApp.app() { database = Database.database(app: app, url: url) database = Database.database(app: app) } // Retrieve FirebaseApp let /* app */ _: FirebaseApp? = database.app // Retrieve DatabaseReference var databaseReference: DatabaseReference = database.reference() databaseReference = database.reference(withPath: path) databaseReference = database.reference(fromURL: url) // Instance methods database.purgeOutstandingWrites() database.goOffline() database.goOnline() database.useEmulator(withHost: host, port: port) // Instance members let /* isPersistenceEnabled */ _: Bool = database.isPersistenceEnabled let /* persistenceCacheSizeBytes */ _: UInt = database.persistenceCacheSizeBytes let /* callbackQueue */ _: DispatchQueue = database.callbackQueue // Class methods Database.setLoggingEnabled(yes) let /* sdkVersion */ _: String = Database.sdkVersion() // MARK: - DatabaseQuery let uint: UInt = 0 let dataEventType: DataEventType = .value let child = "child" let childKey: String? = "key" let value: Any? = "value" let priority: Any? = "priority" var databaseHandle: DatabaseHandle = uint var databaseQuery = DatabaseQuery() // Observe for data // observe(_ eventType:with block:) databaseHandle = databaseQuery.observe(dataEventType) { dataSnapshot in let /* dataSnapshot */ _: DataSnapshot = dataSnapshot } // observe(_ eventType:andPreviousSiblingKeyWith block:) databaseHandle = databaseQuery.observe(dataEventType) { dataSnapshot, optionalString in let /* dataSnapshot */ _: DataSnapshot = dataSnapshot let /* optionalString */ _: String? = optionalString } // observe(_ eventType:with block:withCancel cancelBlock:) databaseHandle = databaseQuery.observe(dataEventType) { dataSnapshot in let /* dataSnapshot */ _: DataSnapshot = dataSnapshot } withCancel: { error in let /* error */ _: Error = error } // observe(_ eventType:andPreviousSiblingKeyWith block:withCancel cancelBlock:) databaseHandle = databaseQuery.observe(dataEventType) { dataSnapshot, optionalString in let /* dataSnapshot */ _: DataSnapshot = dataSnapshot let /* optionalString */ _: String? = optionalString } withCancel: { error in let /* error */ _: Error = error } // Get data // getData(completion block:) databaseQuery.getData { optionalError, dataSnapshot in let /* optionalError */ _: Error? = optionalError let /* dataSnapshot */ _: DataSnapshot? = dataSnapshot } #if compiler(>=5.5.2) && canImport(_Concurrency) if #available(iOS 13.0, macOS 10.15, macCatalyst 13.0, tvOS 13.0, watchOS 7.0, *) { // async/await is a Swift 5.5+ feature available on iOS 15+ Task { do { let /* dataSnapshot */ _: DataSnapshot = try await DatabaseQuery().getData() } catch { // ... } } } #endif // compiler(>=5.5.2) && canImport(_Concurrency) // Observe Single Event // observeSingleEvent(of eventType:with block:) databaseQuery.observeSingleEvent(of: dataEventType) { dataSnapshot in let /* dataSnapshot */ _: DataSnapshot = dataSnapshot } // observeSingleEvent(of eventType:andPreviousSiblingKeyWith block:) databaseQuery.observeSingleEvent(of: dataEventType) { dataSnapshot, optionalString in let /* dataSnapshot */ _: DataSnapshot = dataSnapshot let /* optionalString */ _: String? = optionalString } #if compiler(>=5.5.2) && canImport(_Concurrency) if #available(iOS 13.0, macOS 10.15, macCatalyst 13.0, tvOS 13.0, watchOS 7.0, *) { // async/await is a Swift 5.5+ feature available on iOS 15+ Task { // observeSingleEvent(of eventType:) let _: (DataSnapshot, String?) = await DatabaseQuery() .observeSingleEventAndPreviousSiblingKey(of: dataEventType) } } #endif // compiler(>=5.5.2) && canImport(_Concurrency) // observeSingleEvent(of eventType:with block:withCancel cancelBlock:) databaseQuery.observeSingleEvent(of: dataEventType) { dataSnapshot in let /* dataSnapshot */ _: DataSnapshot = dataSnapshot } withCancel: { error in let /* error */ _: Error = error } // observeSingleEvent(of eventType:andPreviousSiblingKeyWith block:withCancel cancelBlock:) databaseQuery.observeSingleEvent(of: dataEventType) { dataSnapshot, optionalString in let /* dataSnapshot */ _: DataSnapshot = dataSnapshot let /* optionalString */ _: String? = optionalString } withCancel: { error in let /* error */ _: Error = error } // Remove Observers databaseQuery.removeObserver(withHandle: databaseHandle) databaseQuery.removeAllObservers() // Keep Synced databaseQuery.keepSynced(yes) // Limited Views of Data databaseQuery = databaseQuery.queryLimited(toFirst: databaseHandle) databaseQuery = databaseQuery.queryLimited(toLast: databaseHandle) databaseQuery = databaseQuery.queryOrdered(byChild: child) databaseQuery = databaseQuery.queryOrderedByKey() databaseQuery = databaseQuery.queryOrderedByValue() databaseQuery = databaseQuery.queryOrderedByPriority() databaseQuery = databaseQuery.queryStarting(atValue: value) databaseQuery = databaseQuery.queryStarting(atValue: value, childKey: childKey) databaseQuery = databaseQuery.queryStarting(afterValue: value) databaseQuery = databaseQuery.queryStarting(afterValue: value, childKey: childKey) databaseQuery = databaseQuery.queryEnding(atValue: value) databaseQuery = databaseQuery.queryEnding(beforeValue: value) databaseQuery = databaseQuery.queryEnding(beforeValue: value, childKey: childKey) databaseQuery = databaseQuery.queryEqual(toValue: value) databaseQuery = databaseQuery.queryEqual(toValue: value, childKey: childKey) // Retrieve DatabaseReference Instance databaseReference = databaseQuery.ref // MARK: - DatabaseReference let priorityAny: Any = "priority" let values = [AnyHashable: Any]() var transactionResult = TransactionResult() // Retreive Child DatabaseReference databaseReference = databaseReference.child(child) databaseReference = databaseReference.childByAutoId() // Set value databaseReference.setValue(value) // setValue(_ value:withCompletionBlock block:) databaseReference.setValue(value) { optionalError, databaseReference in let /* optionalError */ _: Error? = optionalError let /* databaseReference */ _: DatabaseReference = databaseReference } #if compiler(>=5.5.2) && canImport(_Concurrency) if #available(iOS 13.0, macOS 10.15, macCatalyst 13.0, tvOS 13.0, watchOS 7.0, *) { // async/await is a Swift 5.5+ feature available on iOS 15+ Task { do { // setValue(_ value:) let /* ref */ _: DatabaseReference = try await DatabaseReference().setValue(value) } catch { // ... } } } #endif // compiler(>=5.5.2) && canImport(_Concurrency) databaseReference.setValue(value, andPriority: priority) // setValue(_ value:andPriority priority:withCompletionBlock block:) databaseReference.setValue(value, andPriority: priority) { optionalError, databaseReference in let /* optionalError */ _: Error? = optionalError let /* databaseReference */ _: DatabaseReference = databaseReference } #if compiler(>=5.5.2) && canImport(_Concurrency) if #available(iOS 13.0, macOS 10.15, macCatalyst 13.0, tvOS 13.0, watchOS 7.0, *) { // async/await is a Swift 5.5+ feature available on iOS 15+ Task { do { // setValue(_ value:andPriority priority:) let /* ref */ _: DatabaseReference = try await DatabaseReference() .setValue(value, andPriority: priority) } catch { // ... } } } #endif // compiler(>=5.5.2) && canImport(_Concurrency) // Remove value databaseReference.removeValue() // removeValue(completionBlock block:) databaseReference.removeValue { optionalError, databaseReference in let /* optionalError */ _: Error? = optionalError let /* databaseReference */ _: DatabaseReference = databaseReference } #if compiler(>=5.5.2) && canImport(_Concurrency) if #available(iOS 13.0, macOS 10.15, macCatalyst 13.0, tvOS 13.0, watchOS 7.0, *) { // async/await is a Swift 5.5+ feature available on iOS 15+ Task { do { let /* ref */ _: DatabaseReference = try await DatabaseReference().removeValue() } catch { // ... } } } #endif // compiler(>=5.5.2) && canImport(_Concurrency) // Set priority databaseReference.setPriority(priority) // setPriority(_ priority:withCompletionBlock block:) databaseReference.setPriority(priority) { optionalError, databaseReference in let /* optionalError */ _: Error? = optionalError let /* databaseReference */ _: DatabaseReference = databaseReference } #if compiler(>=5.5.2) && canImport(_Concurrency) if #available(iOS 13.0, macOS 10.15, macCatalyst 13.0, tvOS 13.0, watchOS 7.0, *) { // async/await is a Swift 5.5+ feature available on iOS 15+ Task { do { // setPriority(_ priority:) let /* ref */ _: DatabaseReference = try await DatabaseReference().setPriority(priority) } catch { // ... } } } #endif // compiler(>=5.5.2) && canImport(_Concurrency) // Update child values databaseReference.updateChildValues(values) // updateChildValues(_ values:withCompletionBlock block:) databaseReference.updateChildValues(values) { optionalError, databaseReference in let /* optionalError */ _: Error? = optionalError let /* databaseReference */ _: DatabaseReference = databaseReference } #if compiler(>=5.5.2) && canImport(_Concurrency) if #available(iOS 13.0, macOS 10.15, macCatalyst 13.0, tvOS 13.0, watchOS 7.0, *) { // async/await is a Swift 5.5+ feature available on iOS 15+ Task { do { // updateChildValues(_ values:) let /* ref */ _: DatabaseReference = try await DatabaseReference() .updateChildValues(values) } catch { // ... } } } #endif // compiler(>=5.5.2) && canImport(_Concurrency) // Observe for data // observe(_ eventType:with block:) databaseHandle = databaseReference.observe(dataEventType) { dataSnapshot in let /* dataSnapshot */ _: DataSnapshot = dataSnapshot } // observe(_ eventType:andPreviousSiblingKeyWith block:) databaseHandle = databaseReference.observe(dataEventType) { dataSnapshot, optionalString in let /* dataSnapshot */ _: DataSnapshot = dataSnapshot let /* optionalString */ _: String? = optionalString } // observe(_ eventType:with block:withCancel cancelBlock:) databaseHandle = databaseReference.observe(dataEventType) { dataSnapshot in let /* dataSnapshot */ _: DataSnapshot = dataSnapshot } withCancel: { error in let /* error */ _: Error = error } // observe(_ eventType:andPreviousSiblingKeyWith block:withCancel cancelBlock:) databaseHandle = databaseReference.observe(dataEventType) { dataSnapshot, optionalString in let /* dataSnapshot */ _: DataSnapshot = dataSnapshot let /* optionalString */ _: String? = optionalString } withCancel: { error in let /* error */ _: Error = error } // Observe Single Event // observeSingleEvent(of eventType:with block:) databaseReference.observeSingleEvent(of: dataEventType) { dataSnapshot in let /* dataSnapshot */ _: DataSnapshot = dataSnapshot } // observeSingleEvent(of eventType:andPreviousSiblingKeyWith block:) databaseReference.observeSingleEvent(of: dataEventType) { dataSnapshot, optionalString in let /* dataSnapshot */ _: DataSnapshot = dataSnapshot let /* optionalString */ _: String? = optionalString } #if compiler(>=5.5.2) && canImport(_Concurrency) if #available(iOS 13.0, macOS 10.15, macCatalyst 13.0, tvOS 13.0, watchOS 7.0, *) { // async/await is a Swift 5.5+ feature available on iOS 15+ Task { // observeSingleEvent(of eventType:) let _: (DataSnapshot, String?) = await DatabaseReference() .observeSingleEventAndPreviousSiblingKey(of: dataEventType) } } #endif // compiler(>=5.5.2) && canImport(_Concurrency) // observeSingleEvent(of eventType:with block:withCancel cancelBlock:) databaseReference.observeSingleEvent(of: dataEventType) { dataSnapshot in let /* dataSnapshot */ _: DataSnapshot = dataSnapshot } withCancel: { error in let /* error */ _: Error = error } // observeSingleEvent(of eventType:andPreviousSiblingKeyWith block:withCancel cancelBlock:) databaseReference.observeSingleEvent(of: dataEventType) { dataSnapshot, optionalString in let /* dataSnapshot */ _: DataSnapshot = dataSnapshot let /* optionalString */ _: String? = optionalString } withCancel: { error in let /* error */ _: Error = error } // Get data // getData(completion block:) databaseReference.getData { optionalError, dataSnapshot in let /* optionalError */ _: Error? = optionalError let /* dataSnapshot */ _: DataSnapshot? = dataSnapshot } #if compiler(>=5.5.2) && canImport(_Concurrency) if #available(iOS 13.0, macOS 10.15, macCatalyst 13.0, tvOS 13.0, watchOS 7.0, *) { // async/await is a Swift 5.5+ feature available on iOS 15+ Task { do { let /* dataSnapshot */ _: DataSnapshot = try await DatabaseReference().getData() } catch { // ... } } } #endif // compiler(>=5.5.2) && canImport(_Concurrency) // Remove Observers databaseReference.removeObserver(withHandle: databaseHandle) databaseReference.removeAllObservers() // Keep Synced databaseReference.keepSynced(yes) // Limited Views of Data databaseQuery = databaseReference.queryLimited(toFirst: databaseHandle) databaseQuery = databaseReference.queryLimited(toLast: databaseHandle) databaseQuery = databaseReference.queryOrdered(byChild: child) databaseQuery = databaseReference.queryOrderedByKey() databaseQuery = databaseReference.queryOrderedByPriority() databaseQuery = databaseReference.queryStarting(atValue: value) databaseQuery = databaseReference.queryStarting(atValue: value, childKey: childKey) databaseQuery = databaseReference.queryStarting(afterValue: value) databaseQuery = databaseReference.queryStarting(afterValue: value, childKey: childKey) databaseQuery = databaseReference.queryEnding(atValue: value) databaseQuery = databaseReference.queryEnding(atValue: value, childKey: childKey) databaseQuery = databaseReference.queryEqual(toValue: value) databaseQuery = databaseReference.queryEqual(toValue: value, childKey: childKey) // onDisconnectSetValue databaseReference.onDisconnectSetValue(value) // onDisconnectSetValue(_ value:withCompletionBlock block:) databaseReference.onDisconnectSetValue(value) { optionalError, databaseReference in let /* optionalError */ _: Error? = optionalError let /* databaseReference */ _: DatabaseReference = databaseReference } #if compiler(>=5.5.2) && canImport(_Concurrency) if #available(iOS 13.0, macOS 10.15, macCatalyst 13.0, tvOS 13.0, watchOS 7.0, *) { // async/await is a Swift 5.5+ feature available on iOS 15+ Task { do { // onDisconnectSetValue(_ value:) let /* ref */ _: DatabaseReference = try await DatabaseReference() .onDisconnectSetValue(value) } catch { // ... } } } #endif // compiler(>=5.5.2) && canImport(_Concurrency) databaseReference.onDisconnectSetValue(value, andPriority: priorityAny) // onDisconnectSetValue(_ value:andPriority priority:withCompletionBlock block:) databaseReference .onDisconnectSetValue(value, andPriority: priority) { optionalError, databaseReference in let /* optionalError */ _: Error? = optionalError let /* databaseReference */ _: DatabaseReference = databaseReference } #if compiler(>=5.5.2) && canImport(_Concurrency) if #available(iOS 13.0, macOS 10.15, macCatalyst 13.0, tvOS 13.0, watchOS 7.0, *) { // async/await is a Swift 5.5+ feature available on iOS 15+ Task { do { // onDisconnectSetValue(_ value:andPriority priority:) let /* ref */ _: DatabaseReference = try await DatabaseReference().onDisconnectSetValue( value, andPriority: priority ) } catch { // ... } } } #endif // compiler(>=5.5.2) && canImport(_Concurrency) // onDisconnectRemoveValue databaseReference.onDisconnectRemoveValue() // onDisconnectRemoveValue(completionBlock block:) databaseReference.onDisconnectRemoveValue { optionalError, databaseReference in let /* optionalError */ _: Error? = optionalError let /* databaseReference */ _: DatabaseReference = databaseReference } #if compiler(>=5.5.2) && canImport(_Concurrency) if #available(iOS 13.0, macOS 10.15, macCatalyst 13.0, tvOS 13.0, watchOS 7.0, *) { // async/await is a Swift 5.5+ feature available on iOS 15+ Task { do { let /* ref */ _: DatabaseReference = try await DatabaseReference() .onDisconnectRemoveValue() } catch { // ... } } } #endif // compiler(>=5.5.2) && canImport(_Concurrency) // onDisconnectUpdateChildValues databaseReference.onDisconnectUpdateChildValues(values) // onDisconnectUpdateChildValues(_ values:withCompletionBlock block:) databaseReference.onDisconnectUpdateChildValues(values) { optionalError, databaseReference in let /* optionalError */ _: Error? = optionalError let /* databaseReference */ _: DatabaseReference = databaseReference } #if compiler(>=5.5.2) && canImport(_Concurrency) if #available(iOS 13.0, macOS 10.15, macCatalyst 13.0, tvOS 13.0, watchOS 7.0, *) { // async/await is a Swift 5.5+ feature available on iOS 15+ Task { do { // onDisconnectUpdateChildValues(_ values:) let /* ref */ _: DatabaseReference = try await DatabaseReference() .onDisconnectUpdateChildValues(values) } catch { // ... } } } #endif // compiler(>=5.5.2) && canImport(_Concurrency) // cancelDisconnectOperations databaseReference.cancelDisconnectOperations() // cancelDisconnectOperations(completionBlock block:) databaseReference.cancelDisconnectOperations { optionalError, databaseReference in let /* optionalError */ _: Error? = optionalError let /* databaseReference */ _: DatabaseReference = databaseReference } #if compiler(>=5.5.2) && canImport(_Concurrency) if #available(iOS 13.0, macOS 10.15, macCatalyst 13.0, tvOS 13.0, watchOS 7.0, *) { // async/await is a Swift 5.5+ feature available on iOS 15+ Task { do { let /* ref */ _: DatabaseReference = try await DatabaseReference() .cancelDisconnectOperations() } catch { // ... } } } #endif // compiler(>=5.5.2) && canImport(_Concurrency) // runTransactionBlock // runTransactionBlock(_ block:) databaseReference.runTransactionBlock { mutableData in let /* mutableData */ _: MutableData = mutableData return transactionResult } // runTransactionBlock(_ block:andCompletionBlock completionBlock:) databaseReference.runTransactionBlock { mutableData in let /* mutableData */ _: MutableData = mutableData return transactionResult } andCompletionBlock: { optionalError, bool, optionalDataSnapshot in let /* optionalError */ _: Error? = optionalError let /* bool */ _: Bool = bool let /* optionalDataSnapshot */ _: DataSnapshot? = optionalDataSnapshot } #if compiler(>=5.5.2) && canImport(_Concurrency) if #available(iOS 13.0, macOS 10.15, macCatalyst 13.0, tvOS 13.0, watchOS 7.0, *) { // async/await is a Swift 5.5+ feature available on iOS 15+ Task { do { // runTransactionBlock(_ block:) let _: (Bool, DataSnapshot) = try await DatabaseReference() .runTransactionBlock { mutableData in let /* mutableData */ _: MutableData = mutableData return TransactionResult() } } catch { // ... } } } #endif // compiler(>=5.5.2) && canImport(_Concurrency) // runTransactionBlock(_ block:andCompletionBlock completionBlock:withLocalEvents localEvents:) databaseReference.runTransactionBlock({ mutableData in let /* mutableData */ _: MutableData = mutableData return transactionResult }, andCompletionBlock: { optionalError, bool, optionalDataSnapshot in let /* optionalError */ _: Error? = optionalError let /* bool */ _: Bool = bool let /* optionalDataSnapshot */ _: DataSnapshot? = optionalDataSnapshot }, withLocalEvents: yes) // description let /* description */ _: String = databaseReference.description() // Class methods DatabaseReference.goOffline() DatabaseReference.goOnline() // Instance properties let /* parent */ _: DatabaseReference? = databaseReference.parent let /* childKey */ _: String? = databaseReference.key databaseReference = databaseReference.root url = databaseReference.url database = databaseReference.database // MARK: - DataEventType let optionalDataEventType = DataEventType(rawValue: 0) switch optionalDataEventType { case .childAdded: break case .childRemoved: break case .childChanged: break case .childMoved: break case .value: break case .none, .some: break } // MARK: - DataSnapshot var dataSnapshot = DataSnapshot() // Navigating and inspecting a snapshot dataSnapshot = dataSnapshot.childSnapshot(forPath: path) let /* hasChild */ _: Bool = dataSnapshot.hasChild(child) let /* hasChildren */ _: Bool = dataSnapshot.hasChildren() let /* exists */ _: Bool = dataSnapshot.exists() // Data export let /* value */ _: Any? = dataSnapshot.valueInExportFormat() // Properties databaseReference = dataSnapshot.ref let /* value */ _: Any? = dataSnapshot.value let /* uint */ _: UInt = dataSnapshot.childrenCount let /* child */ _: String? = dataSnapshot.key let /* children */ _: NSEnumerator = dataSnapshot.children let /* priority */ _: Any? = dataSnapshot.priority // MARK: - MutableData var mutableData = MutableData() // Inspecting and navigating the data let /* hasChildren */ _: Bool = mutableData.hasChildren() let /* hasChild */ _: Bool = mutableData.hasChild(atPath: path) mutableData = mutableData.childData(byAppendingPath: path) // Properties let /* value */ _: Any? = mutableData.value let /* priority */ _: Any? = mutableData.priority let /* uint */ _: UInt = mutableData.childrenCount let /* children */ _: NSEnumerator = mutableData.children let /* childKey */ _: String? = mutableData.key // MARK: - ServerValue let nsNumber: NSNumber = 0 let /* values */ _: [AnyHashable: Any] = ServerValue.timestamp() let /* values */ _: [AnyHashable: Any] = ServerValue.increment(nsNumber) // MARK: - TransactionResult transactionResult = TransactionResult.success(withValue: mutableData) transactionResult = TransactionResult.abort() } }
apache-2.0
0bc062af3df1198c412be98d64330224
36.560472
100
0.653538
4.748462
false
false
false
false
banjun/SwiftBeaker
Examples/13. Named Endpoints.swift
1
4574
import Foundation import APIKit import URITemplate protocol URITemplateContextConvertible: Encodable {} extension URITemplateContextConvertible { var context: [String: String] { return ((try? JSONSerialization.jsonObject(with: JSONEncoder().encode(self))) as? [String: String]) ?? [:] } } public enum RequestError: Error { case encode } public enum ResponseError: Error { case undefined(Int, String?) case invalidData(Int, String?) } struct RawDataParser: DataParser { var contentType: String? {return nil} func parse(data: Data) -> Any { return data } } struct TextBodyParameters: BodyParameters { let contentType: String let content: String func buildEntity() throws -> RequestBodyEntity { guard let r = content.data(using: .utf8) else { throw RequestError.encode } return .data(r) } } public protocol APIBlueprintRequest: Request {} extension APIBlueprintRequest { public var dataParser: DataParser {return RawDataParser()} func contentMIMEType(in urlResponse: HTTPURLResponse) -> String? { return (urlResponse.allHeaderFields["Content-Type"] as? String)?.components(separatedBy: ";").first?.trimmingCharacters(in: .whitespaces) } func data(from object: Any, urlResponse: HTTPURLResponse) throws -> Data { guard let d = object as? Data else { throw ResponseError.invalidData(urlResponse.statusCode, contentMIMEType(in: urlResponse)) } return d } func string(from object: Any, urlResponse: HTTPURLResponse) throws -> String { guard let s = String(data: try data(from: object, urlResponse: urlResponse), encoding: .utf8) else { throw ResponseError.invalidData(urlResponse.statusCode, contentMIMEType(in: urlResponse)) } return s } func decodeJSON<T: Decodable>(from object: Any, urlResponse: HTTPURLResponse) throws -> T { return try JSONDecoder().decode(T.self, from: data(from: object, urlResponse: urlResponse)) } public func intercept(object: Any, urlResponse: HTTPURLResponse) throws -> Any { return object } } protocol URITemplateRequest: Request { static var pathTemplate: URITemplate { get } associatedtype PathVars: URITemplateContextConvertible var pathVars: PathVars { get } } extension URITemplateRequest { // reconstruct URL to use URITemplate.expand. NOTE: APIKit does not support URITemplate format other than `path + query` public func intercept(urlRequest: URLRequest) throws -> URLRequest { var req = urlRequest req.url = URL(string: baseURL.absoluteString + type(of: self).pathTemplate.expand(pathVars.context))! return req } } /// indirect Codable Box-like container for recursive data structure definitions public class Indirect<V: Codable>: Codable { public var value: V public init(_ value: V) { self.value = value } public required init(from decoder: Decoder) throws { self.value = try V(from: decoder) } public func encode(to encoder: Encoder) throws { try value.encode(to: encoder) } } // MARK: - Transitions /// Start out by creating a message for the world to see. struct Create_message: APIBlueprintRequest { let baseURL: URL var method: HTTPMethod {return .post} var path: String {return "/messages"} enum Responses { case http201_(Void) } func response(from object: Any, urlResponse: HTTPURLResponse) throws -> Responses { let contentType = contentMIMEType(in: urlResponse) switch (urlResponse.statusCode, contentType) { case (201, _): return .http201_(try decodeJSON(from: object, urlResponse: urlResponse)) default: throw ResponseError.undefined(urlResponse.statusCode, contentType) } } } /// Now create a task that you need to do at a later date. struct Create_a_new_task: APIBlueprintRequest { let baseURL: URL var method: HTTPMethod {return .post} var path: String {return "/tasks"} enum Responses { case http201_(Void) } func response(from object: Any, urlResponse: HTTPURLResponse) throws -> Responses { let contentType = contentMIMEType(in: urlResponse) switch (urlResponse.statusCode, contentType) { case (201, _): return .http201_(try decodeJSON(from: object, urlResponse: urlResponse)) default: throw ResponseError.undefined(urlResponse.statusCode, contentType) } } } // MARK: - Data Structures
mit
ed3889944060b003ec29254b42e8f59c
30.544828
145
0.68146
4.555777
false
false
false
false
totocaster/Nihongo
YahooMAParser.swift
1
2271
// // YahooMAParser.swift // Nihongo // // Created by Toto Tvalavadze on 2016/12/17. // Copyright © 2016 Toto Tvalavadze. All rights reserved. // import Foundation class YahooMAServiceResponseParser: NSObject, XMLParserDelegate { let parser: XMLParser private var completionCallback: ParsingCompleteCallback init(data: Data, completion: @escaping ParsingCompleteCallback) { parser = XMLParser(data: data) completionCallback = completion } typealias ParsingCompleteCallback = ([Word]) -> () func parse() { parser.delegate = self parser.parse() } private var words: [Word] = [] private var isParsingWord = false private var currentWordNode: String? private var intermediateWord:[String: String] = [:] // MARK: XMLParserDelegate func parser(_ parser: XMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String] = [:]) { if elementName == "word" { isParsingWord = true } else { if isParsingWord { currentWordNode = elementName } } } func parser(_ parser: XMLParser, foundCharacters string: String) { guard isParsingWord else { return } if let currentNode = currentWordNode { intermediateWord[currentNode] = string } } func parser(_ parser: XMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?) { if elementName == "word" { isParsingWord = false if let position = intermediateWord["pos"], let text = intermediateWord["surface"], let reading = intermediateWord["reading"], let base = intermediateWord["baseform"], let lexical = WordClass(rawValue: position) { let word = Word(text: text, reading: reading, class: lexical, base: base) words.append(word) } intermediateWord = [:] currentWordNode = nil } } func parserDidEndDocument(_ parser: XMLParser) { completionCallback(words) } }
mit
68fab1a681173dc34e1c8fd0dfeea323
31.428571
179
0.605286
4.97807
false
false
false
false
AnarchyTools/atpm
tests/atpm_tools/VersionRangeTests.swift
1
7865
// Copyright (c) 2016 Anarchy Tools Contributors. // // 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. @testable import atpm_tools import XCTest class VersionRangeTests: XCTestCase { // MARK: - Initialization tests func testInitSimple() throws { let v = VersionRange(versionString: "1.2.3") XCTAssert(v.min == Version(string: "1.2.3")) XCTAssert(v.max == Version(string: "1.2.3")) XCTAssert(v.minInclusive == true) XCTAssert(v.maxInclusive == true) XCTAssert(v.description == "==1.2.3") } func testInitSmaller() throws { let v = VersionRange(versionString: "<1.2.3") XCTAssert(v.min == nil) XCTAssert(v.max == Version(string: "1.2.3")) XCTAssert(v.minInclusive == nil) XCTAssert(v.maxInclusive == false) XCTAssert(v.description == "<1.2.3") } func testInitBigger() throws { let v = VersionRange(versionString: ">1.2.3") XCTAssert(v.min == Version(string: "1.2.3")) XCTAssert(v.max == nil) XCTAssert(v.minInclusive == false) XCTAssert(v.maxInclusive == nil) XCTAssert(v.description == ">1.2.3") } func testInitSmallerEqual() throws { let v = VersionRange(versionString: "<=1.2.3") XCTAssert(v.min == nil) XCTAssert(v.max == Version(string: "1.2.3")) XCTAssert(v.minInclusive == nil) XCTAssert(v.maxInclusive == true) XCTAssert(v.description == "<=1.2.3") } func testInitBiggerEqual() throws { let v = VersionRange(versionString: ">=1.2.3") XCTAssert(v.min == Version(string: "1.2.3")) XCTAssert(v.max == nil) XCTAssert(v.minInclusive == true) XCTAssert(v.maxInclusive == nil) XCTAssert(v.description == ">=1.2.3") } func testInitEqual() throws { let v = VersionRange(versionString: "==1.2.3") XCTAssert(v.min == Version(string: "1.2.3")) XCTAssert(v.max == Version(string: "1.2.3")) XCTAssert(v.minInclusive == true) XCTAssert(v.maxInclusive == true) XCTAssert(v.description == "==1.2.3") } // MARK: - Valid combination tests func testCombineWithLowerBound() throws { let v = VersionRange(versionString: "<2.0.0") try v.combine(">1.0.1") XCTAssert(v.min == Version(string: "1.0.1")) XCTAssert(v.max == Version(string: "2.0.0")) XCTAssert(v.minInclusive == false) XCTAssert(v.maxInclusive == false) XCTAssert(v.description == ">1.0.1, <2.0.0") } func testCombineWithUpperBound() throws { let v = VersionRange(versionString: ">1.0.1") try v.combine("<2.0.0") XCTAssert(v.min == Version(string: "1.0.1")) XCTAssert(v.max == Version(string: "2.0.0")) XCTAssert(v.minInclusive == false) XCTAssert(v.maxInclusive == false) XCTAssert(v.description == ">1.0.1, <2.0.0") } func testCombineMultipleUpper() throws { let v = VersionRange(versionString: ">1.0.1") try v.combine("<=2.0.0") try v.combine("<1.9.0") try v.combine("<3.0.0") try v.combine("<=2.1.0") XCTAssert(v.min == Version(string: "1.0.1")) XCTAssert(v.max == Version(string: "1.9.0")) XCTAssert(v.minInclusive == false) XCTAssert(v.maxInclusive == false) XCTAssert(v.description == ">1.0.1, <1.9.0") } func testCombineMultipleLower() throws { let v = VersionRange(versionString: "<2.0.0") try v.combine(">=1.0.1") try v.combine(">1.5.0") try v.combine(">0.9.0") try v.combine(">=0.8.0") XCTAssert(v.min == Version(string: "1.5.0")) XCTAssert(v.max == Version(string: "2.0.0")) XCTAssert(v.minInclusive == false) XCTAssert(v.maxInclusive == false) XCTAssert(v.description == ">1.5.0, <2.0.0") } func testCombineEqual() throws { let v = VersionRange(versionString: "<2.0.0") try v.combine(">=1.0.1") try v.combine("==1.5.0") XCTAssert(v.min == Version(string: "1.5.0")) XCTAssert(v.max == Version(string: "1.5.0")) XCTAssert(v.minInclusive == true) XCTAssert(v.maxInclusive == true) XCTAssert(v.description == "==1.5.0") } // MARK: - Invalid combination tests func testCombineFailLower() throws { let v = VersionRange(versionString: "<2.0.0") try v.combine(">1.0.0") do { try v.combine("<1.0.0") XCTFail("Invalid combination should throw") } catch { // expected } } func testCombineFailUpper() throws { let v = VersionRange(versionString: "<2.0.0") try v.combine(">1.0.0") do { try v.combine(">2.0.0") XCTFail("Invalid combination should throw") } catch { // expected } } func testCombineFailLowerEqual() throws { let v = VersionRange(versionString: "<2.0.0") try v.combine(">=1.0.0") do { try v.combine("<1.0.0") XCTFail("Invalid combination should throw") } catch { // expected } } func testCombineFailUpperEqual() throws { let v = VersionRange(versionString: "<=2.0.0") try v.combine(">1.0.0") do { try v.combine(">2.0.0") XCTFail("Invalid combination should throw") } catch { // expected } } func testCombineFailEqualTooLow() throws { let v = VersionRange(versionString: "<2.0.0") try v.combine(">1.0.0") do { try v.combine("==0.9.0") XCTFail("Invalid combination should throw") } catch { // expected } } func testCombineFailEqualTooBig() throws { let v = VersionRange(versionString: "<2.0.0") try v.combine(">1.0.0") do { try v.combine("==2.1.0") XCTFail("Invalid combination should throw") } catch { // expected } } } extension VersionRangeTests { static var allTests : [(String, (VersionRangeTests) -> () throws -> Void)] { return [ ("testInitSimple", testInitSimple), ("testInitSmaller", testInitSmaller), ("testInitBigger", testInitBigger), ("testInitSmallerEqual", testInitSmallerEqual), ("testInitBiggerEqual", testInitBiggerEqual), ("testInitEqual", testInitEqual), ("testCombineWithLowerBound", testCombineWithLowerBound), ("testCombineWithUpperBound", testCombineWithUpperBound), ("testCombineMultipleUpper", testCombineMultipleUpper), ("testCombineMultipleLower", testCombineMultipleLower), ("testCombineEqual", testCombineEqual), ("testCombineFailLower", testCombineFailLower), ("testCombineFailUpper", testCombineFailUpper), ("testCombineFailLowerEqual", testCombineFailLowerEqual), ("testCombineFailUpperEqual", testCombineFailUpperEqual), ("testCombineFailEqualTooLow", testCombineFailEqualTooLow), ("testCombineFailEqualTooBig", testCombineFailEqualTooBig), ] } }
apache-2.0
04c097e57e73b7187409eca5c9ffa9c6
34.116071
80
0.575588
3.794018
false
true
false
false
Noobish1/KeyedMapper
KeyedMapper/Protocols/DefaultConvertible.swift
1
1307
import Foundation public protocol DefaultConvertible: Convertible {} extension DefaultConvertible { public static func fromMap(_ value: Any) throws -> ConvertedType { guard let object = value as? ConvertedType else { throw MapperError.convertible(value: value, expectedType: ConvertedType.self) } return object } } extension DefaultConvertible where ConvertedType: RawRepresentable { public static func fromMap(_ value: Any) throws -> ConvertedType { guard let rawValue = value as? ConvertedType.RawValue else { throw MapperError.convertible(value: value, expectedType: ConvertedType.RawValue.self) } guard let value = ConvertedType(rawValue: rawValue) else { throw MapperError.invalidRawValue(rawValue: rawValue, rawValueType: ConvertedType.self) } return value } } extension NSDictionary: DefaultConvertible { public typealias ConvertedType = NSDictionary } extension NSArray: DefaultConvertible { public typealias ConvertedType = NSArray } extension String: DefaultConvertible {} extension Int: DefaultConvertible {} extension UInt: DefaultConvertible {} extension Float: DefaultConvertible {} extension Double: DefaultConvertible {} extension Bool: DefaultConvertible {}
mit
65d1401cf765f503f7b479b539c4c2aa
30.878049
99
0.731446
5.356557
false
false
false
false
rymcol/Server-Side-Swift-Benchmarks-Summer-2017
PerfectPress/Sources/BlogPageHandler.swift
1
1707
// // BlogPageHandler.swift // PerfectPress // // Created by Ryan Collins on 6/9/16. // Copyright (C) 2016 Ryan M. Collins. // //===----------------------------------------------------------------------===// // // This source file is part of the PerfectPress open source blog project // //===----------------------------------------------------------------------===// // #if os(Linux) import Glibc #else import Darwin #endif let start1 = "<section id=\"content\"><div class=\"container\">" let start2 = "<div class=\"row blog-post\"><div class=\"col-xs-12\"><h1>Test Post " let start4 = "</h1><img src=\"/img/random/random-" let start5 = ".jpg\" alt=\"Random Image " let start6 = "\" class=\"alignleft feature-image img-responsive\" /><div class=\"content\">" let start7 = "</div>" let start8 = "</div></div</div></section>" struct BlogPageHandler { func loadPageContent() -> String { var finalContent = start1 let randomContent = ContentGenerator().generate() for _ in 1...5 { let index: Int = Int(arc4random_uniform(UInt32(randomContent.count))) let value = Array(randomContent.values)[index] let imageNumber = Int(arc4random_uniform(25) + 1) finalContent += start2 finalContent += "\(index)" finalContent += start4 finalContent += "\(imageNumber)" finalContent += start5 finalContent += "\(imageNumber)" finalContent += start6 finalContent += value finalContent += start7 } finalContent += start8 return finalContent } }
apache-2.0
3746f30c37dabbbfd47b6d1d7e9815fa
28.431034
92
0.518453
4.676712
false
false
false
false
IamAlchemist/DemoAnimations
Animations/DissolvedShowViewController.swift
2
4804
// // DissolvedShowViewController.swift // Animations // // Created by Wizard Li on 1/20/16. // Copyright © 2016 Alchemist. All rights reserved. // import UIKit extension UIView { func snapshot() -> UIImage { UIGraphicsBeginImageContextWithOptions(bounds.size, false, 0) layer.renderInContext(UIGraphicsGetCurrentContext()!) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return image } } class DissolvedShowAnimatedTrasition : NSObject, UIViewControllerAnimatedTransitioning { let duration : NSTimeInterval = 1 var animatingView = FilteredImageView(frame: CGRectZero) var displayLink : CADisplayLink! var startTime : NSTimeInterval = 0 var progress : Double = 0 var transitionContext : UIViewControllerContextTransitioning! override init() { super.init() setup() } func setup() { animatingView.backgroundColor = UIColor.whiteColor() displayLink = CADisplayLink(target: self, selector: #selector(DissolvedShowAnimatedTrasition.update(_:))) displayLink.addToRunLoop(NSRunLoop.mainRunLoop(), forMode: NSRunLoopCommonModes) displayLink.paused = true } func update(displayLink: CADisplayLink){ if startTime == 0 { startTime = displayLink.timestamp } progress = max(min((displayLink.timestamp - startTime) / duration, 1), Double(0)) animatingView.filter = dissolveFilter2DWithProgress(Float(progress)) if progress == 1 { finishInteractiveTransition() } } func finishInteractiveTransition() { displayLink.paused = true animatingView.removeFromSuperview() transitionContext.viewControllerForKey(UITransitionContextToViewControllerKey)?.view.alpha = 1 transitionContext.viewControllerForKey(UITransitionContextFromViewControllerKey)?.view.alpha = 1 transitionContext.completeTransition(true) } func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval { return duration } func animateTransition(transitionContext: UIViewControllerContextTransitioning) { self.transitionContext = transitionContext let toViewController = transitionContext.viewControllerForKey(UITransitionContextToViewControllerKey)! let fromViewController = transitionContext.viewControllerForKey(UITransitionContextFromViewControllerKey)! let toView = toViewController.view let fromView = fromViewController.view let containerView = transitionContext.containerView()! containerView.addSubview(toView) containerView.sendSubviewToBack(toView) let sourceImage = fromView.snapshot() let targeImage = toView.snapshot() animatingView.frame = containerView.bounds animatingView.inputImages = [sourceImage, targeImage] toView.alpha = 0 containerView.addSubview(animatingView) startTime = 0 displayLink.paused = false } } class DissolvedShowNavigationDelegate : NSObject, UINavigationControllerDelegate { func navigationController(navigationController: UINavigationController, animationControllerForOperation operation: UINavigationControllerOperation, fromViewController fromVC: UIViewController, toViewController toVC: UIViewController) -> UIViewControllerAnimatedTransitioning? { switch operation { case .Push: return DissolvedShowAnimatedTrasition() case .Pop: return nil case .None: return nil } } } class DissolvedShowViewController : UIViewController { @IBOutlet weak var dissolvedImageView: FilteredImageView! @IBAction func quit(sender: AnyObject) { navigationController?.dismissViewControllerAnimated(true, completion: nil) } var displayLink : CADisplayLink? var progress : Float = 0 override func viewDidLoad() { super.viewDidLoad() dissolvedImageView.contentMode = .ScaleAspectFit dissolvedImageView.inputImages = [UIImage(named: "john-paulson")!,UIImage(named: "john-paulson-2")!] displayLink = CADisplayLink(target: self, selector: #selector(DissolvedShowAnimatedTrasition.update(_:))) displayLink?.addToRunLoop(NSRunLoop.mainRunLoop(), forMode: NSRunLoopCommonModes) displayLink?.paused = true } func update(displayLink : CADisplayLink) { progress += 0.02 progress = progress > 1 ? 0 : progress; dissolvedImageView.filter = dissolveFilter2DWithProgress(progress) } }
mit
0819ee5afeb7c2df29df302898b2107b
34.058394
281
0.691651
6.03392
false
false
false
false
FKlemke/helloVapor
Sources/App/Models/Friend.swift
1
1189
import Foundation import Vapor struct Friend: Model { var exists: Bool = false var id: Node? let name: String let age: Int let email: String init(name: String, age: Int, email: String) { self.name = name self.age = age self.email = email } // NodeInitializable init(node: Node, in context: Context) throws { id = try node.extract("id") name = try node.extract("name") age = try node.extract("age") email = try node.extract("email") } // NodeRepresentable func makeNode(context: Context) throws -> Node { return try Node(node: ["id": id, "name": name, "age": age, "email": email]) } // Preparation static func prepare(_ database: Database) throws { try database.create("friends") { friends in friends.id() friends.string("name") friends.int("age") friends.string("email") } } static func revert(_ database: Database) throws { try database.delete("friends") } }
mit
ac1260cb8648a090e8d8f71aaca642b2
23.770833
54
0.512195
4.538168
false
false
false
false
svenbacia/SVBAudioKit
Sources/AudioRecorder.swift
1
4882
// // AudioRecorder.swift // SVBAudioKit // // Created by Sven Bacia on 02/09/15. // Copyright © 2015 Sven Bacia. All rights reserved. // import Foundation import AVFoundation public class AudioRecorder: NSObject { public private(set) var fileName: String public private(set) var directory: NSURL public var path: NSURL { return directory.URLByAppendingPathComponent(fileName).URLByAppendingPathExtension("caf") } public var delegate: AudioRecorderDelegate? // MARK: - private var recorder: AVAudioRecorder! // MARK: - public var recording: Bool { return recorder.recording } public var meteringEnabled: Bool { set { recorder.meteringEnabled = newValue } get { return recorder.meteringEnabled } } // MARK: - Init public init(fileName: String = AudioRecorder.defaultFileName, url: NSURL = AudioRecorder.defaultPath, settings: AudioRecorderSettings = defaultAudioRecorderSettings) throws { self.directory = url self.fileName = fileName super.init() recorder = try AVAudioRecorder(URL: path, settings: settings) recorder.delegate = self recorder.prepareToRecord() } deinit { deleteRecording() } // MARK: - Functions /// Starts or resumes recording. /// - returns `true` if successful, otherwise `false` public func record() -> Bool { return recorder.record() } /// Pauses a recording. /// Invoke the `record` method to resume recording. public func pause() { recorder.pause() } /// Stops recording and closes the audio file. public func stop() { recorder.stop() } /// Refreshes the average and peak power values for all channels of an audio recorder. /// - parameter channels: An array of integers that you want the peak and average power value for. /// - returns: An array of current peak and average power values for the specified channels. public func updateMetersForChannels(channels: [Int]) -> [(peakPower: Float, averagePower: Float)] { guard meteringEnabled else { return [] } recorder.updateMeters() let powers: [(peakPower: Float, averagePower: Float)] = channels.map { (recorder.peakPowerForChannel($0), recorder.averagePowerForChannel($0)) } return powers } /// Refreshes the peak powervalues for all channels of an audio recorder. /// - parameter channels: An array of integers that you want the peak power value for. /// - returns: An array of current peak and average power values for the specified channels. public func updatePeakPower(channels: [Int]) -> [Float] { guard meteringEnabled else { return [] } recorder.updateMeters() return channels.map { recorder.peakPowerForChannel($0) } } /// Refreshes the average power values for all channels of an audio recorder. /// - parameter channels: An array of integers that you want the peak and average power value for. /// - returns: An array of current peak and average power values for the specified channels. public func updateAveragePower(channels: [Int]) -> [Float] { guard meteringEnabled else { return [] } recorder.updateMeters() return channels.map { recorder.averagePowerForChannel($0) } } } // Save / Delete Function public extension AudioRecorder { /// Closes the audio file and moves the file to the new directory if needed. /// - parameter toURL: Moves the file to the `toURL`. func saveRecording(toURL: NSURL? = nil) throws { let destination = toURL ?? AudioRecorder.documentsDirectory.URLByAppendingPathComponent(fileName).URLByAppendingPathExtension("caf") do { try NSFileManager.defaultManager().moveItemAtURL(path, toURL: destination) } catch { print("Error moving file to destination url") } } /// Deletes a recorded audio file. /// - returns `true` if successful, otherwise `false` func deleteRecording() -> Bool { return recorder.deleteRecording() } } private extension AudioRecorder { static var defaultPath: NSURL { return NSURL(fileURLWithPath: NSTemporaryDirectory()) } static var defaultFileName: String { return AudioRecorder.stringFromDate(NSDate()) } static func stringFromDate(date: NSDate) -> String { let formatter = NSDateFormatter() formatter.dateFormat = "yyyyMMdd_HHmmss_recording" return formatter.stringFromDate(date) } static var documentsDirectory: NSURL { let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask) return urls.last! } } extension AudioRecorder: AVAudioRecorderDelegate { public func audioRecorderEncodeErrorDidOccur(recorder: AVAudioRecorder, error: NSError?) { delegate?.audioRecorderEncodeErrorDidOccur(self, error: error) } }
mit
ca9641f88e7787d41f154aef0e6ea5ed
27.213873
176
0.69371
4.813609
false
false
false
false
xilosada/TravisViewerIOS
TVViewModel/BuildTableViewCellModel.swift
1
795
// // BuildTableViewCellModel.swift // TravisViewerIOS // // Created by X.I. Losada on 10/02/16. // Copyright © 2016 XiLosada. All rights reserved. // import TVModel public final class BuildTableViewCellModel: BuildTableViewCellModeling { public let number: String public let branchText: String public let statusText: String public let result: Bool internal init(build: BuildEntity) { number = build.number branchText = "\(build.branch)" switch build.status { case .Errored: statusText = "Errored ❗" result = false case .Failed: statusText = "Failed ❌" result = false case .Passed: statusText = "Passed ✅" result = true } } }
mit
af1e4410b97a5048ab5289f8337d220d
23.65625
72
0.595178
4.282609
false
false
false
false
zhangao0086/DKImagePickerController
Sources/DKImagePickerController/DKImageAssetExporter.swift
1
26772
// // DKImageAssetExporter.swift // DKImagePickerController // // Created by ZhangAo on 15/11/2017. // Copyright © 2017 ZhangAo. All rights reserved. // import UIKit import Photos /// Purge disk on system UIApplicationWillTerminate notifications. public class DKImageAssetDiskPurger { static let sharedInstance = DKImageAssetDiskPurger() private var directories = Set<URL>() private init() { NotificationCenter.default.addObserver(self, selector: #selector(removeFiles), name: UIApplication.willTerminateNotification, object: nil) } deinit { NotificationCenter.default.removeObserver(self) } public func add(directory: URL) { objc_sync_enter(self) defer { objc_sync_exit(self) } self.directories.insert(directory) } public func clear() { self.removeFiles() } // MARK: - Private @objc private func removeFiles() { objc_sync_enter(self) defer { objc_sync_exit(self) } let manager = FileManager.default for directory in self.directories { try? manager.removeItem(at: directory) } } } ///////////////////////////////////////////////////////////////////////////// // The Error that describes the failure can be obtained from the error property of DKAsset. @objc public enum DKImageAssetExporterError: Int { case cancelled, exportFailed } @objc public enum DKImageExportPresent: Int { case compatible, // A preset for converting HEIF formatted images to JPEG. current // A preset for passing image data as-is to the client. } public typealias DKImageAssetExportRequestID = Int32 public let DKImageAssetExportInvalidRequestID: DKImageAssetExportRequestID = 0 public let DKImageAssetExporterDomain = "DKImageAssetExporterDomain" // Result's handler info dictionary keys public let DKImageAssetExportResultRequestIDKey = "DKImageExportResultRequestIDKey" // key (DKImageAssetExportRequestID) public let DKImageAssetExportResultCancelledKey = "DKImageExportCancelledKey" // key (Bool): result is not available because the request was cancelled @objc public protocol DKImageAssetExporterObserver { @objc optional func exporterWillBeginExporting(exporter: DKImageAssetExporter, asset: DKAsset) /// The progress can be obtained from the DKAsset. @objc optional func exporterDidUpdateProgress(exporter: DKImageAssetExporter, asset: DKAsset) /// When the asset's error is not nil, it indicates that an error occurred while exporting. @objc optional func exporterDidEndExporting(exporter: DKImageAssetExporter, asset: DKAsset) } /* Configuration options for a DKImageAssetExporter. When an exporter is created, a copy of the configuration object is made - you cannot modify the configuration of an exporter after it has been created. */ @objc public class DKImageAssetExporterConfiguration: NSObject, NSCopying { @objc public var imageExportPreset = DKImageExportPresent.compatible /// videoExportPreset can be used to specify the transcoding quality for videos (via a AVAssetExportPreset* string). @objc public var videoExportPreset = AVAssetExportPresetHighestQuality #if swift(>=4.0) @objc public var avOutputFileType = AVFileType.mov #else @objc public var avOutputFileType = AVFileTypeQuickTimeMovie #endif @objc public var exportDirectory = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent("DKImageAssetExporter") @objc public var compressionQuality = CGFloat(0.9) public required override init() { super.init() } public func copy(with zone: NSZone? = nil) -> Any { let copy = type(of: self).init() copy.imageExportPreset = self.imageExportPreset copy.videoExportPreset = self.videoExportPreset copy.avOutputFileType = self.avOutputFileType copy.exportDirectory = self.exportDirectory copy.compressionQuality = self.compressionQuality return copy } } /* A DKImageAssetExporter object exports DKAsset(PHAsset) from album (or iCloud) to the app's tmp directory(by default). It automatically deletes the exported directories when it receives a UIApplicationWillTerminate notification. */ @objc open class DKImageAssetExporter: DKImageBaseManager { @objc static public let sharedInstance = DKImageAssetExporter(configuration: DKImageAssetExporterConfiguration()) private let configuration: DKImageAssetExporterConfiguration private var exportQueue: OperationQueue = { let exportQueue = OperationQueue() exportQueue.name = "DKImageAssetExporter_ExportQueue" exportQueue.maxConcurrentOperationCount = 1 return exportQueue }() private let semaphore = DispatchSemaphore(value: 0) private var operations = [DKImageAssetExportRequestID : Operation]() private weak var currentAVExportSession: AVAssetExportSession? private var currentAssetInRequesting: DKAsset? @objc public init(configuration: DKImageAssetExporterConfiguration) { self.configuration = configuration.copy() as! DKImageAssetExporterConfiguration super.init() DKImageAssetDiskPurger.sharedInstance.add(directory: self.configuration.exportDirectory) } /// This method starts an asynchronous export operation of a batch of asset. @discardableResult @objc public func exportAssetsAsynchronously(assets: [DKAsset], completion: ((_ info: [AnyHashable : Any]) -> Void)?) -> DKImageAssetExportRequestID { guard assets.count > 0 else { completion?([ DKImageAssetExportResultRequestIDKey : DKImageAssetExportInvalidRequestID, DKImageAssetExportResultCancelledKey : false ]) return DKImageAssetExportInvalidRequestID } let requestID = self.getSeed() let operation = BlockOperation { guard let operation = self.operations[requestID] else { return } operation.completionBlock = nil var exportedCount = 0 let exportCompletionBlock: (DKAsset, Error?) -> Void = { asset, error in exportedCount += 1 defer { self.notify(with: #selector(DKImageAssetExporterObserver.exporterDidEndExporting(exporter:asset:)), object: self, objectTwo: asset) if exportedCount == assets.count { self.operations[requestID] = nil self.semaphore.signal() DispatchQueue.main.async { completion?([ DKImageAssetExportResultRequestIDKey : requestID, DKImageAssetExportResultCancelledKey : operation.isCancelled ]) } } } if let error = error as NSError? { asset.error = error asset.localTemporaryPath = nil } else { do { let attributes = try FileManager.default.attributesOfItem(atPath: asset.localTemporaryPath!.path) asset.fileSize = (attributes[FileAttributeKey.size] as! NSNumber).uintValue } catch let error as NSError { asset.error = error asset.localTemporaryPath = nil } } } for i in 0..<assets.count { let asset = assets[i] asset.progress = 0.0 self.notify(with: #selector(DKImageAssetExporterObserver.exporterWillBeginExporting(exporter:asset:)), object: self, objectTwo: asset) if operation.isCancelled { exportCompletionBlock(asset, self.makeCancelledError()) continue } asset.localTemporaryPath = self.generateTemporaryPath(with: asset) asset.error = nil if let localTemporaryPath = asset.localTemporaryPath, let subpaths = try? FileManager.default.contentsOfDirectory(at: localTemporaryPath, includingPropertiesForKeys: [], options: .skipsHiddenFiles), subpaths.count > 0 { asset.localTemporaryPath = subpaths[0] asset.fileName = subpaths[0].lastPathComponent exportCompletionBlock(asset, nil) continue } self.exportAsset(with: asset, requestID: requestID, progress: { progress in asset.progress = progress self.notify(with: #selector(DKImageAssetExporterObserver.exporterDidUpdateProgress(exporter:asset:)), object: self, objectTwo: asset) }, completion: { error in exportCompletionBlock(asset, error) }) } self.semaphore.wait() } operation.completionBlock = { [weak operation] in if let operation = operation { if operation.isCancelled { // Not yet executing. for asset in assets { asset.error = self.makeCancelledError() self.notify(with: #selector(DKImageAssetExporterObserver.exporterDidEndExporting(exporter:asset:)), object: self, objectTwo: asset) } DispatchQueue.main.async { completion?([ DKImageAssetExportResultRequestIDKey : requestID, DKImageAssetExportResultCancelledKey : true ]) } } else { self.operations[requestID] = nil } } } self.operations[requestID] = operation self.exportQueue.addOperation(operation) return requestID } @objc public func cancel(requestID: DKImageAssetExportRequestID) { if let operation = self.operations[requestID] { if operation.isExecuting { self.currentAVExportSession?.cancelExport() } operation.cancel() self.operations[requestID] = nil } } @objc public func cancelAll() { self.operations.removeAll() self.exportQueue.cancelAllOperations() self.currentAssetInRequesting?.cancelRequests() self.currentAVExportSession?.cancelExport() } // MARK: - RequestID static private var seed: DKImageAssetExportRequestID = 0 private func getSeed() -> DKImageAssetExportRequestID { objc_sync_enter(self) defer { objc_sync_exit(self) } DKImageAssetExporter.seed += 1 return DKImageAssetExporter.seed } // MARK: - Private private func makeCancelledError() -> Error { return NSError(domain: DKImageAssetExporterDomain, code: DKImageAssetExporterError.cancelled.rawValue, userInfo: [NSLocalizedDescriptionKey : "The operation was cancelled."]) } private func isHEIC(with imageData: Data) -> Bool { if imageData.count >= 12, let firstByte = imageData.first, firstByte == 0 { let subdata = imageData.subdata(in: 4..<12) let str = String(data: subdata, encoding: .ascii) return str == "ftypheic" || str == "ftypheix" || str == "ftyphevc" || str == "ftyphevx" } else { return false } } private func imageToJPEG(with imageData: Data) -> Data? { if #available(iOS 10.0, *), let ciImage = CIImage(data: imageData), let colorSpace = ciImage.colorSpace { return CIContext().jpegRepresentation( of: ciImage, colorSpace: colorSpace, options: [ CIImageRepresentationOption(rawValue: kCGImageDestinationLossyCompressionQuality as String) : configuration.compressionQuality ] ) } else if let image = UIImage(data: imageData) { return image.jpegData(compressionQuality: configuration.compressionQuality) } else { return nil } } private func generateAuxiliaryPath(with url: URL) -> (auxiliaryDirectory: URL, auxiliaryFilePath: URL) { let parentDirectory = url.deletingLastPathComponent() let auxiliaryDirectory = parentDirectory.appendingPathComponent(".tmp") let auxiliaryFilePath = auxiliaryDirectory.appendingPathComponent(url.lastPathComponent) return (auxiliaryDirectory, auxiliaryFilePath) } private func generateTemporaryPath(with asset: DKAsset) -> URL { let localIdentifier = asset.localIdentifier.data(using: .utf8)?.base64EncodedString() ?? "\(Date.timeIntervalSinceReferenceDate)" var directoryName = localIdentifier if let originalAsset = asset.originalAsset { if let modificationDate = originalAsset.modificationDate { directoryName = directoryName + "/" + String(modificationDate.timeIntervalSinceReferenceDate) } if asset.type == .photo { directoryName = directoryName + "/" + String(self.configuration.imageExportPreset.rawValue) } else { #if swift(>=4.0) directoryName = directoryName + "/" + self.configuration.videoExportPreset + self.configuration.avOutputFileType.rawValue #else directoryName = directoryName + "/" + self.configuration.videoExportPreset + self.configuration.avOutputFileType #endif } } let directory = self.configuration.exportDirectory.appendingPathComponent(directoryName) if !FileManager.default.fileExists(atPath: directory.path) { try? FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true, attributes: nil) } return directory } static let ioQueue = DispatchQueue(label: "DKPhotoImagePreviewVC.ioQueue") private func exportAsset(with asset: DKAsset, requestID: DKImageAssetExportRequestID, progress: @escaping (Double) -> Void, completion: @escaping (Error?) -> Void) { switch asset.type { case .photo: self.exportImage(with: asset, requestID: requestID, progress: progress, completion: completion) case .video: self.exportAVAsset(with: asset, requestID: requestID, progress: progress, completion: completion) } } private func exportImage(with asset: DKAsset, requestID: DKImageAssetExportRequestID, progress: @escaping (Double) -> Void, completion: @escaping (Error?) -> Void) { func write(data: Data, to url: URL) throws { let (auxiliaryDirectory, auxiliaryFilePath) = self.generateAuxiliaryPath(with: url) let fileManager = FileManager.default try fileManager.createDirectory(at: auxiliaryDirectory, withIntermediateDirectories: true, attributes: nil) try data.write(to: auxiliaryFilePath, options: [.atomic]) try fileManager.moveItem(at: auxiliaryFilePath, to: url) try fileManager.removeItem(at: auxiliaryDirectory) } if let originalAsset = asset.originalAsset { autoreleasepool { let options = PHImageRequestOptions() options.version = .current options.progressHandler = { (p, _, _, _) in progress(p) } let semaphore = DispatchSemaphore(value: 0) asset.fetchImageData(options: options, compressionQuality: configuration.compressionQuality) { (data, info) in self.currentAssetInRequesting = nil semaphore.signal() DKImageAssetExporter.ioQueue.async { if self.operations[requestID] == nil { return completion(self.makeCancelledError()) } if var imageData = data { if #available(iOS 9, *) { var resource: PHAssetResource? = nil for assetResource in PHAssetResource.assetResources(for: originalAsset) { if assetResource.type == .photo { resource = assetResource break } } if let resource = resource { asset.fileName = resource.originalFilename } } if asset.fileName == nil { if let info = info, let fileURL = info["PHImageFileURLKey"] as? NSURL { asset.fileName = fileURL.lastPathComponent ?? "Image" } else { asset.fileName = "Image.jpg" } } if self.configuration.imageExportPreset == .compatible && self.isHEIC(with: imageData) { if let fileName = asset.fileName, let jpgData = self.imageToJPEG(with: imageData) { imageData = jpgData if fileName.uppercased().hasSuffix(".HEIC") { asset.fileName = fileName.dropLast(4) + "jpg" } } } asset.localTemporaryPath = asset.localTemporaryPath?.appendingPathComponent(asset.fileName!) if FileManager.default.fileExists(atPath: asset.localTemporaryPath!.path) { return completion(nil) } do { try write(data: imageData, to: asset.localTemporaryPath!) completion(nil) } catch { completion(error) } } else { if let info = info, let isCancelled = info[PHImageCancelledKey] as? NSNumber, isCancelled.boolValue { completion(self.makeCancelledError()) } else { completion(NSError(domain: DKImageAssetExporterDomain, code: DKImageAssetExporterError.exportFailed.rawValue, userInfo: [NSLocalizedDescriptionKey : "Failed to fetch image data."])) } } } } self.currentAssetInRequesting = asset semaphore.wait() } } else { let quality = configuration.compressionQuality DKImageAssetExporter.ioQueue.async { if self.operations[requestID] == nil { return completion(self.makeCancelledError()) } do { try write(data: asset.image!.jpegData(compressionQuality: quality)!, to: asset.localTemporaryPath!) completion(nil) } catch { completion(error) } } } } private func exportAVAsset(with asset: DKAsset, requestID: DKImageAssetExportRequestID, progress: @escaping (Double) -> Void, completion: @escaping (Error?) -> Void) { var isNotInLocal = false let options = PHVideoRequestOptions() options.deliveryMode = .mediumQualityFormat options.progressHandler = { (p, _, _, _) in isNotInLocal = true progress(p * 0.85) } let semaphore = DispatchSemaphore(value: 0) asset.fetchAVAsset(options: options) { (avAsset, info) in self.currentAssetInRequesting = nil #if swift(>=4.0) let mediaTypeVideo = AVMediaType.video #else let mediaTypeVideo = AVMediaTypeVideo #endif if let avAsset = avAsset { if let avURLAsset = avAsset as? AVURLAsset { asset.fileName = avURLAsset.url.lastPathComponent } else if let composition = avAsset as? AVComposition, let sourceURL = composition.tracks(withMediaType: mediaTypeVideo).first?.segments.first?.sourceURL { asset.fileName = sourceURL.lastPathComponent } else { asset.fileName = "Video.mov" } asset.localTemporaryPath = asset.localTemporaryPath?.appendingPathComponent(asset.fileName!) semaphore.signal() DKImageAssetExporter.ioQueue.async { if self.operations[requestID] == nil { return completion(self.makeCancelledError()) } let group = DispatchGroup() group.enter() if avAsset.isExportable, let exportSession = AVAssetExportSession(asset: avAsset, presetName: self.configuration.videoExportPreset) { let (auxiliaryDirectory, auxiliaryFilePath) = self.generateAuxiliaryPath(with: asset.localTemporaryPath!) let fileManager = FileManager.default if fileManager.fileExists(atPath: auxiliaryFilePath.path) { try? fileManager.removeItem(at: auxiliaryFilePath) } try? fileManager.createDirectory(at: auxiliaryDirectory, withIntermediateDirectories: true, attributes: nil) exportSession.outputFileType = self.configuration.avOutputFileType exportSession.outputURL = auxiliaryFilePath exportSession.shouldOptimizeForNetworkUse = true exportSession.directoryForTemporaryFiles = auxiliaryDirectory exportSession.exportAsynchronously(completionHandler: { defer { try? fileManager.removeItem(at: auxiliaryDirectory) } group.leave() switch (exportSession.status) { case .completed: try! fileManager.moveItem(at: auxiliaryFilePath, to: asset.localTemporaryPath!) completion(nil) case .cancelled: completion(self.makeCancelledError()) case .failed: completion(exportSession.error) default: assert(false) } }) self.currentAVExportSession = exportSession self.waitForExportToFinish(exportSession: exportSession, group: group) { p in progress(isNotInLocal ? min(0.85 + p * 0.15, 1.0) : p) } } else { if let info = info, let isCancelled = info[PHImageCancelledKey] as? NSNumber, isCancelled.boolValue { completion(self.makeCancelledError()) } else { completion(NSError(domain: DKImageAssetExporterDomain, code: DKImageAssetExporterError.exportFailed.rawValue, userInfo: [NSLocalizedDescriptionKey : "Can't setup AVAssetExportSession."])) } } } } else { completion(NSError(domain: DKImageAssetExporterDomain, code: DKImageAssetExporterError.exportFailed.rawValue, userInfo: [NSLocalizedDescriptionKey : "Failed to fetch AVAsset."])) } } self.currentAssetInRequesting = asset semaphore.wait() } private func waitForExportToFinish(exportSession: AVAssetExportSession, group: DispatchGroup, progress: (Double) -> Void) { while exportSession.status == .waiting || exportSession.status == .exporting { let _ = group.wait(timeout: .now() + .milliseconds(500)) if exportSession.status == .exporting { progress(Double(exportSession.progress)) } } } }
mit
9dd7fd857b2c8cf90e23bc239f422c2f
42.815057
171
0.540361
6.13873
false
false
false
false
wl879/SwiftyCss
SwiftyCss/SwiftyCss/MediaRule.swift
1
4340
// Created by Wang Liang on 2017/4/8. // Copyright © 2017年 Wang Liang. All rights reserved. #if os(watchOS) import WatchKit #elseif os(iOS) || os(tvOS) import UIKit #endif import CoreGraphics import SwiftyNode import SwiftyBox extension Css { public static func MediaRule(_ param: String, _ context:inout AtRuleContext ) -> Bool { let parmas = param.components(separatedBy: ":", trim: .whitespacesAndNewlines) let name = parmas[0].lowercased() let value = parmas.count > 1 ? parmas[1] : "" switch name { case "orientation": var size: CGSize = .zero #if os(watchOS) size = WKInterfaceDevice.currentDevice().screenBounds.size #elseif os(iOS) || os(tvOS) size = UIScreen.main.bounds.size #else return false #endif switch value { case "landscape": return size.width > size.height case "portrait": return size.width <= size.height default: return false } case "min-width", "max-width", "width", "min-height", "max-height", "height": guard value.isEmpty == false else { return false } guard let val = CGFloat(value) else { return false } var size: CGSize = .zero #if os(watchOS) size = WKInterfaceDevice.currentDevice().screenBounds.size #elseif os(iOS) || os(tvOS) size = UIScreen.main.bounds.size #else return false #endif switch name { case "min-width": return size.width >= val case "max-width": return size.width <= val case "width": return size.width == val case "min-height": return size.height >= val case "max-height": return size.height <= val case "height": return size.height == val default: return false } default: #if os(watchOS) let size = WKInterfaceDevice.currentDevice().screenBounds.size switch name { case "watchos": return true case "watch-48": return min(size.width, size.height)/max(size.width, size.height) == 136/170 case "watch-42": return min(size.width, size.height)/max(size.width, size.height) == 156/195 default: break } #elseif os(iOS) || os(tvOS) switch name { case "tvos": return UIDevice.current.userInterfaceIdiom == .tv case "ios": return UIDevice.current.userInterfaceIdiom == .phone || UIDevice.current.userInterfaceIdiom == .pad case "iphone": return UIDevice.current.userInterfaceIdiom == .phone case "ipad": return UIDevice.current.userInterfaceIdiom == .pad case "iphone4", "iphone5", "iphone6", "iphone6plus", "ipadmin", "ipadpro": let width = UIScreen.main.bounds.width let height = UIScreen.main.bounds.height let size = min(width, height)/max(width, height) switch name { case "iphone4": return size == 320 / 480 case "iphone5": return size == 320 / 568 case "iphone6": return size == 375 / 667 case "iphone6plus": return size == 414 / 736 case "ipadpro": return size == 2732/2048 default: return false } default: break } #endif break } return false } }
mit
9533f0245092c01586bc140f0b2f99f2
33.696
119
0.454462
5.341133
false
false
false
false
inderdhir/Gifmaster-ios
GifMaster/CustomRequestAdapter.swift
1
799
// // CustomRequestRetrier.swift // GifMaster // // Created by Inder Dhir on 8/27/17. // Copyright © 2017 Inder Dhir. All rights reserved. // import Alamofire class CustomRequestAdapter: RequestRetrier { private let maxRetries = 2 private var retryCount = 0 // MARK: - RequestRetrier func should(_ manager: SessionManager, retry request: Request, with error: Error, completion: @escaping RequestRetryCompletion) { if let response = request.task?.response as? HTTPURLResponse, response.statusCode >= 400, retryCount < maxRetries { print("retrying network request") retryCount += 1 completion(true, 1.0) } else { retryCount = 0 completion(false, 0.0) } } }
mit
250251de07494829ba0f293e0cd44cf6
23.9375
97
0.616541
4.586207
false
false
false
false
lgp123456/tiantianTV
douyuTV/douyuTV/douyuTV.swift
1
503
// // douyuTV.swift // douyuTV // // Created by 李贵鹏 on 16/8/24. // Copyright © 2016年 李贵鹏. All rights reserved. // import UIKit ///屏幕宽度 let XTScreenW = UIScreen.mainScreen().bounds.width ///屏幕高度 let XTScreenH = UIScreen.mainScreen().bounds.height ///顶部预留的间距 let XTTopSpace = XTScreenW / 414 * 240 ///标题(顶部view)栏高度 let XTTopViewH = XTScreenW / 414 * 35 ///间距 let XTMagin = 10 ///基本的url let baseUrl = "http://capi.douyucdn.cn"
mit
fb293896f83fbfec6e096913b264d739
15.730769
51
0.679724
2.679012
false
false
false
false
moysklad/ios-remap-sdk
Sources/MoyskladiOSRemapSDK/Structs/BaseDocumentProtocols.swift
1
4864
// // BaseDocumentProtocols.swift // MoyskladiOSRemapSDK // // Created by Anton Efimenko on 24.08.17. // Copyright © 2017 Andrey Parshakov. All rights reserved. // import Foundation public protocol MSBaseDocumentType : class, Metable, MSRequestEntity, NSCopying { var id : MSID { get } var meta : MSMeta { get } var info : MSInfo { get set } var agent : MSEntity<MSAgent>? { get set } var contract : MSEntity<MSContract>? { get set } var sum : Money { get set } var vatSum : Money { get set } var payedSum: Money { get set} var rate : MSRate? { get set } var moment : Date { get set } var project : MSEntity<MSProject>? { get set } var organization : MSEntity<MSAgent>? { get set } var owner : MSEntity<MSEmployee>? { get set } var group : MSEntity<MSGroup> { get set } var shared : Bool { get set } var applicable : Bool { get set } var state : MSEntity<MSState>? { get set } var attributes : [MSEntity<MSAttribute>]? { get set } var originalApplicable: Bool { get } var stateContractId: String? { get set } func copyDocument() -> MSDocument func dictionary(metaOnly: Bool) -> [String: Any] func templateBody(forDocument type: MSObjectType) -> [String: Any]? var documentType: MSDocumentType? { get } } public extension MSBaseDocumentType { var documentType: MSDocumentType? { return MSDocumentType(rawValue: meta.type.rawValue) } func requestUrl() -> MSApiRequest? { return MSDocumentType.fromMSObjectType(meta.type)?.apiRequest } func deserializationError() -> MSError { return MSDocumentType.fromMSObjectType(meta.type)?.requestError ?? MSError.genericError(errorText: LocalizedStrings.genericDeserializationError.value) } func pathComponents() -> [String] { return [] } func templateBody(forDocument type: MSObjectType) -> [String: Any]? { guard let newDocType = MSDocumentType.fromMSObjectType(type) else { return nil } // если будет создаваться платежный документ, то для него связанные документы нужно класть в operations switch newDocType { case .cashin, .cashout, .paymentin, .paymentout: return ["operations": [dictionary(metaOnly: true)]] case .customerorder, .demand, .invoiceout, .operation, .supply, .invoicein, .purchaseorder, .move, .inventory, .purchasereturn, .salesreturn: break case .retaildemand, .retailsalesreturn, .retaildrawercashout, .retaildrawercashin: break } guard let currentDocType = self.documentType else { return nil } switch currentDocType { case .customerorder: return type == .purchaseorder ? ["customerOrders": [dictionary(metaOnly: true)]] : ["customerOrder": dictionary(metaOnly: true)] case .demand: return ["demands": [dictionary(metaOnly: true)]] case .invoiceout: return ["invoicesOut": [dictionary(metaOnly: true)]] case .purchaseorder: return ["purchaseOrder": dictionary(metaOnly: true)] case .invoicein: return type == .supply ? ["invoicesIn": [dictionary(metaOnly: true)]] : ["invoiceIn": dictionary(metaOnly: true)] case .supply: return ["supplies": [dictionary(metaOnly: true)]] case .paymentin, .paymentout, .cashin, .cashout, .operation, .move, .inventory: return nil case .retaildemand, .retailsalesreturn, .retaildrawercashout, .purchasereturn, .retaildrawercashin, .salesreturn: return nil } } } /** Represents generalized document (CustomerOrder, Demand or OnvoiceOut). For more information see API reference for [ customer order](https://online.moysklad.ru/api/remap/1.1/doc/index.html#документ-заказ-покупателя), [ demand](https://online.moysklad.ru/api/remap/1.1/doc/index.html#документ-отгрузка) and [ invoice out](https://online.moysklad.ru/api/remap/1.1/doc/index.html#документ-счёт-покупателю) */ public protocol MSGeneralDocument: MSBaseDocumentType { var agentAccount : MSEntity<MSAccount>? { get set } var organizationAccount : MSEntity<MSAccount>? { get set } var vatIncluded : Bool { get set } var vatEnabled : Bool { get set } var store : MSEntity<MSStore>? { get set } var originalStoreId: UUID? { get } var positions : [MSEntity<MSPosition>] { get set } /// Через expand в поле positions можно загрузить максимум 100 объектов, /// данное значение показывает реальное количество позиций в документе var totalPositionsCount: Int { get set } var stock : [MSEntity<MSDocumentStock>] { get set } var positionsManager: ObjectManager<MSPosition>? { get set } }
mit
9cf2471aaa779b0917740d22a4d500e4
47.705263
331
0.687486
3.7016
false
false
false
false
moysklad/ios-remap-sdk
Sources/MoyskladiOSRemapSDK/Money/Shared/Decimal/DecimalNumberType.swift
1
16520
// // DecimalNumberType.swift // Money // // The MIT License (MIT) // // Copyright (c) 2015 Daniel Thorpe // // 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 /** # DecimalNumberBehaviorType Defines the decimal number behavior, i.e. `NSDecimalNumberBehaviors` of the type. */ public protocol DecimalNumberBehaviorType { /// Specify the decimal number (i.e. rounding, scale etc) for base 10 calculations static var decimalNumberBehaviors: NSDecimalNumberBehaviors { get } } /** # DecimalNumberBehavior This is a name space of types which conform to `DecimalNumberBehaviorType` with common rounding modes. All have maximum precision, of 38 significant digits. */ public struct DecimalNumberBehavior { /// Plain rounding mode public struct Plain: DecimalNumberBehaviorType { public static let decimalNumberBehaviors = DecimalNumberBehavior.behaviorWithRoundingMode(mode: .plain) } /// Round down mode public struct RoundDown: DecimalNumberBehaviorType { public static let decimalNumberBehaviors = DecimalNumberBehavior.behaviorWithRoundingMode(mode: .down) } /// Round up mode public struct RoundUp: DecimalNumberBehaviorType { public static let decimalNumberBehaviors = DecimalNumberBehavior.behaviorWithRoundingMode(mode: .up) } /// Bankers rounding mode, see `NSRoundingMode.RoundBankers` for info. public struct Bankers: DecimalNumberBehaviorType { public static let decimalNumberBehaviors = DecimalNumberBehavior.behaviorWithRoundingMode(mode: .bankers) } private static func behaviorWithRoundingMode(mode: NSDecimalNumber.RoundingMode, scale: Int16 = 38) -> NSDecimalNumberBehaviors { return NSDecimalNumberHandler(roundingMode: mode, scale: 38, raiseOnExactness: false, raiseOnOverflow: true, raiseOnUnderflow: true, raiseOnDivideByZero: true) } } /** # DecimalNumberType A protocol which defines the necessary interface to support decimal number calculations and operators. */ public protocol DecimalNumberType: Hashable, SignedNumeric, ExpressibleByFloatLiteral, CustomStringConvertible { associatedtype DecimalStorageType associatedtype DecimalNumberBehavior: DecimalNumberBehaviorType /// Access the underlying storage var storage: DecimalStorageType { get } /// Flag to indicate if the decimal number is less than zero var isNegative: Bool { get } /** Negates the receiver, equivalent to multiplying it by -1 - returns: another instance of this type. */ var negative: Self { get } /// Access an integer value representation var intValue: Swift.IntegerLiteralType { get } /// Access a float value representation var floatValue: FloatLiteralType { get } /** Initialize a new `DecimalNumberType` with the underlying storage. This is necessary in order to convert between different decimal number types. - parameter storage: the underlying decimal storage type e.g. NSDecimalNumber or NSDecimal */ init(storage: DecimalStorageType) /** Subtract a matching `DecimalNumberType` from the receiver. - parameter other: another instance of this type. - returns: another instance of this type. */ func subtract(_: Self) -> Self /** Add a matching `DecimalNumberType` to the receiver. - parameter other: another instance of this type. - returns: another instance of this type. */ func add(_: Self) -> Self /** Multiply the receive by 10^n - parameter n: an `Int` for the 10 power index - returns: another instance of this type. */ func multiply(byPowerOf10: Int) -> Self /** Multiply a matching `DecimalNumberType` with the receiver. - parameter other: another instance of this type. - returns: another instance of this type. */ func multiply(by: Self) -> Self /** Multiply another `DecimalNumberType` with the receiver. The other `DecimalNumberType` must have the same underlying `DecimalStorageType` as this `DecimalNumberType`. - parameter other: another `DecimalNumberType` value of different type. - returns: a different `DecimalNumberType` value. */ func multiply<Other: DecimalNumberType>(by: Other) -> Other where Other.DecimalStorageType == DecimalStorageType /** Divide the receiver by a matching `DecimalNumberType`. - parameter other: another instance of this type. - returns: another instance of this type. */ func divide(by: Self) -> Self /** Divide the receiver by another `DecimalNumberType`. The other `DecimalNumberType` must have the same underlying `DecimalStorageType` as this `DecimalNumberType`. - parameter other: another `DecimalNumberType` value of different type. - returns: another instance of this type. */ func divide<Other: DecimalNumberType>(by: Other) -> Other where Other.DecimalStorageType == DecimalStorageType /** The remainder of dividing another `DecimalNumberType` into the receiver. - parameter other: another instance of this type. - returns: another instance of this type. */ func remainder(of: Self) -> Self } // MARK: - Extensions /** Extensions on `DecimalNumberType` where the underlying storage type is `NSDecimalNumber`. */ public extension DecimalNumberType where DecimalStorageType == NSDecimalNumber { /// Flag to indicate if the decimal number is less than zero var isNegative: Bool { return storage.isNegative } /// The negative of Self. /// - returns: a `_Decimal<Behavior>` var negative: Self { return Self(storage: storage.negate(withBehaviors: DecimalNumberBehavior.decimalNumberBehaviors)) } /// Access an integer value representation var intValue: Int { return storage.intValue } /// Access a float value representation var floatValue: Double { return storage.doubleValue } /// Text description. var description: String { return "\(storage.description)" } func hash(into hasher: inout Hasher) { hasher.combine(storage.hashValue) } /// Initialize a new decimal with an `Int`. /// - parameter value: an `Int`. /// - returns: an initialized `DecimalNumberType`. init(_ value: Int) { switch value { case 0: self.init(storage: NSDecimalNumber.zero) case 1: self.init(storage: NSDecimalNumber.one) default: self.init(storage: NSDecimalNumber(integerLiteral: value).rounding(accordingToBehavior: DecimalNumberBehavior.decimalNumberBehaviors)) } } /// Initialize a new decimal with an `UInt8`. /// - parameter value: an `UInt8`. /// - returns: an initialized `DecimalNumberType`. init(_ value: UInt8) { self.init(Int(value)) } /// Initialize a new decimal with an `Int8`. /// - parameter value: an `Int8`. /// - returns: an initialized `DecimalNumberType`. init(_ value: Int8) { self.init(Int(value)) } /// Initialize a new decimal with an `UInt16`. /// - parameter value: an `UInt16`. /// - returns: an initialized `DecimalNumberType`. init(_ value: UInt16) { self.init(Int(value)) } /// Initialize a new decimal with an `Int16`. /// - parameter value: an `Int16`. /// - returns: an initialized `DecimalNumberType`. init(_ value: Int16) { self.init(Int(value)) } /// Initialize a new decimal with an `UInt32`. /// - parameter value: an `UInt32`. /// - returns: an initialized `DecimalNumberType`. init(_ value: UInt32) { self.init(Int(value)) } /// Initialize a new decimal with an `Int32`. /// - parameter value: an `Int32`. /// - returns: an initialized `DecimalNumberType`. init(_ value: Int32) { self.init(Int(value)) } /// Initialize a new decimal with an `UInt64`. /// - parameter value: an `UInt64`. /// - returns: an initialized `DecimalNumberType`. init(_ value: UInt64) { self.init(Int(value)) } /// Initialize a new decimal with an `Int64`. /// - parameter value: an `Int64`. /// - returns: an initialized `DecimalNumberType`. init(_ value: Int64) { self.init(Int(value)) } /** Initialize a new value using a `IntegerLiteralType` - parameter integerLiteral: a `IntegerLiteralType` for the system, probably `Int`. */ init(integerLiteral value: Swift.IntegerLiteralType) { self.init(value) } /// Initialize a new decimal with an `Double`. /// - parameter value: an `Double`. /// - returns: an initialized `DecimalNumberType`. init(_ value: Double) { self.init(storage: NSDecimalNumber(floatLiteral: value).rounding(accordingToBehavior: DecimalNumberBehavior.decimalNumberBehaviors)) } /// Initialize a new decimal with a `Float`. /// - parameter value: an `Float`. /// - returns: an initialized `DecimalNumberType`. init(_ value: Float) { self.init(Double(value)) } /** Initialize a new value using a `FloatLiteralType` - parameter floatLiteral: a `FloatLiteralType` for the system, probably `Double`. */ init(floatLiteral value: Swift.FloatLiteralType) { self.init(value) } /** Subtract a matching `DecimalNumberType` from the receiver. - parameter other: another instance of this type. - returns: another instance of this type. */ func subtract(_ other: Self) -> Self { return Self(storage: storage.subtract(other.storage, withBehaviors: DecimalNumberBehavior.decimalNumberBehaviors)) } /** Add a matching `DecimalNumberType` from the receiver. - parameter other: another instance of this type. - returns: another instance of this type. */ func add(_ other: Self) -> Self { return Self(storage: storage.add(other.storage, withBehaviors: DecimalNumberBehavior.decimalNumberBehaviors)) } /** Multiply the receive by 10^n - parameter n: an `Int` for the 10 power index - returns: another instance of this type. */ func multiply(byPowerOf10 index: Int) -> Self { return Self(storage: storage.multiply(byPowerOf10: index, withBehaviors: DecimalNumberBehavior.decimalNumberBehaviors)) } /** Multiply a matching `DecimalNumberType` with the receiver. - parameter other: another instance of this type. - returns: another instance of this type. */ func multiply(by other: Self) -> Self { return Self(storage: storage.multiply(by: other.storage, withBehaviors: DecimalNumberBehavior.decimalNumberBehaviors)) } /** Multiply a different `DecimalNumberType` which also has `NSDecimalNumber` as the storage type with the receiver. - parameter other: another `DecimalNumberType` with `NSDecimalNumber` storage. - returns: another instance of this type. */ func multiply<Other: DecimalNumberType>(by other: Other) -> Other where Other.DecimalStorageType == NSDecimalNumber { return Other(storage: storage.multiply(by: other.storage, withBehaviors: Other.DecimalNumberBehavior.decimalNumberBehaviors) ) } /** Divide the receiver by another instance of this type. - parameter other: another instance of this type. - returns: another instance of this type. */ func divide(by other: Self) -> Self { return Self(storage: storage.divide(by: other.storage, withBehaviors: DecimalNumberBehavior.decimalNumberBehaviors)) } /** Divide the receiver by a different `DecimalNumberType` which also has `NSDecimalNumber` as the storage type. - parameter other: another `DecimalNumberType` with `NSDecimalNumber` storage. - returns: another instance of this type. */ func divide<Other: DecimalNumberType>(by other: Other) -> Other where Other.DecimalStorageType == NSDecimalNumber { return Other(storage: storage.divide(by: other.storage, withBehaviors: Other.DecimalNumberBehavior.decimalNumberBehaviors)) } /** The remainder of dividing another instance of this type into the receiver. - parameter other: another instance of this type. - returns: another instance of this type. */ func remainder(of other: Self) -> Self { return Self(storage: storage.remainder(other: other.storage, withBehaviors: DecimalNumberBehavior.decimalNumberBehaviors)) } } extension DecimalNumberType where Self.IntegerLiteralType == Int { /// Get the reciprocal of the receiver. public var reciprocal: Self { return Self(integerLiteral: 1).divide(by: self) } } // MARK: - Operators // MARK: - Subtraction public func -<T: DecimalNumberType>(lhs: T, rhs: T) -> T { return lhs.subtract(rhs) } public func -<T: DecimalNumberType>(lhs: T, rhs: T.IntegerLiteralType) -> T { return lhs - T(integerLiteral: rhs) } public func -<T: DecimalNumberType>(lhs: T.IntegerLiteralType, rhs: T) -> T { return T(integerLiteral: lhs) - rhs } public func -<T: DecimalNumberType>(lhs: T, rhs: T.FloatLiteralType) -> T { return lhs - T(floatLiteral: rhs) } public func -<T: DecimalNumberType>(lhs: T.FloatLiteralType, rhs: T) -> T { return T(floatLiteral: lhs) - rhs } // MARK: - Addition public func +<T: DecimalNumberType>(lhs: T, rhs: T) -> T { return lhs.add(rhs) } public func +<T: DecimalNumberType>(lhs: T, rhs: T.IntegerLiteralType) -> T { return lhs + T(integerLiteral: rhs) } public func +<T: DecimalNumberType>(lhs: T.IntegerLiteralType, rhs: T) -> T { return T(integerLiteral: lhs) + rhs } public func +<T: DecimalNumberType>(lhs: T, rhs: T.FloatLiteralType) -> T { return lhs + T(floatLiteral: rhs) } public func +<T: DecimalNumberType>(lhs: T.FloatLiteralType, rhs: T) -> T { return T(floatLiteral: lhs) + rhs } // MARK: - Multiplication public func *<T: DecimalNumberType>(lhs: T, rhs: T) -> T { return lhs.multiply(by: rhs) } public func *<T: DecimalNumberType>(lhs: T, rhs: T.IntegerLiteralType) -> T { return lhs * T(integerLiteral: rhs) } public func *<T: DecimalNumberType>(lhs: T, rhs: T.FloatLiteralType) -> T { return lhs * T(floatLiteral: rhs) } public func *<T: DecimalNumberType>(lhs: T.IntegerLiteralType, rhs: T) -> T { return rhs * lhs } public func *<T: DecimalNumberType>(lhs: T.FloatLiteralType, rhs: T) -> T { return rhs * lhs } public func *<T, V>(lhs: T, rhs: V) -> V where T: DecimalNumberType, V: DecimalNumberType, T.DecimalStorageType == V.DecimalStorageType { return lhs.multiply(by: rhs) } // MARK: - Division public func /<T: DecimalNumberType>(lhs: T, rhs: T) -> T { return lhs.divide(by: rhs) } public func /<T: DecimalNumberType>(lhs: T, rhs: T.IntegerLiteralType) -> T { return lhs / T(integerLiteral: rhs) } public func /<T: DecimalNumberType>(lhs: T, rhs: T.FloatLiteralType) -> T { return lhs / T(floatLiteral: rhs) } public func /<T, V>(lhs: T, rhs: V) -> V where T: DecimalNumberType, V: DecimalNumberType, T.DecimalStorageType == V.DecimalStorageType { return lhs.divide(by: rhs) } // MARK: - Remainder public func %<T: DecimalNumberType>(lhs: T, rhs: T) -> T { return lhs.remainder(of: rhs) }
mit
3ef5d5976a774aa45633443ce0666618
30.769231
167
0.679782
4.417112
false
false
false
false
cozkurt/coframework
COFramework/COFramework/Swift/Extentions/UIDevice+Additions.swift
1
2577
// // UIDevice+Additions.swift // FuzFuz // // Created by Cenker Ozkurt on 10/07/19. // Copyright © 2019 Cenker Ozkurt, Inc. All rights reserved. // import UIKit extension UIDevice { public static var isSimulator: Bool { return ProcessInfo.processInfo.environment["SIMULATOR_DEVICE_NAME"] != nil } public var iPhone: Bool { return UIDevice().userInterfaceIdiom == .phone } public enum ScreenType: String { case i35 case i4 case i47 case i55 case ix // no home button case iPadx // no home button case Unknown } public var bounds: CGRect { return UIScreen.main.bounds } public var screenType: ScreenType? { switch UIScreen.main.nativeBounds.height { case 480, 960: return .i35 case 1136: return .i4 case 1334: return .i47 case 1920: return .i55 case 2360, 2388, 2732: return .iPadx case 1792, 2436, 2532, 2688, 2778: return .ix default: return nil } } public func isScreen35or4inch() -> Bool { return isScreen35inch() || isScreen4inch() } public func isScreen35inch() -> Bool { return UIDevice().screenType == .i35 } public func isScreen4inch() -> Bool { return UIDevice().screenType == .i4 } public func isScreen47inch() -> Bool { return UIDevice().screenType == .i47 } public func isScreen55inch() -> Bool { return UIDevice().screenType == .i55 } public func isIPhoneX() -> Bool { return UIDevice().screenType == .ix } public func isIPad() -> Bool { return UIDevice.current.userInterfaceIdiom == .pad } public func isIPadx() -> Bool { return UIDevice().screenType == .iPadx } public func isIPhone() -> Bool { return UIDevice.current.userInterfaceIdiom == .phone } public func preferredStyle() -> UIAlertController.Style { return UIDevice().isIPad() ? .alert : .actionSheet } public func isMac() -> Bool { #if targetEnvironment(macCatalyst) return true #else return false #endif } public func deviceInfo() -> String { if self.isMac() { return "Mac" } else if self.isIPhone() { return "iPhone" } else if self.isIPad() { return "iPad" } return UIDevice().model } }
gpl-3.0
ad0c28be82ffb8f2bac84b7681b2f8c9
21.79646
82
0.553183
4.456747
false
false
false
false
eoger/firefox-ios
Client/Application/WebServer.swift
2
3903
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import GCDWebServers import Shared class WebServer { private let log = Logger.browserLogger static let WebServerSharedInstance = WebServer() class var sharedInstance: WebServer { return WebServerSharedInstance } let server: GCDWebServer = GCDWebServer() var base: String { return "http://localhost:\(server.port)" } /// The private credentials for accessing resources on this Web server. let credentials: URLCredential /// A random, transient token used for authenticating requests. /// Other apps are able to make requests to our local Web server, /// so this prevents them from accessing any resources. fileprivate let sessionToken = UUID().uuidString init() { credentials = URLCredential(user: sessionToken, password: "", persistence: .forSession) } @discardableResult func start() throws -> Bool { if !server.isRunning { try server.start(options: [ GCDWebServerOption_Port: 6571, GCDWebServerOption_BindToLocalhost: true, GCDWebServerOption_AutomaticallySuspendInBackground: true, GCDWebServerOption_AuthenticationMethod: GCDWebServerAuthenticationMethod_Basic, GCDWebServerOption_AuthenticationAccounts: [sessionToken: ""] ]) } return server.isRunning } /// Convenience method to register a dynamic handler. Will be mounted at $base/$module/$resource func registerHandlerForMethod(_ method: String, module: String, resource: String, handler: @escaping (_ request: GCDWebServerRequest?) -> GCDWebServerResponse?) { // Prevent serving content if the requested host isn't a whitelisted local host. let wrappedHandler = {(request: GCDWebServerRequest?) -> GCDWebServerResponse? in guard let request = request, request.url.isLocal else { return GCDWebServerResponse(statusCode: 403) } return handler(request) } server.addHandler(forMethod: method, path: "/\(module)/\(resource)", request: GCDWebServerRequest.self, processBlock: wrappedHandler) } /// Convenience method to register a resource in the main bundle. Will be mounted at $base/$module/$resource func registerMainBundleResource(_ resource: String, module: String) { if let path = Bundle.main.path(forResource: resource, ofType: nil) { server.addGETHandler(forPath: "/\(module)/\(resource)", filePath: path, isAttachment: false, cacheAge: UInt.max, allowRangeRequests: true) } } /// Convenience method to register all resources in the main bundle of a specific type. Will be mounted at $base/$module/$resource func registerMainBundleResourcesOfType(_ type: String, module: String) { for path: String in Bundle.paths(forResourcesOfType: type, inDirectory: Bundle.main.bundlePath) { if let resource = NSURL(string: path)?.lastPathComponent { server.addGETHandler(forPath: "/\(module)/\(resource)", filePath: path as String, isAttachment: false, cacheAge: UInt.max, allowRangeRequests: true) } else { log.warning("Unable to locate resource at path: '\(path)'") } } } /// Return a full url, as a string, for a resource in a module. No check is done to find out if the resource actually exist. func URLForResource(_ resource: String, module: String) -> String { return "\(base)/\(module)/\(resource)" } func baseReaderModeURL() -> String { return WebServer.sharedInstance.URLForResource("page", module: "reader-mode") } }
mpl-2.0
29b4ebc36cda75ebef4a3723de145f94
43.352273
166
0.673328
5.036129
false
false
false
false
nickfrey/knightsapp
Newman Knights/GradesViewController.swift
1
3008
// // GradesViewController.swift // Newman Knights // // Created by Nick Frey on 12/20/15. // Copyright © 2015 Nick Frey. All rights reserved. // import UIKit class GradesViewController: WebViewController { init() { super.init(URL: URL(string: AppConfiguration.PowerSchoolURLString)!) self.title = "Grades" self.tabBarItem.image = UIImage(named: "tabGrades") } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func loadView() { super.loadView() self.navigationItem.leftBarButtonItems = [ UIBarButtonItem(image: UIImage(named: "gradesBack"), style: .plain, target: self.webView, action: #selector(UIWebView.goBack)), UIBarButtonItem(image: UIImage(named: "gradesForward"), style: .plain, target: self.webView, action: #selector(UIWebView.goForward)) ] for barButtonItem in self.navigationItem.leftBarButtonItems! { barButtonItem.isEnabled = false } self.webView?.addObserver(self, forKeyPath: "canGoBack", options: [], context: nil) self.webView?.addObserver(self, forKeyPath: "canGoForward", options: [], context: nil) self.webView?.addObserver(self, forKeyPath: "loading", options: [], context: nil) } deinit { self.webView?.removeObserver(self, forKeyPath: "canGoBack") self.webView?.removeObserver(self, forKeyPath: "canGoForward") self.webView?.removeObserver(self, forKeyPath: "loading") } override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { let superImplementation = { super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context) } guard let keyPath = keyPath else { return superImplementation() } guard let object = object as? NSObject else { return superImplementation() } guard let webView = self.webView, object == webView else { return superImplementation() } if keyPath == "canGoBack" { self.navigationItem.leftBarButtonItems?.first?.isEnabled = webView.canGoBack } else if keyPath == "canGoForward" { self.navigationItem.leftBarButtonItems?.last?.isEnabled = webView.canGoForward } else if keyPath == "loading" { if webView.isLoading { let indicatorView = UIActivityIndicatorView(activityIndicatorStyle: .white) indicatorView.startAnimating() self.navigationItem.rightBarButtonItem = UIBarButtonItem(customView: indicatorView) } else { self.navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .refresh, target: self.webView, action: #selector(UIWebView.reload)) } } else { superImplementation() } } }
mit
3a3657f6fd8a8f8b549f8fc742f79693
41.957143
162
0.647822
5.06229
false
false
false
false
ainopara/Stage1st-Reader
Stage1st/Scene/Settings/CloudKitViewController.swift
1
11629
// // CloudKitViewController.swift // Stage1st // // Created by Zheng Li on 2018/4/20. // Copyright © 2018 Renaissance. All rights reserved. // import SnapKit import QuickTableViewController import YapDatabase import Combine class CloudKitViewController: QuickTableViewController { private var bag = Set<AnyCancellable>() override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) NotificationCenter.default.addObserver( self, selector: #selector(dataSourceDidChanged), name: .YapDatabaseCloudKitSuspendCountChanged, object: nil ) NotificationCenter.default.addObserver( self, selector: #selector(dataSourceDidChanged), name: .YapDatabaseCloudKitInFlightChangeSetChanged, object: nil ) AppEnvironment.current.cloudkitManager.state.sink { [weak self] (_) in self?.dataSourceDidChanged() }.store(in: &bag) AppEnvironment.current.cloudkitManager.accountStatus.signal.observeValues { [weak self] (_) in self?.dataSourceDidChanged() } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } deinit { NotificationCenter.default.removeObserver(self) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) updateTable() } @objc func dataSourceDidChanged() { DispatchQueue.main.async { self.updateTable() } } func updateTable() { let iCloudSection = Section( title: NSLocalizedString("CloudKitViewController.iCloudSection.header", comment: ""), rows: [], footer: NSLocalizedString("CloudKitViewController.iCloudSection.footer", comment: "") ) iCloudSection.rows.append(NavigationRow( text: NSLocalizedString("CloudKitViewController.AccountStatusRow.title", comment: ""), detailText: DetailText.value1(AppEnvironment.current.cloudkitManager.accountStatus.value.debugDescription) )) iCloudSection.rows.append(SwitchRow( text: NSLocalizedString("CloudKitViewController.iCloudSwitchRow.title", comment: ""), switchValue: AppEnvironment.current.settings.enableCloudKitSync.value, action: { [weak self] row in AppEnvironment.current.settings.enableCloudKitSync.value.toggle() if AppEnvironment.current.settings.enableCloudKitSync.value == false { let title = NSLocalizedString("CloudKitViewController.iCloudSwitchRow.EnableMessage", comment: "") let alertController = UIAlertController(title: title, message: "", preferredStyle: .alert) self?.present(alertController, animated: true, completion: nil) AppEnvironment.current.cloudkitManager.unregister { DispatchQueue.main.async { alertController.dismiss(animated: true, completion: nil) } } } else { let title = NSLocalizedString("CloudKitViewController.iCloudSwitchRow.DisableMessage", comment: "") let message = "" let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert) alertController.addAction(UIAlertAction(title: NSLocalizedString("Message_OK", comment: ""), style: .default, handler: nil)) self?.present(alertController, animated: true, completion: nil) } } )) tableContents = [ iCloudSection ] #if DEBUG let detailSection = Section( title: NSLocalizedString("CloudKitViewController.DetailSection.header", comment: ""), rows: [] ) detailSection.rows.append(NavigationRow( text: "Container ID", detailText: DetailText.value1(AppEnvironment.current.cloudkitManager.cloudKitContainer.containerIdentifier ?? "") )) detailSection.rows.append(NavigationRow( text: NSLocalizedString("CloudKitViewController.StateRow.title", comment: ""), detailText: DetailText.value1(AppEnvironment.current.cloudkitManager.state.value.debugDescription) )) detailSection.rows.append(NavigationRow( text: NSLocalizedString("CloudKitViewController.SuspendCountRow.title", comment: ""), detailText: DetailText.value1("\(AppEnvironment.current.databaseManager.cloudKitExtension.suspendCount)") )) let queued = AppEnvironment.current.databaseManager.cloudKitExtension.numberOfQueuedChangeSets let inFlight = AppEnvironment.current.databaseManager.cloudKitExtension.numberOfInFlightChangeSets detailSection.rows.append(NavigationRow( text: NSLocalizedString("CloudKitViewController.UploadQueueRow.title", comment: ""), detailText: DetailText.value1("\(inFlight) - \(queued)"), action: { [weak self] (_) in guard let strongSelf = self else { return } strongSelf.navigationController?.pushViewController(CloudKitUploadQueueViewController(nibName: nil, bundle: nil), animated: true) } )) detailSection.rows.append(NavigationRow( text: NSLocalizedString("CloudKitViewController.ErrorsRow.title", comment: ""), detailText: DetailText.value1("\(AppEnvironment.current.cloudkitManager.errors.count)"), action: { [weak self] (_) in guard let strongSelf = self else { return } strongSelf.navigationController?.pushViewController(CloudKitErrorListViewController(nibName: nil, bundle: nil), animated: true) } )) tableContents.append(detailSection) #endif tableView.reloadData() } } class CloudKitUploadQueueViewController: UIViewController { let tableView = UITableView(frame: .zero, style: .insetGrouped) var changeSets = [YDBCKChangeSet]() override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) changeSets = AppEnvironment.current.cloudkitManager.cloudKitExtension.pendingChangeSets() tableView.rowHeight = UITableView.automaticDimension tableView.estimatedRowHeight = 100.0 tableView.delegate = self tableView.dataSource = self NotificationCenter.default.addObserver( self, selector: #selector(dataSourceDidChanged), name: .YapDatabaseCloudKitInFlightChangeSetChanged, object: nil ) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } deinit { NotificationCenter.default.removeObserver(self) } override func viewDidLoad() { super.viewDidLoad() view.addSubview(tableView) tableView.snp.makeConstraints { (make) in make.edges.equalTo(self.view) } } @objc func dataSourceDidChanged() { changeSets = AppEnvironment.current.cloudkitManager.cloudKitExtension.pendingChangeSets() tableView.reloadData() } } extension CloudKitUploadQueueViewController: UITableViewDataSource { func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return changeSets.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "cell") ?? UITableViewCell(style: .default, reuseIdentifier: "cell") cell.textLabel?.numberOfLines = 0 let changeSet = changeSets[indexPath.item] cell.textLabel?.text = "Deleted: \(changeSet.recordIDsToDeleteCount) Changed: \(changeSet.recordsToSaveCount)" return cell } } extension CloudKitUploadQueueViewController: UITableViewDelegate { func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) } } class CloudKitUploadChangeSetViewController: UIViewController { } class CloudKitErrorListViewController: UIViewController { let tableView = UITableView(frame: .zero, style: .insetGrouped) var errors: [S1CloudKitError] = [] override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) errors = AppEnvironment.current.cloudkitManager.errors.reversed() tableView.rowHeight = UITableView.automaticDimension tableView.estimatedRowHeight = 100.0 tableView.delegate = self tableView.dataSource = self } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() view.addSubview(tableView) tableView.snp.makeConstraints { (make) in make.edges.equalTo(self.view) } } } extension CloudKitErrorListViewController: UITableViewDataSource { func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return errors.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { if let cell = tableView.dequeueReusableCell(withIdentifier: "cell") { let error = errors[indexPath.row] configure(cell: cell, with: error) return cell } else { let cell = UITableViewCell(style: .default, reuseIdentifier: "cell") cell.textLabel?.numberOfLines = 0 let error = errors[indexPath.row] configure(cell: cell, with: error) return cell } } func configure(cell: UITableViewCell, with cloudKitError: S1CloudKitError) { let prefix: String let underlyingError: Error switch cloudKitError { case let .createZoneError(error): prefix = "CreateZoneError: " underlyingError = error case let .createZoneSubscriptionError(error): prefix = "CreateZoneSubscriptionError: " underlyingError = error case let .fetchChangesError(error): prefix = "FetchChangesError: " underlyingError = error case let .uploadError(error): prefix = "UploadError: " underlyingError = error } if let ckError = underlyingError as? CKError { cell.textLabel?.text = "\(prefix)\(ckError.errorCode) \(ckError.localizedDescription)" } else { cell.textLabel?.text = "\(prefix)\(underlyingError)" } } } extension CloudKitErrorListViewController: UITableViewDelegate { func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) } } class CloudKitErrorDetailViewController: UIViewController { } // MARK: - extension Bool { mutating func toggle() { self = !self } }
bsd-3-clause
1688260ca4f41b5adb9c09f5ba469e55
35.3375
145
0.654627
5.370901
false
false
false
false
AaronMT/firefox-ios
Client/Frontend/EnhancedTrackingProtection/ETPViewModel.swift
7
3370
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import Shared import Leanplum class ETPViewModel { // Internal vars var etpCoverSheetmodel: ETPCoverSheetModel? var startBrowsing: (() -> Void)? var goToSettings: (() -> Void)? // We only show ETP coversheet for specific app updates and not all. The list below is for the version(s) // we would like to show the coversheet for. static let etpCoverSheetSupportedAppVersion = ["24.0"] init() { setupUpdateModel() } private func setupUpdateModel() { etpCoverSheetmodel = ETPCoverSheetModel(titleImage: #imageLiteral(resourceName: "shield"), titleText: Strings.CoverSheetETPTitle, descriptionText: Strings.CoverSheetETPDescription) } static func shouldShowETPCoverSheet(userPrefs: Prefs, currentAppVersion: String = VersionSetting.appVersion, isCleanInstall: Bool, supportedAppVersions: [String] = etpCoverSheetSupportedAppVersion) -> Bool { // 0,1,2 so we show on 3rd session as a requirement on Github #6012 let maxSessionCount = 2 var shouldShow = false // Default type is upgrade as in user is upgrading from a different version of the app var type: ETPCoverSheetShowType = isCleanInstall ? .CleanInstall : .Upgrade var sessionCount: Int32 = 0 if let etpShowType = userPrefs.stringForKey(PrefsKeys.KeyETPCoverSheetShowType) { type = ETPCoverSheetShowType(rawValue: etpShowType) ?? .Unknown } // Get the session count from preferences if let currentSessionCount = userPrefs.intForKey(PrefsKeys.KeyInstallSession) { sessionCount = currentSessionCount } // Two flows: Coming from clean install or otherwise upgrade flow switch type { case .CleanInstall: // We don't show it but save the 1st clean install session number if sessionCount < maxSessionCount { // Increment the session number userPrefs.setInt(sessionCount + 1, forKey: PrefsKeys.KeyInstallSession) userPrefs.setString(ETPCoverSheetShowType.CleanInstall.rawValue, forKey: PrefsKeys.KeyETPCoverSheetShowType) } else if sessionCount == maxSessionCount { userPrefs.setString(ETPCoverSheetShowType.DoNotShow.rawValue, forKey: PrefsKeys.KeyETPCoverSheetShowType) shouldShow = true } break case .Upgrade: // This will happen if its not a clean install and we are upgrading from another version. // This is where we tag it as an upgrade flow and try to present it for specific version(s) Eg. v24.0 userPrefs.setString(ETPCoverSheetShowType.Upgrade.rawValue, forKey: PrefsKeys.KeyETPCoverSheetShowType) if supportedAppVersions.contains(currentAppVersion) { userPrefs.setString(ETPCoverSheetShowType.DoNotShow.rawValue, forKey: PrefsKeys.KeyETPCoverSheetShowType) shouldShow = true } break case .DoNotShow: break case .Unknown: break } return shouldShow } }
mpl-2.0
12e3705f3ca864e1b110703ca3594e0d
46.464789
211
0.672107
5.022355
false
false
false
false
TrondKjeldas/KnxBasics2
Source/KnxNetIpHeader.swift
1
2459
// // KnxNetIpHeader.swift // KnxBasics2 // // The KnxBasics2 framework provides basic interworking with a KNX installation. // Copyright © 2016 Trond Kjeldås ([email protected]). // // This library is free software; you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License Version 2.1 // as published by the Free Software Foundation. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public License // along with this library; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. // import Foundation import SwiftyBeaver /// Class representing a KNXnet/IP header. open class KnxNetIpHeader { // MARK: Public API public enum ServiceTypeIdentifier: UInt16 { case unknown = 0x0000 case routingIndication = 0x0530 case routingBusy = 0x0531 case routingLostMessage = 0x0532 func highByte() -> UInt8 { return UInt8((self.rawValue >> 8) & 0x00FF) } func lowByte() -> UInt8 { return UInt8(self.rawValue & 0x00FF) } } /// Default initializer. public init() { _hdrLength = 6 _protocolVersion = 0x10 _serviceTypeIdentifier = .unknown _totalLength = 6 } /// Convinience initializer. public convenience init(asType type: ServiceTypeIdentifier, withLength length: Int = 0) { self.init() _serviceTypeIdentifier = type _totalLength = 6 + UInt16(length) } public var payload: Data { let data = Data(bytes: [ _hdrLength, _protocolVersion, _serviceTypeIdentifier.highByte(), _serviceTypeIdentifier.lowByte(), UInt8(_totalLength >> 8), UInt8(_totalLength)]) log.debug("HDR: \(data.hexEncodedString())") return data } // MARK: Internal and private declarations fileprivate var _hdrLength: UInt8 fileprivate var _protocolVersion: UInt8 fileprivate var _serviceTypeIdentifier: ServiceTypeIdentifier fileprivate var _totalLength: UInt16 fileprivate let log = SwiftyBeaver.self }
lgpl-2.1
a62a88261a2d64b4e0e2cebff2344e20
30.101266
101
0.663004
4.310526
false
false
false
false
Harley-xk/SimpleDataKit
Example/Pods/Comet/Comet/Extensions/UIColor+Comet.swift
1
1659
// // UIColor+Comet.swift // Comet // // Created by Harley on 2016/11/8. // // import UIKit public extension UIColor { /** * 使用16进制字符串创建颜色 * * @param hexString 16进制字符串,可以是 0XFFFFFF/#FFFFFF/FFFFFF 三种格式之一 * * @return 返回创建的UIColor对象 */ public convenience init?(hex: String, alpha: CGFloat = 1) { let characterSet = CharacterSet.whitespacesAndNewlines var string = hex.trimmingCharacters(in: characterSet).uppercased() if string.count < 6 { return nil } if string.hasPrefix("0X") { let ns = string as NSString string = ns.substring(from: 2) } if string.hasPrefix("#") { let ns = string as NSString string = ns.substring(from: 1) } if string.count != 6 { return nil } let colorString = string as NSString var range = NSMakeRange(0, 2) let rString = colorString .substring(with: range) range.location += 2 let gString = colorString.substring(with: range) range.location += 2 let bString = colorString.substring(with: range) var r: UInt32 = 0 var g: UInt32 = 0 var b: UInt32 = 0 Scanner(string: rString).scanHexInt32(&r) Scanner(string: gString).scanHexInt32(&g) Scanner(string: bString).scanHexInt32(&b) self.init(red: CGFloat(r) / 255.0, green: CGFloat(g) / 255.0, blue: CGFloat(b) / 255.0, alpha: alpha) } }
mit
50fa6b60499a95af98b1dc9f9b83796c
24.693548
109
0.546139
4.159269
false
false
false
false
tkremenek/swift
test/SILGen/casts.swift
15
3571
// RUN: %target-swift-emit-silgen -module-name casts %s | %FileCheck %s class B { } class D : B { } // CHECK-LABEL: sil hidden [ossa] @$s5casts6upcast{{[_0-9a-zA-Z]*}}F func upcast(d: D) -> B { // CHECK: {{%.*}} = upcast return d } // CHECK-LABEL: sil hidden [ossa] @$s5casts8downcast{{[_0-9a-zA-Z]*}}F func downcast(b: B) -> D { // CHECK: {{%.*}} = unconditional_checked_cast return b as! D } // CHECK-LABEL: sil hidden [ossa] @$s5casts3isa{{[_0-9a-zA-Z]*}}F func isa(b: B) -> Bool { // CHECK: bb0([[ARG:%.*]] : @guaranteed $B): // CHECK: [[COPIED_BORROWED_ARG:%.*]] = copy_value [[ARG]] // CHECK: checked_cast_br [[COPIED_BORROWED_ARG]] : $B to D, [[YES:bb[0-9]+]], [[NO:bb[0-9]+]] // // CHECK: [[YES]]([[CASTED_VALUE:%.*]] : @owned $D): // CHECK: integer_literal {{.*}} -1 // CHECK: destroy_value [[CASTED_VALUE]] // // CHECK: [[NO]]([[ORIGINAL_VALUE:%.*]] : @owned $B): // CHECK: destroy_value [[ORIGINAL_VALUE]] // CHECK: integer_literal {{.*}} 0 return b is D } // CHECK-LABEL: sil hidden [ossa] @$s5casts16upcast_archetype{{[_0-9a-zA-Z]*}}F func upcast_archetype<T : B>(t: T) -> B { // CHECK: {{%.*}} = upcast return t } // CHECK-LABEL: sil hidden [ossa] @$s5casts25upcast_archetype_metatype{{[_0-9a-zA-Z]*}}F func upcast_archetype_metatype<T : B>(t: T.Type) -> B.Type { // CHECK: {{%.*}} = upcast return t } // CHECK-LABEL: sil hidden [ossa] @$s5casts18downcast_archetype{{[_0-9a-zA-Z]*}}F func downcast_archetype<T : B>(b: B) -> T { // CHECK: {{%.*}} = unconditional_checked_cast return b as! T } // This is making sure that we do not have the default propagating behavior in // the address case. // // CHECK-LABEL: sil hidden [ossa] @$s5casts12is_archetype{{[_0-9a-zA-Z]*}}F func is_archetype<T : B>(b: B, _: T) -> Bool { // CHECK: bb0([[ARG1:%.*]] : @guaranteed $B, [[ARG2:%.*]] : @guaranteed $T): // CHECK: checked_cast_br {{%.*}}, [[YES:bb[0-9]+]], [[NO:bb[0-9]+]] // CHECK: [[YES]]([[CASTED_ARG:%.*]] : @owned $T): // CHECK: integer_literal {{.*}} -1 // CHECK: destroy_value [[CASTED_ARG]] // CHECK: [[NO]]([[ORIGINAL_VALUE:%.*]] : @owned $B): // CHCEK: destroy_value [[CASTED_ARG]] // CHECK: integer_literal {{.*}} 0 return b is T } // CHECK: } // end sil function '$s5casts12is_archetype{{[_0-9a-zA-Z]*}}F' // CHECK: sil hidden [ossa] @$s5casts20downcast_conditional{{[_0-9a-zA-Z]*}}F // CHECK: checked_cast_br {{%.*}} : $B to D // CHECK: bb{{[0-9]+}}({{.*}} : $Optional<D>) func downcast_conditional(b: B) -> D? { return b as? D } protocol P {} struct S : P {} // CHECK: sil hidden [ossa] @$s5casts32downcast_existential_conditional{{[_0-9a-zA-Z]*}}F // CHECK: bb0([[IN:%.*]] : $*P): // CHECK: [[COPY:%.*]] = alloc_stack $P // CHECK: copy_addr [[IN]] to [initialization] [[COPY]] // CHECK: [[TMP:%.*]] = alloc_stack $S // CHECK: checked_cast_addr_br take_always P in [[COPY]] : $*P to S in [[TMP]] : $*S, bb1, bb2 // Success block. // CHECK: bb1: // CHECK: [[T0:%.*]] = load [trivial] [[TMP]] : $*S // CHECK: [[T1:%.*]] = enum $Optional<S>, #Optional.some!enumelt, [[T0]] : $S // CHECK: dealloc_stack [[TMP]] // CHECK: br bb3([[T1]] : $Optional<S>) // Failure block. // CHECK: bb2: // CHECK: [[T0:%.*]] = enum $Optional<S>, #Optional.none!enumelt // CHECK: dealloc_stack [[TMP]] // CHECK: br bb3([[T0]] : $Optional<S>) // Continuation block. // CHECK: bb3([[RESULT:%.*]] : $Optional<S>): // CHECK: dealloc_stack [[COPY]] // CHECK: return [[RESULT]] func downcast_existential_conditional(p: P) -> S? { return p as? S }
apache-2.0
457ba579526af3e1fe3ab35cadf55063
33.669903
98
0.563428
2.870579
false
false
false
false
danilotorrisi/SyncthingKit
Sources/Event.swift
1
10307
// // Event.swift // Syncthing-Finder // // Created by Danilo Torrisi on 16/01/15. // Copyright (c) 2015 Danilo Torrisi. All rights reserved. // import Foundation import SwiftyJSON import Alamofire import BrightFutures public struct Event: Printable { /** Based on the Event Interface wiki on github https://github.com/syncthing/syncthing/wiki/Event-Interface */ public enum Type : Printable { /** Emitted exactly once, when syncthing starts, before parsing configuration etc */ case Starting(home: String) /** Emitted exactly once, when initialization is complete and syncthing is ready to start exchanging data with other devices. */ case StartupComplete /** The Ping event is generated automatically every five minutes. This means that even in the absence of any other activity, the event polling HTTP request will return within five minutes. */ case Ping /** Emitted when a new device is discovered using local discovery. */ case DeviceDiscovered(addrs: [String], device: String) /** Generated each time a connection to a device has been established. */ case DeviceConnected(addr: String, identifier: String) /** Generated each time a connection to a device has been terminated. */ case DeviceDisconnected(error: String, identifier: String) /** Generated each time new index information is received from a device. */ case RemoteIndexUpdated(device: String, folder: String, items: Int) /** Generated when the local index information has changed, due to synchronizing an item from the cluster. */ case LocalIndexUpdated(flags: String, modified: String, name: String, folder: String, size: Int) /** Generated when syncthing begins synchronizing a file to a newer version. */ case ItemStarted(item: String, folder: String) /** Emitted when a folder changes state. Possible states are idle, scanning, cleaning and syncing. The field duration is the number of seconds the folder spent in state from. In the example below, the folder default was in state scanning for 0.198 seconds and is now in state idle. */ case StateChanged(folder: String, from: String, duration: Double, to: String) /** Emitted when a device sends index information for a folder we do not have, or have but do not share with the device in question. */ case FolderRejected(device: String, folder: String) /** Emitted when there is a connection from a device we are not configured to talk to. */ case DeviceRejected(address: String, device: String) /** Emitted after the config has been saved by the user or by Syncthing itself. */ case ConfigSaved(version: String) /** Emitted during file downloads for each folder for each file. By default only a single file in a folder is handled at the same time, but custom configuration can cause multiple files to be shown. */ case DownloadProgress // Private initializer to build a Type from its json representation. Because the type and its data are on the event top level json object you have to pass the event representation. init?(json: JSON) { // If type string found if let type = json["type"].string { // Get the data. let data = json["data"] // Check the type switch type { // On starting, we have to fetch the home string on the data json object. case "Starting": self = Type.Starting(home: data["home"].stringValue) // On startup complete, no data to be fetched at all. case "StartupComplete": self = Type.StartupComplete // On ping, no data to be fetched at all. case "Ping": self = Type.Ping // On device discovered, fetch addrs and device. case "DeviceDiscovered": self = Type.DeviceDiscovered(addrs: data["addres"].arrayObject as? [String] ?? [], device: data["device"].stringValue) // On device connected, fetch addrs and device. case "DeviceConnected": self = Type.DeviceConnected(addr: data["addr"].stringValue, identifier: data["id"].stringValue) // On device disconnected, fetch error and id. case "DeviceDisconnected": self = Type.DeviceDisconnected(error: data["error"].stringValue, identifier: data["id"].stringValue) // On remote index update. case "RemoteIndexUpdated": self = Type.RemoteIndexUpdated(device: data["device"].stringValue, folder: data["folder"].stringValue, items: data["items"].intValue) // On local index update. case "LocalIndexUpdated": self = Type.LocalIndexUpdated(flags: data["flags"].stringValue, modified: data["modified"].stringValue, name: data["name"].stringValue, folder: data["folder"].stringValue, size: data["size"].intValue) // On item started. case "ItemStarted": self = Type.ItemStarted(item: data["item"].stringValue, folder: data["folder"].stringValue) // On state changed case "StateChanged": self = Type.StateChanged(folder: data["folder"].stringValue, from: data["from"].stringValue, duration: data["duration"].doubleValue, to: data["to"].stringValue) // On folder rejected case "FolderRejected": self = Type.FolderRejected(device: data["device"].stringValue, folder: data["folder"].stringValue) // On device rejected case "DeviceRejected": self = Type.DeviceRejected(address: data["address"].stringValue, device: data["device"].stringValue) // On config saved case "ConfigSaved": self = Type.ConfigSaved(version: data["version"].stringValue) // On download progress. case "DownloadProgress": self = Type.DownloadProgress // Otherwise default: println("[Event] Malformed json object, could not obtain the Event on type \(type)") return nil } } else { // If something happened, return nil return nil } } // MARK: - Printable public var description: String { switch self { case .Starting(let home): return "Starting home: \(home)" case .StartupComplete: return "StartupComplete" case .Ping: return "Ping" case .DeviceDiscovered(let addrs, let device): return "DeviceDiscovered addrs: \(addrs), device: \(device)" case .DeviceConnected(let addr, let identifier): return "DeviceConnected addr: \(addr), identifier: \(identifier)" case .DeviceDisconnected(let error, let identifier): return "DeviceDisconnected error: \(error), identifier: \(identifier)" case .RemoteIndexUpdated(let device, let folder, let items): return "RemoteIndexUpdated device: \(device), folder: \(folder), items: \(items)" case .LocalIndexUpdated(let flags, let modified, let name, let folder, let size): return "LocalIndexUpdated flags: \(flags), modified: \(modified), name: \(name), folder: \(folder), size: \(size)" case .ItemStarted(let item, let folder): return "ItemStarted item: \(item), folder: \(folder)" case .StateChanged(let folder, let from, let duration, let to): return "StateChanged folder: \(folder), from: \(from), duration: \(duration), to: \(to)" case .DeviceRejected(let address, let device): return "DeviceRejected address: \(address), device: \(device)" case .ConfigSaved(let version): return "ConfigSaved version: \(version)" case .DownloadProgress: return "DownloadProgress" default: return "Unknown" } } } /** The ID field on the even. */ public let identifier: Int /** The event type. */ public let type: Type // The private init in order to retrieve an event from its json representation. private init?(json: JSON) { // Get the fiedls if let identifier = json["id"].int { self.identifier = identifier } else { return nil } if let typeString = json["type"].string { if let type = Type(json: json) { self.type = type } else { return nil } } else { return nil } } // MARK: - Printable public var description: String { return "Event: \(identifier) \(type)" } } public func retrieveNewEvents(lastIdentifier: Int, limit: Int) -> Future<Array<Event>> { // Get the events from the Syncthing API. return Syncthing.get("events", parameters: ["since": lastIdentifier, "limit": limit]).map { (json) in // Get all the json object and map to Event return json.array?.map { Event(json: $0)! } ?? [] } }
mit
66c5ca91fcadb3d407d8ef89eb97f696
48.080952
285
0.556224
5.304683
false
false
false
false
TucoBZ/GitHub_APi_Test
GitHub_API/User.swift
1
568
// // User.swift // GitHub_API // // Created by Túlio Bazan da Silva on 11/01/16. // Copyright © 2016 TulioBZ. All rights reserved. // import Foundation import SwiftyJSON class User{ var id: Int? var login: String? var repos_url: String? var avatar_url: String? var url: String? required init(json: JSON) { self.repos_url = json["repos_url"].string self.id = json["id"].int self.login = json["login"].string self.avatar_url = json["avatar_url"].string self.url = json["url"].string } }
mit
c9be98219f92984b6511b4c07f07db72
19.962963
51
0.600707
3.349112
false
false
false
false
diwu/LeetCode-Solutions-in-Swift
Solutions/Solutions/Medium/Medium_095_Unique_Binary_Search_Trees_II.swift
1
1815
/* https://leetcode.com/problems/unique-binary-search-trees-ii/ #95 Unique Binary Search Trees II Level: medium Given n, generate all structurally unique BST's (binary search trees) that store values 1...n. For example, Given n = 3, your program should return all 5 unique BST's shown below. 1 3 3 2 1 \ / / / \ \ 3 2 1 1 3 2 / / \ \ 2 1 2 3 Inspired by @Jayanta at https://leetcode.com/discuss/10254/a-simple-recursive-solution */ import Foundation class Medium_095_Unique_Binary_Search_Trees_II { class Node { var value: Int var left: Node? var right: Node? init(value: Int, left: Node?, right: Node?) { self.value = value self.left = left self.right = right } } private class func genTrees (start: Int, end: Int) -> [Node?] { var ret: [Node?] = [] if start > end { ret.append(nil) return ret } else if start == end { ret.append(Node(value: start, left: nil, right: nil)) return ret } var left: [Node?] = [] var right: [Node?] = [] for i in start ... end { left = genTrees(start: start, end: i - 1) right = genTrees(start: i + 1, end: end) for left_node in left { for right_node in right { let root = Node(value: i, left: left_node, right: right_node) ret.append(root) } } } return ret } // t = O(n^(n-1)) a.k.a Catalan Number, s = I've no idea class func generateTrees(_ n: Int) -> [Node?] { return genTrees(start: 1, end: n) } }
mit
49f9f3a1e57b00b2b6889fc61841b146
27.359375
94
0.494215
3.689024
false
false
false
false
tryswift/trySwiftData
TrySwiftData/Models/Speaker.swift
1
1906
// // Speaker.swift // trySwift // // Created by Natasha Murashev on 2/10/16. // Copyright © 2016 NatashaTheRobot. All rights reserved. // public enum SpeakerType: Int { case presentation case lightningTalk case instructor case emcee } public struct Speaker { public let id: Int public let name: String public let nameJP: String? public let twitter: String public let imageAssetName: String? public let imageWebURL: String? public let bio: String public let bioJP: String? public let hidden: Bool public let type: SpeakerType init(id: Int, name: String, nameJP: String? = nil, twitter: String, imageAssetName: String?, imageWebURL: String? = nil, bio: String, bioJP: String? = nil, hidden: Bool = false, type: SpeakerType = .presentation) { self.id = id self.name = name self.nameJP = nameJP self.twitter = twitter self.imageAssetName = imageAssetName self.imageWebURL = imageWebURL self.bio = bio self.bioJP = bioJP self.hidden = hidden self.type = type } public static var all: [Speaker] { let speakers = nyc2019Speakers.values.filter { $0.hidden == false} return speakers.sorted { $0.name < $1.name } } public var localizedName: String { return localizedString(for: name, japaneseString: nameJP) } public var localizedBio: String { return localizedString(for: bio, japaneseString: bioJP) } public var imageURL: URL? { if let url = imageWebURL, !url.isEmpty { return URL(string: url)! } if let assetName = imageAssetName { return Bundle.trySwiftAssetURL(for: assetName)! } return Bundle.trySwiftAssetURL(for: "Logo.png")! } }
mit
0f858b1e60c32d79df3257aedb825ace
23.74026
74
0.603675
4.132321
false
false
false
false
devxoul/Slots
Slots/Slots.swift
1
7387
// The MIT License (MIT) // // Copyright (c) 2015 Suyeol Jeon (xoul.kr) // // 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 open class Slots { open var header: [String]? { didSet { self.setNeedsSort() } } open var pattern: [String]! { didSet { self.setNeedsSort() } } open var repeatables: [String]? { didSet { self.setNeedsSort() } } /// If content type is invalid or exhausted, Slots uses `defaultContentType` instead. `repeatables` will be ignored /// if `defaultContentType` is set. open var defaultContentType: String? { didSet { self.setNeedsSort() } } /// Fix content type in specific position. The pattern already exists in `pattern` would be ignored. /// /// Example:: /// slots.fixed = [ /// 0: "SomeContentType", /// 3: "SomeContentType", /// ] open var fixed: [Int: String]? { didSet { self.setNeedsSort() } } private var _patterns: [String]! private var _contentsForType: [String: [Any]]! private var _contents: [Any]! open var contents: [Any] { self.sortIfNeeded() return self._contents } private(set) open var needsSort: Bool = false open var count: Int { self.sortIfNeeded() return self._contents.count } /// if set to `true`, subscript will return empty array(`[]`) instead of `nil` for undefined content types. Default /// value is `false`. /// /// Example:: /// /// slots["undefined"] // nil /// slots.prefersEmptyArrayForUndefinedContentTypes = true /// slots["undefined"] // [] open var prefersEmptyArrayForUndefinedContentTypes = false // MARK: - Init public init() { self.pattern = [] self._patterns = [] self._contentsForType = [String: [Any]]() self._contents = [] } public convenience init(pattern: [String]) { self.init() self.pattern = pattern } // MARK: - Type At Index open func type(at index: Int) -> String? { if index < 0 { return nil } self.sortIfNeeded() if index >= self._patterns.count { return nil } return self._patterns[index] } // MARK: - Subscripts open subscript(index: Int) -> Any? { if index < 0 { return nil } self.sortIfNeeded() if index >= self._contents.count { return nil } return self._contents[index] } open subscript(subRange: Range<Int>) -> ArraySlice<Any> { self.sortIfNeeded() return self._contents[subRange] } open subscript(type: String) -> [Any]? { get { let contents = self._contentsForType[type] if self.prefersEmptyArrayForUndefinedContentTypes { return contents ?? [] } return contents } set { self._contentsForType[type] = newValue self.setNeedsSort() } } // MARK: - Sort open func setNeedsSort() { self.needsSort = true } open func sortIfNeeded() { if self.needsSort { self.sort() } } open func sort() { self.needsSort = false self._patterns.removeAll() self._contents.removeAll() if self.pattern.count == 0 || self._contentsForType.count == 0 { return } var stacks = [String: [Any]]() for (type, contents) in self._contentsForType { stacks[type] = contents.reversed() } var repeatableTypes = Set<String>() // if `defaultContentType` is set, `repeatables` will be ignored. if let repeatables = self.repeatables , self.defaultContentType == nil { repeatableTypes.formIntersection(Set(self.pattern)) for type in self.pattern { if repeatables.contains(type) { repeatableTypes.insert(type) } } } let enumerate = { (from: [String]) -> Bool in var nonRepeatableFinished = false for type in from { // no more data in stack if stacks[type] == nil || stacks[type]!.count == 0 { // if `defaultContentType` exists, use it. if let defaultType = self.defaultContentType, let stack = stacks[defaultType] , stack.count > 0 { let last: Any = stacks[defaultType]!.removeLast() self._patterns.append(defaultType) self._contents.append(last) } // if `type` is repeatable, remove it from repeatables. else { if repeatableTypes.contains(type) { repeatableTypes.remove(type) } else { nonRepeatableFinished = true } if repeatableTypes.count == 0 { return true } } continue } if !nonRepeatableFinished || repeatableTypes.contains(type) { let last: Any = stacks[type]!.removeLast() self._patterns.append(type) self._contents.append(last) } } return false } if let header = self.header { if enumerate(header) { return } } while true { if enumerate(self.pattern) { break } } if let fixed = self.fixed { for index in fixed.keys.sorted() { let type = fixed[index]! // ignore if the type already exists in `pattern` if self.pattern.contains(type) { continue } if let content: Any = stacks[type]?.last , (0...self._patterns.count).contains(index) { stacks[type]?.removeLast() self._patterns.insert(type, at: index) self._contents.insert(content, at: index) } } } } }
mit
bca34029f0efe28f939b4b2a793e6c2c
30.168776
119
0.541763
4.729193
false
false
false
false
zixun/GodEye
Core/UIThreadEye/Classes/UIThreadEye.swift
1
2013
// // Created by zixun on 2018/5/13. // Copyright (c) 2018 zixun. All rights reserved. // import Foundation import UIKit extension UIView { @objc open func hook_setNeedsLayout() { self.checkThread() self.hook_setNeedsLayout() } @objc open func hook_setNeedsDisplay(_ rect: CGRect) { self.checkThread() self.hook_setNeedsDisplay(rect) } func checkThread() { assert(Thread.isMainThread,"You changed UI element not on main thread") } } open class UIThreadEye: NSObject { open class func open() { if self.isSwizzled == false { self.isSwizzled = true self.hook() }else { print("[NetworkEye] already started or hook failure") } } open class func close() { if self.isSwizzled == true { self.isSwizzled = false self.hook() }else { print("[NetworkEye] already stoped or hook failure") } } public static var isWatching: Bool { get { return self.isSwizzled } } private class func hook() { _ = UIView.swizzleInstanceMethod(origSelector: #selector(UIView.setNeedsLayout), toAlterSelector: #selector(UIView.hook_setNeedsLayout)) _ = UIView.swizzleInstanceMethod(origSelector: #selector(UIView.setNeedsDisplay(_:)), toAlterSelector: #selector(UIView.hook_setNeedsDisplay(_:))) } private static var isSwizzled: Bool { set{ objc_setAssociatedObject(self, &key.isSwizzled, isSwizzled, .OBJC_ASSOCIATION_ASSIGN); } get{ let result = objc_getAssociatedObject(self, &key.isSwizzled) as? Bool if result == nil { return false } return result! } } private struct key { static var isSwizzled: Character = "c" } }
mit
26a2f161f9252c83184a542a079c383c
25.142857
101
0.5539
4.781473
false
false
false
false
AleksanderKoko/WikimediaCommonsApi
WCApi/Classes/UploadMultimedia.swift
1
8414
import Alamofire public class UploadMultimedia : GetTokenHandlerProtocol { internal let handler: UploadMultimediaHandlerProtocol internal let getToken: GetToken internal var username: UserModel? internal var title: String? internal var description: String? internal var license: MultimediaModel.Licenses? internal var categories: [String]? internal var comment: String? internal var token: String? internal var imageData: NSData? internal var text: String? internal struct Results{ let Success = "Success" } internal enum ResetPasswordResults : String { case Success = "success" case Failed = "throttled-mailpassword" case NotSuchUser = "nosuchuser" } public init(handler: UploadMultimediaHandlerProtocol){ self.handler = handler self.getToken = GetToken() self.getToken.setHandler(self) } public func setToken(token: String) -> Void{ self.token = token self.uploadNetworking() } public func getTokenFatalError(error: GetTokenErrorFatal) { self.handler.uploadMultimediaError(error) } public func upload(user: UserModel, title: String, description: String, comment: String, license: String, categories: [String], imageData: NSData, date: String?) -> Void { self.title = title self.comment = comment self.imageData = imageData self.text = self.buildText(user, description: description, license: license, categories: categories, date: date) do { try self.getToken.getToken(GetToken.TokenTypes.CSRF) }catch{} } internal func buildText(user: UserModel, description: String, license: String, categories: [String], date: String?) -> String{ var dateStr: String = "" if date != nil{ dateStr = "|date=\(date)\n" }else{ dateStr = "|date=\(self.getCurrentDateString())\n" } let fileDescHeader = "=={{int:filedesc}}==\n{{Information\n" let description = "|description={{en|1=\(description)}} \n" let source = "|source={{own}}\n" let author = "|author=[[User:\(user.username)|\(user.username)]]\n" let permission = "|permission=\n" let otherVersions = "|other versions=\n" let fileDescEnd = "}}\n\n" let licenseStr = "=={{int:license-header}}==\n{{self|\(license)}}\n\n" var textStr = fileDescHeader + description + dateStr + source + author + permission + otherVersions + fileDescEnd + licenseStr for category in categories { textStr += "[[Category:\(category)]]\n" } return textStr } internal func uploadNetworking() -> Void { print("Starting to upload") Alamofire.upload( .POST, Config.apiUrl, multipartFormData: { multipartFormData in multipartFormData.appendBodyPart(data: self.imageData!, name: "file", fileName: "\(self.title).jpeg", mimeType: "image/jpeg") multipartFormData.appendBodyPart(data: "upload".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!, name :"action") multipartFormData.appendBodyPart(data: "json".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!, name :"format") multipartFormData.appendBodyPart(data: "1".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!, name :"ignorewarnings") multipartFormData.appendBodyPart(data: self.comment!.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!, name :"comment") multipartFormData.appendBodyPart(data: self.token!.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!, name :"token") multipartFormData.appendBodyPart(data: self.text!.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!, name :"text") multipartFormData.appendBodyPart(data: "\(self.title!).jpeg".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!, name :"filename") }, encodingCompletion: { encodingResult in switch encodingResult { case .Success(let upload, _, _): upload.responseJSON { response in if let JSON = response.result.value{ if let result = JSON.objectForKey("upload")?.objectForKey("result"){ print(result) // IT WORKS HERE }else{ print("Jo dhe kete here") } }else{ print("Cant parse the JSON") } } case .Failure(let encodingError): print(encodingError) } } ) /*Alamofire.request( .POST, Config.apiUrl, parameters: [ "action": "upload", "format": "json", "ignorewarnings": 1, "filename": self.title!, "comment": self.comment!, "token": self.token!, ] ).responseJSON { response in if let JSON = response.result.value { // Case error /*if let result = JSON.objectForKey("error")?.objectForKey("code") { let resultStr : String = result as! String switch resultStr { case ResetPasswordResults.Failed.rawValue: self.handler.resetPasswordError(ResetPasswordThrottle()) break case ResetPasswordResults.NotSuchUser.rawValue: self.handler.resetPasswordError(ResetPasswordBadInfo()) break default: print(resultStr) self.handler.resetPasswordError(ResetPasswordErrorFatal(message: GeneralErrorMessages.FatalErrorCantProcessJSON.rawValue)) } // Case when is success }else if let result = JSON.objectForKey("resetpassword")?.objectForKey("status") { let resultStr : String = result as! String if resultStr == ResetPasswordResults.Success.rawValue { self.handler.resetPasswordSuccess() }else{ self.handler.resetPasswordError(ResetPasswordErrorFatal(message: GeneralErrorMessages.FatalErrorCantProcessJSON.rawValue)) } // when it cant process json data }else{ self.handler.resetPasswordError(ResetPasswordErrorFatal(message: GeneralErrorMessages.FatalErrorCantProcessJSON.rawValue)) } */ // Case when it cant get response }else{ self.handler.uploadMultimediaError(UploadMultimediaErrorFatal(message: GeneralErrorMessages.FatalErrorCantGetResponse.rawValue)) } }*/ } internal func getCurrentDateString() -> String{ let dateFormater = NSDateFormatter() dateFormater.dateFormat = "yyyy-MM-dd" return dateFormater.stringFromDate(NSDate()) } } public protocol UploadMultimediaHandlerProtocol { func uploadMultimediaSuccess() func uploadMultimediaError(error: UploadMultimediaErrorFatal) func uploadMultimediaError(error: GetTokenErrorFatal) }
mit
d8f618f6bd866414be4e878b4c1e3a60
40.453202
173
0.539458
5.875698
false
false
false
false
xiaoleixy/Cocoa_swift
Random/Random/RandomController.swift
1
648
// // RandomController.swift // Random // // Created by michael on 15/2/14. // Copyright (c) 2015年 michael. All rights reserved. // import Cocoa class RandomController: NSObject { @IBOutlet weak var textField: NSTextField! @IBAction func seed(sender: AnyObject) { srandom(UInt32(time(nil))) textField.stringValue = "Generator seeded" } @IBAction func generate(sender: AnyObject) { var generated = Int(random()%100 + 1) textField.stringValue = String(generated) } override func awakeFromNib() { let now = NSDate() textField.objectValue = now } }
mit
72704cc42835a8d999e49ca3e6246ae8
20.533333
53
0.625387
4.167742
false
false
false
false
worchyld/FanDuelSample
FanDuelSample/FanDuelSample/FDPlayer.swift
1
1521
// // FDPlayer.swift // FanDuelSample // // Created by Amarjit on 14/12/2016. // Copyright © 2016 Amarjit. All rights reserved. // import Foundation import ObjectMapper // Player model. Basic structure based off: // @https://cdn.rawgit.com/liamjdouglas/bb40ee8721f1a9313c22c6ea0851a105/raw/6b6fc89d55ebe4d9b05c1469349af33651d7e7f1/Player.json class FDPlayer : NSObject, Mappable { var firstName: String? var lastName: String? var fppg : Float = Float(0) var remoteid: String! var images:[String:Any]? var fullName: String? { guard let firstName = self.firstName else { return nil } guard let lastName = self.lastName else { return nil } return firstName + " " + lastName } var imagePath:String? { guard let imgsDefault = self.getImageMeta else { return nil } guard let imgURL = imgsDefault["url"] else { return nil } return imgURL as? String } var getImageMeta:[String:Any]? { guard let imgs = images else { return nil } let imgsDefault = imgs["default"] as! [String:Any] return imgsDefault } required init?(map: Map) { super.init() } // Mappable func mapping(map: Map) { firstName <- map["first_name"] lastName <- map["last_name"] remoteid <- map["id"] fppg <- map["fppg"] images <- map["images"] } }
gpl-3.0
6e8523923ed903a65211897da86ce881
22.75
129
0.576974
3.771712
false
false
false
false
spritekitbook/flappybird-swift
Chapter 8/Start/FloppyBird/FloppyBird/MenuScene.swift
10
1946
// // MenuScene.swift // FloppyBird // // Created by Jeremy Novak on 9/24/16. // Copyright © 2016 SpriteKit Book. All rights reserved. // import SpriteKit class MenuScene: SKScene { // MARK: - Private class constants private let cloudController = CloudController() private let hills = Hills() private let ground = Ground() private let title = Title() private let logo = Logo() private let playButton = PlayButton() // MARK: - Private class variables private var lastUpdateTime:TimeInterval = 0.0 // MARK: - Init required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override init(size: CGSize) { super.init(size: size) } override func didMove(to view: SKView) { setup() } // MARK: - Setup private func setup() { self.backgroundColor = Colors.colorFrom(rgb: Colors.sky) self.addChild(cloudController) self.addChild(hills) self.addChild(ground) self.addChild(title) self.addChild(logo) self.addChild(playButton) } // MARK: - Update override func update(_ currentTime: TimeInterval) { let delta = currentTime - lastUpdateTime lastUpdateTime = currentTime cloudController.update(delta: delta) } // MARK: - Touch Events override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { let touch:UITouch = touches.first! as UITouch let touchLocation = touch.location(in: self) if playButton.contains(touchLocation) { loadScene() } } // MARK: - Load Scene private func loadScene() { let scene = GameScene(size: kViewSize) let transition = SKTransition.fade(with: SKColor.black, duration: 0.5) self.view?.presentScene(scene, transition: transition) } }
apache-2.0
1d5d760270182efa6ba8618986dab7b7
25.283784
79
0.607198
4.523256
false
false
false
false
mohamede1945/quran-ios
Quran/QuartersDataRetriever.swift
2
1912
// // QuartersDataRetriever.swift // Quran // // Created by Mohamed Afifi on 4/25/16. // // Quran for iOS is a Quran reading application for iOS. // Copyright (C) 2017 Quran.com // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // import PromiseKit struct QuartersDataRetriever: Interactor { func execute(_ input: Void) -> Promise<[(Juz, [Quarter])]> { return DispatchQueue.default.promise2 { guard let ayahsText = NSArray(contentsOf: Files.quarterPrefixArray) as? [String] else { fatalError("Couldn't load `\(Files.quarterPrefixArray)` file") } let juzs = Juz.getJuzs() var juzsGroup: [(Juz, [Quarter])] = [] let numberOfQuarters = Quran.Quarters.count / juzs.count for (juzIndex, juz) in juzs.enumerated() { var quarters: [Quarter] = [] for i in 0..<numberOfQuarters { let order = juzIndex * numberOfQuarters + i let ayah = Quran.Quarters[order] let quarter = Quarter(order: order, ayah: ayah, juz: juz, startPageNumber: ayah.getStartPage(), ayahText: ayahsText[order]) quarters.append(quarter) } juzsGroup.append((juz, quarters)) } return juzsGroup } } }
gpl-3.0
ac22b57ea11a5f14c0719194c86f196a
32.54386
99
0.584728
4.365297
false
false
false
false
zhiquan911/CHKLineChart
CHKLineChart/Example/Example/Demo/SettingDetailViewController.swift
1
2086
// // SettingDetailViewController.swift // Example // // Created by Chance on 2018/3/1. // Copyright © 2018年 Chance. All rights reserved. // import UIKit class SettingDetailViewController: UIViewController { var seriesParam: SeriesParam! lazy var tableView: UITableView = { let table = UITableView(frame: CGRect.zero, style: .plain) table.dataSource = self table.delegate = self return table }() override func viewDidLoad() { super.viewDidLoad() self.setupUI() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /// 配置UI func setupUI() { self.view.backgroundColor = .white self.view.addSubview(self.tableView) self.tableView.snp.makeConstraints { (make) in make.top.bottom.right.left.equalToSuperview() } } } extension SettingDetailViewController: UITableViewDataSource, UITableViewDelegate { func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.seriesParam.params.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { var cell: SeriesSettingDetailCell? cell = tableView.dequeueReusableCell(withIdentifier: SeriesSettingDetailCell.identify) as? SeriesSettingDetailCell if cell == nil { cell = SeriesSettingDetailCell() } let param = self.seriesParam.params[indexPath.row] cell?.configCell(param: param) cell?.didStepperChanged = { (c, s) in if let ip = self.tableView.indexPath(for: c) { let sc = self.seriesParam.params[ip.row] sc.value = s.value _ = SeriesParamList.shared.saveUserData() } } return cell! } }
mit
c2bc554f184d18ac732d5bccdee16d2c
26.355263
122
0.618086
4.880282
false
false
false
false
Marquis103/OnTheMap
UIHelper.swift
1
567
// // UIHelper.swift // OnTheMap // // Created by Marquis Dennis on 2/9/16. // Copyright © 2016 Marquis Dennis. All rights reserved. // import UIKit class UIHelper { static func activityIndicatorViewLoadingView(center: CGPoint) -> UIView { let loadingView: UIView = UIView() loadingView.frame = CGRectMake(0, 0, 80, 80) loadingView.center = center loadingView.backgroundColor = UIColor(red: 107/255.0, green: 105/255.0, blue: 105/255.0, alpha: 0.7) loadingView.clipsToBounds = true loadingView.layer.cornerRadius = 10 return loadingView } }
mit
4726e3a56f2e25958f7db152dece4d90
24.727273
102
0.717314
3.472393
false
false
false
false
shajrawi/swift
validation-test/Evolution/test_backward_deploy_protocol.swift
1
2725
// RUN: %target-resilience-test --backward-deployment // REQUIRES: executable_test // Use swift-version 4. // UNSUPPORTED: swift_test_mode_optimize_none_with_implicit_dynamic import StdlibUnittest import backward_deploy_protocol var BackwardDeployProtocolTest = TestSuite("BackwardDeployProtocol") struct ConformsToOldWithDefault : OldProtocol {} struct MyConcrete : OtherProtocol {} struct ConformsToOldWithNonDefault : OldProtocol { typealias NewType = MyConcrete } BackwardDeployProtocolTest.test("OldProtocol") { if getVersion() == 1 { _ = ConformsToOldWithDefault().newMethod() _ = ConformsToOldWithNonDefault().newMethod() } } struct MyNewConforms : NewProtocol { func newMethod() {} } func dynamicCast<T, U>(_ t: T, _: U.Type) -> Bool { return t is U } BackwardDeployProtocolTest.test("NewProtocol") { if getVersion() == 1 { let x1 = NewConforms() let x2 = MyNewConforms() let x3 = ConformsToOldWithDefault() expectEqual(true, dynamicCast(x1, NewProtocol.self)) expectEqual(true, dynamicCast(x2, NewProtocol.self)) expectEqual(false, dynamicCast(x3, NewProtocol.self)) } // Make sure that dynamic casts don't crash in the backward // deployment case. do { let x1 = ConformsToOldWithDefault() let x2 = MyConcrete() expectEqual(false, dynamicCast(x1, OtherProtocol.self)) expectEqual(true, dynamicCast(x2, OtherProtocol.self)) } } // Weak reference to a conformance descriptor from another module public protocol RefinedProtocol : NewProtocol {} extension NewConforms : RefinedProtocol {} BackwardDeployProtocolTest.test("RefinedProtocol") { if getVersion() == 1 { let x1 = NewConforms() let x2 = MyNewConforms() let x3 = ConformsToOldWithDefault() expectEqual(true, dynamicCast(x1, RefinedProtocol.self)) expectEqual(false, dynamicCast(x2, RefinedProtocol.self)) expectEqual(false, dynamicCast(x3, RefinedProtocol.self)) } } // Witness tables that are weak-linked for various reasons BackwardDeployProtocolTest.test("WeakWitnessTables") { if getVersion() == 1 { func f1<T : OtherProtocol>(_: T) {} func f2<T : NewProtocol>(_: T) {} func f3<T : NewConformanceProtocol>(_: T) {} f1(OtherConforms()) f2(NewConforms()) f3(NewConformanceConforms()) } } // Conditional conformance with weak-linked requirement struct Box<T> {} extension Box : OtherProtocol where T : NewProtocol {} BackwardDeployProtocolTest.test("ConditionalConformance") { if getVersion() == 1 { let x1 = Box<MyNewConforms>() expectEqual(true, dynamicCast(x1, OtherProtocol.self)) } do { let x2 = Box<Int>() expectEqual(false, dynamicCast(x2, OtherProtocol.self)) } } runAllTests()
apache-2.0
bd419951306e924d9599df276d13c368
25.201923
68
0.71633
3.937861
false
true
false
false
samburnstone/SwiftStudyGroup
Practical Playgrounds/FirstInteractivePlayground.playground/Pages/Functions with argument labels.xcplaygroundpage/Contents.swift
1
602
//: [Previous](@previous) import Foundation import UIKit import XCPlayground let view = UIView() view.frame = CGRect(x: 0, y: 0, width: 300, height: 300) let subview1 = UIView(frame: view.frame) subview1.backgroundColor = .purpleColor() let subview2 = UIView(frame: view.frame) subview2.backgroundColor = .greenColor() let func1 = view.insertSubview(_: atIndex:) let func2 = view.insertSubview(_: aboveSubview:) let func3 = view.insertSubview(_: belowSubview:) func1(subview1, atIndex: 0) func2(subview2, aboveSubview: subview1) XCPlaygroundPage.currentPage.liveView = view //: [Next](@next)
mit
4cd80e4f8349ba1f6854e01fcf952ebb
21.296296
56
0.740864
3.56213
false
false
false
false
wordpress-mobile/AztecEditor-iOS
Aztec/Classes/Libxml2/Converters/Out/HTMLSerializer.swift
2
6685
import Foundation import libxml2 protocol HTMLSerializerCustomizer { func converter(for element: ElementNode) -> ElementToTagConverter? } /// Composes the provided nodes into its HTML representation. /// public class HTMLSerializer { /// Indentation Spaces to be applied /// let indentationSpaces: Int /// Converters private let genericElementConverter = GenericElementToTagConverter() private let customizer: HTMLSerializerCustomizer? /// Default Initializer /// /// - Parameters: /// - indentationSpaces: Indicates the number of indentation spaces to be applied, per level. /// public init(indentationSpaces: Int = 2) { self.customizer = nil self.indentationSpaces = indentationSpaces } init(indentationSpaces: Int = 2, customizer: HTMLSerializerCustomizer? = nil) { self.customizer = customizer self.indentationSpaces = indentationSpaces } /// Serializes a node into its HTML representation /// public func serialize(_ node: Node, prettify: Bool = false) -> String { return serialize(node: node, prettify: prettify).trimmingCharacters(in: CharacterSet.newlines) } func serialize(_ nodes: [Node], prettify: Bool, level: Int = 0) -> String { return nodes.reduce("") { (previous, child) in return previous + serialize(node: child, prettify: prettify, level: level) } } } // MARK: - Nodes: Composition // private extension HTMLSerializer { /// Serializes a node into its HTML representation /// func serialize(node: Node, prettify: Bool, level: Int = 0) -> String { switch node { case let node as RootNode: return serialize(node, prettify: prettify) case let node as CommentNode: return serialize(node) case let node as ElementNode: return serialize(node, prettify: prettify, level: level) case let node as TextNode: return serialize(text: node) default: fatalError("We're missing support for a node type. This should not happen.") } } /// Serializes a `RootNode` into its HTML representation /// private func serialize(_ rootNode: RootNode, prettify: Bool) -> String { return rootNode.children.reduce("") { (result, node) in return result + serialize(node: node, prettify: prettify) } } /// Serializes a `CommentNode` into its HTML representation /// private func serialize(_ commentNode: CommentNode) -> String { return "<!--" + commentNode.comment + "-->" } /// Serializes an `ElementNode` into its HTML representation /// private func serialize(_ elementNode: ElementNode, prettify: Bool, level: Int) -> String { let tag = converter(for: elementNode).convert(elementNode) let openingTagPrefix = self.openingTagPrefix(for: elementNode, prettify: prettify, level: level) let opening = openingTagPrefix + tag.opening let children = serialize(elementNode.children, prettify: prettify, level: level + 1) let closing: String if let closingTag = tag.closing { let prefix = self.closingTagPrefix(for: elementNode, prettify: prettify, withSpacesForIndentationLevel: level) let suffix = self.closingTagSuffix(for: elementNode, prettify: prettify) closing = prefix + closingTag + suffix } else { closing = "" } return opening + children + closing } /// Serializes an `TextNode` into its HTML representation /// private func serialize(text node: TextNode) -> String { return node.text().escapeHtmlNamedEntities() } } // MARK: - Indentation & newlines private extension HTMLSerializer { /// Returns the Tag Prefix String at the specified level /// private func prefix(for level: Int) -> String { let indentation = level > 0 ? String(repeating: String(.space), count: level * indentationSpaces) : "" return String(.lineFeed) + indentation } } // MARK: - Opening Tag Affixes private extension HTMLSerializer { private func openingTagPrefix(for elementNode: ElementNode, prettify: Bool, level: Int) -> String { guard requiresOpeningTagPrefix(elementNode, prettify: prettify) else { return "" } return prefix(for: level) } /// Required whenever the node is a blocklevel element /// private func requiresOpeningTagPrefix(_ node: ElementNode, prettify: Bool) -> Bool { return node.isBlockLevel() && prettify } } // MARK: - Closing Tag Affixes private extension HTMLSerializer { private func closingTagPrefix(for elementNode: ElementNode, prettify: Bool, withSpacesForIndentationLevel level: Int) -> String { guard requiresClosingTagPrefix(elementNode, prettify: prettify) else { return "" } return prefix(for: level) } private func closingTagSuffix(for elementNode: ElementNode, prettify: Bool) -> String { guard prettify, requiresClosingTagSuffix(elementNode, prettify: prettify) else { return "" } return String(.lineFeed) } /// ClosingTag Prefix: Required whenever one of the children is a blocklevel element /// private func requiresClosingTagPrefix(_ node: ElementNode, prettify: Bool) -> Bool { guard prettify else { return false } return node.children.contains { child in let elementChild = child as? ElementNode return elementChild?.isBlockLevel() == true } } /// ClosingTag Suffix: Required whenever the node is blocklevel, and the right sibling is not /// private func requiresClosingTagSuffix(_ node: ElementNode, prettify: Bool) -> Bool { guard prettify, let rightSibling = node.rightSibling() else { return false } let rightElementNode = rightSibling as? ElementNode let isRightNodeRegularElement = rightElementNode == nil || rightElementNode?.isBlockLevel() == false return isRightNodeRegularElement && node.isBlockLevel() } } // MARK: - Element Conversion Logic extension HTMLSerializer { private func converter(for elementNode: ElementNode) -> ElementToTagConverter { return customizer?.converter(for: elementNode) ?? genericElementConverter } }
mpl-2.0
239720a0f0fefe0de4807f2c8f8e4d9c
31.609756
133
0.633957
4.955523
false
false
false
false
Piwigo/Piwigo-Mobile
piwigo/Supporting Files/Macros/UIImage+AppTools.swift
1
4860
// // UIImage+AppTools.swift // piwigo // // Created by Eddy Lelièvre-Berna on 06/11/2021. // Copyright © 2021 Piwigo.org. All rights reserved. // import Vision import UIKit @objc extension UIImage { // MARK: - Saliency Analysis @available(iOS 13.0, *) func processSaliency() -> UIImage? { // Disabled when using simulator #if targetEnvironment(simulator) return nil #else // Retrieve CGImage version guard let cgImage = self.cgImage else { return nil } // Create request handler // let start:Double = CFAbsoluteTimeGetCurrent() let requestHandler = VNImageRequestHandler(cgImage: cgImage, options: [:]) // Create attention based saliency request let attentionRequest = VNGenerateAttentionBasedSaliencyImageRequest() attentionRequest.revision = VNGenerateAttentionBasedSaliencyImageRequestRevision1 // Create objectness based saliency request let objectnessRequest = VNGenerateObjectnessBasedSaliencyImageRequest() objectnessRequest.revision = VNGenerateObjectnessBasedSaliencyImageRequestRevision1 // Search for regions of interest try? requestHandler.perform([attentionRequest, objectnessRequest]) // Attention-based saliency requests return only one bounding box var attentionConfidence:Float = 0.0 let attentionResult = attentionRequest.results?.first let attentionObservation = attentionResult as VNSaliencyImageObservation? let attentionObject = attentionObservation?.salientObjects?.first attentionConfidence = attentionObject?.confidence ?? 0.0 // Object-based saliency requests return up to three bounding boxes var objectnessConfidence:Float = 0.0 let objectnessResult = objectnessRequest.results?.first let objectnessObservation = objectnessResult as VNSaliencyImageObservation? let objectnessObject = objectnessObservation?.salientObjects? .sorted(by: { $0.confidence > $1.confidence }).first objectnessConfidence = objectnessObject?.confidence ?? 0.0 // Priority to attention-based saliency if attentionConfidence > 0.7, attentionConfidence > objectnessConfidence, let salientObject = attentionObject, salientObject.boundingBox.width > 0.3, salientObject.boundingBox.height > 0.3 { let salientRect = VNImageRectForNormalizedRect(salientObject.boundingBox, cgImage.width, cgImage.height) // Crop image guard let croppedImage = cgImage.cropping(to: salientRect) else { return nil } // let diff:Double = (CFAbsoluteTimeGetCurrent() - start)*1000.0 // print(" processed attention based saliency in \(round(diff*10.0)/10.0) ms") return UIImage(cgImage:croppedImage) } // Objectness-based saliency if objectnessConfidence > 0.7, let salientObject = objectnessObject, salientObject.boundingBox.width > 0.3, salientObject.boundingBox.height > 0.3 { let salientRect = VNImageRectForNormalizedRect(salientObject.boundingBox, cgImage.width, cgImage.height) // Crop image guard let croppedImage = cgImage.cropping(to: salientRect) else { return nil } // let diff:Double = (CFAbsoluteTimeGetCurrent() - start)*1000.0 // print(" processed objectness based saliency in \(round(diff*10.0)/10.0) ms") return UIImage(cgImage:croppedImage) } return nil #endif } // MARK: - Image Manipulation func rotated(by angle:CGFloat) -> UIImage? { var newSize = CGRect(origin: CGPoint.zero, size: self.size) .applying(CGAffineTransform(rotationAngle: angle)).size // Trim off the extremely small float value to prevent core graphics from rounding it up newSize.width = floor(newSize.width) newSize.height = floor(newSize.height) UIGraphicsBeginImageContextWithOptions(newSize, false, self.scale) let context = UIGraphicsGetCurrentContext()! // Move origin to middle context.translateBy(x: newSize.width/2, y: newSize.height/2) // Rotate around middle context.rotate(by: angle) // Draw the image at its center let xPos: CGFloat = -self.size.width/2.0 let yPos: CGFloat = -self.size.height/2.0 self.draw(in: CGRect(x: xPos, y: yPos, width: self.size.width, height: self.size.height)) let newImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return newImage } }
mit
5fb4258890f5c7f886a027354628d451
42.375
97
0.652738
4.848303
false
false
false
false
georgievtodor/ios
TV Show Calendar/TV Show Calendar/Data/LocalData.swift
1
2318
import Foundation import UIKit import CoreData class LocalData { let tvShowEntity = "TvShow" func getAll() -> [TvShow] { let tvShows = self.fetch(entityName: tvShowEntity) as? [TvShow] return tvShows ?? [TvShow]() } func save(tvShow: TvShowModelDelegate) { let entity = self.createEntity(for: tvShowEntity) let tvShowToAdd: TvShow = TvShow(entity: entity!, insertInto: self.context) tvShowToAdd.id = tvShow.id tvShowToAdd.name = tvShow.name tvShowToAdd.tvDescription = tvShow.description tvShowToAdd.imagePath = tvShow.imagePath tvShowToAdd.backDropPath = tvShow.backDropPath tvShowToAdd.rating = tvShow.rating self.context.insert(tvShowToAdd) self.appDelegate.saveContext() } var appDelegate: AppDelegate { get { return UIApplication.shared.delegate as! AppDelegate } } var context: NSManagedObjectContext { get { return self.appDelegate.persistentContainer.viewContext } } func checkIfExists(tvShowId id: String) -> Bool { let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: tvShowEntity) fetchRequest.predicate = NSPredicate(format: "id = %@", id) let result = try? self.context.fetch(fetchRequest) as? [TvShow] if(result??.count != 0) { return true } else { return false } } func deleteTvShow(tvShowId id: String) { let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: tvShowEntity) fetchRequest.predicate = NSPredicate(format: "id = %@", id) let result = try? self.context.fetch(fetchRequest) as? [TvShow] result??.forEach { tvShow in self.context.delete(tvShow) } } func createEntity(for entityName: String) -> NSEntityDescription? { return NSEntityDescription.entity(forEntityName: entityName, in: self.context) } func fetch(entityName: String) -> [Any]? { let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: entityName) let data = try? self.context.fetch(fetchRequest) return data } }
mit
b0c26a5f1ef19c70e81cda31396faf50
30.324324
89
0.620362
4.581028
false
false
false
false
li841001/SixGestures_Practice
SixGestureDemo/ViewController.swift
1
7464
// // ViewController.swift // SixGestureDemo // // Created by 李 jia on 15/9/5. // Copyright (c) 2015年 l+. All rights reserved. // import UIKit class ViewController: UIViewController { var scrW = UIScreen.mainScreen().bounds.width var scrH = UIScreen.mainScreen().bounds.height var labTap: ModifyLabel4Present? override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = UIColor.lightGrayColor() tapTesting() swipeRightTesting() swipeLeftTesting() panTesting() longPressTesting() rotationTest() pinchTest() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func tapTesting(){ let tap = UITapGestureRecognizer(target: self, action: "tapShow:") self.view.addGestureRecognizer(tap) } func tapShow(sender: UITapGestureRecognizer){ let animateLabTest=ModifyLabel4Present(position: sender.locationInView(self.view), textinfo: "TAP", backGroundColor: UIColor.yellowColor(), infoColor: UIColor.blackColor()) animateLabTest.frame.size = CGSize(width: 80, height: 80) animateLabTest.center = sender.locationInView(self.view) animateLabTest.layer.cornerRadius = 40 animateLabTest.clipsToBounds = true self.view.addSubview(animateLabTest) //上面创建图层,下面创建动画(动画只做淡出消失),图层出现不做动画处理 UIView.beginAnimations("tapShowOut", context: nil) UIView.setAnimationDelay(0.2) UIView.setAnimationDuration(0.5) animateLabTest.alpha = 0.0 UIView.commitAnimations() } var swipeRight: UISwipeGestureRecognizer? func swipeRightTesting(){ swipeRight = UISwipeGestureRecognizer(target: self, action: "swipeRightShow:") swipeRight!.direction = UISwipeGestureRecognizerDirection.Right self.view.addGestureRecognizer(swipeRight!) swipeRight?.numberOfTouchesRequired = 2 } func swipeRightShow(sender: UISwipeGestureRecognizer){ let swipeRightLab = ModifyLabel4Present(position: sender.locationInView(self.view), textinfo: "RIGHT➡️", backGroundColor: UIColor.magentaColor(), infoColor: UIColor.whiteColor()) swipeRightLab.layer.cornerRadius = 25 swipeRightLab.clipsToBounds = true self.view.addSubview(swipeRightLab) UIView.beginAnimations("swipeRightOut", context: nil) UIView.setAnimationDuration(1.5) swipeRightLab.frame.origin.x = scrW swipeRightLab.alpha = 0.0 UIView.commitAnimations() } var swipeLeft: UISwipeGestureRecognizer? func swipeLeftTesting(){ self.swipeLeft = UISwipeGestureRecognizer(target: self, action: "swipeLeftShow:") self.swipeLeft!.direction = UISwipeGestureRecognizerDirection.Left self.view.addGestureRecognizer(self.swipeLeft!) self.swipeLeft?.numberOfTouchesRequired = 2 } func swipeLeftShow(sender: UISwipeGestureRecognizer){ let swipeLeftLab = ModifyLabel4Present(position: sender.locationInView(self.view), textinfo: "⬅️LEFT", backGroundColor: UIColor.cyanColor(), infoColor: UIColor.whiteColor()) swipeLeftLab.layer.cornerRadius = 25 swipeLeftLab.clipsToBounds = true self.view.addSubview(swipeLeftLab) UIView.beginAnimations("swipeLeftOut", context: nil) UIView.setAnimationDuration(1.5) swipeLeftLab.frame.origin.x = 0-100 swipeLeftLab.alpha = 0.0 UIView.commitAnimations() } func panTesting(){ let pan = UIPanGestureRecognizer(target: self, action: "panShow:") pan.requireGestureRecognizerToFail(swipeLeft!) pan.requireGestureRecognizerToFail(swipeRight!) self.view.addGestureRecognizer(pan) } func panShow(sender: UIPanGestureRecognizer){ let panLab = ModifyLabel4Present(position: sender.locationInView(self.view), textinfo: "拖着走", backGroundColor: UIColor.redColor(), infoColor: UIColor.whiteColor()) panLab.frame.size = CGSize(width: 90, height: 90) panLab.layer.cornerRadius = 45 panLab.clipsToBounds = true self.view.addSubview(panLab) _ = sender.translationInView(self.view).x _ = sender.translationInView(self.view).y //panLab.transform = CGAffineTransformMakeTranslation(transX, transY) UIView.beginAnimations("panFinished", context: nil) UIView.setAnimationDuration(0.3) panLab.alpha = 0.0 UIView.commitAnimations() } func longPressTesting(){ let longPress = UILongPressGestureRecognizer(target: self, action: "longPressShow:") self.view.addGestureRecognizer(longPress) } func longPressShow(sender: UILongPressGestureRecognizer){ let lpLab = ModifyLabel4Present(position: sender.locationInView(self.view), textinfo: "长按", backGroundColor: UIColor.purpleColor(), infoColor: UIColor.whiteColor()) lpLab.frame.size = CGSizeMake(90, 90) lpLab.layer.cornerRadius = 45 lpLab.layer.borderWidth = 5 lpLab.layer.borderColor = UIColor.whiteColor().CGColor lpLab.clipsToBounds = true self.view.addSubview(lpLab) UIView.beginAnimations("longpressShow", context: nil) UIView.setAnimationBeginsFromCurrentState(true) UIView.setAnimationDuration(1) UIView.setAnimationRepeatCount(3) lpLab.alpha = 0.0 UIView.commitAnimations() } var rotation: UIRotationGestureRecognizer? func rotationTest(){ self.rotation = UIRotationGestureRecognizer(target: self, action: "rotateShow:") self.view.addGestureRecognizer(rotation!) } func rotateShow(sender: UIRotationGestureRecognizer){ let rotateLab = ModifyLabel4Present(position: sender.locationInView(self.view), textinfo: "Rotate", backGroundColor: UIColor.orangeColor(), infoColor: UIColor.whiteColor()) self.view.addSubview(rotateLab) rotateLab.transform = CGAffineTransformMakeRotation(sender.rotation) UIView.beginAnimations("rotateShow", context: nil) UIView.setAnimationDuration(0.2) rotateLab.alpha = 0.0 UIView.commitAnimations() } func pinchTest(){ let pinch = UIPinchGestureRecognizer(target: self, action: "pinchShow:") //pinch.requireGestureRecognizerToFail(self.rotation!) self.view.addGestureRecognizer(pinch) } func pinchShow(sender: UIPinchGestureRecognizer){ let pinchLab = ModifyLabel4Present(position: CGPoint(x: scrW/2-50, y: scrH/2-25), textinfo: "PINCH", backGroundColor: UIColor.whiteColor(), infoColor: UIColor.magentaColor()) self.view.addSubview(pinchLab) UIView.animateWithDuration(0.5, delay: 0.01, options: UIViewAnimationOptions.TransitionNone, animations: { () -> Void in //self.view.layer.setAffineTransform(CGAffineTransformMakeScale(sender.scale, sender.scale))//动画时间有待研究 self.view.transform = CGAffineTransformMakeScale(sender.scale, sender.scale) } , completion: { (finished:Bool) -> Void in UIView.animateWithDuration(1, animations: { () -> Void in self.view.layer.setAffineTransform(CGAffineTransformIdentity)//很重要的回复原值的方法 pinchLab.alpha = 0.0 }) }) } }//@end
apache-2.0
f8d9f9c7aedb001cb1454e3f2822a535
45.43038
186
0.698337
4.714653
false
true
false
false
enpitut/SAWARITAI
iOS/PoiPet/Visualizer.swift
2
6571
// // TouchVisualizer.swift // TouchVisualizer // import UIKit final public class Visualizer { // MARK: - Public Variables static public let sharedInstance = Visualizer() private var enabled = false private var config: Configuration! private var touchViews = [TouchView]() private var previousLog = "" // MARK: - Object life cycle private init() { NSNotificationCenter .defaultCenter() .addObserver(self, selector: "orientationDidChangeNotification:", name: UIDeviceOrientationDidChangeNotification, object: nil) NSNotificationCenter .defaultCenter() .addObserver(self, selector: "applicationDidBecomeActiveNotification:", name: UIApplicationDidBecomeActiveNotification, object: nil) UIDevice .currentDevice() .beginGeneratingDeviceOrientationNotifications() warnIfSimulator() } deinit { NSNotificationCenter .defaultCenter() .removeObserver(self) } // MARK: - Helper Functions @objc internal func applicationDidBecomeActiveNotification(notification: NSNotification) { UIApplication.sharedApplication().keyWindow?.swizzle() } @objc internal func orientationDidChangeNotification(notification: NSNotification) { let instance = Visualizer.sharedInstance for touch in instance.touchViews { touch.removeFromSuperview() } } } extension Visualizer { public class func isEnabled() -> Bool { return sharedInstance.enabled } // MARK: - Start and Stop functions public class func start() { start(Configuration()) } public class func start(config: Configuration) { let instance = sharedInstance instance.enabled = true instance.config = config if let window = UIApplication.sharedApplication().keyWindow { for subview in window.subviews { if let subview = subview as? TouchView { subview.removeFromSuperview() } } } } public class func stop() { let instance = sharedInstance instance.enabled = false for touch in instance.touchViews { touch.removeFromSuperview() } } // MARK: - Dequeue and locating TouchViews and handling events private func dequeueTouchView() -> TouchView { var touchView: TouchView? for view in touchViews { if view.superview == nil { touchView = view break } } if touchView == nil { touchView = TouchView() touchViews.append(touchView!) } return touchView! } private func findTouchView(touch: UITouch) -> TouchView? { for view in touchViews { if touch == view.touch { return view } } return nil } public func handleEvent(event: UIEvent) { if event.type != .Touches { return } if !Visualizer.sharedInstance.enabled { return } let keyWindow = UIApplication.sharedApplication().keyWindow! for touch in event.allTouches()! { let phase = touch.phase switch phase { case .Began: let view = dequeueTouchView() view.config = Visualizer.sharedInstance.config view.touch = touch view.beginTouch() view.center = touch.locationInView(keyWindow) keyWindow.addSubview(view) log(touch) case .Moved: if let view = findTouchView(touch) { view.center = touch.locationInView(keyWindow) } log(touch) case .Stationary: log(touch) break case .Ended, .Cancelled: if let view = findTouchView(touch) { UIView.animateWithDuration(0.2, delay: 0.0, options: .AllowUserInteraction, animations: {() -> Void in view.alpha = 0.0 view.endTouch() }, completion: { [unowned self] (finished) -> Void in view.removeFromSuperview() self.log(touch) }) } log(touch) } } } } extension Visualizer { public func warnIfSimulator() { #if (arch(i386) || arch(x86_64)) && os(iOS) print("[TouchVisualizer] Warning: TouchRadius doesn't work on the simulator because it is not possible to read touch radius on it.") #endif } // MARK: - Logging public func log(touch: UITouch) { if !config.showsLog { return } var ti = 0.0 var viewLogs = [[String:String]]() for view in touchViews { var index = "" if view.superview != nil { index = "\(ti)" ++ti } var phase: String! switch touch.phase { case .Began: phase = "B" case .Moved: phase = "M" case .Ended: phase = "E" case .Cancelled: phase = "C" case .Stationary: phase = "S" } let x = String(format: "%.02f", view.center.x) let y = String(format: "%.02f", view.center.y) let center = "(\(x), \(y))" let radius = String(format: "%.02f", touch.majorRadius) viewLogs.append(["index": index, "center": center, "phase": phase, "radius": radius]) } var log = "TV: " for viewLog in viewLogs { /*if count(Int(viewLog["index"]!)) == 0 { continue }*/ let index = viewLog["index"]! let center = viewLog["center"]! let phase = viewLog["phase"]! let radius = viewLog["radius"]! log += "[\(index)]<\(phase)> c:\(center) r:\(radius)\t" } if log == previousLog { return } previousLog = log print(log) } }
gpl-2.0
ad1b38648752a9ef2819f4b5d6569ecb
28.603604
144
0.507229
5.417148
false
false
false
false
raysarebest/Meghann
Bucket Game/bucket-watch Extension/MHPeripheralCommunicationManager.swift
1
5325
// // MHPhoneCommunicationManager.swift // Bucket Game // // Created by Michael Hulet on 3/31/16. // Copyright © 2016 Michael Hulet. All rights reserved. // import Foundation import WatchConnectivity protocol MHPeripheralCommunicationDelegate{ func applicationDidRecieveData(data: [String: AnyObject], responseHandler: (([String: AnyObject]) -> Void)?) -> Void } protocol MHSerializable{ func serialize() -> [String: AnyObject] } private struct MHWaitingMessage{ let data: [String: AnyObject] let replyHandler: (([String: AnyObject]) -> Void) let errorHandler: ((NSError) -> Void)? init(data: [String: AnyObject], replyHandler: (([String: AnyObject]) -> Void), errorHandler: ((NSError) -> Void)? = nil){ self.data = data self.replyHandler = replyHandler self.errorHandler = errorHandler } } let MHDataQueueKey = "MHDataQueueKey" class MHPeripheralCommunicationManager: NSObject, WCSessionDelegate{ //MARK: - Properties static let mainCommunicator = MHPeripheralCommunicationManager() var delegate: MHPeripheralCommunicationDelegate? = nil var session: WCSession?{ get{ #if os(iOS) let condition = WCSession.defaultSession().paired && WCSession.defaultSession().watchAppInstalled #else #if os(watchOS) let condition = true #else let condition = false #endif #endif return WCSession.isSupported() && condition ? WCSession.defaultSession() : nil } } private var messageQueue: [MHWaitingMessage] = [] //MARK: - Public Functions func connect() -> Void{ session?.delegate = self session?.activateSession() if session?.applicationContext[MHDataQueueKey] == nil{ do{ try session?.updateApplicationContext([MHDataQueueKey: []]) } catch let error{ print(error) } } guard #available(iOS 9.3, watchOS 2.2, *) else{ sendWaitingMessages() //FIXME: If I ever add more in the future, I need to go back to making this the else block of an if condition return } } func sendData(data: [String: AnyObject], replyHandler: (([String: AnyObject]) -> Void)? = nil, errorHandler: ((NSError) -> Void)? = nil) -> Void{ guard let session = session else{ return } if session.reachable{ session.sendMessage(data, replyHandler: replyHandler, errorHandler: errorHandler) } else{ if replyHandler != nil{ messageQueue.append(MHWaitingMessage(data: data, replyHandler: replyHandler!, errorHandler: errorHandler)) } else{ do{ try session.updateApplicationContext([MHDataQueueKey: (session.applicationContext[MHDataQueueKey] as! [[String: AnyObject]]) + [data]]) } catch let error{ print(error) } } } } func sendData(data: MHSerializable, replyHandler: (([String: AnyObject]) -> Void)? = nil, errorHandler: ((NSError) -> Void)? = nil) -> Void{ sendData(data.serialize(), replyHandler: replyHandler, errorHandler: errorHandler) } //MARK: - Private Helpers private override init(){ super.init() session?.delegate = self } private func sendWaitingMessages() -> Void{ if !(session?.applicationContext[MHDataQueueKey] as! [[String: AnyObject]]).isEmpty{ for message in (session?.applicationContext[MHDataQueueKey] as! [[String: AnyObject]]){ let condition: Bool if #available(iOS 9.3, watchOS 2.2, *){ condition = session?.activationState == .Activated } else{ condition = true } if condition{ sendData(message) } else{ break } } } } //MARK: - WCSessionDelegate Methods func session(session: WCSession, didReceiveMessage message: [String: AnyObject]) -> Void{ delegate?.applicationDidRecieveData(message, responseHandler: nil) } func session(session: WCSession, didReceiveMessage message: [String: AnyObject], replyHandler: ([String: AnyObject]) -> Void) -> Void{ delegate?.applicationDidRecieveData(message, responseHandler: replyHandler) } func session(session: WCSession, didReceiveUserInfo userInfo: [String: AnyObject]) { delegate?.applicationDidRecieveData(userInfo, responseHandler: nil) } @available(iOS 9.3, watchOS 2.2, *) func session(session: WCSession, activationDidCompleteWithState activationState: WCSessionActivationState, error: NSError?) -> Void{ if activationState == .Activated{ sendWaitingMessages() } } @available(iOS 9.3, *) func sessionDidBecomeInactive(session: WCSession) -> Void{ //Just have to implement it } @available(iOS 9.3, *) func sessionDidDeactivate(session: WCSession) { MHPeripheralCommunicationManager.mainCommunicator.connect() } }
gpl-3.0
56f7425d1cfb4ecc615dd3deacd50cff
37.309353
172
0.603681
4.934198
false
false
false
false
chenzhuanglong/CZLPractice
ZLSPAR/ZLSPAR/Classer/Mine/View/ZLFaceView.swift
1
4081
// // ZLFaceView.swift // ZLSPAR // // Created by yuzeux on 2018/1/26. // Copyright © 2018年 晶石. All rights reserved. // import UIKit //@IBDesignable class ZLFaceView: UIView { // @IBInspectable var scale : CGFloat = 0.9 { didSet { setNeedsDisplay() } } var eyesOpen : Bool = false { didSet { setNeedsDisplay() } } var mouthCurvature: Double = -0.5 { didSet { setNeedsDisplay() } } var lineWidth: CGFloat = 5.0 { didSet { setNeedsDisplay() } } var faceColor : UIColor = UIColor.blue { didSet { setNeedsDisplay() } } @objc func changeScale(byReactingTo pinchRecognizer:UIPinchGestureRecognizer) { switch pinchRecognizer.state { case .changed,.ended: scale *= pinchRecognizer.scale pinchRecognizer.scale = 1 default: break } } //圆脸 view 半径 private var skullRadius:CGFloat { return min(bounds.size.width, bounds.size.height) / 2 * scale } //圆脸 view 中心 private var skullCenter: CGPoint { return CGPoint.init(x: bounds.midX, y: bounds.midY) } private enum Eye { case left case right } private func pathForEye(_ eye: Eye) -> UIBezierPath { func centerOfEye(_ eye: Eye) -> CGPoint { let eyeOffset = skullRadius / Ratios.skullRadiusToEyeOffset var eyeCenter = skullCenter eyeCenter.y -= eyeOffset eyeCenter.x += ((eye == .left) ? -1 : 1) * eyeOffset return eyeCenter } let eyeRadius = skullRadius / Ratios.skullRadiusToEyeRadius let eyeCenter = centerOfEye(eye) let path:UIBezierPath if eyesOpen { path = UIBezierPath(arcCenter: eyeCenter, radius: eyeRadius, startAngle: 0, endAngle: CGFloat.pi * 2, clockwise: true) }else { path = UIBezierPath() path.move(to: CGPoint(x:eyeCenter.x - eyeRadius, y:eyeCenter.y)) path.addLine(to: CGPoint(x: eyeCenter.x + eyeRadius, y: eyeCenter.y)) } path.lineWidth = lineWidth return path } private func pathForMouth() -> UIBezierPath { let mouthWidth = skullRadius / Ratios.skullRadiusToMouthWidth let mouthHeight = skullRadius / Ratios.skullRadiusToMouthHeight let mouthOffset = skullRadius / Ratios.skullRadiusToMouthHeight let mouthRect = CGRect( x: skullCenter.x - mouthWidth / 2, y: skullCenter.y + mouthOffset, width: mouthWidth, height: mouthHeight ) let smileOffset = CGFloat(max(-1,min(mouthCurvature,1))) * mouthRect.height let start = CGPoint(x: mouthRect.minX, y: mouthRect.midY) let end = CGPoint(x: mouthRect.maxX, y: mouthRect.midY) let cp1 = CGPoint(x: start.x + mouthRect.width / 3, y: start.y + smileOffset) let cp2 = CGPoint(x: end.x - mouthRect.width / 3, y: start.y + smileOffset) let path = UIBezierPath() path.move(to: start) path.addCurve(to: end, controlPoint1: cp1, controlPoint2: cp2) path.lineWidth = lineWidth return path } private func pathForSkull() -> UIBezierPath { let path = UIBezierPath(arcCenter: skullCenter, radius: skullRadius, startAngle: 0, endAngle:2 * CGFloat.pi, clockwise: false) //线宽5.0 path.lineWidth = lineWidth return path } override func draw(_ rect: CGRect) { faceColor.set() pathForSkull().stroke() pathForEye(.left).stroke() pathForEye(.right).stroke() pathForMouth().stroke() } private struct Ratios { static let skullRadiusToEyeOffset : CGFloat = 3 static let skullRadiusToEyeRadius : CGFloat = 10 static let skullRadiusToMouthWidth : CGFloat = 1 static let skullRadiusToMouthHeight : CGFloat = 3 static let skullRadiusToMouthOffset : CGFloat = 3 } }
mit
bb25dd58b704fbdf6bb5364c94bd66e4
31.174603
134
0.597928
4.262881
false
false
false
false
googlearchive/science-journal-ios
ScienceJournal/UI/SettingsSwitchCell.swift
1
4781
/* * Copyright 2019 Google LLC. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import UIKit import third_party_objective_c_material_components_ios_components_Typography_Typography /// A settings cell with a title, description and switch. class SettingsSwitchCell: SettingsCell { private enum Metrics { static let switchWidth: CGFloat = { return UISwitch().frame.size.width }() } // MARK: - Properties /// The switch. let aSwitch = UISwitch() /// Calculates the height required to display this view, given the data provided. /// /// - Parameters: /// - width: Maximum width for this view, used to constrain measurements. /// - title: The title string to measure. /// - description: The description string to measure. Optional. /// - Returns: The total height of this view. Ideally, controllers would cache this value as it /// will not change for different instances of this view type. static func height(inWidth width: CGFloat, title: String, description: String?) -> CGFloat { // Constrained width, including padding. let constrainedWidth = width - SettingsCell.Metrics.cellInsets.left - SettingsCell.Metrics.cellInsets.right - SettingsCell.Metrics.innerHorizontalSpacing - Metrics.switchWidth var totalHeight = title.labelHeight(withConstrainedWidth: constrainedWidth, font: SettingsCell.Metrics.textLabelFont) if let description = description { totalHeight += SettingsCell.Metrics.innerVerticalSpacing totalHeight += description.labelHeight(withConstrainedWidth: constrainedWidth, font: SettingsCell.Metrics.descriptionLabelFont) } // Add the vertical padding on top and bottom of the cell. totalHeight += SettingsCell.Metrics.cellInsets.top + SettingsCell.Metrics.cellInsets.bottom return totalHeight } override func layoutSubviews() { super.layoutSubviews() // Measure the label widths given constraints. let labelWidth = contentView.bounds.size.width - SettingsCell.Metrics.cellInsets.left - SettingsCell.Metrics.cellInsets.right - SettingsCell.Metrics.innerHorizontalSpacing - Metrics.switchWidth // Determine the X position for the label and the switch based on RTL status. var labelX = SettingsCell.Metrics.cellInsets.left var switchX = contentView.bounds.size.width - aSwitch.frame.size.width - SettingsCell.Metrics.cellInsets.right if UIApplication.shared.userInterfaceLayoutDirection == .rightToLeft { labelX = contentView.bounds.size.width - labelWidth - SettingsCell.Metrics.cellInsets.right switchX = SettingsCell.Metrics.cellInsets.left } // Lay out the title label first. if let title = titleLabel.text { let titleLabelHeight = title.labelHeight(withConstrainedWidth: labelWidth, font: SettingsCell.Metrics.textLabelFont) titleLabel.frame = CGRect(x: labelX, y: SettingsCell.Metrics.cellInsets.top, width: labelWidth, height: titleLabelHeight) } // Lay out the description label based on the title label. if let description = descriptionLabel.text { let descriptionLabelHeight = description.labelHeight(withConstrainedWidth: labelWidth, font: SettingsCell.Metrics.descriptionLabelFont) descriptionLabel.frame = CGRect(x: titleLabel.frame.minX, y: titleLabel.frame.maxY + SettingsCell.Metrics.innerVerticalSpacing, width: labelWidth, height: descriptionLabelHeight) } // Lay out the switch. aSwitch.frame = CGRect(x: switchX, y: ceil((contentView.bounds.size.height - aSwitch.frame.size.height) / 2), width: aSwitch.frame.size.width, height: aSwitch.frame.size.height) } override func configureView() { super.configureView() contentView.addSubview(aSwitch) } }
apache-2.0
378db2a39ce7ca985c0af50e759d9374
40.215517
97
0.664296
4.888548
false
false
false
false
Fitbit/RxBluetoothKit
ExampleApp/ExampleApp/Screens/CentralServices/CentralServicesViewController.swift
1
3513
import RxBluetoothKit import RxSwift import UIKit class CentralSericesViewController: UITableViewController { init(peripheral: Peripheral, bluetoothProvider: BluetoothProvider) { self.peripheral = peripheral self.bluetoothProvider = bluetoothProvider super.init(nibName: nil, bundle: nil) navigationItem.title = "Peripheral's services" } required init?(coder: NSCoder) { nil } // MARK: - Lifecycle override func viewDidLoad() { super.viewDidLoad() setupBindings() tableView.register(CentralServiceCell.self, forCellReuseIdentifier: CentralServiceCell.reuseId) } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(true) didAppearSubject.onNext(()) } // MARK: - TableView override func numberOfSections(in tableView: UITableView) -> Int { 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { services.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { guard let cell = tableView.dequeueReusableCell(withIdentifier: CentralServiceCell.reuseId, for: indexPath) as? CentralServiceCell else { fatalError("Something went wrong :(") } let service = services[indexPath.row] cell.uuidLabel.text = service.uuid.uuidString cell.isPrimaryLabel.text = "isPrimary: \(service.isPrimary)" cell.characterisicsCountLabel.text = "chcarac. count: \(service.characteristics?.count ?? -1)" return cell } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let service = services[indexPath.row] bluetoothProvider.characteristics(for: service) .subscribe( onSuccess: { [weak self] in self?.pushCharacteristicsController(with: $0) }, onFailure: { [weak self] in AlertPresenter.presentError(with: $0.printable, on: self?.navigationController) } ) .disposed(by: disposeBag) } // MARK: - Private private let peripheral: Peripheral private let bluetoothProvider: BluetoothProvider private let didAppearSubject = PublishSubject<Void>() private let disposeBag = DisposeBag() private var services = [Service]() { didSet { tableView.reloadData() } } private func setupBindings() { didAppearSubject .take(1) .flatMap { [bluetoothProvider, peripheral] in bluetoothProvider.discoveredServices(for: peripheral) } // discovering characterisics can take some time so it might be useful to block UI or show progress bar here, // probably with .do(onSubscribe: { startProgressIndicator() }, onCompleted: { stopProgressIndicator() }) .subscribe( onNext: { [weak self] in self?.services = $0 }, onError: { [weak self] in AlertPresenter.presentError(with: $0.printable, on: self?.navigationController) } ) .disposed(by: disposeBag) } private func pushCharacteristicsController(with characteristics: [Characteristic]) { let controller = CharacteristicsViewController(characteristics: characteristics, bluetoothProvider: bluetoothProvider) navigationController?.pushViewController(controller, animated: true) } }
apache-2.0
b5e28957a88a0dcfef1bfc3119cfdc88
35.59375
144
0.661543
5.282707
false
false
false
false
martinomamic/CarBooking
CarBooking/Controllers/CarsList/CarsListRouter.swift
1
1462
// // CarsListRouter.swift // CarBooking // // Created by Martino Mamic on 29/07/2017. // Copyright © 2017 Martino Mamic. All rights reserved. // import Foundation import UIKit @objc protocol CarListRoutingDelegate { func routeToCarDetails(segue: UIStoryboardSegue) } protocol CarListDataSource { var dataStore: CarListDataStore? { get } } class CarListRouter: NSObject, CarListRoutingDelegate, CarListDataSource { weak var viewController: CarsTableViewController? var dataStore: CarListDataStore? func routeToCarDetails(segue: UIStoryboardSegue) { if let destinationVC = segue.destination as? CarDetailsViewController, let destinationRouter = destinationVC.router, var destinationDS = destinationRouter.dataStore { self.passDataToCarDetails(source: dataStore!, destination: &destinationDS) } } func navigateToCarDetails(source: CarsTableViewController, destination: CarDetailsViewController) { destination.tabBarController?.tabBar.isHidden = true source.show(destination, sender: nil) } func passDataToCarDetails(source: CarListDataStore, destination: inout CarDetailsDataStore) { let selectedRow = viewController?.tableView.indexPathForSelectedRow?.row if let sortedCars = source.cars?.sorted(by: { $0.0.name.lowercased() < $0.1.name.lowercased() }) { destination.car = sortedCars[selectedRow!] } } }
mit
793e4ca9e57500ed7a4d7b277ec0e4e9
31.466667
106
0.720739
4.728155
false
false
false
false
stephenelliott/SparkChamber
SparkChamber/SparkChamberTests/SparkEventDataTests.swift
1
3217
/** * SparkMetaDataTests.swift * SparkChamberTests * * Created by Steve Elliott on 01/27/2016. * Copyright (c) 2016 eBay Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. **/ import XCTest @testable import SparkChamber class SparkEventDataTests: XCTestCase { let object = NSObject() override func setUp() { super.setUp() } override func tearDown() { object.sparkEvents = nil super.tearDown() } func testSparkEvents() { let sparkEvent = SparkEvent(trigger: SparkTriggerType.didAppear, trace: "foo", action: nil) object.sparkEvents = [sparkEvent] let events = object.sparkEvents XCTAssert(events! == [sparkEvent], "Spark events weren't returned after having been set.") } func testSparkEventsWithOtherAssociatedObjectsPresent() { // First, attach an unrelated associated object let foo = "foo" var fooKey = "fooKey" objc_setAssociatedObject(object, &fooKey, foo, objc_AssociationPolicy.OBJC_ASSOCIATION_COPY) // Second, set the spark events for the object let sparkEvent = SparkEvent(trigger: SparkTriggerType.didAppear, trace: "foo", action: nil) object.sparkEvents = [sparkEvent] let events = object.sparkEvents XCTAssert(events! == [sparkEvent], "Spark events weren't returned after having been set.") let otherAasociatedObjects = objc_getAssociatedObject(object, &fooKey) as? String XCTAssert(otherAasociatedObjects == foo, "Other associated objects weren't in place when they shouldn't have been.") } func testNilSparkEvents() { // First, set the spark events for the object let sparkEvent = SparkEvent(trigger: SparkTriggerType.didAppear, trace: "foo", action: nil) object.sparkEvents = [sparkEvent] // Then, nil it out object.sparkEvents = nil let events = object.sparkEvents XCTAssertNil(events, "A nil events object wasn't returned when expected.") } func testNilSparkEventsWithOtherAssociatedObjectsPresent() { // First, attach an unrelated associated object let foo = "foo" var fooKey = "fooKey" objc_setAssociatedObject(object, &fooKey, foo, objc_AssociationPolicy.OBJC_ASSOCIATION_COPY) // Second, set the spark events for the object let sparkEvent = SparkEvent(trigger: SparkTriggerType.didAppear, trace: "foo", action: nil) object.sparkEvents = [sparkEvent] // Then, nil out the spark events object.sparkEvents = nil let events = object.sparkEvents XCTAssertNil(events, "A nil events object wasn't returned when expected.") let otherAasociatedObjects = objc_getAssociatedObject(object, &fooKey) as? String XCTAssert(otherAasociatedObjects == foo, "Other associated objects weren't in place when they shouldn't have been.") } }
apache-2.0
c81976d1082539ce17bd1cf468336b83
33.223404
118
0.738576
3.8026
false
true
false
false
ABTSoftware/SciChartiOSTutorial
v2.x/Tutorials/Swift/SwiftUtil/SCIGenericWrapper.swift
1
7221
// // SCIGenericWrapper.swift // SciChart // // Created by Admin on 31/05/16. // Copyright © 2016 SciChart Ltd. All rights reserved. // /** \addtogroup SCIGenericType * @{ */ import Foundation import SciChart /** @file SCIGenericType */ #if swift(>=3.0) /** * @brief It is wrapper function that constructs SCIGenericType * @code * let generic1 = SCIGeneric(0) * let variable = 1 * let generic2 = SCIGeneric( variable ) * let generic3 = SCIGeneric( NSDate() ) * let doubleVariable = SCIGenericDouble(generic1) * let intVariable = SCIGenericInt(generic2) * let floatVariable = SCIGenericFloat(generic2) * let date = SCIGenericDate(generic3) * let timeIntervalSince1970 = SCIGenericDouble(generic3) * @endcode * @see SCIGenericType */ public protocol SCIGenericInfo { func getInfoType() -> SCIDataType } extension Int16 : SCIGenericInfo { public func getInfoType() -> SCIDataType { return SCIDataType.int16 } } extension Int32 : SCIGenericInfo { public func getInfoType() -> SCIDataType { return SCIDataType.int32 } } extension Int : SCIGenericInfo { public func getInfoType() -> SCIDataType { return SCIDataType.int32 } } extension Int64 : SCIGenericInfo { public func getInfoType() -> SCIDataType { return SCIDataType.int64 } } extension UInt : SCIGenericInfo { public func getInfoType() -> SCIDataType { return SCIDataType.int32 } } extension UInt8 : SCIGenericInfo { public func getInfoType() -> SCIDataType { return SCIDataType.byte } } extension UInt16 : SCIGenericInfo { public func getInfoType() -> SCIDataType { return SCIDataType.int16 } } extension UInt64 : SCIGenericInfo { public func getInfoType() -> SCIDataType { return SCIDataType.int64 } } extension UInt32 : SCIGenericInfo { public func getInfoType() -> SCIDataType { return SCIDataType.int32 } } extension Double : SCIGenericInfo { public func getInfoType() -> SCIDataType { return SCIDataType.double } } extension Float : SCIGenericInfo { public func getInfoType() -> SCIDataType { return SCIDataType.float } } extension Character : SCIGenericInfo { public func getInfoType() -> SCIDataType { return SCIDataType.byte } } extension CChar : SCIGenericInfo { public func getInfoType() -> SCIDataType { return SCIDataType.byte } } extension NSArray : SCIGenericInfo { public func getInfoType() -> SCIDataType { return SCIDataType.array } } extension NSDate : SCIGenericInfo { public func getInfoType() -> SCIDataType { return SCIDataType.dateTime } } extension Date : SCIGenericInfo { public func getInfoType() -> SCIDataType { return SCIDataType.swiftDateTime } } extension UnsafeMutablePointer : SCIGenericInfo { public func getInfoType() -> SCIDataType { if let pointerType = pointee as? SCIGenericInfo { switch pointerType.getInfoType() { case .int16: return SCIDataType.int16Ptr case .int32: return SCIDataType.int32Ptr case .int64: return SCIDataType.int64Ptr case .byte: return SCIDataType.charPtr case .float: return SCIDataType.floatPtr case .double: return SCIDataType.doublePtr default: return SCIDataType.voidPtr } } return SCIDataType.voidPtr } } extension UnsafeMutableRawPointer : SCIGenericInfo { public func getInfoType() -> SCIDataType { return SCIDataType.voidPtr } } public func SCIGeneric<T: SCIGenericInfo>(_ x: T) -> SCIGenericType { var data = x var typeData = data.getInfoType() if typeData == .swiftDateTime { if let date = x as? Date { let timeInterval = date.timeIntervalSince1970 var nsDate = NSDate.init(timeIntervalSince1970: timeInterval) typeData = .dateTime return SCI_constructGenericTypeWithInfo(&nsDate, typeData) } } return SCI_constructGenericTypeWithInfo(&data, typeData) } #else /** @brief It is wrapper function that constructs SCIGenericType @code let generic1 = SCIGeneric(0) let variable = 1 let generic2 = SCIGeneric( variable ) let generic3 = SCIGeneric( NSDate() ) let doubleVariable = SCIGenericDouble(generic1) let intVariable = SCIGenericInt(generic2) let floatVariable = SCIGenericFloat(generic2) let date = SCIGenericDate(generic3) let timeIntervalSince1970 = SCIGenericDouble(generic3) @endcode @see SCIGenericType */ public func SCIGeneric<T>(x: T) -> SCIGenericType { var data = x if x is Double { return SCI_constructGenericTypeWithInfo(&data, SCIDataType.Double) } else if x is Float { return SCI_constructGenericTypeWithInfo(&data, SCIDataType.Float) } else if x is Int32 { return SCI_constructGenericTypeWithInfo(&data, SCIDataType.Int32) } else if x is Int16 { return SCI_constructGenericTypeWithInfo(&data, SCIDataType.Int16) } else if x is Int64 { return SCI_constructGenericTypeWithInfo(&data, SCIDataType.Int64) } else if x is Int8 { return SCI_constructGenericTypeWithInfo(&data, SCIDataType.Byte) } else if x is NSDate { return SCI_constructGenericTypeWithInfo(&data, SCIDataType.DateTime) } else if x is NSArray { return SCI_constructGenericTypeWithInfo(&data, SCIDataType.Array) } else if x is Int { // TODO: implement correct unsigned type handling return SCI_constructGenericTypeWithInfo(&data, SCIDataType.Int32) } else if x is UInt32 { return SCI_constructGenericTypeWithInfo(&data, SCIDataType.Int32) } else if x is UInt16 { return SCI_constructGenericTypeWithInfo(&data, SCIDataType.Int16) } else if x is UInt64 { return SCI_constructGenericTypeWithInfo(&data, SCIDataType.Int64) } else if x is UInt8 { return SCI_constructGenericTypeWithInfo(&data, SCIDataType.Byte) } else if x is UInt { return SCI_constructGenericTypeWithInfo(&data, SCIDataType.Int32) } else { return SCI_constructGenericTypeWithInfo(&data, SCIDataType.None) } } #endif /** @} */
mit
c029b6c973891d2a5963376490b244a8
29.336134
80
0.590582
4.891599
false
false
false
false
KarlWarfel/nutshell-ios
Nutshell/DataModel/NutWorkout.swift
1
1277
// // NutWorkout.swift // Nutshell // // Created by Larry Kenyon on 10/6/15. // Copyright © 2015 Tidepool. All rights reserved. // import Foundation class NutWorkout: NutEventItem { var distance: NSNumber? var duration: NSTimeInterval var calories: NSNumber? init(workout: Workout) { self.distance = workout.distance self.duration = NSTimeInterval(workout.duration ?? 0.0) self.calories = workout.calories super.init(eventItem: workout) } override func prefix() -> String { // Subclass! return "W" } // // MARK: - Overrides // override func copyChanges() { if let workout = eventItem as? Workout { workout.distance = distance workout.duration = duration } super.copyChanges() } override func changed() -> Bool { if let workout = eventItem as? Workout { let currentDistance = workout.distance ?? 0.0 if distance != currentDistance { return true } let currentDuration = workout.duration ?? 0.0 if duration != currentDuration { return true } } return super.changed() } }
bsd-2-clause
34195871e64b6850bd898a37b8b9f247
22.62963
63
0.557994
4.779026
false
false
false
false
el-hoshino/NotAutoLayout
Sources/NotAutoLayout/LayoutMaker/MakerBasics/LayoutPropertyCanStoreCenterType.swift
1
2441
// // LayoutPropertyCanStoreCenterType.swift // NotAutoLayout // // Created by 史翔新 on 2017/11/12. // Copyright © 2017年 史翔新. All rights reserved. // import UIKit public protocol LayoutPropertyCanStoreCenterType: LayoutMakerPropertyType { associatedtype WillSetCenterProperty: LayoutMakerPropertyType func storeCenter(_ center: LayoutElement.Horizontal) -> WillSetCenterProperty } private extension LayoutMaker where Property: LayoutPropertyCanStoreCenterType { func storeCenter(_ center: LayoutElement.Horizontal) -> LayoutMaker<Property.WillSetCenterProperty> { let newProperty = self.didSetProperty.storeCenter(center) let newMaker = self.changintProperty(to: newProperty) return newMaker } } extension LayoutMaker where Property: LayoutPropertyCanStoreCenterType { public func setCenter(to center: Float) -> LayoutMaker<Property.WillSetCenterProperty> { let center = LayoutElement.Horizontal.constant(center) let maker = self.storeCenter(center) return maker } public func setCenter(by center: @escaping (_ property: ViewLayoutGuides) -> Float) -> LayoutMaker<Property.WillSetCenterProperty> { let center = LayoutElement.Horizontal.byParent(center) let maker = self.storeCenter(center) return maker } public func pinCenter(to referenceView: UIView?, with center: @escaping (ViewPinGuides.Horizontal) -> Float) -> LayoutMaker<Property.WillSetCenterProperty> { return self.pinCenter(by: { [weak referenceView] in referenceView }, with: center) } public func pinCenter(by referenceView: @escaping () -> UIView?, with center: @escaping (ViewPinGuides.Horizontal) -> Float) -> LayoutMaker<Property.WillSetCenterProperty> { let center = LayoutElement.Horizontal.byReference(referenceGetter: referenceView, center) let maker = self.storeCenter(center) return maker } } public protocol LayoutPropertyCanStoreCenterToEvaluateFrameType: LayoutPropertyCanStoreCenterType { func evaluateFrame(center: LayoutElement.Horizontal, parameters: IndividualFrameCalculationParameters) -> Rect } extension LayoutPropertyCanStoreCenterToEvaluateFrameType { public func storeCenter(_ center: LayoutElement.Horizontal) -> IndividualProperty.Layout { let layout = IndividualProperty.Layout(frame: { (parameters) -> Rect in return self.evaluateFrame(center: center, parameters: parameters) }) return layout } }
apache-2.0
a5f4bd4c367b3e45aeac1fe97f6328df
26.885057
174
0.768755
4.484288
false
false
false
false
esttorhe/RxSwift
RxExample/RxExample/Examples/TableView/RandomUserAPI.swift
1
2040
// // RandomUserAPI.swift // RxExample // // Created by carlos on 28/5/15. // Copyright (c) 2015 Krunoslav Zaher. All rights reserved. // import Foundation import RxSwift class RandomUserAPI { static let sharedAPI = RandomUserAPI() private init() {} func getExampleUserResultSet() -> Observable<[User]> { let url = NSURL(string: "http://api.randomuser.me/?results=20")! return NSURLSession.sharedSession().rx_JSON(url) >- observeSingleOn(Dependencies.sharedDependencies.backgroundWorkScheduler) >- mapOrDie { json in return castOrFail(json).flatMap { (json: [String: AnyObject]) in return self.parseJSON(json) } } >- observeSingleOn(Dependencies.sharedDependencies.mainScheduler) } private func parseJSON(json: [String: AnyObject]) -> RxResult<[User]> { let results = json["results"] as? [[String: AnyObject]] let users = results?.map { $0["user"] as? [String: AnyObject] } let error = NSError(domain: "UserAPI", code: 0, userInfo: nil) if let users = users { let searchResults: [RxResult<User>] = users.map { user in let name = user?["name"] as? [String: String] let pictures = user?["picture"] as? [String: String] if let firstName = name?["first"], let lastName = name?["last"], let imageURL = pictures?["medium"] { let returnUser = User(firstName: firstName.capitalizedString, lastName: lastName.capitalizedString, imageURL: imageURL) return success(returnUser) } else { return failure(error) } } let values = (searchResults.filter { $0.isSuccess }).map { $0.get() } return success(values) } return failure(error) } }
mit
52bc078f4952da4fe5853584bb0c3fb0
34.189655
117
0.544118
4.857143
false
false
false
false
byu-oit-appdev/ios-byuSuite
byuSuite/Apps/Vending/controller/VendingMapViewController.swift
1
3558
// // VendingMapViewController.swift // byuSuite // // Created by Alex Boswell on 1/3/18. // Copyright © 2018 Brigham Young University. All rights reserved. // import UIKit private let DETAIL_SEGUE_ID = "goToMachineDetail" enum VendingMapType { case allMachines, allMicrowaves, product } class VendingMapViewController: ByuMapViewController2 { @IBOutlet private weak var spinner: UIActivityIndicatorView! var type: VendingMapType! var product: VendingProduct? var item: VendingItem? override func viewDidLoad() { super.viewDidLoad() //Depending on the type, we should load up different data guard let type = type else { return } switch type { case .allMachines: title = "Machines" VendingClient.getAllMachines(callback: { (machines, error) in self.handleResponseWithAnnotations(machines, error: error) }) case .allMicrowaves: title = "Microwaves" VendingClient.getAllMicrowaves(callback: { (microwaves, error) in self.handleResponseWithAnnotations(microwaves, error: error) }) case .product: //change title and product id based on if we have an item or not. let (title, productId) = item != nil ? (item?.name, item?.productId) : (product?.desc, product?.productId) navigationItem.title = title if let productId = productId { VendingClient.getAllMachinesContainingProduct(productId: productId, callback: { (machines, error) in self.handleResponseWithAnnotations(machines, error: error) }) } else { super.displayAlert(error: InvalidModelError.byuError) } } } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) mapView.deselectSelectedAnnotation() } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == DETAIL_SEGUE_ID, let vc = segue.destination as? VendingMachineDetailViewController, let vendingMachine = sender as? VendingMachine { vc.vendingMachine = vendingMachine } } //MARK: MKMapViewDelegate callback func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? { //If this is the user's location, just skip it if annotation.isKind(of: MKUserLocation.self) { return nil } let annotationView = MKPinAnnotationView(annotation: annotation, pinTintColor: MKPinAnnotationView.purplePinColor()) if type == .allMachines { annotationView.rightCalloutAccessoryView = UIButton(type: .detailDisclosure) } else if type == .product { //If there are none of this product in this machine currently, make the annontation red if let vendingMachine = annotation as? VendingMachine, vendingMachine.items.first?.amount == 0 { annotationView.pinTintColor = MKPinAnnotationView.redPinColor() } } return annotationView } func mapView(_ mapView: MKMapView, annotationView view: MKAnnotationView, calloutAccessoryControlTapped control: UIControl) { //Only the allMachines type allows clickable callout if type == .allMachines, let machine = view.annotation as? VendingMachine { performSegue(withIdentifier: DETAIL_SEGUE_ID, sender: machine) } } //MARK: Private Functions private func handleResponseWithAnnotations(_ annotations: [VendingMachine]?, error: ByuError?) { spinner.stopAnimating() if let annotations = annotations { mapView.addAnnotations(annotations) zoomToFitMapAnnotations(includeUserLocation: true, keepByuInFrame: true) } else { super.displayAlert(error: error, title: "Error", message: "The server encountered an error. Please try again later.") } } }
apache-2.0
4b0886c2e278c79e9881e80cf11117fb
32.556604
157
0.743604
4.001125
false
false
false
false
andyshep/CoreDataPlayground
nstableview-core-data.playground/Contents.swift
1
2488
//: Playground - noun: a place where people can play import Cocoa import CoreData import PlaygroundSupport enum CoreDataError: Error { case modelNotFound case modelNotCreated } func createManagedObjectContext() throws -> NSManagedObjectContext { guard let url = Bundle.main.url(forResource: "Model", withExtension: "momd") else { throw CoreDataError.modelNotFound } guard let model = NSManagedObjectModel(contentsOf: url) else { throw CoreDataError.modelNotCreated } let psc = NSPersistentStoreCoordinator(managedObjectModel: model) try psc.addPersistentStore(ofType: NSInMemoryStoreType, configurationName: nil, at: nil, options: nil) let context = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType) context.persistentStoreCoordinator = psc return context } func insertObjectsIntoContext(_ context: NSManagedObjectContext) throws { let names = ["apricot", "nectarine", "grapefruit", "papaya", "peach", "orange"] for name in names { let entity = NSEntityDescription.insertNewObject(forEntityName: "Fruit", into: context) entity.setValue(name, forKey: "name") } try context.save() } class DataSource: NSObject { let context: NSManagedObjectContext init(context: NSManagedObjectContext) { self.context = context super.init() } lazy var arrayController: NSArrayController = { let arrayController = NSArrayController() arrayController.managedObjectContext = self.context arrayController.entityName = "Fruit" arrayController.automaticallyPreparesContent = false arrayController.sortDescriptors = [NSSortDescriptor(key: "name", ascending: true)] return arrayController }() } let identifier = NSUserInterfaceItemIdentifier.init("Name") let column = NSTableColumn(identifier: identifier) column.width = 300 let tableView = NSTableView(frame: CGRect(x: 0, y: 0, width: 230, height: 300)) tableView.addTableColumn(column) tableView.usesAlternatingRowBackgroundColors = true let context = try createManagedObjectContext() try insertObjectsIntoContext(context) let dataSource = DataSource(context: context) column.bind(NSBindingName.value, to: dataSource.arrayController, withKeyPath: "arrangedObjects.name", options: nil) try dataSource.arrayController.fetch(with: nil, merge: false) PlaygroundPage.current.liveView = tableView
mit
90d61e9611cf40ca330e9cfbc8ca3e29
30.493671
115
0.727492
4.995984
false
false
false
false
sketchytech/Aldwych_JSON_Swift
Sources/StringExtensions.swift
2
1525
// // StringExtensions.swift // SaveFile // // Created by Anthony Levings on 06/04/2015. // import Foundation extension String { func nsRangeToRange(range:NSRange) -> Range<String.Index> { return Range(start: advance(self.startIndex, range.location), end: advance(self.startIndex, range.location+range.length)) } public mutating func replaceStringsUsingRegularExpression(expression exp:String, withString:String, options opt:NSMatchingOptions = nil, error err:NSErrorPointer) { let strLength = count(self) if let regexString = NSRegularExpression(pattern: exp, options: nil, error: err) { let st = regexString.stringByReplacingMatchesInString(self, options: opt, range: NSMakeRange(0, strLength), withTemplate: withString) self = st } } public func getMatches(regex: String, options: NSStringCompareOptions?) -> [Range<String.Index>] { var arr = [Range<String.Index>]() var rang = Range(start: self.startIndex, end: self.endIndex) var foundRange:Range<String.Index>? do { foundRange = self.rangeOfString(regex, options: options ?? nil, range: rang, locale: nil) if let a = foundRange { arr.append(a) rang.startIndex = foundRange!.endIndex } } while foundRange != nil return arr } }
mit
253e85577e81213bfafed594070dce66
33.659091
168
0.593443
4.663609
false
false
false
false
airbnb/lottie-ios
Sources/Private/Model/DotLottie/Zip/Data+Compression.swift
2
4994
// // Data+Compression.swift // ZIPFoundation // // Copyright © 2017-2021 Thomas Zoechling, https://www.peakstep.com and the ZIP Foundation project authors. // Released under the MIT License. // // See https://github.com/weichsel/ZIPFoundation/blob/master/LICENSE for license information. // import Foundation #if canImport(zlib) import zlib #endif /// A custom handler that consumes a `Data` object containing partial entry data. /// - Parameters: /// - data: A chunk of `Data` to consume. /// - Throws: Can throw to indicate errors during data consumption. typealias ZipDataCallback = (_ data: Data) throws -> Void /// A custom handler that receives a position and a size that can be used to provide data from an arbitrary source. /// - Parameters: /// - position: The current read position. /// - size: The size of the chunk to provide. /// - Returns: A chunk of `Data`. /// - Throws: Can throw to indicate errors in the data source. typealias ZipDataProvider = (_ position: Int64, _ size: Int) throws -> Data extension Data { enum CompressionError: Error { case invalidStream case corruptedData } /// Decompress the output of `provider` and pass it to `consumer`. /// - Parameters: /// - size: The compressed size of the data to be decompressed. /// - bufferSize: The maximum size of the decompression buffer. /// - provider: A closure that accepts a position and a chunk size. Returns a `Data` chunk. /// - consumer: A closure that processes the result of the decompress operation. /// - Returns: The checksum of the processed content. static func decompress(size: Int64, bufferSize: Int, provider: ZipDataProvider, consumer: ZipDataCallback) throws -> UInt32 { try process( operation: COMPRESSION_STREAM_DECODE, size: size, bufferSize: bufferSize, provider: provider, consumer: consumer) } /// Calculate the `CRC32` checksum of the receiver. /// /// - Parameter checksum: The starting seed. /// - Returns: The checksum calculated from the bytes of the receiver and the starting seed. func crc32(checksum: UInt32) -> UInt32 { #if canImport(zlib) return withUnsafeBytes { bufferPointer in let length = UInt32(count) return UInt32(zlib.crc32(UInt(checksum), bufferPointer.bindMemory(to: UInt8.self).baseAddress, length)) } #else return builtInCRC32(checksum: checksum) #endif } } import Compression extension Data { static func process( operation: compression_stream_operation, size: Int64, bufferSize: Int, provider: ZipDataProvider, consumer: ZipDataCallback) throws -> UInt32 { var crc32 = UInt32(0) let destPointer = UnsafeMutablePointer<UInt8>.allocate(capacity: bufferSize) defer { destPointer.deallocate() } let streamPointer = UnsafeMutablePointer<compression_stream>.allocate(capacity: 1) defer { streamPointer.deallocate() } var stream = streamPointer.pointee var status = compression_stream_init(&stream, operation, COMPRESSION_ZLIB) guard status != COMPRESSION_STATUS_ERROR else { throw CompressionError.invalidStream } defer { compression_stream_destroy(&stream) } stream.src_size = 0 stream.dst_ptr = destPointer stream.dst_size = bufferSize var position: Int64 = 0 var sourceData: Data? repeat { let isExhausted = stream.src_size == 0 if isExhausted { do { sourceData = try provider(position, Int(Swift.min(size - position, Int64(bufferSize)))) position += Int64(stream.prepare(for: sourceData)) } catch { throw error } } if let sourceData = sourceData { sourceData.withUnsafeBytes { rawBufferPointer in if let baseAddress = rawBufferPointer.baseAddress { let pointer = baseAddress.assumingMemoryBound(to: UInt8.self) stream.src_ptr = pointer.advanced(by: sourceData.count - stream.src_size) let flags = sourceData.count < bufferSize ? Int32(COMPRESSION_STREAM_FINALIZE.rawValue) : 0 status = compression_stream_process(&stream, flags) } } if operation == COMPRESSION_STREAM_ENCODE, isExhausted { crc32 = sourceData.crc32(checksum: crc32) } } switch status { case COMPRESSION_STATUS_OK, COMPRESSION_STATUS_END: let outputData = Data(bytesNoCopy: destPointer, count: bufferSize - stream.dst_size, deallocator: .none) try consumer(outputData) if operation == COMPRESSION_STREAM_DECODE { crc32 = outputData.crc32(checksum: crc32) } stream.dst_ptr = destPointer stream.dst_size = bufferSize default: throw CompressionError.corruptedData } } while status == COMPRESSION_STATUS_OK return crc32 } } extension compression_stream { fileprivate mutating func prepare(for sourceData: Data?) -> Int { guard let sourceData = sourceData else { return 0 } src_size = sourceData.count return sourceData.count } }
apache-2.0
ec15e58339d87c05b2d184a2f7d53da9
36.261194
127
0.689165
4.213502
false
false
false
false
zwaldowski/ParksAndRecreation
Swift-2/CustomTruncation.playground/Sources/IntegralRect.swift
1
1044
// // IntegralRect.swift // // Created by Zachary Waldowski on 6/26/15. // Copyright (c) 2015 Zachary Waldowski. Some rights reserved. Licensed under MIT. // import UIKit private func roundUp(value: CGFloat) -> CGFloat { return floor(value + 0.5) } private extension CGFloat { func adjustToScale(scale: CGFloat, @noescape adjustment: CGFloat -> CGFloat) -> CGFloat { guard scale > 1 else { return adjustment(self) } return adjustment(self * scale) / scale } } extension CGRect { func integralizeOutward(scale: CGFloat = UIScreen.mainScreen().scale) -> CGRect { var integralRect = CGRect.zero integralRect.origin.x = minX.adjustToScale(scale, adjustment: roundUp) integralRect.size.width = max(width.adjustToScale(scale, adjustment: ceil), 0) integralRect.origin.y = minY.adjustToScale(scale, adjustment: roundUp) integralRect.size.height = max(height.adjustToScale(scale, adjustment: ceil), 0) return integralRect } }
mit
fc07ebd10e0f611fa2886de3ca3f8dbb
28
93
0.668582
3.954545
false
false
false
false
walmartlabs-asdaios/SwiftPromises
SwiftPromisesDemo/ChainedNetworkCallDemoViewController.swift
1
3575
// // ChainedNetworkCallDemoViewController.swift // SwiftPromises // // Created by Douglas Sjoquist on 3/1/15. // Copyright (c) 2015 Ivy Gulch LLC. All rights reserved. // import UIKit import SwiftPromises class ChainedNetworkCallDemoViewController: BaseDemoViewController { @IBOutlet var url1TextField:UITextField? @IBOutlet var url2TextField:UITextField? @IBOutlet var url3TextField:UITextField? @IBOutlet var url1StatusImageView:UIImageView? @IBOutlet var url2StatusImageView:UIImageView? @IBOutlet var url3StatusImageView:UIImageView? @IBOutlet var finalStatusImageView:UIImageView? @IBOutlet var stopOnErrorSwitch:UISwitch? override func viewWillAppear(animated: Bool) { url1TextField!.text = "http://cnn.com" url2TextField!.text = "http://apple.com" url3TextField!.text = "http://nytimes.com" super.viewWillAppear(animated) } override func clearStatus() { url1StatusImageView!.setStatus(nil) url2StatusImageView!.setStatus(nil) url3StatusImageView!.setStatus(nil) finalStatusImageView!.setStatus(nil) } override func readyToStart() -> Bool { return true } override func start() { clearStatus() clearLog() startActivityIndicator() loadURL1StepPromise().then( { [weak self] value in return .Pending(self!.loadURL2StepPromise()) } ).then( { [weak self] value in return .Pending(self!.loadURL3StepPromise()) }).then( { [weak self] value in self?.log("final success") self?.finalStatusImageView!.setStatus(true) self?.stopActivityIndicator() return .Value(value) }, reject: { [weak self] error in self?.log("final error: \(error)") self?.finalStatusImageView!.setStatus(false) self?.stopActivityIndicator() return .Error(error) }) } func loadURL1StepPromise() -> Promise<NSData> { return loadURLStepPromise(url1TextField!.text, statusImageView:url1StatusImageView!) } func loadURL2StepPromise() -> Promise<NSData> { return loadURLStepPromise(url2TextField!.text, statusImageView:url2StatusImageView!) } func loadURL3StepPromise() -> Promise<NSData> { return loadURLStepPromise(url3TextField!.text, statusImageView:url3StatusImageView!) } func loadURLStepPromise(urlString:String?, statusImageView:UIImageView?) -> Promise<NSData> { let url:NSURL? = (urlString == nil) ? nil : NSURL(string:urlString!) return loadURLPromise(url).then( { [weak self] value in statusImageView?.setStatus(true) self?.log("loaded \(value?.length) bytes from URL \(url)") return .Value(value) }, reject: { [weak self] error in statusImageView?.setStatus(false) var stopOnError = true if let stopOnErrorSwitch = self?.stopOnErrorSwitch { stopOnError = stopOnErrorSwitch.on } if stopOnError { self?.log("Stopping on error while loading URL \(url): \(error)") return .Error(error) } else { self?.log("Ignore error while loading URL \(url): \(error)") return .Value(nil) // don't stop the chain } } ) } }
mit
66c477b1920e4cc3dcd18a8e79ada284
33.047619
97
0.603636
4.837618
false
false
false
false
sergdort/CleanArchitectureRxSwift
NetworkPlatform/Entries/Post+Mapping.swift
1
2290
// // Post+Mapping.swift // CleanArchitectureRxSwift // // Created by Andrey Yastrebov on 10.03.17. // Copyright © 2017 sergdort. All rights reserved. // import Domain extension Post: Identifiable {} extension Post { func toJSON() -> [String: Any] { return [ "body": body, "title": title, "uid": uid, "userId": userId, "createdAt": createdAt ] } } extension Post: Encodable { var encoder: NETPost { return NETPost(with: self) } } final class NETPost: NSObject, NSCoding, DomainConvertibleType { struct Keys { static let body = "body" static let title = "title" static let uid = "uid" static let userId = "userId" static let createdAt = "createdAt" } let body: String let title: String let uid: String let userId: String let createdAt: String init(with domain: Post) { self.body = domain.body self.title = domain.title self.uid = domain.uid self.userId = domain.userId self.createdAt = domain.createdAt } init?(coder aDecoder: NSCoder) { guard let body = aDecoder.decodeObject(forKey: Keys.body) as? String, let title = aDecoder.decodeObject(forKey: Keys.title) as? String, let uid = aDecoder.decodeObject(forKey: Keys.uid) as? String, let userId = aDecoder.decodeObject(forKey: Keys.userId) as? String, let createdAt = aDecoder.decodeObject(forKey: Keys.createdAt) as? String else { return nil } self.body = body self.title = title self.uid = uid self.userId = userId self.createdAt = createdAt } func encode(with aCoder: NSCoder) { aCoder.encode(body, forKey: Keys.body) aCoder.encode(title, forKey: Keys.title) aCoder.encode(uid, forKey: Keys.uid) aCoder.encode(userId, forKey: Keys.userId) aCoder.encode(createdAt, forKey: Keys.createdAt) } func asDomain() -> Post { return Post(body: body, title: title, uid: uid, userId: userId, createdAt: createdAt) } }
mit
c9b5ced58c25ddefe4ef3854a36c3dee
25.929412
84
0.568807
4.310734
false
false
false
false
diegocavalca/Studies
programming/Swift/TaskNote/TaskNote/TaskDetailViewController.swift
1
1795
// // TaskDetailViewController.swift // TaskNote // // Created by Diego Cavalca on 05/05/15. // Copyright (c) 2015 Diego Cavalca. All rights reserved. // import UIKit import CoreData class TaskDetailViewController: UIViewController { var task: Task? = nil @IBOutlet weak var txtDescricao: UITextField! // Instancia do CoreData / Tratamento de erro (ponteiro)... let managedObjectContext = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext var err: NSErrorPointer = nil override func viewDidLoad() { super.viewDidLoad() // Modo edição... if task != nil { txtDescricao.text = task?.desc } } // Criando novo registro na classe Task... func createTask() { // Carregando estrutura da classe Task... let entityDescripition = NSEntityDescription.entityForName("Task", inManagedObjectContext: managedObjectContext!) // Instância de novo registro... let task = Task(entity: entityDescripition!, insertIntoManagedObjectContext: managedObjectContext) // Preenchendo campos... task.desc = txtDescricao.text // Salvando registro... managedObjectContext?.save(self.err) } func editTask() { task?.desc = txtDescricao.text self.managedObjectContext!.save(nil) } @IBAction func saveTask(sender: AnyObject) { // Salvar ação (Edição ou Inclusão...) if task != nil { editTask() } else { createTask() } // Voltar para tela anterior... self.navigationController!.popViewControllerAnimated(true) } }
cc0-1.0
2f44d4d228c06f4bfc1218df7412b7e7
26.075758
121
0.603246
4.67801
false
false
false
false
uphold/uphold-sdk-ios
Tests/UtilTests/MockRequest.swift
1
2552
import Foundation import Mockingjay import UpholdSdk @testable import SwiftClient /// MockRequest test util. public class MockRequest: Request { /// The mock request HTTP status code. let code: Int /// The mock request URL. let mockURL: String = "http://foobar.com" /** Constructor. - parameter body: The request body. - parameter code: The HTTP status code. - parameter errorHandler: The errorHandler method. - parameter headers: The request headers. - parameter method: The HTTP method. */ init(body: String?, code: Int, errorHandler: @escaping (Error) -> Void, headers: [String: String]?, method: String) { self.code = code super.init(method: method, url: mockURL, errorHandler: errorHandler) if let body = body { super.data = body } if let headers = headers { super.headers = headers } } /** Mock response builder method. - parameter request: The mock request. - returns: The mock response. */ func builder(request: NSURLRequest) -> Mockingjay.Response { let response = HTTPURLResponse(url: request.url!, statusCode: self.code, httpVersion: nil, headerFields: self.headers)! guard let body = self.data, let data = body as? String, let content = data.data(using: .utf8) else { return .success(response, nil) } return .success(response, .content(content)) } /** Mock SwiftClient Request class end method. - parameter done: The completion handler. - parameter errorHandler: The error handler. */ public override func end(done: @escaping (SwiftClient.Response) -> Void, onError errorHandler: ((Error) -> Void)? = nil) { let request = NSMutableURLRequest(url: URL(string: self.mockURL)!, cachePolicy: NSURLRequest.CachePolicy.useProtocolCachePolicy, timeoutInterval: TimeInterval(self.timeout)) request.httpMethod = self.method self.headers["content-type"] = "json" switch builder(request: request) { case let .success(response, .content(data)): return done(self.transformer(SwiftClient.Response(response: (response as? HTTPURLResponse)!, request: self, rawData: data))) case let .success(response, .noContent): return done(self.transformer(SwiftClient.Response(response: (response as? HTTPURLResponse)!, request: self, rawData: nil))) default: return } } }
mit
a17dc09c1956f4e80986824062f4b9f8
31.717949
181
0.637539
4.648452
false
false
false
false
netyouli/WHC_Layout
WHC_Layout/示例demo/AutoCellHeightDemo/MyCell.swift
1
3870
// // MyCell.swift // WHC_AutoLayoutKit(Swift) // // Created by WHC on 16/7/10. // Copyright © 2016年 WHC. All rights reserved. // /********************************************************* * gitHub:https://github.com/netyouli/WHC_Layout * * 本人其他优秀开源库:https://github.com/netyouli * *********************************************************/ import UIKit class MyCell: UITableViewCell , UITableViewDataSource, UITableViewDelegate { fileprivate let myImage = UILabel() fileprivate let title = UILabel() fileprivate let content = UILabel() fileprivate let tableView = UITableView() fileprivate var other: UILabel! override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) tableView.delegate = self tableView.dataSource = self tableView.isScrollEnabled = false self.contentView.addSubview(myImage) self.contentView.addSubview(title) self.contentView.addSubview(content) self.contentView.addSubview(tableView) title.text = "WHC"; myImage.textAlignment = .center myImage.backgroundColor = UIColor.orange // 添加约束 title.whc_AutoWidth(left: 10, top: 0, right: 10, height: 30) myImage.whc_Left(10).whc_Top(10, toView: title).whc_Size(40, height: 40) content.whc_Top(10, toView: title) .whc_Left(10, toView: myImage) .whc_Right(10) .whc_HeightAuto() tableView.whc_Top(10, toView: content) .whc_LeftEqual(myImage) .whc_Right(10) .whc_Height(44) // 设置cell子视图内容与底部间隙 self.whc_CellBottomOffset = 10 self.whc_CellTableView = tableView } func setContent(_ content: String, index: Int) -> Void { self.content.text = content myImage.text = String(index) tableView.reloadData() tableView.whc_Height(tableView.contentSize.height) if index < 5 { if other == nil { other = UILabel() other.backgroundColor = UIColor.magenta } other.text = content if !self.contentView.subviews.contains(other) { self.contentView.addSubview(other) // 添加约束 other.whc_ResetConstraints() .whc_Top(10, toView: tableView) .whc_Left(10, toView: myImage) .whc_Right(10) .whc_HeightAuto() } self.whc_CellBottomView = other }else { if other != nil && self.contentView.subviews.contains(other) { other.removeFromSuperview() } self.whc_CellBottomView = tableView } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 3 } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 44 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let identifier = "WHC_AutoLayout" var cell = tableView.dequeueReusableCell(withIdentifier: identifier) if cell == nil { cell = UITableViewCell(style: .default, reuseIdentifier: identifier) } cell?.textLabel?.text = "cell嵌套tableView演示" return cell! } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: false) } }
mit
cd12cfbb8c1ef75d05678c838da294e1
32.619469
100
0.577257
4.577108
false
false
false
false
naebada-dev/swift
language-guide/Tests/language-guideTests/initialization/InitializerDelegationForValueTypesTests.swift
1
2765
import XCTest class InitializerDelegationForValueTypesTests : XCTestCase { override func setUp() { super.setUp(); print("############################"); } override func tearDown() { print("############################"); super.tearDown(); } /* Initializer Delegation for Value Types 이니셜라이저는 인스턴스의 초기화 과정의 일부분을 수행하기 위해 다른 이니셜라이저를 호출할 수 있다. 이것을 intialzer delegation이라고 부른다. 그리고 이 과정은 여러 개의 이니셜라이저에 걸쳐 코드 중복을 피한다. 밸류(Value) 타입은 상속을 지원하지 않기 때문에 비교적 간단하다. 즉, 그들 스스로가 제공하는 다른 이니셜라이저에게만 위임할 수 있다. 밸류 타입에 커스텀 이니셜라이저를 정의했다면, 그 타입에 대한 기본 이니셜라이저(구조체인 경우, 맴버와이즈)를 더 이상 사용되지 않을 것이다. 커스텀 밸류 타입이 기본 이니셜라이저와 맴버와이즈 이니셜라이저와 커스텀 이니셜라이저를 동시에 사용하고 싶다면, 커스텀 이니셜라이저를 확장(extension)에 정의해라. */ func testInitializerDelegationForValueTypes() { // init() let basicRect = Rect() basicRect.debug() //init(origin: Point, size: Size) let originRect = Rect(origin: Point(x: 2.0, y: 2.0), size: Size(width: 5.0, height: 5.0)) originRect.debug() // init(center: Point, size: Size) let centerRect = Rect(center: Point(x: 4.0, y: 4.0), size: Size(width: 3.0, height: 3.0)) centerRect.debug() } private struct Size { var width = 0.0, height = 0.0 func debug() { print("width: \(width), height: \(height)") } } private struct Point { var x = 0.0, y = 0.0 func debug() { print("x: \(x), y: \(y)") } } private struct Rect { var origin = Point() var size = Size() // 기능적으로 기본 이니셜라이저와 동일 init() {} init(origin: Point, size: Size) { self.origin = origin self.size = size } init(center: Point, size: Size) { let originX = center.x - (size.width / 2) let originY = center.y - (size.height / 2) self.init(origin: Point(x: originX, y: originY), size: size) } func debug() { origin.debug() size.debug() } } }
apache-2.0
ab0d8b81922e4aa6b2c8bb4663691564
22.88172
66
0.497073
3.093315
false
false
false
false
dreamsxin/swift
validation-test/compiler_crashers_fixed/00190-swift-constraints-constraintgraph-unbindtypevariable.swift
11
1126
// This source file is part of the Swift.org open source project // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -parse protocol A { typealias B func b(B) } struct X<Y> : A { func b(b: X.Type) { } } protocol A { typealias E } struct B<T : A> { let h: T let i: T.E } protocol C { typealias F func g<T where T.E == F>(f: B<T>) } struct D : C { typealias F = Int func g<T where T.E == F>(f: B<T>) { } } func ^(a: Boolean, Bool) -> Bool { return !(a) } a) func a<b:a struct A<T> { let a: [( th } func prefix(with: String) x1 ool !(a) } func prefix(with: Strin) -> <T>(() -> T) in\ import Foundation class Foo<T>: NSObject { var f<g>() -> (es: Int = { x, f in A.B == D>(e: A.B) { } } protocol a : a { } class a { typealias b = b } func prefi su1ype, ere Optional<T> return !(a) }
apache-2.0
cc643e9da28e5eb376d4cabdf879f9ef
19.107143
78
0.590586
2.836272
false
false
false
false
KrishMunot/swift
test/Interpreter/protocol_extensions.swift
2
5823
// RUN: %target-run-simple-swift | FileCheck %s // REQUIRES: executable_test // Extend a protocol with a property. extension Sequence { final var myCount: Int { var result = 0 for _ in self { result += 1 } return result } } // CHECK: 4 print(["a", "b", "c", "d"].myCount) // Extend a protocol with a function. extension Collection { final var myIndices: Range<Index> { return startIndex..<endIndex } func clone() -> Self { return self } } // CHECK: 4 print(["a", "b", "c", "d"].clone().myCount) extension Collection { final func indexMatching(_ fn: Iterator.Element -> Bool) -> Index? { for i in myIndices { if fn(self[i]) { return i } } return nil } } // CHECK: 2 print(["a", "b", "c", "d"].indexMatching({$0 == "c"})!) // Extend certain instances of a collection (those that have equatable // element types) with another algorithm. extension Collection where Self.Iterator.Element : Equatable { final func myIndexOf(_ element: Iterator.Element) -> Index? { for i in self.indices { if self[i] == element { return i } } return nil } } // CHECK: 3 print(["a", "b", "c", "d", "e"].myIndexOf("d")!) extension Sequence { final public func myEnumerated() -> EnumeratedSequence<Self> { return self.enumerated() } } // CHECK: (0, a) // CHECK-NEXT: (1, b) // CHECK-NEXT: (2, c) for (index, element) in ["a", "b", "c"].myEnumerated() { print("(\(index), \(element))") } extension Sequence { final public func myReduce<T>( _ initial: T, @noescape combine: (T, Self.Iterator.Element) -> T ) -> T { var result = initial for value in self { result = combine(result, value) } return result } } // CHECK: 15 print([1, 2, 3, 4, 5].myReduce(0, combine: +)) extension Sequence { final public func myZip<S : Sequence>(_ s: S) -> Zip2Sequence<Self, S> { return Zip2Sequence(_sequence1: self, _sequence2: s) } } // CHECK: (1, a) // CHECK-NEXT: (2, b) // CHECK-NEXT: (3, c) for (a, b) in [1, 2, 3].myZip(["a", "b", "c"]) { print("(\(a), \(b))") } // Mutating algorithms. extension MutableCollection where Self.Index: RandomAccessIndex, Self.Iterator.Element : Comparable { public final mutating func myPartition() -> Index { return self.partition() } } // CHECK: 4 3 1 2 | 5 9 8 6 7 6 var evenOdd = [5, 3, 6, 2, 4, 9, 8, 1, 7, 6] var evenOddSplit = evenOdd.myPartition() for i in evenOdd.myIndices { if i == evenOddSplit { print(" |", terminator: "") } if i > 0 { print(" ", terminator: "") } print(evenOdd[i], terminator: "") } print("") extension RangeReplaceableCollection { public final func myJoin<S : Sequence where S.Iterator.Element == Self>( _ elements: S ) -> Self { var result = Self() var iter = elements.makeIterator() if let first = iter.next() { result.append(contentsOf: first) while let next = iter.next() { result.append(contentsOf: self) result.append(contentsOf: next) } } return result } } // CHECK: a,b,c print( String( ",".characters.myJoin(["a".characters, "b".characters, "c".characters]) ) ) // Constrained extensions for specific types. extension Collection where Self.Iterator.Element == String { final var myCommaSeparatedList: String { if startIndex == endIndex { return "" } var result = "" var first = true for x in self { if first { first = false } else { result += ", " } result += x } return result } } // CHECK: x, y, z print(["x", "y", "z"].myCommaSeparatedList) // CHECK: {{[tuv], [tuv], [tuv]}} print((["t", "u", "v"] as Set).myCommaSeparatedList) // Existentials protocol ExistP1 { func existP1() } extension ExistP1 { final func runExistP1() { print("runExistP1") self.existP1() } } struct ExistP1_Struct : ExistP1 { func existP1() { print(" - ExistP1_Struct") } } class ExistP1_Class : ExistP1 { func existP1() { print(" - ExistP1_Class") } } // CHECK: runExistP1 // CHECK-NEXT: - ExistP1_Struct var existP1: ExistP1 = ExistP1_Struct() existP1.runExistP1() // CHECK: runExistP1 // CHECK-NEXT: - ExistP1_Class existP1 = ExistP1_Class() existP1.runExistP1() protocol P { mutating func setValue(_ b: Bool) func getValue() -> Bool } extension P { final var extValue: Bool { get { return getValue() } set(newValue) { setValue(newValue) } } } extension Bool : P { mutating func setValue(_ b: Bool) { self = b } func getValue() -> Bool { return self } } class C : P { var theValue: Bool = false func setValue(_ b: Bool) { theValue = b } func getValue() -> Bool { return theValue } } func toggle(_ value: inout Bool) { value = !value } var p: P = true // CHECK: Bool print("Bool") // CHECK: true p.extValue = true print(p.extValue) // CHECK: false p.extValue = false print(p.extValue) // CHECK: true toggle(&p.extValue) print(p.extValue) // CHECK: C print("C") p = C() // CHECK: true p.extValue = true print(p.extValue) // CHECK: false p.extValue = false print(p.extValue) // CHECK: true toggle(&p.extValue) print(p.extValue) // Logical lvalues of existential type. struct HasP { var _p: P var p: P { get { return _p } set { _p = newValue } } } var hasP = HasP(_p: false) // CHECK: true hasP.p.extValue = true print(hasP.p.extValue) // CHECK: false toggle(&hasP.p.extValue) print(hasP.p.extValue) // rdar://problem/20739719 class Super: Init { required init(x: Int) { print("\(x) \(self.dynamicType)") } } class Sub: Super {} protocol Init { init(x: Int) } extension Init { init() { self.init(x: 17) } } // CHECK: 17 Super _ = Super() // CHECK: 17 Sub _ = Sub() // CHECK: 17 Super var sup: Super.Type = Super.self _ = sup.init() // CHECK: 17 Sub sup = Sub.self _ = sup.init() // CHECK: DONE print("DONE")
apache-2.0
89265a56d9bf2d94c4a6fc5edeb3e3f8
18.217822
75
0.613773
3.079323
false
false
false
false
VadimPavlov/Swifty
Sources/Swifty/Common/Codable/MetaArray.swift
1
2115
// // MetaArray.swift // Swifty // // Created by Vadym Pavlov on 10/24/18. // Copyright © 2018 Vadym Pavlov. All rights reserved. // import Foundation public protocol Meta: Codable { associatedtype Element static func metatype(for element: Element) -> Self var type: Decodable.Type { get } init?(rawValue: String) var rawValue: String { get } } public struct MetaArray<M: Meta>: Codable, ExpressibleByArrayLiteral { public let array: [M.Element] public init(_ array: [M.Element]) { self.array = array } public init(arrayLiteral elements: M.Element...) { self.array = elements } struct ElementKey: CodingKey { var stringValue: String init?(stringValue: String) { self.stringValue = stringValue } var intValue: Int? { return nil } init?(intValue: Int) { return nil } } public init(from decoder: Decoder) throws { var container = try decoder.unkeyedContainer() var elements: [M.Element] = [] while !container.isAtEnd { let nested = try container.nestedContainer(keyedBy: ElementKey.self) guard let key = nested.allKeys.first else { continue } let metatype = M(rawValue: key.stringValue) let superDecoder = try nested.superDecoder(forKey: key) let object = try metatype?.type.init(from: superDecoder) if let element = object as? M.Element { elements.append(element) } } array = elements } public func encode(to encoder: Encoder) throws { var container = encoder.unkeyedContainer() try array.forEach { object in var nested = container.nestedContainer(keyedBy: ElementKey.self) let metatype = M.metatype(for: object) if let key = ElementKey(stringValue: metatype.rawValue) { let superEncoder = nested.superEncoder(forKey: key) let encodable = object as? Encodable try encodable?.encode(to: superEncoder) } } } }
mit
01de251e65e41c831d68883bb37df141
28.774648
80
0.607379
4.565875
false
false
false
false
mrdepth/Neocom
Neocom/Neocom/Killboard/zKillboard/ZKillboardSearchForm.swift
2
9425
// // ZKillboardSearchForm.swift // Neocom // // Created by Artem Shimanski on 4/2/20. // Copyright © 2020 Artem Shimanski. All rights reserved. // import SwiftUI import EVEAPI import CoreData private let startDate: Date = { let calendar = Calendar(identifier: .gregorian) return calendar.date(from: DateComponents(year: 2003, month: 5, day: 6))! }() struct ZKillboardSearchForm: View { struct Filter { var from = startDate var to = Date() var pilot: Contact? var location: NSManagedObject? var ship: NSManagedObject? var soloOnly = false var whOnly = false } @EnvironmentObject private var sharedState: SharedState @Environment(\.self) private var environment @State private var filter = Filter() @State private var isContactsPresented = false @State private var isShipPickerPresented = false @State private var isLocationPickerPresented = false private var pilotButton: some View { HStack { Button(action: {self.isContactsPresented = true}) { if filter.pilot != nil { ContactCell(contact: filter.pilot!).contentShape(Rectangle()) } else { HStack { Text("Pilot/Corporation/Alliance") Spacer() Text("Any").foregroundColor(.secondary) }.frame(height: 30).contentShape(Rectangle()) } }.buttonStyle(PlainButtonStyle()) Spacer() if filter.pilot != nil { Button(NSLocalizedString("Clear", comment: "")) { withAnimation { self.filter.pilot = nil } } } } .sheet(isPresented: $isContactsPresented) { NavigationView { ContactPicker { contact in self.filter.pilot = contact self.isContactsPresented = false }.navigationBarItems(leading: BarButtonItems.close { self.isContactsPresented = false }) } .modifier(ServicesViewModifier(environment: self.environment, sharedState: self.sharedState)) .navigationViewStyle(StackNavigationViewStyle()) } } private var shipButton: some View { HStack { Button(action: {self.isShipPickerPresented = true}) { if filter.ship != nil { HStack { if filter.ship is SDEInvType { TypeCell(type: filter.ship as! SDEInvType) } else if filter.ship is SDEInvGroup { GroupCell(group: filter.ship as! SDEInvGroup) } Spacer() }.contentShape(Rectangle()) } else { HStack { Text("Ship") Spacer() Text("Any").foregroundColor(.secondary) }.frame(height: 30).contentShape(Rectangle()) } }.buttonStyle(PlainButtonStyle()) Spacer() if filter.ship != nil { Button(NSLocalizedString("Clear", comment: "")) { withAnimation { self.filter.ship = nil } } } } .sheet(isPresented: $isShipPickerPresented) { NavigationView { ShipPicker { ship in self.filter.ship = ship self.isShipPickerPresented = false }.navigationBarItems(leading: BarButtonItems.close { self.isShipPickerPresented = false }) } .modifier(ServicesViewModifier(environment: self.environment, sharedState: self.sharedState)) .navigationViewStyle(StackNavigationViewStyle()) } } private var locationButton: some View { HStack { Button(action: {self.isLocationPickerPresented = true}) { if filter.location != nil { HStack { if filter.location is SDEMapRegion { Text((filter.location as! SDEMapRegion).regionName ?? "") } else if filter.location is SDEMapSolarSystem { SolarSystemCell(solarSystem: filter.location as! SDEMapSolarSystem) } Spacer() }.contentShape(Rectangle()) } else { HStack { Text("Location") Spacer() Text("Any").foregroundColor(.secondary) }.frame(height: 30).contentShape(Rectangle()) } }.buttonStyle(PlainButtonStyle()) Spacer() if filter.location != nil { Button(NSLocalizedString("Clear", comment: "")) { withAnimation { self.filter.location = nil } } } } .sheet(isPresented: $isLocationPickerPresented) { NavigationView { LocationPicker { location in self.filter.location = location self.isLocationPickerPresented = false }.navigationBarItems(leading: BarButtonItems.close { self.isLocationPickerPresented = false }) } .modifier(ServicesViewModifier(environment: self.environment, sharedState: self.sharedState)) .navigationViewStyle(StackNavigationViewStyle()) } } var wSpaceCell: some View { Toggle(isOn: $filter.whOnly) { Text("W-Space") } } var soloCell: some View { Toggle(isOn: $filter.soloOnly) { Text("Solo") } } var body: some View { let values = filter.values return List { Section(footer: Text("Select at least one modifier")) { pilotButton shipButton if !filter.whOnly { locationButton } if filter.location == nil { wSpaceCell } soloCell DatePicker(selection: $filter.from, in: startDate...filter.to, displayedComponents: .date) { Text("From Date") } DatePicker(selection: $filter.to, in: filter.from...Date(), displayedComponents: .date) { Text("To Date") } } Section { NavigationLink(NSLocalizedString("Kills", comment: ""), destination: ZKillboardSearchResults(filter: values + [.kills])) NavigationLink(NSLocalizedString("Losses", comment: ""), destination: ZKillboardSearchResults(filter: values + [.losses])) }.disabled(values.isEmpty) } .listStyle(GroupedListStyle()) .navigationBarTitle(Text("zKillboard")) } } extension ZKillboardSearchForm.Filter { var values: [ZKillboard.Filter] { var values = [ZKillboard.Filter]() if let pilot = pilot { switch pilot.recipientType { case .character?: values.append(.characterID([pilot.contactID])) case .corporation?: values.append(.corporationID([pilot.contactID])) case .alliance?: values.append(.allianceID([pilot.contactID])) default: break } } switch ship { case let type as SDEInvType: values.append(.shipTypeID([Int(type.typeID)])) case let group as SDEInvGroup: values.append(.groupID([Int(group.groupID)])) default: break } switch location { case let solarSystem as SDEMapSolarSystem: values.append(.solarSystemID([Int(solarSystem.solarSystemID)])) case let region as SDEMapRegion: values.append(.regionID([Int(region.regionID)])) default: break } if soloOnly { values.append(.solo) } if whOnly && location == nil { values.append(.wSpace) } let calendar = Calendar(identifier: .gregorian) let components = calendar.dateComponents([.year, .month, .day], from: Date()) let endDate = calendar.date(from: components)! if from > startDate { values.append(.startTime(from)) } if to < endDate { values.append(.endTime(to)) } return values } } #if DEBUG struct ZKillboardSearchForm_Previews: PreviewProvider { static var previews: some View { NavigationView { ZKillboardSearchForm() } .modifier(ServicesViewModifier.testModifier()) } } #endif
lgpl-2.1
6713a4c702ede93c04b3924ae3ceb41f
33.021661
138
0.499576
5.663462
false
false
false
false
bumpersfm/handy
Handy/UILayoutGuide.swift
1
991
// // Created by Dani Postigo on 11/25/16. // import Foundation import UIKit extension UILayoutGuide { public func anchor(withSubview view: UIView, insets: UIEdgeInsets? = nil) { view.preservesSuperviewLayoutMargins = true self.anchor(toViewFrame: view) } public func anchor(toViewFrame view: UIView, insets: UIEdgeInsets? = nil) { NSLayoutConstraint.activateConstraints([ self.leadingAnchor.constraintEqualToAnchor(view.leadingAnchor), self.trailingAnchor.constraintEqualToAnchor(view.trailingAnchor), self.topAnchor.constraintEqualToAnchor(view.topAnchor), self.bottomAnchor.constraintEqualToAnchor(view.bottomAnchor), ]) } } extension UIView { public func anchor(view: UIView, layoutMargins margins: UIEdgeInsets? = nil) { self.addView(view) self.layoutMargins = margins ?? self.layoutMargins self.layoutMarginsGuide.anchor(withSubview: view) } }
mit
946dd911c50f49affbec8ef68b785cad
30.967742
82
0.695257
5.030457
false
false
false
false
xwu/swift
stdlib/public/core/Builtin.swift
1
36585
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// import SwiftShims // Definitions that make elements of Builtin usable in real code // without gobs of boilerplate. // This function is the implementation of the `_roundUp` overload set. It is // marked `@inline(__always)` to make primary `_roundUp` entry points seem // cheap enough for the inliner. @inlinable @inline(__always) internal func _roundUpImpl(_ offset: UInt, toAlignment alignment: Int) -> UInt { _internalInvariant(alignment > 0) _internalInvariant(_isPowerOf2(alignment)) // Note, given that offset is >= 0, and alignment > 0, we don't // need to underflow check the -1, as it can never underflow. let x = offset + UInt(bitPattern: alignment) &- 1 // Note, as alignment is a power of 2, we'll use masking to efficiently // get the aligned value return x & ~(UInt(bitPattern: alignment) &- 1) } @inlinable internal func _roundUp(_ offset: UInt, toAlignment alignment: Int) -> UInt { return _roundUpImpl(offset, toAlignment: alignment) } @inlinable internal func _roundUp(_ offset: Int, toAlignment alignment: Int) -> Int { _internalInvariant(offset >= 0) return Int(_roundUpImpl(UInt(bitPattern: offset), toAlignment: alignment)) } /// Returns a tri-state of 0 = no, 1 = yes, 2 = maybe. @_transparent public // @testable func _canBeClass<T>(_: T.Type) -> Int8 { return Int8(Builtin.canBeClass(T.self)) } /// Returns the bits of the given instance, interpreted as having the specified /// type. /// /// Use this function only to convert the instance passed as `x` to a /// layout-compatible type when conversion through other means is not /// possible. Common conversions supported by the Swift standard library /// include the following: /// /// - Value conversion from one integer type to another. Use the destination /// type's initializer or the `numericCast(_:)` function. /// - Bitwise conversion from one integer type to another. Use the destination /// type's `init(truncatingIfNeeded:)` or `init(bitPattern:)` initializer. /// - Conversion from a pointer to an integer value with the bit pattern of the /// pointer's address in memory, or vice versa. Use the `init(bitPattern:)` /// initializer for the destination type. /// - Casting an instance of a reference type. Use the casting operators (`as`, /// `as!`, or `as?`) or the `unsafeDowncast(_:to:)` function. Do not use /// `unsafeBitCast(_:to:)` with class or pointer types; doing so may /// introduce undefined behavior. /// /// - Warning: Calling this function breaks the guarantees of the Swift type /// system; use with extreme care. /// /// - Parameters: /// - x: The instance to cast to `type`. /// - type: The type to cast `x` to. `type` and the type of `x` must have the /// same size of memory representation and compatible memory layout. /// - Returns: A new instance of type `U`, cast from `x`. @inlinable // unsafe-performance @_transparent public func unsafeBitCast<T, U>(_ x: T, to type: U.Type) -> U { _precondition(MemoryLayout<T>.size == MemoryLayout<U>.size, "Can't unsafeBitCast between types of different sizes") return Builtin.reinterpretCast(x) } /// Returns `x` as its concrete type `U`. /// /// This cast can be useful for dispatching to specializations of generic /// functions. /// /// - Requires: `x` has type `U`. @_transparent public func _identityCast<T, U>(_ x: T, to expectedType: U.Type) -> U { _precondition(T.self == expectedType, "_identityCast to wrong type") return Builtin.reinterpretCast(x) } /// `unsafeBitCast` something to `AnyObject`. @usableFromInline @_transparent internal func _reinterpretCastToAnyObject<T>(_ x: T) -> AnyObject { return unsafeBitCast(x, to: AnyObject.self) } @usableFromInline @_transparent internal func == ( lhs: Builtin.NativeObject, rhs: Builtin.NativeObject ) -> Bool { return unsafeBitCast(lhs, to: Int.self) == unsafeBitCast(rhs, to: Int.self) } @usableFromInline @_transparent internal func != ( lhs: Builtin.NativeObject, rhs: Builtin.NativeObject ) -> Bool { return !(lhs == rhs) } @usableFromInline @_transparent internal func == ( lhs: Builtin.RawPointer, rhs: Builtin.RawPointer ) -> Bool { return unsafeBitCast(lhs, to: Int.self) == unsafeBitCast(rhs, to: Int.self) } @usableFromInline @_transparent internal func != (lhs: Builtin.RawPointer, rhs: Builtin.RawPointer) -> Bool { return !(lhs == rhs) } /// Returns a Boolean value indicating whether two types are identical. /// /// - Parameters: /// - t0: A type to compare. /// - t1: Another type to compare. /// - Returns: `true` if both `t0` and `t1` are `nil` or if they represent the /// same type; otherwise, `false`. @inlinable public func == (t0: Any.Type?, t1: Any.Type?) -> Bool { switch (t0, t1) { case (.none, .none): return true case let (.some(ty0), .some(ty1)): return Bool(Builtin.is_same_metatype(ty0, ty1)) default: return false } } /// Returns a Boolean value indicating whether two types are not identical. /// /// - Parameters: /// - t0: A type to compare. /// - t1: Another type to compare. /// - Returns: `true` if one, but not both, of `t0` and `t1` are `nil`, or if /// they represent different types; otherwise, `false`. @inlinable public func != (t0: Any.Type?, t1: Any.Type?) -> Bool { return !(t0 == t1) } /// Tell the optimizer that this code is unreachable if condition is /// known at compile-time to be true. If condition is false, or true /// but not a compile-time constant, this call has no effect. @usableFromInline @_transparent internal func _unreachable(_ condition: Bool = true) { if condition { // FIXME: use a parameterized version of Builtin.unreachable when // <rdar://problem/16806232> is closed. Builtin.unreachable() } } /// Tell the optimizer that this code is unreachable if this builtin is /// reachable after constant folding build configuration builtins. @usableFromInline @_transparent internal func _conditionallyUnreachable() -> Never { Builtin.conditionallyUnreachable() } @usableFromInline @_silgen_name("_swift_isClassOrObjCExistentialType") internal func _swift_isClassOrObjCExistentialType<T>(_ x: T.Type) -> Bool /// Returns `true` iff `T` is a class type or an `@objc` existential such as /// `AnyObject`. @inlinable @inline(__always) internal func _isClassOrObjCExistential<T>(_ x: T.Type) -> Bool { switch _canBeClass(x) { // Is not a class. case 0: return false // Is a class. case 1: return true // Maybe a class. default: return _swift_isClassOrObjCExistentialType(x) } } /// Converts a reference of type `T` to a reference of type `U` after /// unwrapping one level of Optional. /// /// Unwrapped `T` and `U` must be convertible to AnyObject. They may /// be either a class or a class protocol. Either T, U, or both may be /// optional references. @_transparent public func _unsafeReferenceCast<T, U>(_ x: T, to: U.Type) -> U { return Builtin.castReference(x) } /// Returns the given instance cast unconditionally to the specified type. /// /// The instance passed as `x` must be an instance of type `T`. /// /// Use this function instead of `unsafeBitcast(_:to:)` because this function /// is more restrictive and still performs a check in debug builds. In -O /// builds, no test is performed to ensure that `x` actually has the dynamic /// type `T`. /// /// - Warning: This function trades safety for performance. Use /// `unsafeDowncast(_:to:)` only when you are confident that `x is T` always /// evaluates to `true`, and only after `x as! T` has proven to be a /// performance problem. /// /// - Parameters: /// - x: An instance to cast to type `T`. /// - type: The type `T` to which `x` is cast. /// - Returns: The instance `x`, cast to type `T`. @_transparent public func unsafeDowncast<T: AnyObject>(_ x: AnyObject, to type: T.Type) -> T { _debugPrecondition(x is T, "invalid unsafeDowncast") return Builtin.castReference(x) } @_transparent public func _unsafeUncheckedDowncast<T: AnyObject>(_ x: AnyObject, to type: T.Type) -> T { _internalInvariant(x is T, "invalid unsafeDowncast") return Builtin.castReference(x) } @inlinable @inline(__always) public func _getUnsafePointerToStoredProperties(_ x: AnyObject) -> UnsafeMutableRawPointer { let storedPropertyOffset = _roundUp( MemoryLayout<SwiftShims.HeapObject>.size, toAlignment: MemoryLayout<Optional<AnyObject>>.alignment) return UnsafeMutableRawPointer(Builtin.bridgeToRawPointer(x)) + storedPropertyOffset } /// Get the minimum alignment for manually allocated memory. /// /// Memory allocated via UnsafeMutable[Raw][Buffer]Pointer must never pass /// an alignment less than this value to Builtin.allocRaw. This /// ensures that the memory can be deallocated without specifying the /// alignment. @inlinable @inline(__always) internal func _minAllocationAlignment() -> Int { return _swift_MinAllocationAlignment } //===----------------------------------------------------------------------===// // Branch hints //===----------------------------------------------------------------------===// // Use @_semantics to indicate that the optimizer recognizes the // semantics of these function calls. This won't be necessary with // mandatory generic inlining. /// Optimizer hint that `x` is expected to be `true`. @_transparent @_semantics("fastpath") public func _fastPath(_ x: Bool) -> Bool { return Bool(Builtin.int_expect_Int1(x._value, true._value)) } /// Optimizer hint that `x` is expected to be `false`. @_transparent @_semantics("slowpath") public func _slowPath(_ x: Bool) -> Bool { return Bool(Builtin.int_expect_Int1(x._value, false._value)) } /// Optimizer hint that the code where this function is called is on the fast /// path. @_transparent public func _onFastPath() { Builtin.onFastPath() } // Optimizer hint that the condition is true. The condition is unchecked. // The builtin acts as an opaque instruction with side-effects. @usableFromInline @_transparent func _uncheckedUnsafeAssume(_ condition: Bool) { _ = Builtin.assume_Int1(condition._value) } //===--- Runtime shim wrappers --------------------------------------------===// /// Returns `true` iff the class indicated by `theClass` uses native /// Swift reference-counting. #if _runtime(_ObjC) // Declare it here instead of RuntimeShims.h, because we need to specify // the type of argument to be AnyClass. This is currently not possible // when using RuntimeShims.h @usableFromInline @_silgen_name("_swift_objcClassUsesNativeSwiftReferenceCounting") internal func _usesNativeSwiftReferenceCounting(_ theClass: AnyClass) -> Bool /// Returns the class of a non-tagged-pointer Objective-C object @_effects(readonly) @_silgen_name("_swift_classOfObjCHeapObject") internal func _swift_classOfObjCHeapObject(_ object: AnyObject) -> AnyClass #else @inlinable @inline(__always) internal func _usesNativeSwiftReferenceCounting(_ theClass: AnyClass) -> Bool { return true } #endif @usableFromInline @_silgen_name("_swift_getSwiftClassInstanceExtents") internal func getSwiftClassInstanceExtents(_ theClass: AnyClass) -> (negative: UInt, positive: UInt) @usableFromInline @_silgen_name("_swift_getObjCClassInstanceExtents") internal func getObjCClassInstanceExtents(_ theClass: AnyClass) -> (negative: UInt, positive: UInt) @inlinable @inline(__always) internal func _class_getInstancePositiveExtentSize(_ theClass: AnyClass) -> Int { #if _runtime(_ObjC) return Int(getObjCClassInstanceExtents(theClass).positive) #else return Int(getSwiftClassInstanceExtents(theClass).positive) #endif } #if INTERNAL_CHECKS_ENABLED && COW_CHECKS_ENABLED @usableFromInline @_silgen_name("_swift_isImmutableCOWBuffer") internal func _swift_isImmutableCOWBuffer(_ object: AnyObject) -> Bool @usableFromInline @_silgen_name("_swift_setImmutableCOWBuffer") internal func _swift_setImmutableCOWBuffer(_ object: AnyObject, _ immutable: Bool) -> Bool #endif @inlinable internal func _isValidAddress(_ address: UInt) -> Bool { // TODO: define (and use) ABI max valid pointer value return address >= _swift_abi_LeastValidPointerValue } //===--- Builtin.BridgeObject ---------------------------------------------===// // TODO(<rdar://problem/34837023>): Get rid of superfluous UInt constructor // calls @inlinable internal var _bridgeObjectTaggedPointerBits: UInt { @inline(__always) get { return UInt(_swift_BridgeObject_TaggedPointerBits) } } @inlinable internal var _objCTaggedPointerBits: UInt { @inline(__always) get { return UInt(_swift_abi_ObjCReservedBitsMask) } } @inlinable internal var _objectPointerSpareBits: UInt { @inline(__always) get { return UInt(_swift_abi_SwiftSpareBitsMask) & ~_bridgeObjectTaggedPointerBits } } @inlinable internal var _objectPointerLowSpareBitShift: UInt { @inline(__always) get { _internalInvariant(_swift_abi_ObjCReservedLowBits < 2, "num bits now differs from num-shift-amount, new platform?") return UInt(_swift_abi_ObjCReservedLowBits) } } #if arch(i386) || arch(arm) || arch(wasm32) || arch(powerpc64) || arch( powerpc64le) || arch(s390x) || arch(arm64_32) @inlinable internal var _objectPointerIsObjCBit: UInt { @inline(__always) get { return 0x0000_0002 } } #else @inlinable internal var _objectPointerIsObjCBit: UInt { @inline(__always) get { return 0x4000_0000_0000_0000 } } #endif /// Extract the raw bits of `x`. @inlinable @inline(__always) internal func _bitPattern(_ x: Builtin.BridgeObject) -> UInt { return UInt(Builtin.castBitPatternFromBridgeObject(x)) } /// Extract the raw spare bits of `x`. @inlinable @inline(__always) internal func _nonPointerBits(_ x: Builtin.BridgeObject) -> UInt { return _bitPattern(x) & _objectPointerSpareBits } @inlinable @inline(__always) internal func _isObjCTaggedPointer(_ x: AnyObject) -> Bool { return (Builtin.reinterpretCast(x) & _objCTaggedPointerBits) != 0 } @inlinable @inline(__always) internal func _isObjCTaggedPointer(_ x: UInt) -> Bool { return (x & _objCTaggedPointerBits) != 0 } /// TODO: describe extras @inlinable @inline(__always) public // FIXME func _isTaggedObject(_ x: Builtin.BridgeObject) -> Bool { return _bitPattern(x) & _bridgeObjectTaggedPointerBits != 0 } @inlinable @inline(__always) public // FIXME func _isNativePointer(_ x: Builtin.BridgeObject) -> Bool { return ( _bitPattern(x) & (_bridgeObjectTaggedPointerBits | _objectPointerIsObjCBit) ) == 0 } @inlinable @inline(__always) public // FIXME func _isNonTaggedObjCPointer(_ x: Builtin.BridgeObject) -> Bool { return !_isTaggedObject(x) && !_isNativePointer(x) } @inlinable @inline(__always) func _getNonTagBits(_ x: Builtin.BridgeObject) -> UInt { // Zero out the tag bits, and leave them all at the top. _internalInvariant(_isTaggedObject(x), "not tagged!") return (_bitPattern(x) & ~_bridgeObjectTaggedPointerBits) >> _objectPointerLowSpareBitShift } // Values -> BridgeObject @inline(__always) @inlinable public func _bridgeObject(fromNative x: AnyObject) -> Builtin.BridgeObject { _internalInvariant(!_isObjCTaggedPointer(x)) let object = Builtin.castToBridgeObject(x, 0._builtinWordValue) _internalInvariant(_isNativePointer(object)) return object } @inline(__always) @inlinable public func _bridgeObject( fromNonTaggedObjC x: AnyObject ) -> Builtin.BridgeObject { _internalInvariant(!_isObjCTaggedPointer(x)) let object = _makeObjCBridgeObject(x) _internalInvariant(_isNonTaggedObjCPointer(object)) return object } @inline(__always) @inlinable public func _bridgeObject(fromTagged x: UInt) -> Builtin.BridgeObject { _internalInvariant(x & _bridgeObjectTaggedPointerBits != 0) let object: Builtin.BridgeObject = Builtin.valueToBridgeObject(x._value) _internalInvariant(_isTaggedObject(object)) return object } @inline(__always) @inlinable public func _bridgeObject(taggingPayload x: UInt) -> Builtin.BridgeObject { let shifted = x &<< _objectPointerLowSpareBitShift _internalInvariant(x == (shifted &>> _objectPointerLowSpareBitShift), "out-of-range: limited bit range requires some zero top bits") _internalInvariant(shifted & _bridgeObjectTaggedPointerBits == 0, "out-of-range: post-shift use of tag bits") return _bridgeObject(fromTagged: shifted | _bridgeObjectTaggedPointerBits) } // BridgeObject -> Values @inline(__always) @inlinable public func _bridgeObject(toNative x: Builtin.BridgeObject) -> AnyObject { _internalInvariant(_isNativePointer(x)) return Builtin.castReferenceFromBridgeObject(x) } @inline(__always) @inlinable public func _bridgeObject( toNonTaggedObjC x: Builtin.BridgeObject ) -> AnyObject { _internalInvariant(_isNonTaggedObjCPointer(x)) return Builtin.castReferenceFromBridgeObject(x) } @inline(__always) @inlinable public func _bridgeObject(toTagged x: Builtin.BridgeObject) -> UInt { _internalInvariant(_isTaggedObject(x)) let bits = _bitPattern(x) _internalInvariant(bits & _bridgeObjectTaggedPointerBits != 0) return bits } @inline(__always) @inlinable public func _bridgeObject(toTagPayload x: Builtin.BridgeObject) -> UInt { return _getNonTagBits(x) } @inline(__always) @inlinable public func _bridgeObject( fromNativeObject x: Builtin.NativeObject ) -> Builtin.BridgeObject { return _bridgeObject(fromNative: _nativeObject(toNative: x)) } // // NativeObject // @inlinable @inline(__always) public func _nativeObject(fromNative x: AnyObject) -> Builtin.NativeObject { _internalInvariant(!_isObjCTaggedPointer(x)) let native = Builtin.unsafeCastToNativeObject(x) // _internalInvariant(native == Builtin.castToNativeObject(x)) return native } @inlinable @inline(__always) public func _nativeObject( fromBridge x: Builtin.BridgeObject ) -> Builtin.NativeObject { return _nativeObject(fromNative: _bridgeObject(toNative: x)) } @inlinable @inline(__always) public func _nativeObject(toNative x: Builtin.NativeObject) -> AnyObject { return Builtin.castFromNativeObject(x) } // FIXME extension ManagedBufferPointer { // FIXME: String Guts @inline(__always) @inlinable public init(_nativeObject buffer: Builtin.NativeObject) { self._nativeBuffer = buffer } } /// Create a `BridgeObject` around the given `nativeObject` with the /// given spare bits. /// /// Reference-counting and other operations on this /// object will have access to the knowledge that it is native. /// /// - Precondition: `bits & _objectPointerIsObjCBit == 0`, /// `bits & _objectPointerSpareBits == bits`. @inlinable @inline(__always) internal func _makeNativeBridgeObject( _ nativeObject: AnyObject, _ bits: UInt ) -> Builtin.BridgeObject { _internalInvariant( (bits & _objectPointerIsObjCBit) == 0, "BridgeObject is treated as non-native when ObjC bit is set" ) return _makeBridgeObject(nativeObject, bits) } /// Create a `BridgeObject` around the given `objCObject`. @inlinable @inline(__always) public // @testable func _makeObjCBridgeObject( _ objCObject: AnyObject ) -> Builtin.BridgeObject { return _makeBridgeObject( objCObject, _isObjCTaggedPointer(objCObject) ? 0 : _objectPointerIsObjCBit) } /// Create a `BridgeObject` around the given `object` with the /// given spare bits. /// /// - Precondition: /// /// 1. `bits & _objectPointerSpareBits == bits` /// 2. if `object` is a tagged pointer, `bits == 0`. Otherwise, /// `object` is either a native object, or `bits == /// _objectPointerIsObjCBit`. @inlinable @inline(__always) internal func _makeBridgeObject( _ object: AnyObject, _ bits: UInt ) -> Builtin.BridgeObject { _internalInvariant(!_isObjCTaggedPointer(object) || bits == 0, "Tagged pointers cannot be combined with bits") _internalInvariant( _isObjCTaggedPointer(object) || _usesNativeSwiftReferenceCounting(type(of: object)) || bits == _objectPointerIsObjCBit, "All spare bits must be set in non-native, non-tagged bridge objects" ) _internalInvariant( bits & _objectPointerSpareBits == bits, "Can't store non-spare bits into Builtin.BridgeObject") return Builtin.castToBridgeObject( object, bits._builtinWordValue ) } @_silgen_name("_swift_class_getSuperclass") internal func _swift_class_getSuperclass(_ t: AnyClass) -> AnyClass? /// Returns the superclass of `t`, if any. The result is `nil` if `t` is /// a root class or class protocol. public func _getSuperclass(_ t: AnyClass) -> AnyClass? { return _swift_class_getSuperclass(t) } /// Returns the superclass of `t`, if any. The result is `nil` if `t` is /// not a class, is a root class, or is a class protocol. @inlinable @inline(__always) public // @testable func _getSuperclass(_ t: Any.Type) -> AnyClass? { return (t as? AnyClass).flatMap { _getSuperclass($0) } } //===--- Builtin.IsUnique -------------------------------------------------===// // _isUnique functions must take an inout object because they rely on // Builtin.isUnique which requires an inout reference to preserve // source-level copies in the presence of ARC optimization. // // Taking an inout object makes sense for two additional reasons: // // 1. You should only call it when about to mutate the object. // Doing so otherwise implies a race condition if the buffer is // shared across threads. // // 2. When it is not an inout function, self is passed by // value... thus bumping the reference count and disturbing the // result we are trying to observe, Dr. Heisenberg! // // _isUnique cannot be made public or the compiler // will attempt to generate generic code for the transparent function // and type checking will fail. /// Returns `true` if `object` is uniquely referenced. @usableFromInline @_transparent internal func _isUnique<T>(_ object: inout T) -> Bool { return Bool(Builtin.isUnique(&object)) } /// Returns `true` if `object` is uniquely referenced. /// This provides sanity checks on top of the Builtin. @_transparent public // @testable func _isUnique_native<T>(_ object: inout T) -> Bool { // This could be a bridge object, single payload enum, or plain old // reference. Any case it's non pointer bits must be zero, so // force cast it to BridgeObject and check the spare bits. _internalInvariant( (_bitPattern(Builtin.reinterpretCast(object)) & _objectPointerSpareBits) == 0) _internalInvariant(_usesNativeSwiftReferenceCounting( type(of: Builtin.reinterpretCast(object) as AnyObject))) return Bool(Builtin.isUnique_native(&object)) } @_alwaysEmitIntoClient @_transparent public // @testable func _COWBufferForReading<T: AnyObject>(_ object: T) -> T { return Builtin.COWBufferForReading(object) } /// Returns `true` if type is a POD type. A POD type is a type that does not /// require any special handling on copying or destruction. @_transparent public // @testable func _isPOD<T>(_ type: T.Type) -> Bool { return Bool(Builtin.ispod(type)) } /// Returns `true` if `type` is known to refer to a concrete type once all /// optimizations and constant folding has occurred at the call site. Otherwise, /// this returns `false` if the check has failed. /// /// Note that there may be cases in which, despite `T` being concrete at some /// point in the caller chain, this function will return `false`. @_alwaysEmitIntoClient @_transparent public // @testable func _isConcrete<T>(_ type: T.Type) -> Bool { return Bool(Builtin.isConcrete(type)) } /// Returns `true` if type is a bitwise takable. A bitwise takable type can /// just be moved to a different address in memory. @_transparent public // @testable func _isBitwiseTakable<T>(_ type: T.Type) -> Bool { return Bool(Builtin.isbitwisetakable(type)) } /// Returns `true` if type is nominally an Optional type. @_transparent public // @testable func _isOptional<T>(_ type: T.Type) -> Bool { return Bool(Builtin.isOptional(type)) } /// Extract an object reference from an Any known to contain an object. @inlinable internal func _unsafeDowncastToAnyObject(fromAny any: Any) -> AnyObject { _internalInvariant(type(of: any) is AnyObject.Type || type(of: any) is AnyObject.Protocol, "Any expected to contain object reference") // Ideally we would do something like this: // // func open<T>(object: T) -> AnyObject { // return unsafeBitCast(object, to: AnyObject.self) // } // return _openExistential(any, do: open) // // Unfortunately, class constrained protocol existentials conform to AnyObject // but are not word-sized. As a result, we cannot currently perform the // `unsafeBitCast` on them just yet. When they are word-sized, it would be // possible to efficiently grab the object reference out of the inline // storage. return any as AnyObject } // Game the SIL diagnostic pipeline by inlining this into the transparent // definitions below after the stdlib's diagnostic passes run, so that the // `staticReport`s don't fire while building the standard library, but do // fire if they ever show up in code that uses the standard library. @inlinable @inline(__always) public // internal with availability func _trueAfterDiagnostics() -> Builtin.Int1 { return true._value } /// Returns the dynamic type of a value. /// /// You can use the `type(of:)` function to find the dynamic type of a value, /// particularly when the dynamic type is different from the static type. The /// *static type* of a value is the known, compile-time type of the value. The /// *dynamic type* of a value is the value's actual type at run-time, which /// can be a subtype of its concrete type. /// /// In the following code, the `count` variable has the same static and dynamic /// type: `Int`. When `count` is passed to the `printInfo(_:)` function, /// however, the `value` parameter has a static type of `Any` (the type /// declared for the parameter) and a dynamic type of `Int`. /// /// func printInfo(_ value: Any) { /// let t = type(of: value) /// print("'\(value)' of type '\(t)'") /// } /// /// let count: Int = 5 /// printInfo(count) /// // '5' of type 'Int' /// /// The dynamic type returned from `type(of:)` is a *concrete metatype* /// (`T.Type`) for a class, structure, enumeration, or other nonprotocol type /// `T`, or an *existential metatype* (`P.Type`) for a protocol or protocol /// composition `P`. When the static type of the value passed to `type(of:)` /// is constrained to a class or protocol, you can use that metatype to access /// initializers or other static members of the class or protocol. /// /// For example, the parameter passed as `value` to the `printSmileyInfo(_:)` /// function in the example below is an instance of the `Smiley` class or one /// of its subclasses. The function uses `type(of:)` to find the dynamic type /// of `value`, which itself is an instance of the `Smiley.Type` metatype. /// /// class Smiley { /// class var text: String { /// return ":)" /// } /// } /// /// class EmojiSmiley: Smiley { /// override class var text: String { /// return "😀" /// } /// } /// /// func printSmileyInfo(_ value: Smiley) { /// let smileyType = type(of: value) /// print("Smile!", smileyType.text) /// } /// /// let emojiSmiley = EmojiSmiley() /// printSmileyInfo(emojiSmiley) /// // Smile! 😀 /// /// In this example, accessing the `text` property of the `smileyType` metatype /// retrieves the overridden value from the `EmojiSmiley` subclass, instead of /// the `Smiley` class's original definition. /// /// Finding the Dynamic Type in a Generic Context /// ============================================= /// /// Normally, you don't need to be aware of the difference between concrete and /// existential metatypes, but calling `type(of:)` can yield unexpected /// results in a generic context with a type parameter bound to a protocol. In /// a case like this, where a generic parameter `T` is bound to a protocol /// `P`, the type parameter is not statically known to be a protocol type in /// the body of the generic function. As a result, `type(of:)` can only /// produce the concrete metatype `P.Protocol`. /// /// The following example defines a `printGenericInfo(_:)` function that takes /// a generic parameter and declares the `String` type's conformance to a new /// protocol `P`. When `printGenericInfo(_:)` is called with a string that has /// `P` as its static type, the call to `type(of:)` returns `P.self` instead /// of `String.self` (the dynamic type inside the parameter). /// /// func printGenericInfo<T>(_ value: T) { /// let t = type(of: value) /// print("'\(value)' of type '\(t)'") /// } /// /// protocol P {} /// extension String: P {} /// /// let stringAsP: P = "Hello!" /// printGenericInfo(stringAsP) /// // 'Hello!' of type 'P' /// /// This unexpected result occurs because the call to `type(of: value)` inside /// `printGenericInfo(_:)` must return a metatype that is an instance of /// `T.Type`, but `String.self` (the expected dynamic type) is not an instance /// of `P.Type` (the concrete metatype of `value`). To get the dynamic type /// inside `value` in this generic context, cast the parameter to `Any` when /// calling `type(of:)`. /// /// func betterPrintGenericInfo<T>(_ value: T) { /// let t = type(of: value as Any) /// print("'\(value)' of type '\(t)'") /// } /// /// betterPrintGenericInfo(stringAsP) /// // 'Hello!' of type 'String' /// /// - Parameter value: The value for which to find the dynamic type. /// - Returns: The dynamic type, which is a metatype instance. @_transparent @_semantics("typechecker.type(of:)") public func type<T, Metatype>(of value: T) -> Metatype { // This implementation is never used, since calls to `Swift.type(of:)` are // resolved as a special case by the type checker. Builtin.staticReport(_trueAfterDiagnostics(), true._value, ("internal consistency error: 'type(of:)' operation failed to resolve" as StaticString).utf8Start._rawValue) Builtin.unreachable() } /// Allows a nonescaping closure to temporarily be used as if it were allowed /// to escape. /// /// You can use this function to call an API that takes an escaping closure in /// a way that doesn't allow the closure to escape in practice. The examples /// below demonstrate how to use `withoutActuallyEscaping(_:do:)` in /// conjunction with two common APIs that use escaping closures: lazy /// collection views and asynchronous operations. /// /// The following code declares an `allValues(in:match:)` function that checks /// whether all the elements in an array match a predicate. The function won't /// compile as written, because a lazy collection's `filter(_:)` method /// requires an escaping closure. The lazy collection isn't persisted, so the /// `predicate` closure won't actually escape the body of the function; /// nevertheless, it can't be used in this way. /// /// func allValues(in array: [Int], match predicate: (Int) -> Bool) -> Bool { /// return array.lazy.filter { !predicate($0) }.isEmpty /// } /// // error: closure use of non-escaping parameter 'predicate'... /// /// `withoutActuallyEscaping(_:do:)` provides a temporarily escapable copy of /// `predicate` that _can_ be used in a call to the lazy view's `filter(_:)` /// method. The second version of `allValues(in:match:)` compiles without /// error, with the compiler guaranteeing that the `escapablePredicate` /// closure doesn't last beyond the call to `withoutActuallyEscaping(_:do:)`. /// /// func allValues(in array: [Int], match predicate: (Int) -> Bool) -> Bool { /// return withoutActuallyEscaping(predicate) { escapablePredicate in /// array.lazy.filter { !escapablePredicate($0) }.isEmpty /// } /// } /// /// Asynchronous calls are another type of API that typically escape their /// closure arguments. The following code declares a /// `perform(_:simultaneouslyWith:)` function that uses a dispatch queue to /// execute two closures concurrently. /// /// func perform(_ f: () -> Void, simultaneouslyWith g: () -> Void) { /// let queue = DispatchQueue(label: "perform", attributes: .concurrent) /// queue.async(execute: f) /// queue.async(execute: g) /// queue.sync(flags: .barrier) {} /// } /// // error: passing non-escaping parameter 'f'... /// // error: passing non-escaping parameter 'g'... /// /// The `perform(_:simultaneouslyWith:)` function ends with a call to the /// `sync(flags:execute:)` method using the `.barrier` flag, which forces the /// function to wait until both closures have completed running before /// returning. Even though the barrier guarantees that neither closure will /// escape the function, the `async(execute:)` method still requires that the /// closures passed be marked as `@escaping`, so the first version of the /// function does not compile. To resolve these errors, you can use /// `withoutActuallyEscaping(_:do:)` to get copies of `f` and `g` that can be /// passed to `async(execute:)`. /// /// func perform(_ f: () -> Void, simultaneouslyWith g: () -> Void) { /// withoutActuallyEscaping(f) { escapableF in /// withoutActuallyEscaping(g) { escapableG in /// let queue = DispatchQueue(label: "perform", attributes: .concurrent) /// queue.async(execute: escapableF) /// queue.async(execute: escapableG) /// queue.sync(flags: .barrier) {} /// } /// } /// } /// /// - Important: The escapable copy of `closure` passed to `body` is only valid /// during the call to `withoutActuallyEscaping(_:do:)`. It is undefined /// behavior for the escapable closure to be stored, referenced, or executed /// after the function returns. /// /// - Parameters: /// - closure: A nonescaping closure value that is made escapable for the /// duration of the execution of the `body` closure. If `body` has a /// return value, that value is also used as the return value for the /// `withoutActuallyEscaping(_:do:)` function. /// - body: A closure that is executed immediately with an escapable copy of /// `closure` as its argument. /// - Returns: The return value, if any, of the `body` closure. @_transparent @_semantics("typechecker.withoutActuallyEscaping(_:do:)") public func withoutActuallyEscaping<ClosureType, ResultType>( _ closure: ClosureType, do body: (_ escapingClosure: ClosureType) throws -> ResultType ) rethrows -> ResultType { // This implementation is never used, since calls to // `Swift.withoutActuallyEscaping(_:do:)` are resolved as a special case by // the type checker. Builtin.staticReport(_trueAfterDiagnostics(), true._value, ("internal consistency error: 'withoutActuallyEscaping(_:do:)' operation failed to resolve" as StaticString).utf8Start._rawValue) Builtin.unreachable() } @_transparent @_semantics("typechecker._openExistential(_:do:)") public func _openExistential<ExistentialType, ContainedType, ResultType>( _ existential: ExistentialType, do body: (_ escapingClosure: ContainedType) throws -> ResultType ) rethrows -> ResultType { // This implementation is never used, since calls to // `Swift._openExistential(_:do:)` are resolved as a special case by // the type checker. Builtin.staticReport(_trueAfterDiagnostics(), true._value, ("internal consistency error: '_openExistential(_:do:)' operation failed to resolve" as StaticString).utf8Start._rawValue) Builtin.unreachable() } /// Given a string that is constructed from a string literal, return a pointer /// to the global string table location that contains the string literal. /// This function will trap when it is invoked on strings that are not /// constructed from literals or if the construction site of the string is not /// in the function containing the call to this SPI. @_transparent @_alwaysEmitIntoClient public // @SPI(OSLog) func _getGlobalStringTablePointer(_ constant: String) -> UnsafePointer<CChar> { return UnsafePointer<CChar>(Builtin.globalStringTablePointer(constant)); }
apache-2.0
02038806911434c13fb7e0e025da60ea
35.28869
95
0.695344
4.088867
false
false
false
false
eric1202/LZJ_Coin
LZJ_Coin/LZJ_Coin/Section/Gravity/GravityViewController.swift
1
3558
// // GravityViewController.swift // LZJ_Coin // // Created by Heyz on 2017/7/19. // Copyright © 2017年 LZJ. All rights reserved. // import UIKit import CoreMotion class GravityViewController: UIViewController { var animator: UIDynamicAnimator! var motionMgr : CMMotionManager! override func viewDidLoad() { super.viewDidLoad() self.title = "重力沙丘" animator = UIDynamicAnimator.init(referenceView: self.view) motionMgr = CMMotionManager.init() var vs = [UIView]() for _ in 0..<200{ let random :Int = Int(arc4random()%14) + 1 let v = UIView.init(frame: CGRect.init(x: 10 * random, y:(10+15*random), width: random, height: random)) v.layer.masksToBounds = true v.layer.cornerRadius = CGFloat(random)/2.0 let r = arc4random()%155 let g = arc4random()%155 let b = arc4random()%155 v.backgroundColor = UIColor.init(red: CGFloat(r+8)/255.0, green: CGFloat(g)/255.0, blue: CGFloat(b+99)/255.0, alpha: 1) self.view .addSubview(v) vs .append(v) } let itemBehavior = UIDynamicItemBehavior.init(items:vs) animator.addBehavior(itemBehavior) let gravityBehavior = UIGravityBehavior.init(items: vs) gravityBehavior.magnitude = 2 animator.addBehavior(gravityBehavior) let collisionBehavior = UICollisionBehavior.init(items: vs) collisionBehavior.translatesReferenceBoundsIntoBoundary = true; //框 let leftV = UIView.init(frame: CGRect.init(x: 40, y: 300, width: 2, height: 100)) leftV.backgroundColor = UIColor.blue self.view.addSubview(leftV) let middleV = UIView.init(frame: CGRect.init(x: 40, y: 400, width: 100, height: 2)) middleV.backgroundColor = UIColor.orange self.view.addSubview(middleV) let rightV = UIView.init(frame: CGRect.init(x: 140, y: 300, width: 2, height: 100)) rightV.backgroundColor = UIColor.cyan self.view.addSubview(rightV) collisionBehavior.addBoundary(withIdentifier: "right" as NSCopying, for: UIBezierPath.init(rect: rightV.frame)) collisionBehavior.addBoundary(withIdentifier: "middle" as NSCopying, for: UIBezierPath.init(rect: middleV.frame)) collisionBehavior.addBoundary(withIdentifier: "left" as NSCopying, for: UIBezierPath.init(rect: leftV.frame)) animator.addBehavior(collisionBehavior) motionMgr .startDeviceMotionUpdates(to: OperationQueue.main) { (cm, error) in NSLog("device update : %@", cm?.attitude.description ?? "nothing") let grav : CMAcceleration = cm!.gravity; let x = CGFloat(grav.x) let y = CGFloat(grav.y) var p = CGPoint.init(x: x, y: y) // Have to correct for orientation. let orientation = UIApplication.shared.statusBarOrientation; if orientation == UIInterfaceOrientation.landscapeLeft { let t = p.x p.x = 0 - p.y p.y = t } else if orientation == UIInterfaceOrientation.landscapeRight { let t = p.x p.x = p.y p.y = 0 - t } else if orientation == UIInterfaceOrientation.portraitUpsideDown { p.x *= -1 p.y *= -1 } let v = CGVector(dx:p.x, dy:0 - p.y); gravityBehavior.gravityDirection = v; } } }
mit
dbf999a07281065d482acd55dd11b533
33.754902
131
0.603103
4.260817
false
false
false
false
gpancio/iOS-Prototypes
GPUIKit/GPUIKit/Classes/GPNavController.swift
1
4288
// // GPNavController.swift // GPUIKit // // Created by Graham Pancio on 2016-04-27. // Copyright © 2016 Graham Pancio. All rights reserved. // import UIKit /** Extends UINavigationController to provide a customized navigation experience. This navigation controller basically transforms the view controller's navigationItem.rightBarButtonItem into a button which is placed near the bottom of the screen (called the "nextButton"). For now, set up the nextButton by adding a navigation item and right bar button to the view controller. This can be done via storyboard or programmatically. The GPNavController will use rightBarButton item's title as it's title (prepended by "Next: "), and will use any target/action assigned to the rightBarButton item (such as a segue). */ public class GPNavController: UINavigationController, UINavigationControllerDelegate { override public func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. delegate = self readDynamicVCs() } var dynamicVCs = [String:NextObject]() class NextObject: NSObject { var title: String var storyboardName: String var bundleIdentifier: String var vcIdentifier: String var navController: UINavigationController init(title: String, storyboardName: String, bundleIdentifier: String, vcIdentifier: String, navController: UINavigationController) { self.title = title self.storyboardName = storyboardName self.bundleIdentifier = bundleIdentifier self.vcIdentifier = vcIdentifier self.navController = navController } func execute() { let st = UIStoryboard(name: storyboardName, bundle: NSBundle(identifier: bundleIdentifier)) let nextVC = st.instantiateViewControllerWithIdentifier(vcIdentifier) navController.pushViewController(nextVC, animated: true) } } func readDynamicVCs() { if let infoPlist = NSBundle.mainBundle().infoDictionary, let config = infoPlist["Dynamic VCs"] as? Array<Dictionary<String, AnyObject>> { for vcConfig in config { if let origVc = vcConfig["originatingVC"] as? String, let destVC = vcConfig["destination"] as? Dictionary<String, AnyObject> { if let title = destVC["title"] as? String, let bundleIdentifier = destVC["bundleIdentifier"] as? String, let storyboardName = destVC["storyboardName"] as? String, let vcIdentifier = destVC["vcIdentifier"] as? String { dynamicVCs[origVc] = NextObject(title: title, storyboardName: storyboardName, bundleIdentifier: bundleIdentifier, vcIdentifier: vcIdentifier, navController: self) } } } } } func addNextVC(viewController: UIViewController) { if let origVcId = viewController.restorationIdentifier { if let nextObj = dynamicVCs[origVcId] { viewController.navigationItem.rightBarButtonItem = UIBarButtonItem(title: nextObj.title, style: .Plain, target: nextObj, action: #selector(NextObject.execute)) } } } // MARK: - UINavigationControllerDelegate public func navigationController(navigationController: UINavigationController, willShowViewController viewController: UIViewController, animated: Bool) { addNextVC(viewController) if let item = viewController.navigationItem.rightBarButtonItem { if viewController is GPNavControllable { var vc = viewController as! GPNavControllable if vc.showNextButton() { let nextButton = RoundedCornerButton() nextButton.setNextButtonTitle(item, nextButtonTitle: vc.nextButtonTitle()) nextButton.setTargetAndAction(item) vc.nextButton = nextButton } if vc.showNextButton() { item.hide() } } } } }
mit
52b9022e76f0bbf6710036b2c8c2cdf2
40.221154
186
0.635409
5.723632
false
false
false
false
legendecas/Rocket.Chat.iOS
Rocket.Chat/Controllers/Auth/TwoFactorAuthenticationViewController.swift
1
3562
// // TwoFactorAuthenticationViewController.swift // Rocket.Chat // // Created by Rafael Kellermann Streit on 30/03/17. // Copyright © 2017 Rocket.Chat. All rights reserved. // import UIKit import SwiftyJSON final class TwoFactorAuthenticationViewController: BaseViewController, AuthManagerInjected { internal var requesting = false var username: String = "" var password: String = "" @IBOutlet weak var viewFields: UIView! { didSet { viewFields.layer.cornerRadius = 4 viewFields.layer.borderColor = UIColor.RCLightGray().cgColor viewFields.layer.borderWidth = 0.5 } } @IBOutlet weak var visibleViewBottomConstraint: NSLayoutConstraint! @IBOutlet weak var textFieldCode: UITextField! @IBOutlet weak var activityIndicator: UIActivityIndicatorView! deinit { NotificationCenter.default.removeObserver(self) } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) NotificationCenter.default.addObserver( self, selector: #selector(keyboardWillShow(_:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil ) NotificationCenter.default.addObserver( self, selector: #selector(keyboardWillHide(_:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil ) textFieldCode.becomeFirstResponder() } func startLoading() { textFieldCode.alpha = 0.5 requesting = true activityIndicator.startAnimating() textFieldCode.resignFirstResponder() } func stopLoading() { textFieldCode.alpha = 1 requesting = false activityIndicator.stopAnimating() } // MARK: Keyboard Handlers override func keyboardWillShow(_ notification: Notification) { if let keyboardSize = ((notification as NSNotification).userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue { visibleViewBottomConstraint.constant = keyboardSize.height } } override func keyboardWillHide(_ notification: Notification) { visibleViewBottomConstraint.constant = 0 } // MARK: Request username fileprivate func authenticate() { startLoading() authManager.auth(username, password: password, code: textFieldCode.text ?? "") { [weak self] (response) in self?.stopLoading() if response.isError() { if let error = response.result["error"].dictionary { let alert = UIAlertController( title: localized("error.socket.default_error_title"), message: error["message"]?.string ?? localized("error.socket.default_error_message"), preferredStyle: .alert ) alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil)) self?.present(alert, animated: true, completion: nil) } } else { self?.dismiss(animated: true, completion: nil) } } } } extension TwoFactorAuthenticationViewController: UITextFieldDelegate { func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { return !requesting } func textFieldShouldReturn(_ textField: UITextField) -> Bool { authenticate() return true } }
mit
eb03ea8b0b7ae5263eb190cd8cd90e0a
29.698276
134
0.630441
5.546729
false
false
false
false
L-Zephyr/Drafter
Sources/Drafter/Parser/File/FileParser.swift
1
3012
// // FileParser.swift // DrafterTests // // Created by LZephyr on 2018/5/17. // import Foundation import PathKit /* FileParser并没有继承自ConcreteParserType,它整合了底层所有ConcreteParser并对所有类型的源文件提供一致的接口(Facade模式), 封装了将一个源码文件解析成FileNode的过程,并缓存结果 */ class FileParser { // MARK: - Public /// 接受一个文件路径来初始化 /// /// - Parameter path: 源码文件的路径 init(_ path: Path) { self.sourcePath = path } /// 执行解析并获得结果,该方法会优先使用缓存 /// /// - Returns: 解析结果 func run(_ usingCache: Bool = true) -> FileNode? { // Read File var content: String do { content = try sourcePath.read() sourceMD5 = content.md5 } catch { print("Fail To Read File: \(error)") return nil } if usingCache, sourcePath.cachePath().exists, let data: Data = try? sourcePath.cachePath().read(), let cache = try? JSONDecoder().decode(FileNode.self, from: data) { // 有缓存 if cache.drafterVersion == DrafterVersion && cache.md5 == sourceMD5 { return cache } else { // 缓存失效 return parseAndCache() } } else { // 无缓存 return parseAndCache() } } // MARK: - Private /// 缓存未命中,执行解析并缓存结果 fileprivate func parseAndCache() -> FileNode { // 1. parse var result: FileNode if sourcePath.isSwift { let tokens = SourceLexer(file: sourcePath.string).allTokens let types = SwiftTypeParser().parser.run(tokens) ?? [] result = FileNode(md5: sourceMD5, drafterVersion: DrafterVersion, path: sourcePath.absolute().string, type: sourcePath.fileType, swiftTypes: types, objcTypes: []) } else { let tokens = SourceLexer(file: sourcePath.string).allTokens let types = ObjcTypeParser().parser.run(tokens) ?? [] result = FileNode(md5: sourceMD5, drafterVersion: DrafterVersion, path: sourcePath.absolute().string, type: sourcePath.fileType, swiftTypes: [], objcTypes: types) } // 2. cache if let data = try? JSONEncoder().encode(result) { try? sourcePath.cachePath().write(data) } return result } fileprivate let sourcePath: Path // 源代码文件路径 fileprivate var sourceMD5: String = "" }
mit
1ebd0ab643b4dad5f9d4e36561cce96d
28.505376
86
0.500364
4.588629
false
false
false
false
huangboju/Moots
UICollectionViewLayout/SwiftNetworkImages-master/SwiftNetworkImages/ViewControllers/Transitions/ImageDetailPresentationController.swift
2
2444
// // ImageDetailPresentationController.swift // SwiftNetworkImages // // Created by Arseniy on 9/10/16. // Copyright © 2016 Arseniy Kuznetsov. All rights reserved. // import UIKit class ImageDetailPresentationController: UIPresentationController { override init(presentedViewController: UIViewController, presenting presentingViewController: UIViewController?) { dimmerView = UIView(frame: CGRect.zero) dimmerView.backgroundColor = UIColor(white: 0.0, alpha: 0.8) dimmerView.autoresizingMask = [.flexibleWidth, .flexibleHeight] super.init(presentedViewController: presentedViewController, presenting: presentingViewController) } override var frameOfPresentedViewInContainerView: CGRect { return super.frameOfPresentedViewInContainerView.insetBy(dx: 20.0, dy: 20.0) } override var presentedView: UIView? { guard let theView = super.presentedView else { return nil } theView.layer.cornerRadius = 6 theView.layer.masksToBounds = true return theView } override func presentationTransitionWillBegin() { guard let containerView = containerView, let transitionCoordinator = presentedViewController.transitionCoordinator else { return } dimmerView.frame = containerView.bounds dimmerView.alpha = 0.0 containerView.insertSubview(dimmerView, at: 0) transitionCoordinator.animate(alongsideTransition: { _ in self.dimmerView.alpha = 1.0 }) } override func presentationTransitionDidEnd(_ completed: Bool) { // If the presentation didn't complete, remove the dimming view if !completed { dimmerView.removeFromSuperview() } if let adjustedView = self.presentingViewController.view { adjustedView.tintAdjustmentMode = .dimmed } } override func dismissalTransitionWillBegin() { guard let transitionCoordinator = presentedViewController.transitionCoordinator else { return } transitionCoordinator.animate(alongsideTransition: { _ in self.dimmerView.alpha = 0 }) } override func dismissalTransitionDidEnd(_ completed: Bool) { if let adjustedView = self.presentingViewController.view { adjustedView.tintAdjustmentMode = .automatic } } fileprivate var dimmerView: UIView }
mit
a77dae98d75252211bf5131e83f15fcc
36.015152
118
0.68727
5.668213
false
false
false
false
oskarpearson/rileylink_ios
MinimedKitTests/Messages/ReadTempBasalCarelinkMessageBodyTests.swift
1
2050
// // ReadTempBasalCarelinkMessageBodyTests.swift // Naterade // // Created by Nathan Racklyeft on 3/7/16. // Copyright © 2016 Nathan Racklyeft. All rights reserved. // import XCTest @testable import MinimedKit class ReadTempBasalCarelinkMessageBodyTests: XCTestCase { func testReadTempBasal() { // 06 00 00 00 37 00 17 -> 1.375 U @ 23 min remaining let message = PumpMessage(rxData: Data(hexadecimalString: "a7123456980600000037001700000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000ff")!)! let body = message.messageBody as! ReadTempBasalCarelinkMessageBody XCTAssertEqual(TimeInterval(23 * 60), body.timeRemaining) XCTAssertEqual(1.375, body.rate) XCTAssertEqual(ReadTempBasalCarelinkMessageBody.RateType.absolute, body.rateType) } func testReadTempBasalZero() { // 06 00 00 00 00 00 1d -> 0 U @ 29 min remaining let message = PumpMessage(rxData: Data(hexadecimalString: "a7123456980600000000001d00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000ff")!)! let body = message.messageBody as! ReadTempBasalCarelinkMessageBody XCTAssertEqual(TimeInterval(29 * 60), body.timeRemaining) XCTAssertEqual(0, body.rate) XCTAssertEqual(ReadTempBasalCarelinkMessageBody.RateType.absolute, body.rateType) } func testReadHighTempBasalRate() { let message = PumpMessage(rxData: Data(hexadecimalString: "a7754838980600000550001e0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000012")!)! let body = message.messageBody as! ReadTempBasalCarelinkMessageBody XCTAssertEqual(TimeInterval(30 * 60), body.timeRemaining) XCTAssertEqual(34, body.rate) XCTAssertEqual(ReadTempBasalCarelinkMessageBody.RateType.absolute, body.rateType) } }
mit
be347b1473da9053d679bb05121ef0f3
43.543478
214
0.748658
5.392105
false
true
false
false
zpz1237/NirWebImage
NirWebImageOptionsInfo.swift
1
1103
// // NirWebImageOptionsInfo.swift // NirWebImage // // Created by Nirvana on 11/22/15. // Copyright © 2015 NSNirvana. All rights reserved. // import Foundation public typealias NirWebImageOptionsInfo = [NirWebImageOptionsInfoItem] public enum NirWebImageOptionsInfoItem { case Options(NirWebImageOptions) case TargetCache(ImageCache) case Downloader(ImageDownloader) case Transition(ImageTransition) } func ==(a: NirWebImageOptionsInfoItem, b: NirWebImageOptionsInfoItem) -> Bool { switch (a, b) { case (.Options(_), .Options(_)): return true case (.TargetCache(_), .TargetCache(_)): return true case (.Downloader(_), .Downloader(_)): return true case (.Transition(_), .Transition(_)): return true default: return false } } extension CollectionType where Generator.Element == NirWebImageOptionsInfoItem { func nir_findFirstMatch(target: Generator.Element) -> Generator.Element? { let index = indexOf { e in return e == target } return (index != nil) ? self[index!] : nil } }
mit
3c4053760885e8729aa4e6669409aac6
26.575
80
0.666062
4.355731
false
false
false
false
emaloney/CleanroomLogger
Sources/LogChannel.swift
3
5212
// // LogChannel.swift // CleanroomLogger // // Created by Evan Maloney on 3/20/15. // Copyright © 2015 Gilt Groupe. All rights reserved. // import Foundation /** `LogChannel` instances provide the high-level interface for accepting log messages. They are responsible for converting log requests into `LogEntry` instances that they then pass along to their associated `LogReceptacle`s to perform the actual logging. `LogChannel`s are provided as a convenience, exposed as static properties through `Log`. Use of `LogChannel`s and the `Log` is not required for logging; you can also perform logging by creating `LogEntry` instances manually and passing them along to a `LogReceptacle`. */ public struct LogChannel { /** The `LogSeverity` of this `LogChannel`, which determines the severity of the `LogEntry` instances it creates. */ public let severity: LogSeverity /** The `LogReceptacle` into which this `LogChannel` will deposit the `LogEntry` instances it creates. */ public let receptacle: LogReceptacle /** Initializes a new `LogChannel` instance. - parameter severity: The `LogSeverity` to use for each `LogEntry` created by the channel. - parameter receptacle: The `LogReceptacle` to be used for depositing the `LogEntry` instances created by the channel. */ public init(severity: LogSeverity, receptacle: LogReceptacle) { self.severity = severity self.receptacle = receptacle } /** Sends program execution trace information to the log using the receiver's severity. This information includes source-level call site information as well as the stack frame signature of the caller. - parameter function: The default value provided for this parameter captures the signature of the calling function. You should not provide a value for this parameter. - parameter filePath: The default value provided for this parameter captures the file path of the code issuing the call to this function. You should not provide a value for this parameter. - parameter fileLine: The default value provided for this parameter captures the line number issuing the call to this function. You should not provide a value for this parameter. */ public func trace(_ function: String = #function, filePath: String = #file, fileLine: Int = #line) { var threadID: UInt64 = 0 pthread_threadid_np(nil, &threadID) let entry = LogEntry(payload: .trace, severity: severity, callingFilePath: filePath, callingFileLine: fileLine, callingStackFrame: function, callingThreadID: threadID) receptacle.log(entry) } /** Sends a message string to the log using the receiver's severity. - parameter msg: The message to send to the log. - parameter function: The default value provided for this parameter captures the signature of the calling function. You should not provide a value for this parameter. - parameter filePath: The default value provided for this parameter captures the file path of the code issuing the call to this function. You should not provide a value for this parameter. - parameter fileLine: The default value provided for this parameter captures the line number issuing the call to this function. You should not provide a value for this parameter. */ public func message(_ msg: String, function: String = #function, filePath: String = #file, fileLine: Int = #line) { var threadID: UInt64 = 0 pthread_threadid_np(nil, &threadID) let entry = LogEntry(payload: .message(msg), severity: severity, callingFilePath: filePath, callingFileLine: fileLine, callingStackFrame: function, callingThreadID: threadID) receptacle.log(entry) } /** Sends an arbitrary value to the log using the receiver's severity. - parameter value: The value to send to the log. Determining how (and whether) arbitrary values are captured and represented will be handled by the `LogRecorder` implementation(s) that are ultimately called upon to record the log entry. - parameter function: The default value provided for this parameter captures the signature of the calling function. You should not provide a value for this parameter. - parameter filePath: The default value provided for this parameter captures the file path of the code issuing the call to this function. You should not provide a value for this parameter. - parameter fileLine: The default value provided for this parameter captures the line number issuing the call to this function. You should not provide a value for this parameter. */ public func value(_ value: Any?, function: String = #function, filePath: String = #file, fileLine: Int = #line) { var threadID: UInt64 = 0 pthread_threadid_np(nil, &threadID) let entry = LogEntry(payload: .value(value), severity: severity, callingFilePath: filePath, callingFileLine: fileLine, callingStackFrame: function, callingThreadID: threadID) receptacle.log(entry) } }
mit
f9d2e6c038bfefe3dfd27b6a4f430322
38.477273
182
0.715218
4.816081
false
false
false
false
alecananian/osx-coin-ticker
CoinTicker/Source/Exchanges/KorbitExchange.swift
1
2915
// // KorbitExchange.swift // CoinTicker // // Created by Alec Ananian on 6/24/17. // Copyright © 2017 Alec Ananian. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation import SwiftyJSON import PromiseKit class KorbitExchange: Exchange { private struct Constants { static let TickerAPIPathFormat = "https://api.korbit.co.kr/v1/ticker?currency_pair=%@" } init(delegate: ExchangeDelegate? = nil) { super.init(site: .korbit, delegate: delegate) } override func load() { setAvailableCurrencyPairs([ CurrencyPair(baseCurrency: "BTC", quoteCurrency: "KRW", customCode: "btc_krw")!, CurrencyPair(baseCurrency: "BCH", quoteCurrency: "KRW", customCode: "bch_krw")!, CurrencyPair(baseCurrency: "ETH", quoteCurrency: "KRW", customCode: "eth_krw")!, CurrencyPair(baseCurrency: "ETC", quoteCurrency: "KRW", customCode: "etc_krw")!, CurrencyPair(baseCurrency: "XRP", quoteCurrency: "KRW", customCode: "xrp_krw")! ]) } override internal func fetch() { _ = when(resolved: selectedCurrencyPairs.map({ currencyPair -> Promise<ExchangeAPIResponse> in let apiRequestPath = String(format: Constants.TickerAPIPathFormat, currencyPair.customCode) return requestAPI(apiRequestPath, for: currencyPair) })).map { [weak self] results in results.forEach({ result in switch result { case .fulfilled(let value): if let currencyPair = value.representedObject as? CurrencyPair { let price = value.json["last"].doubleValue self?.setPrice(price, for: currencyPair) } default: break } }) self?.onFetchComplete() } } }
mit
4628dc78e3444f3317e03f5ac629d3ec
40.042254
103
0.658545
4.401813
false
false
false
false
Ryan-Vanderhoef/Antlers
AppIdea/ViewControllers/MasterTabBarViewController.swift
1
3379
// // MasterTabBarViewController.swift // AppIdea // // Created by Ryan Vanderhoef on 7/29/15. // Copyright (c) 2015 Ryan Vanderhoef. All rights reserved. // import UIKit import Parse import ParseUI class MasterTabBarViewController: UITabBarController, PFLogInViewControllerDelegate, PFSignUpViewControllerDelegate { override func viewDidLoad() { super.viewDidLoad() println("masterTabBarViewController") // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func viewDidAppear(animated: Bool) { // println("view appeared MASTERTABBARCONTROLLER") // println("\(PFUser.currentUser())") // if PFUser.currentUser() == nil { // // var logInViewController = PFLogInViewController() // logInViewController.delegate = self // var signUpViewController = PFSignUpViewController() // signUpViewController.delegate = self // // logInViewController.signUpController = signUpViewController // // self.presentViewController(logInViewController, animated: true, completion: nil) // // // } // super.viewDidAppear(animated) } func logInViewController(logInController: PFLogInViewController, shouldBeginLogInWithUsername username: String, password: String) -> Bool { if (!username.isEmpty || !password.isEmpty) { return true } else { return false } } func logInViewController(logInController: PFLogInViewController, didLogInUser user: PFUser) { // println("didLogInUser") self.dismissViewControllerAnimated(true, completion: nil) } func logInViewController(logInController: PFLogInViewController, didFailToLogInWithError error: NSError?) { // println("Failed to Login") } func signUpViewController(signUpController: PFSignUpViewController, shouldBeginSignUp info: [NSObject : AnyObject]) -> Bool { if let password = info["password"] as? String { return true //password.utf16Count >= 8 } else { return false } } func signUpViewController(signUpController: PFSignUpViewController, didSignUpUser user: PFUser) { self.dismissViewControllerAnimated(true, completion: nil) } func signUpViewController(signUpController: PFSignUpViewController, didFailToSignUpWithError error: NSError?) { // println("Failed to sign up") } func signUpViewControllerDidCancelSignUp(signUpController: PFSignUpViewController) { // println("User dismissed sign up") } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
mit
c2b8de818e8a16a8b16e3afe12a1390a
29.169643
143
0.631548
5.766212
false
false
false
false