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
jkloo/Evolution
Evolution/GameViewController.swift
1
1405
// // GameViewController.swift // Evolution // // Created by Jeff Kloosterman on 8/22/15. // Copyright (c) 2015 Jeff Kloosterman. All rights reserved. // import UIKit import SpriteKit class GameViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() if let scene = GameScene(fileNamed:"GameScene") { // Configure the view. let skView = self.view as! SKView skView.showsFPS = true skView.showsNodeCount = true /* Sprite Kit applies additional optimizations to improve rendering performance */ skView.ignoresSiblingOrder = true /* Set the scale mode to scale to fit the window */ scene.scaleMode = .ResizeFill skView.presentScene(scene) } } override func shouldAutorotate() -> Bool { return true } override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask { if UIDevice.currentDevice().userInterfaceIdiom == .Phone { return .AllButUpsideDown } else { return .All } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Release any cached data, images, etc that aren't in use. } override func prefersStatusBarHidden() -> Bool { return true } }
mit
992b68c3be64b841832e0a6dab6add0d
25.509434
94
0.610676
5.445736
false
false
false
false
takuran/CoreAnimationLesson
CoreAnimationLesson/Lesson1-5ViewController.swift
1
948
// // Lesson1-5ViewController.swift // CoreAnimationLesson // // Created by Naoyuki Takura on 2015/04/05. // Copyright (c) 2015年 Naoyuki Takura. All rights reserved. // import UIKit class Lesson1_5ViewController: UIViewController { @IBOutlet weak var viewA: UIView! @IBOutlet weak var viewB: UIView! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. // load image once. let image = UIImage(named: "AB.png") // A viewA.layer.contents = image?.CGImage viewA.layer.contentsRect = CGRectMake(0, 0, 0.5, 1.0) // B viewB.layer.contents = image?.CGImage viewB.layer.contentsRect = CGRectMake(0.5, 0, 0.5, 1.0) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
1272b68c1f88e2cb29c51d96da7f0bfe
24.567568
63
0.61945
3.991561
false
false
false
false
frootloops/swift
stdlib/public/core/StringLegacy.swift
1
17842
//===----------------------------------------------------------------------===// // // 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 extension String { /// Creates a new string representing the given string repeated the specified /// number of times. /// /// For example, you can use this initializer to create a string with ten /// `"ab"` strings in a row. /// /// let s = String(repeating: "ab", count: 10) /// print(s) /// // Prints "abababababababababab" /// /// - Parameters: /// - repeatedValue: The string to repeat. /// - count: The number of times to repeat `repeatedValue` in the resulting /// string. @_inlineable // FIXME(sil-serialize-all) public init(repeating repeatedValue: String, count: Int) { if count == 0 { self = "" return } precondition(count > 0, "Negative count not allowed") let s = repeatedValue self = String(_storage: _StringBuffer( capacity: s._core.count * count, initialSize: 0, elementWidth: s._core.elementWidth)) for _ in 0..<count { self += s } } /// A Boolean value indicating whether a string has no characters. @_inlineable // FIXME(sil-serialize-all) public var isEmpty: Bool { return _core.count == 0 } } extension String { @_inlineable // FIXME(sil-serialize-all) public init(_ _c: Unicode.Scalar) { self = String._fromWellFormedCodeUnitSequence( UTF32.self, input: repeatElement(_c.value, count: 1)) } } #if _runtime(_ObjC) /// Determines if `theString` starts with `prefix` comparing the strings under /// canonical equivalence. @_inlineable // FIXME(sil-serialize-all) @_versioned // FIXME(sil-serialize-all) @_silgen_name("swift_stdlib_NSStringHasPrefixNFD") internal func _stdlib_NSStringHasPrefixNFD( _ theString: AnyObject, _ prefix: AnyObject) -> Bool @_inlineable // FIXME(sil-serialize-all) @_versioned // FIXME(sil-serialize-all) @_silgen_name("swift_stdlib_NSStringHasPrefixNFDPointer") internal func _stdlib_NSStringHasPrefixNFDPointer( _ theString: OpaquePointer, _ prefix: OpaquePointer) -> Bool /// Determines if `theString` ends with `suffix` comparing the strings under /// canonical equivalence. @_inlineable // FIXME(sil-serialize-all) @_versioned // FIXME(sil-serialize-all) @_silgen_name("swift_stdlib_NSStringHasSuffixNFD") internal func _stdlib_NSStringHasSuffixNFD( _ theString: AnyObject, _ suffix: AnyObject) -> Bool @_inlineable // FIXME(sil-serialize-all) @_versioned // FIXME(sil-serialize-all) @_silgen_name("swift_stdlib_NSStringHasSuffixNFDPointer") internal func _stdlib_NSStringHasSuffixNFDPointer( _ theString: OpaquePointer, _ suffix: OpaquePointer) -> Bool extension String { /// Returns a Boolean value indicating whether the string begins with the /// specified prefix. /// /// The comparison is both case sensitive and Unicode safe. The /// case-sensitive comparison will only match strings whose corresponding /// characters have the same case. /// /// let cafe = "Café du Monde" /// /// // Case sensitive /// print(cafe.hasPrefix("café")) /// // Prints "false" /// /// The Unicode-safe comparison matches Unicode scalar values rather than the /// code points used to compose them. The example below uses two strings /// with different forms of the `"é"` character---the first uses the composed /// form and the second uses the decomposed form. /// /// // Unicode safe /// let composedCafe = "Café" /// let decomposedCafe = "Cafe\u{0301}" /// /// print(cafe.hasPrefix(composedCafe)) /// // Prints "true" /// print(cafe.hasPrefix(decomposedCafe)) /// // Prints "true" /// /// - Parameter prefix: A possible prefix to test against this string. /// - Returns: `true` if the string begins with `prefix`; otherwise, `false`. @_inlineable // FIXME(sil-serialize-all) public func hasPrefix(_ prefix: String) -> Bool { let selfCore = self._core let prefixCore = prefix._core let prefixCount = prefixCore.count if prefixCount == 0 { return true } if let selfASCIIBuffer = selfCore.asciiBuffer, let prefixASCIIBuffer = prefixCore.asciiBuffer { if prefixASCIIBuffer.count > selfASCIIBuffer.count { // Prefix is longer than self. return false } return _stdlib_memcmp( selfASCIIBuffer.baseAddress!, prefixASCIIBuffer.baseAddress!, prefixASCIIBuffer.count) == (0 as CInt) } if selfCore.hasContiguousStorage && prefixCore.hasContiguousStorage { let lhsStr = _NSContiguousString(selfCore) let rhsStr = _NSContiguousString(prefixCore) return lhsStr._unsafeWithNotEscapedSelfPointerPair(rhsStr) { return _stdlib_NSStringHasPrefixNFDPointer($0, $1) } } return _stdlib_NSStringHasPrefixNFD( self._bridgeToObjectiveCImpl(), prefix._bridgeToObjectiveCImpl()) } /// Returns a Boolean value indicating whether the string ends with the /// specified suffix. /// /// The comparison is both case sensitive and Unicode safe. The /// case-sensitive comparison will only match strings whose corresponding /// characters have the same case. /// /// let plans = "Let's meet at the café" /// /// // Case sensitive /// print(plans.hasSuffix("Café")) /// // Prints "false" /// /// The Unicode-safe comparison matches Unicode scalar values rather than the /// code points used to compose them. The example below uses two strings /// with different forms of the `"é"` character---the first uses the composed /// form and the second uses the decomposed form. /// /// // Unicode safe /// let composedCafe = "café" /// let decomposedCafe = "cafe\u{0301}" /// /// print(plans.hasSuffix(composedCafe)) /// // Prints "true" /// print(plans.hasSuffix(decomposedCafe)) /// // Prints "true" /// /// - Parameter suffix: A possible suffix to test against this string. /// - Returns: `true` if the string ends with `suffix`; otherwise, `false`. @_inlineable // FIXME(sil-serialize-all) public func hasSuffix(_ suffix: String) -> Bool { let selfCore = self._core let suffixCore = suffix._core let suffixCount = suffixCore.count if suffixCount == 0 { return true } if let selfASCIIBuffer = selfCore.asciiBuffer, let suffixASCIIBuffer = suffixCore.asciiBuffer { if suffixASCIIBuffer.count > selfASCIIBuffer.count { // Suffix is longer than self. return false } return _stdlib_memcmp( selfASCIIBuffer.baseAddress! + (selfASCIIBuffer.count - suffixASCIIBuffer.count), suffixASCIIBuffer.baseAddress!, suffixASCIIBuffer.count) == (0 as CInt) } if selfCore.hasContiguousStorage && suffixCore.hasContiguousStorage { let lhsStr = _NSContiguousString(selfCore) let rhsStr = _NSContiguousString(suffixCore) return lhsStr._unsafeWithNotEscapedSelfPointerPair(rhsStr) { return _stdlib_NSStringHasSuffixNFDPointer($0, $1) } } return _stdlib_NSStringHasSuffixNFD( self._bridgeToObjectiveCImpl(), suffix._bridgeToObjectiveCImpl()) } } #else // FIXME: Implement hasPrefix and hasSuffix without objc // rdar://problem/18878343 #endif @_inlineable // FIXME(sil-serialize-all) @_versioned // FIXME(sil-serialize-all) internal func _ascii8(_ c: Unicode.Scalar) -> UInt8 { _sanityCheck(c.value >= 0 && c.value <= 0x7F, "not ASCII") return UInt8(c.value) } @_inlineable // FIXME(sil-serialize-all) @_versioned // FIXME(sil-serialize-all) internal func _digitASCII( _ digit: UInt8, numeralsOnly: Bool, uppercase: Bool ) -> UInt8 { if numeralsOnly || digit < 10 { return _ascii8("0") &+ digit } else { let base = (uppercase ? _ascii8("A") : _ascii8("a")) &- 10 return base &+ digit } } @_inlineable // FIXME(sil-serialize-all) @_versioned // FIXME(sil-serialize-all) internal func _integerToString<T: FixedWidthInteger>( _ value: T, radix: Int, uppercase: Bool ) -> String { if value == 0 { return "0" } // Bit shifting / masking is much faster than division when `radix` // is a power of two. let radixIsPowerOfTwo = radix.nonzeroBitCount == 1 let radix = T.Magnitude(radix) let quotientAndRemainder: (T.Magnitude) -> (T.Magnitude, T.Magnitude) = radixIsPowerOfTwo ? { ( $0 &>> radix.trailingZeroBitCount, $0 & (radix - 1) ) } : { $0.quotientAndRemainder(dividingBy: radix) } let isNegative = T.isSigned && value < 0 var value = value.magnitude var result: [UInt8] = [] while value != 0 { let (q, r) = quotientAndRemainder(value) result.append( _digitASCII( UInt8(truncatingIfNeeded: r), numeralsOnly: radix <= 10, uppercase: uppercase)) value = q } if isNegative { result.append(_ascii8("-")) } return String._fromWellFormedCodeUnitSequence( UTF8.self, input: result.reversed()) } // Conversions to string from other types. extension String { /// Creates a string representing the given value in base 10, or some other /// specified base. /// /// The following example converts the maximal `Int` value to a string and /// prints its length: /// /// let max = String(Int.max) /// print("\(max) has \(max.count) digits.") /// // Prints "9223372036854775807 has 19 digits." /// /// Numerals greater than 9 are represented as Roman letters. These letters /// start with `"A"` if `uppercase` is `true`; otherwise, with `"a"`. /// /// let v = 999_999 /// print(String(v, radix: 2)) /// // Prints "11110100001000111111" /// /// print(String(v, radix: 16)) /// // Prints "f423f" /// print(String(v, radix: 16, uppercase: true)) /// // Prints "F423F" /// /// - Parameters: /// - value: The value to convert to a string. /// - radix: The base to use for the string representation. `radix` must be /// at least 2 and at most 36. The default is 10. /// - uppercase: Pass `true` to use uppercase letters to represent numerals /// greater than 9, or `false` to use lowercase letters. The default is /// `false`. // FIXME(integers): support a more general BinaryInteger protocol // FIXME(integers): support larger bitwidths than 64 @_inlineable // FIXME(sil-serialize-all) public init<T : FixedWidthInteger>( _ value: T, radix: Int = 10, uppercase: Bool = false ) { _precondition(2...36 ~= radix, "Radix must be between 2 and 36") if T.bitWidth <= 64 { self = _int64ToString( Int64(value), radix: Int64(radix), uppercase: uppercase) } else { self = _integerToString(value, radix: radix, uppercase: uppercase) } } /// Creates a string representing the given value in base 10, or some other /// specified base. /// /// The following example converts the maximal `Int` value to a string and /// prints its length: /// /// let max = String(Int.max) /// print("\(max) has \(max.count) digits.") /// // Prints "9223372036854775807 has 19 digits." /// /// Numerals greater than 9 are represented as Roman letters. These letters /// start with `"A"` if `uppercase` is `true`; otherwise, with `"a"`. /// /// let v = 999_999 /// print(String(v, radix: 2)) /// // Prints "11110100001000111111" /// /// print(String(v, radix: 16)) /// // Prints "f423f" /// print(String(v, radix: 16, uppercase: true)) /// // Prints "F423F" /// /// - Parameters: /// - value: The value to convert to a string. /// - radix: The base to use for the string representation. `radix` must be /// at least 2 and at most 36. The default is 10. /// - uppercase: Pass `true` to use uppercase letters to represent numerals /// greater than 9, or `false` to use lowercase letters. The default is /// `false`. // FIXME(integers): tiebreaker between T : FixedWidthInteger and other obsoleted @_inlineable // FIXME(sil-serialize-all) @available(swift, obsoleted: 4) public init<T : FixedWidthInteger>( _ value: T, radix: Int = 10, uppercase: Bool = false ) where T : SignedInteger { _precondition(2...36 ~= radix, "Radix must be between 2 and 36") if T.bitWidth <= 64 { self = _int64ToString( Int64(value), radix: Int64(radix), uppercase: uppercase) } else { self = _integerToString(value, radix: radix, uppercase: uppercase) } } /// Creates a string representing the given value in base 10, or some other /// specified base. /// /// The following example converts the maximal `Int` value to a string and /// prints its length: /// /// let max = String(Int.max) /// print("\(max) has \(max.count) digits.") /// // Prints "9223372036854775807 has 19 digits." /// /// Numerals greater than 9 are represented as Roman letters. These letters /// start with `"A"` if `uppercase` is `true`; otherwise, with `"a"`. /// /// let v: UInt = 999_999 /// print(String(v, radix: 2)) /// // Prints "11110100001000111111" /// /// print(String(v, radix: 16)) /// // Prints "f423f" /// print(String(v, radix: 16, uppercase: true)) /// // Prints "F423F" /// /// - Parameters: /// - value: The value to convert to a string. /// - radix: The base to use for the string representation. `radix` must be /// at least 2 and at most 36. The default is 10. /// - uppercase: Pass `true` to use uppercase letters to represent numerals /// greater than 9, or `false` to use lowercase letters. The default is /// `false`. // FIXME(integers): support a more general BinaryInteger protocol @_inlineable // FIXME(sil-serialize-all) public init<T : FixedWidthInteger>( _ value: T, radix: Int = 10, uppercase: Bool = false ) where T : UnsignedInteger { _precondition(2...36 ~= radix, "Radix must be between 2 and 36") if T.bitWidth <= 64 { self = _uint64ToString( UInt64(value), radix: Int64(radix), uppercase: uppercase) } else { self = _integerToString(value, radix: radix, uppercase: uppercase) } } /// Creates a string representing the given value in base 10, or some other /// specified base. /// /// The following example converts the maximal `Int` value to a string and /// prints its length: /// /// let max = String(Int.max) /// print("\(max) has \(max.count) digits.") /// // Prints "9223372036854775807 has 19 digits." /// /// Numerals greater than 9 are represented as Roman letters. These letters /// start with `"A"` if `uppercase` is `true`; otherwise, with `"a"`. /// /// let v = 999_999 /// print(String(v, radix: 2)) /// // Prints "11110100001000111111" /// /// print(String(v, radix: 16)) /// // Prints "f423f" /// print(String(v, radix: 16, uppercase: true)) /// // Prints "F423F" /// /// - Parameters: /// - value: The value to convert to a string. /// - radix: The base to use for the string representation. `radix` must be /// at least 2 and at most 36. The default is 10. /// - uppercase: Pass `true` to use uppercase letters to represent numerals /// greater than 9, or `false` to use lowercase letters. The default is /// `false`. @_inlineable // FIXME(sil-serialize-all) @available(swift, obsoleted: 4, message: "Please use the version for FixedWidthInteger instead.") public init<T : SignedInteger>( _ value: T, radix: Int = 10, uppercase: Bool = false ) { _precondition(2...36 ~= radix, "Radix must be between 2 and 36") self = _int64ToString( Int64(value), radix: Int64(radix), uppercase: uppercase) } /// Creates a string representing the given value in base 10, or some other /// specified base. /// /// The following example converts the maximal `Int` value to a string and /// prints its length: /// /// let max = String(Int.max) /// print("\(max) has \(max.count) digits.") /// // Prints "9223372036854775807 has 19 digits." /// /// Numerals greater than 9 are represented as Roman letters. These letters /// start with `"A"` if `uppercase` is `true`; otherwise, with `"a"`. /// /// let v: UInt = 999_999 /// print(String(v, radix: 2)) /// // Prints "11110100001000111111" /// /// print(String(v, radix: 16)) /// // Prints "f423f" /// print(String(v, radix: 16, uppercase: true)) /// // Prints "F423F" /// /// - Parameters: /// - value: The value to convert to a string. /// - radix: The base to use for the string representation. `radix` must be /// at least 2 and at most 36. The default is 10. /// - uppercase: Pass `true` to use uppercase letters to represent numerals /// greater than 9, or `false` to use lowercase letters. The default is /// `false`. @_inlineable // FIXME(sil-serialize-all) @available(swift, obsoleted: 4, message: "Please use the version for FixedWidthInteger instead.") public init<T : UnsignedInteger>( _ value: T, radix: Int = 10, uppercase: Bool = false ) { _precondition(2...36 ~= radix, "Radix must be between 2 and 36") self = _uint64ToString( UInt64(value), radix: Int64(radix), uppercase: uppercase) } }
apache-2.0
6c1763d41e6b4062e0ae500d267d59ab
35.771134
99
0.634182
4.068903
false
false
false
false
mrdepth/Neocom
Legacy/Neocom/Neocom/NCFittingAreaEffectsViewController.swift
2
3510
// // NCFittingAreaEffectsViewController.swift // Neocom // // Created by Artem Shimanski on 14.02.17. // Copyright © 2017 Artem Shimanski. All rights reserved. // import UIKit import CoreData import EVEAPI import Futures /*class NCFittingAreaEffectRow: TreeRow { let objectID: NSManagedObjectID lazy var type: NCDBInvType? = { return NCDatabase.sharedDatabase?.viewContext.object(with: self.objectID) as? NCDBInvType }() init(objectID: NSManagedObjectID) { self.objectID = objectID super.init(cellIdentifier: "NCDefaultTableViewCell", accessoryButtonSegue: "NCDatabaseTypeInfoViewController") } override func configure(cell: UITableViewCell) { guard let cell = cell as? NCDefaultTableViewCell else {return} cell.object = type cell.titleLabel?.text = type?.typeName cell.iconView?.image = type?.icon?.image?.image ?? NCDBEveIcon.defaultType.image?.image cell.accessoryType = .detailButton } }*/ class NCFittingAreaEffectsViewController: NCTreeViewController { var category: NCDBDgmppItemCategory? var completionHandler: ((NCFittingAreaEffectsViewController, NCDBInvType?) -> Void)! override func viewDidLoad() { super.viewDidLoad() tableView.register([Prototype.NCDefaultTableViewCell.compact, Prototype.NCHeaderTableViewCell.default ]) } override func content() -> Future<TreeNode?> { guard let managedObjectContext = NCDatabase.sharedDatabase?.viewContext else {return .init(nil)} guard let types: [NCDBInvType] = managedObjectContext.fetch("InvType", sortedBy: [NSSortDescriptor(key: "typeName", ascending: true)], where: "group.groupID == 920") else {return .init(nil)} let prefixes = ["Black Hole Effect Beacon Class", "Cataclysmic Variable Effect Beacon Class", "Magnetar Effect Beacon Class", "Pulsar Effect Beacon Class", "Red Giant Beacon Class", "Wolf Rayet Effect Beacon Class", "Incursion", "Drifter Incursion", ] let n = prefixes.count var arrays = [[NSManagedObjectID]](repeating: [], count: n + 1) types: for type in types { for (i, prefix) in prefixes.enumerated() { if type.typeName?.hasPrefix(prefix) == true { arrays[i].append(type.objectID) continue types } } arrays[n].append(type.objectID) } let sections = arrays.enumerated().map { (i, array) -> DefaultTreeSection in let prefix = i < n ? prefixes[i] : NSLocalizedString("Other", comment: "") let rows = array.map({NCTypeInfoRow(objectID: $0, managedObjectContext: managedObjectContext, accessoryType: .detailButton)}) return DefaultTreeSection(nodeIdentifier: prefix, title: prefix.uppercased(), children: rows) } return .init(RootNode(sections)) } @IBAction func onClear(_ sender: Any) { completionHandler(self, nil) } //MARK: - TreeControllerDelegate override func treeController(_ treeController: TreeController, didSelectCellWithNode node: TreeNode) { super.treeController(treeController, didSelectCellWithNode: node) guard let node = node as? NCTypeInfoRow, let type = node.type else {return} completionHandler(self, type) } override func treeController(_ treeController: TreeController, accessoryButtonTappedWithNode node: TreeNode) { super.treeController(treeController, accessoryButtonTappedWithNode: node) guard let node = node as? NCTypeInfoRow, let type = node.type else {return} Router.Database.TypeInfo(type).perform(source: self, sender: treeController.cell(for: node)) } }
lgpl-2.1
5d981f1328af889a672a3344d9a7989f
33.742574
192
0.726988
4.142857
false
false
false
false
SnipDog/ETV
ETV/Moudel/Mine/MineViewController.swift
1
1260
// // MineViewController.swift // ETV // // Created by Heisenbean on 16/11/13. // Copyright © 2016年 Heisenbean. All rights reserved. // import UIKit class MineViewController: UITableViewController { override func viewDidLoad() { super.viewDidLoad() tableView.contentInset = UIEdgeInsetsMake(-26, 0, 0, 0) navigationItem.rightBarButtonItem = UIBarButtonItem.itemWith("mine_settingIcon2", highBg: "mine_settingIcon2_press", target: self, imageInset: .zero, action: #selector(setting)) } func setting() { let setttingVc = UIStoryboard.initialViewController("Setting") navigationController?.pushViewController(setttingVc, animated: true) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) if indexPath.section == 0{ let login = UIStoryboard.initialViewController("Login") navigationController?.pushViewController(login, animated: true) } } }
mit
5673d3714d4e705bfd9c6dcf48df4305
30.425
185
0.682578
4.853282
false
false
false
false
KrishMunot/swift
stdlib/public/SwiftOnoneSupport/SwiftOnoneSupport.swift
2
4441
//===----------------------------------------------------------------------===// // // 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 // //===----------------------------------------------------------------------===// // Pre-specialization of some popular generic classes and functions. //===----------------------------------------------------------------------===// import Swift struct _Prespecialize { class C {} // Create specializations for the arrays of most // popular builtin integer and floating point types. static internal func _specializeArrays() { func _createArrayUser<Element : Comparable>(_ sampleValue: Element) { // Initializers. let _: [Element] = [ sampleValue ] var a = [Element](repeating: sampleValue, count: 1) // Read array element let _ = a[0] // Set array elements for j in 1..<a.count { a[0] = a[j] a[j-1] = a[j] } for i1 in 0..<a.count { for i2 in 0..<a.count { a[i1] = a[i2] } } a[0] = sampleValue // Get count and capacity let _ = a.count + a.capacity // Iterate over array for e in a { print(e) print("Value: \(e)") } print(a) // Reserve capacity a.removeAll() a.reserveCapacity(100) // Sort array let _ = a.sorted { (a: Element, b: Element) in a < b } a.sort { (a: Element, b: Element) in a < b } // force specialization of append. a.append(a[0]) // force specialization of print<Element> print(sampleValue) print("Element:\(sampleValue)") } func _createArrayUserWithoutSorting<Element>(_ sampleValue: Element) { // Initializers. let _: [Element] = [ sampleValue ] var a = [Element](repeating: sampleValue, count: 1) // Read array element let _ = a[0] // Set array elements for j in 0..<a.count { a[0] = a[j] } for i1 in 0..<a.count { for i2 in 0..<a.count { a[i1] = a[i2] } } a[0] = sampleValue // Get length and capacity let _ = a.count + a.capacity // Iterate over array for e in a { print(e) print("Value: \(e)") } print(a) // Reserve capacity a.removeAll() a.reserveCapacity(100) // force specialization of append. a.append(a[0]) // force specialization of print<Element> print(sampleValue) print("Element:\(sampleValue)") } // Force pre-specialization of arrays with elements of different // integer types. _createArrayUser(1 as Int) _createArrayUser(1 as Int8) _createArrayUser(1 as Int16) _createArrayUser(1 as Int32) _createArrayUser(1 as Int64) _createArrayUser(1 as UInt) _createArrayUser(1 as UInt8) _createArrayUser(1 as UInt16) _createArrayUser(1 as UInt32) _createArrayUser(1 as UInt64) // Force pre-specialization of arrays with elements of different // floating point types. _createArrayUser(1.5 as Float) _createArrayUser(1.5 as Double) // Force pre-specialization of string arrays _createArrayUser("a" as String) // Force pre-specialization of arrays with elements of different // character and unicode scalar types. _createArrayUser("a" as Character) _createArrayUser("a" as UnicodeScalar) _createArrayUserWithoutSorting("a".utf8) _createArrayUserWithoutSorting("a".utf16) _createArrayUserWithoutSorting("a".unicodeScalars) _createArrayUserWithoutSorting("a".characters) } // Force pre-specialization of Range<Int> static internal func _specializeRanges() -> Int { let a = [Int](repeating: 1, count: 10) var count = 0 // Specialize Range for integers for i in 0..<a.count { count += a[i] } return count } } // Mark with optimize.sil.never to make sure its not get // rid of by dead function elimination. @_semantics("optimize.sil.never") internal func _swift_forcePrespecializations() { _Prespecialize._specializeArrays() _Prespecialize._specializeRanges() }
apache-2.0
35d375670391e9af3ed5be8b484c0b11
25.915152
80
0.582752
4.270192
false
false
false
false
chenchangqing/CustomSearchBar
Example/CustomSearchBar/ViewController.swift
1
7634
// // ViewController.swift // CustomSearchBar // // Created by chenchangqing on 12/23/2015. // Copyright (c) 2015 chenchangqing. All rights reserved. // import UIKit let NAVIGATION_BORDER_COLOR:UIColor = UIColor(red: 236.0/255.0, green: 0.0/255.0, blue: 39.0/255.0, alpha: 1.0) let NAVIGATION_BORDER_WIDTH:CGFloat = 2.0 let NAVIGATION_BORDER_TAG:Int = 100 class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UISearchResultsUpdating, UISearchBarDelegate { @IBOutlet weak var tblSearchResults: UITableView! @IBOutlet weak var searchBarButtonItem: UIBarButtonItem! var dataArray = [String]() var searchController: UISearchController! var uiSearchBarView: UIView! // MARK: - Life Cycle override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. tblSearchResults.delegate = self tblSearchResults.dataSource = self loadListOfCountries() configureSearchBarButtonItem() configureNavigationBar() configureSearchController() configureSearchBar() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Custom functions func loadListOfCountries() { // Specify the path to the countries list file. let pathToFile = NSBundle.mainBundle().pathForResource("countries", ofType: "txt") if let path = pathToFile { // Load the file contents as a string. let countriesString = try! String(contentsOfFile: path, encoding: NSUTF8StringEncoding) // Append the countries from the string to the dataArray array by breaking them using the line change character. dataArray = countriesString.componentsSeparatedByString("\n") // Reload the tableview. tblSearchResults.reloadData() } } func configureSearchBarButtonItem() { searchBarButtonItem.tintColor = NAVIGATION_BORDER_COLOR } func configureNavigationBar() { self.navigationController?.navigationBar.translucent = true self.navigationController?.navigationBar.viewWithTag(NAVIGATION_BORDER_TAG)?.removeFromSuperview() let navigationBarBorderOrigin = CGPoint(x: 0, y: self.navigationController!.navigationBar.frame.height) let navigationBarBorderSize = CGSize(width: self.navigationController!.navigationBar.frame.width, height: NAVIGATION_BORDER_WIDTH) let navigationbarBorderRect = CGRect(origin: navigationBarBorderOrigin, size: navigationBarBorderSize) let navigationBarBorder = UIView(frame: navigationbarBorderRect) navigationBarBorder.backgroundColor = NAVIGATION_BORDER_COLOR navigationBarBorder.opaque = true navigationBarBorder.tag = NAVIGATION_BORDER_TAG self.navigationController!.navigationBar.addSubview(navigationBarBorder) } func configureSearchController() { let searchResultsController = self.storyboard?.instantiateViewControllerWithIdentifier("SearchResultsNavController") searchController = UISearchController(searchResultsController: searchResultsController) searchController.searchResultsUpdater = self searchController.dimsBackgroundDuringPresentation = true searchController.hidesNavigationBarDuringPresentation = false } func configureSearchBar() { let uiSearchBarViewRect = CGRect(origin: CGPoint(x: 0, y: -64), size: CGSize(width: self.view.frame.width, height: 64)) uiSearchBarView = UIView(frame: uiSearchBarViewRect) uiSearchBarView.backgroundColor = UIColor.whiteColor() searchController.searchBar.searchBarStyle = .Minimal searchController.searchBar.delegate = self searchController.searchBar.backgroundColor = UIColor.whiteColor() searchController.searchBar.tintColor = NAVIGATION_BORDER_COLOR searchController.searchBar.showsCancelButton = true searchController.searchBar.placeholder = "Search here..." searchController.searchBar.sizeToFit() let contanier = UIView(frame: CGRect(origin: CGPoint(x: 0, y: 20), size: CGSize(width: self.view.frame.width, height: 44))) contanier.addSubview(searchController.searchBar) uiSearchBarView.addSubview(contanier) self.navigationController!.view.addSubview(uiSearchBarView) } @IBAction func startSearch(sender: UIBarButtonItem) { UIView.animateWithDuration(0.25) { () -> Void in self.uiSearchBarView.frame = CGRect(x: 0, y: 0, width: self.view.frame.width, height: 64) self.searchController.searchBar.becomeFirstResponder() } } // MARK: - UITableView Delegate and Datasource functions func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return dataArray.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("idCell", forIndexPath: indexPath) cell.textLabel?.text = dataArray[indexPath.row] return cell } func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return 60.0 } // MARK: - UISearchBarDelegate functions func searchBarCancelButtonClicked(searchBar: UISearchBar) { UIView.animateWithDuration(0.25) { () -> Void in self.searchController.searchBar.text = "" self.searchController.searchBar.resignFirstResponder() self.uiSearchBarView.frame = CGRectMake(0, -64, self.view.frame.width, 64) } } func searchBarSearchButtonClicked(searchBar: UISearchBar) { searchController.searchBar.resignFirstResponder() } // MARK: - UISearchResultsUpdating delegate function func updateSearchResultsForSearchController(searchController: UISearchController) { guard let searchString = searchController.searchBar.text else { return } // Filter the data array and get only those countries that match the search text. let filteredArray = dataArray.filter({ (country) -> Bool in let countryText:NSString = country return (countryText.rangeOfString(searchString, options: NSStringCompareOptions.CaseInsensitiveSearch).location) != NSNotFound }) // Reload the tableview. print(self.searchController.searchResultsController as? UINavigationController) print((self.searchController.searchResultsController as? UINavigationController)?.topViewController) if let searchResultsController = (self.searchController.searchResultsController as? UINavigationController)?.topViewController as? SearchResultsViewController { searchResultsController.filteredArray = filteredArray searchResultsController.tableView.reloadData() } } }
mit
3feb5614a92186e02a4c354da73d3c66
36.605911
168
0.673173
5.950117
false
false
false
false
aschwaighofer/swift
stdlib/public/Darwin/Metal/Metal.swift
2
12344
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// @_exported import Metal // Clang module @available(macOS 10.11, iOS 8.0, tvOS 8.0, *) extension MTLBlitCommandEncoder { public func fill(buffer: MTLBuffer, range: Range<Int>, value: UInt8) { __fill(buffer, range: NSRange(location: range.lowerBound, length: range.count), value: value) } @available(macOS 10.14, iOS 12.0, tvOS 12.0, *) public func resetCommandsInBuffer(_ buffer: MTLIndirectCommandBuffer, range: Range<Int>) { __resetCommands(in: buffer, with: NSRange(location: range.lowerBound, length: range.count)) } @available(macOS 10.14, iOS 12.0, tvOS 12.0, *) public func copyIndirectCommandBuffer (_ buffer: MTLIndirectCommandBuffer, sourceRange: Range<Int>, destination: MTLIndirectCommandBuffer, destinationIndex: Int) { __copy (buffer, sourceRange: NSRange(location: sourceRange.lowerBound, length: sourceRange.count),destination: destination, destinationIndex: destinationIndex) } @available(macOS 10.14, iOS 12.0, tvOS 12.0, *) public func optimizeIndirectCommandBuffer (_ buffer: MTLIndirectCommandBuffer, range: Range<Int>) { __optimizeIndirectCommandBuffer(buffer, with: NSRange(location: range.lowerBound, length: range.count)) } } @available(macOS 10.11, iOS 8.0, tvOS 8.0, *) extension MTLBuffer { #if os(macOS) @available(macOS, introduced: 10.11) public func didModifyRange(_ range: Range<Int>) { __didModifyRange(NSRange(location: range.lowerBound, length: range.count)) } #endif @available(macOS 10.12, iOS 10.0, tvOS 10.0, *) public func addDebugMarker(_ marker: String, range: Range<Int>) { __addDebugMarker(marker, range: NSRange(location: range.lowerBound, length: range.count)) } } @available(macOS 10.11, iOS 8.0, tvOS 8.0, *) extension MTLComputeCommandEncoder { @available(macOS 10.13, iOS 11.0, tvOS 11.0, *) public func useResources(_ resources: [MTLResource], usage: MTLResourceUsage) { __use(resources, count: resources.count, usage: usage) } @available(macOS 10.13, iOS 11.0, tvOS 11.0, *) public func useHeaps(_ heaps: [MTLHeap]) { __use(heaps, count: heaps.count) } public func setBuffers(_ buffers: [MTLBuffer?], offsets: [Int], range: Range<Int>) { __setBuffers(buffers, offsets: offsets, with: NSRange(location: range.lowerBound, length: range.count)) } public func setTextures(_ textures: [MTLTexture?], range: Range<Int>) { __setTextures(textures, with: NSRange(location: range.lowerBound, length: range.count)) } public func setSamplerStates(_ samplers: [MTLSamplerState?], range: Range<Int>) { __setSamplerStates(samplers, with: NSRange(location: range.lowerBound, length: range.count)) } public func setSamplerStates(_ samplers: [MTLSamplerState?], lodMinClamps: [Float], lodMaxClamps: [Float], range: Range<Int>) { __setSamplerStates(samplers, lodMinClamps: lodMinClamps, lodMaxClamps: lodMaxClamps, with: NSRange(location: range.lowerBound, length: range.count)) } @available(macOS 10.14, iOS 12.0, tvOS 12.0, *) public func memoryBarrier(resources:[MTLResource]) { __memoryBarrier(resources: resources, count: resources.count) } } @available(macOS 10.11, iOS 8.0, tvOS 8.0, *) extension MTLDevice { @available(macOS 10.13, iOS 11.0, tvOS 11.0, *) public func getDefaultSamplePositions(sampleCount: Int) -> [MTLSamplePosition] { return [MTLSamplePosition](unsafeUninitializedCapacity: sampleCount) { buf, initializedCount in __getDefaultSamplePositions(buf.baseAddress!, count: sampleCount) initializedCount = sampleCount } } } #if os(macOS) @available(swift 4) @available(macOS 10.13, *) public func MTLCopyAllDevicesWithObserver(handler: @escaping MTLDeviceNotificationHandler) -> (devices:[MTLDevice], observer:NSObject) { var observer: NSObjectProtocol? let devices = __MTLCopyAllDevicesWithObserver(&observer, handler) // FIXME: The force cast here isn't great – ideally we would return the // observer as an NSObjectProtocol. return (devices, observer as! NSObject) } #endif @available(macOS 10.12, iOS 10.0, tvOS 10.0, *) extension MTLFunctionConstantValues { public func setConstantValues(_ values: UnsafeRawPointer, type: MTLDataType, range: Range<Int>) { __setConstantValues(values, type: type, with: NSRange(location: range.lowerBound, length: range.count)) } } @available(macOS 10.13, iOS 11.0, tvOS 11.0, *) extension MTLArgumentEncoder { public func setBuffers(_ buffers: [MTLBuffer?], offsets: [Int], range: Range<Int>) { __setBuffers(buffers, offsets: offsets, with: NSRange(location: range.lowerBound, length: range.count)) } public func setTextures(_ textures: [MTLTexture?], range: Range<Int>) { __setTextures(textures, with: NSRange(location: range.lowerBound, length: range.count)) } public func setSamplerStates(_ samplers: [MTLSamplerState?], range: Range<Int>) { __setSamplerStates(samplers, with: NSRange(location: range.lowerBound, length: range.count)) } #if os(macOS) @available(macOS 10.14, *) public func setRenderPipelineStates(_ pipelines: [MTLRenderPipelineState?], range: Range<Int>) { __setRenderPipelineStates(pipelines, with: NSRange(location: range.lowerBound, length: range.count)) } #endif @available(macOS 10.14, iOS 12.0, tvOS 12.0, *) public func setIndirectCommandBuffers(_ buffers: [MTLIndirectCommandBuffer?], range: Range<Int>) { __setIndirectCommandBuffers(buffers, with: NSRange(location: range.lowerBound, length: range.count)) } } @available(macOS 10.11, iOS 8.0, tvOS 8.0, *) extension MTLRenderCommandEncoder { @available(macOS 10.13, iOS 11.0, tvOS 11.0, *) public func useResources(_ resources: [MTLResource], usage: MTLResourceUsage) { __use(resources, count: resources.count, usage: usage) } @available(macOS 10.13, iOS 11.0, tvOS 11.0, *) public func useHeaps(_ heaps: [MTLHeap]) { __use(heaps, count: heaps.count) } #if os(macOS) || os(iOS) @available(macOS 10.13, iOS 12.0, *) public func setViewports(_ viewports: [MTLViewport]) { __setViewports(viewports, count: viewports.count) } @available(macOS 10.13, iOS 12.0, *) public func setScissorRects(_ scissorRects: [MTLScissorRect]) { __setScissorRects(scissorRects, count: scissorRects.count) } #endif public func setVertexBuffers(_ buffers: [MTLBuffer?], offsets: [Int], range: Range<Int>) { __setVertexBuffers(buffers, offsets: offsets, with: NSRange(location: range.lowerBound, length: range.count)) } public func setVertexTextures(_ textures: [MTLTexture?], range: Range<Int>) { __setVertexTextures(textures, with: NSRange(location: range.lowerBound, length: range.count)) } public func setVertexSamplerStates(_ samplers: [MTLSamplerState?], range: Range<Int>) { __setVertexSamplerStates(samplers, with: NSRange(location: range.lowerBound, length: range.count)) } public func setVertexSamplerStates(_ samplers: [MTLSamplerState?], lodMinClamps: [Float], lodMaxClamps: [Float], range: Range<Int>) { __setVertexSamplerStates(samplers, lodMinClamps: lodMinClamps, lodMaxClamps: lodMaxClamps, with: NSRange(location: range.lowerBound, length: range.count)) } public func setFragmentBuffers(_ buffers: [MTLBuffer?], offsets: [Int], range: Range<Int>) { __setFragmentBuffers(buffers, offsets: offsets, with: NSRange(location: range.lowerBound, length: range.count)) } public func setFragmentTextures(_ textures: [MTLTexture?], range: Range<Int>) { __setFragmentTextures(textures, with: NSRange(location: range.lowerBound, length: range.count)) } public func setFragmentSamplerStates(_ samplers: [MTLSamplerState?], range: Range<Int>) { __setFragmentSamplerStates(samplers, with: NSRange(location: range.lowerBound, length: range.count)) } public func setFragmentSamplerStates(_ samplers: [MTLSamplerState?], lodMinClamps: [Float], lodMaxClamps: [Float], range: Range<Int>) { __setFragmentSamplerStates(samplers, lodMinClamps: lodMinClamps, lodMaxClamps: lodMaxClamps, with: NSRange(location: range.lowerBound, length: range.count)) } #if os(iOS) @available(iOS 11.0, *) public func setTileBuffers(_ buffers: [MTLBuffer?], offsets: [Int], range: Range<Int>) { __setTileBuffers(buffers, offsets: offsets, with: NSRange(location: range.lowerBound, length: range.count)) } @available(iOS 11.0, *) public func setTileTextures(_ textures: [MTLTexture?], range: Range<Int>) { __setTileTextures(textures, with: NSRange(location: range.lowerBound, length: range.count)) } @available(iOS 11.0, *) public func setTileSamplerStates(_ samplers: [MTLSamplerState?], range: Range<Int>) { __setTileSamplerStates(samplers, with: NSRange(location: range.lowerBound, length: range.count)) } @available(iOS 11.0, *) public func setTileSamplerStates(_ samplers: [MTLSamplerState?], lodMinClamps: [Float], lodMaxClamps: [Float], range: Range<Int>) { __setTileSamplerStates(samplers, lodMinClamps: lodMinClamps, lodMaxClamps: lodMaxClamps, with: NSRange(location: range.lowerBound, length: range.count)) } #endif #if os(macOS) @available(macOS 10.14, *) public func memoryBarrier(resources: [MTLResource], after: MTLRenderStages, before: MTLRenderStages) { __memoryBarrier(resources: resources, count: resources.count, after: after, before: before) } #endif @available(macOS 10.14, iOS 12.0, tvOS 12.0, *) public func executeCommandsInBuffer(_ buffer: MTLIndirectCommandBuffer, range: Range<Int>) { __executeCommands(in: buffer, with: NSRange(location: range.lowerBound, length: range.count)) } #if os(macOS) @available(macOS 10.14, *) public func executeCommandsInBuffer(_ buffer: MTLIndirectCommandBuffer, indirectBuffer indirectRangeBuffer: MTLBuffer, offset: Int) { __executeCommands(in: buffer, indirectBuffer: indirectRangeBuffer, indirectBufferOffset: offset) } #endif } @available(macOS 10.14, iOS 12.0, tvOS 12.0, *) extension MTLIndirectCommandBuffer { public func reset(_ range: Range<Int>) { __reset(with: NSRange(location: range.lowerBound, length: range.count)) } } @available(macOS 10.11, iOS 8.0, tvOS 8.0, *) extension MTLRenderPassDescriptor { @available(macOS 10.13, iOS 11.0, tvOS 11.0, *) public func setSamplePositions(_ positions: [MTLSamplePosition]) { __setSamplePositions(positions, count: positions.count) } @available(macOS 10.13, iOS 11.0, tvOS 11.0, *) public func getSamplePositions() -> [MTLSamplePosition] { let numPositions = __getSamplePositions(nil, count: 0) return [MTLSamplePosition](unsafeUninitializedCapacity: numPositions) { buf, initializedCount in __getSamplePositions(buf.baseAddress!, count: numPositions) initializedCount = numPositions } } } @available(macOS 10.11, iOS 8.0, tvOS 8.0, *) extension MTLTexture { @available(macOS 10.11, iOS 9.0, tvOS 9.0, *) public func makeTextureView(pixelFormat: MTLPixelFormat, textureType: MTLTextureType, levels levelRange: Range<Int>, slices sliceRange: Range<Int>) -> MTLTexture? { return __newTextureView(with: pixelFormat, textureType: textureType, levels: NSRange(location: levelRange.lowerBound, length: levelRange.count), slices: NSRange(location: sliceRange.lowerBound, length: sliceRange.count)) } }
apache-2.0
52b0ff01f677be6be8f63ffcc8b37f33
42.765957
228
0.682871
4.25733
false
false
false
false
jorjuela33/JOCoreDataKit
JOCoreDataKit/Extensions/NSPersistentStoreCoordinator+Additions.swift
1
2941
// // NSPersistentStoreCoordinator+Additions.swift // // Copyright © 2017. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import CoreData extension NSPersistentStoreCoordinator { // MARK: Instance methods /// creates a new store /// /// url - the location for the store /// type - the store type @discardableResult public func createPersistentStore(atURL url: URL?, type: String = NSSQLiteStoreType) -> Error? { var error: Error? do { let options = [NSMigratePersistentStoresAutomaticallyOption: true, NSInferMappingModelAutomaticallyOption: true] try addPersistentStore(ofType: type, configurationName: nil, at: url, options: options) } catch let storeError { error = storeError } return error } /// destroy the persistent store for the given context /// /// url - the url for the store location /// type - the store type public func destroyPersistentStore(atURL url: URL, type: String = NSSQLiteStoreType) { do { if #available(iOS 9.0, *) { try destroyPersistentStore(at: url, ofType: type, options: nil) } else if let persistentStore = persistentStores.last { try remove(persistentStore) try FileManager.default.removeItem(at: url) } } catch { print("unable to destroy perstistent store at url: \(url), type: \(type)") } } /// migrates the current store to the given url /// /// url - the new location for the store public func migrate(to url: URL) { guard let currentStore = persistentStores.last else { return } try! migratePersistentStore(currentStore, to: url, options: nil, withType: NSSQLiteStoreType) } }
mit
2522ff002fdaa8d0489d6e35465f8cb7
38.2
124
0.662245
4.835526
false
false
false
false
phimage/Arithmosophi
Samples/Optional.swift
1
3001
// // Optional.swift // Arithmosophi /* The MIT License (MIT) Copyright (c) 2015 Eric Marchand (phimage) 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 Arithmosophi public enum OptionalEnum<T: Initializable>: LogicalOperationsType, Equatable, Initializable { case none case some(T) public init(_ value: T?) { if let v = value { self = .some(v) } else { self = .none } } init(_ value: T) { self = .some(value) } public init() { self = .none } public func unwrap() -> T { switch self { case .some(let value): return value case .none: fatalError("Unexpectedly found nil whie unwrapping an Optional value") } } } public func == <T: Equatable>(left: OptionalEnum<T>, right: OptionalEnum<T>) -> Bool { switch (left, right) { case (.none, .none): return true case (.none, .some), (.some, .none): return false case (.some(let x), .some(let y)): return x == y } } public func == <T>(left: OptionalEnum<T>, right: OptionalEnum<T>) -> Bool { switch (left, right) { case (.none, .none): return true case (.none, .some), (.some, .none): return false case (.some, .some): return true } } public func && <T>(left: OptionalEnum<T>, right: @autoclosure () throws -> OptionalEnum<T>) rethrows -> OptionalEnum<T> { switch left { case .none: return .none case .some: return try right() } } public func || <T>(left: OptionalEnum<T>, right: @autoclosure () throws -> OptionalEnum<T>) rethrows -> OptionalEnum<T> { switch left { case .none: return try right() case .some: return left } } public prefix func ! <T>(value: OptionalEnum<T>) -> OptionalEnum<T> { switch value { case .none: return .some(T()) case .some: return .none } } public func ||= <T>(lhs: inout OptionalEnum<T>?, rhs: OptionalEnum<T>) { if lhs == nil { lhs = rhs } }
mit
ba7dc81bac7477677edbdf90183e7ca9
29.01
122
0.653449
3.985392
false
false
false
false
yajeka/PS
PS/Master/profileController.swift
1
1121
// // profileController.swift // PS // // Created by Yauheni Yarotski on 20.03.16. // Copyright © 2016 hackathon. All rights reserved. // import UIKit class profileController: UIViewController { override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = UIColor(patternImage: UIImage(named: "background")!) hidesBottomBarWhenPushed = false // [[self navigationController] setNavigationBarHidden:YES animated:YES]; navigationController?.setNavigationBarHidden(true, animated: false) } @IBAction func createPostButtonPressed(sender: UIButton) { let sourceNVC = UIStoryboard(name: "Master", bundle: NSBundle.mainBundle()).instantiateViewControllerWithIdentifier("CreatePostViewControllerNav") // vc?.tabC = tabBarController presentViewController(sourceNVC, animated: true, completion: { let c = sourceNVC as? UINavigationController let b = c?.topViewController as? CreatePostViewController b?.tabC = self.tabBarController }) } }
lgpl-3.0
9bdfd43d088b12e88c220e69029eac46
30.111111
154
0.667857
5.283019
false
false
false
false
kickstarter/ios-oss
Kickstarter-iOS/Features/SettingsNotifications/Views/Cells/SettingsNotificationCell.swift
1
6778
import KsApi import Library import Prelude import UIKit protocol SettingsNotificationCellDelegate: AnyObject { func settingsNotificationCell(_ cell: SettingsNotificationCell, didFailToUpdateUser errorMessage: String) func settingsNotificationCell(_ cell: SettingsNotificationCell, didUpdateUser user: User) } final class SettingsNotificationCell: UITableViewCell, NibLoading, ValueCell { @IBOutlet fileprivate var arrowImageView: UIImageView! @IBOutlet fileprivate var emailNotificationsButton: UIButton! @IBOutlet fileprivate var projectCountLabel: UILabel! @IBOutlet fileprivate var pushNotificationsButton: UIButton! @IBOutlet fileprivate var stackView: UIStackView! @IBOutlet fileprivate var titleLabel: UILabel! weak var delegate: SettingsNotificationCellDelegate? private let viewModel: SettingsNotificationCellViewModelType = SettingsNotificationCellViewModel() private lazy var tapGesture: UITapGestureRecognizer = { UITapGestureRecognizer(target: self, action: #selector(cellBackgroundTapped)) }() private var notificationType: SettingsNotificationCellType? public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } func configureWith(value cellValue: SettingsNotificationCellValue) { self.notificationType = cellValue.cellType self.viewModel.inputs.configure(with: cellValue) let accessibilityElementsHidden = cellValue.cellType.accessibilityElementsHidden _ = self |> \.accessibilityTraits .~ cellValue.cellType.accessibilityTraits _ = self.stackView |> \.accessibilityElements .~ ( accessibilityElementsHidden ? [self.emailNotificationsButton, self.pushNotificationsButton].compact() : [] ) _ = self.titleLabel |> UILabel.lens.text .~ cellValue.cellType.title |> \.accessibilityElementsHidden .~ cellValue.cellType.accessibilityElementsHidden _ = self.arrowImageView |> UIImageView.lens.isHidden .~ cellValue.cellType.shouldHideArrowView |> UIImageView.lens.tintColor .~ .ksr_support_400 _ = self.projectCountLabel |> UILabel.lens.isHidden .~ cellValue.cellType.projectCountLabelHidden |> \.accessibilityElementsHidden .~ accessibilityElementsHidden } override func bindStyles() { super.bindStyles() _ = self |> baseTableViewCellStyle() _ = self.titleLabel |> settingsTitleLabelStyle _ = self.projectCountLabel |> UILabel.lens.textColor .~ .ksr_support_400 |> UILabel.lens.font .~ .ksr_body() _ = self.emailNotificationsButton |> notificationButtonStyle |> UIButton.lens.image(for: .normal) .~ Library.image( named: "email-icon", tintColor: .ksr_support_400, inBundle: Bundle.framework ) |> UIButton.lens.image(for: .highlighted) .~ Library.image( named: "email-icon", tintColor: .ksr_support_300, inBundle: Bundle.framework ) |> UIButton.lens.image(for: .selected) .~ Library.image( named: "email-icon", tintColor: .ksr_create_700, inBundle: Bundle.framework ) _ = self.pushNotificationsButton |> notificationButtonStyle |> UIButton.lens.image(for: .normal) .~ Library.image( named: "mobile-icon", tintColor: .ksr_support_400, inBundle: Bundle.framework ) |> UIButton.lens.image(for: .highlighted) .~ Library.image( named: "mobile-icon", tintColor: .ksr_support_300, inBundle: Bundle.framework ) |> UIButton.lens.image(for: .selected) .~ Library.image( named: "mobile-icon", tintColor: .ksr_create_700, inBundle: Bundle.framework ) } override func bindViewModel() { super.bindViewModel() self.emailNotificationsButton.rac.selected = self.viewModel.outputs.emailNotificationsEnabled self.emailNotificationsButton.rac.hidden = self.viewModel.outputs.emailNotificationButtonIsHidden self.emailNotificationsButton.rac.accessibilityLabel = self.viewModel.outputs.emailNotificationsButtonAccessibilityLabel self.projectCountLabel.rac.text = self.viewModel.outputs.projectCountText self.pushNotificationsButton.rac.selected = self.viewModel.outputs.pushNotificationsEnabled self.pushNotificationsButton.rac.hidden = self.viewModel.outputs.pushNotificationButtonIsHidden self.pushNotificationsButton.rac.accessibilityLabel = self.viewModel.outputs.pushNotificationsButtonAccessibilityLabel self.viewModel.outputs.enableButtonAnimation .observeForUI() .observeValues { [weak self] enableAnimation in guard let _self = self else { return } if enableAnimation { _self.addGestureRecognizer(_self.tapGesture) } else { _self.removeGestureRecognizer(_self.tapGesture) } } self.viewModel.outputs.updateCurrentUser .observeForControllerAction() .observeValues { [weak self] user in guard let _self = self else { return } _self.delegate?.settingsNotificationCell(_self, didUpdateUser: user) } self.viewModel.outputs.unableToSaveError .observeForControllerAction() .observeValues { [weak self] errorString in guard let _self = self else { return } _self.delegate?.settingsNotificationCell(_self, didFailToUpdateUser: errorString) } } @IBAction func emailNotificationsButtonTapped(_ sender: UIButton) { self.viewModel.inputs.didTapEmailNotificationsButton(selected: sender.isSelected) } @IBAction func pushNotificationsButtonTapped(_ sender: UIButton) { self.viewModel.inputs.didTapPushNotificationsButton(selected: sender.isSelected) } @IBAction func cellBackgroundTapped(_: Any) { let sizeTransform = CGAffineTransform(scaleX: 1.2, y: 1.2) let animationDuration: TimeInterval = 0.15 UIView.animate(withDuration: animationDuration, animations: { [weak self] in self?.pushNotificationsButton.transform = sizeTransform }, completion: { [weak self] _ in guard let _self = self else { return } _self.identityAnimation(for: _self.pushNotificationsButton) }) UIView.animate( withDuration: animationDuration, delay: 0.1, options: .curveEaseInOut, animations: { [weak self] in self?.emailNotificationsButton.transform = sizeTransform }, completion: { [weak self] _ in guard let _self = self else { return } _self.identityAnimation(for: _self.emailNotificationsButton) } ) } private func identityAnimation(for button: UIButton, duration: TimeInterval = 0.15) { UIView.animate(withDuration: duration, animations: { button.transform = .identity }, completion: nil) } }
apache-2.0
317687336944cb455f8040b624783c21
34.862434
107
0.712452
5.069559
false
false
false
false
apple/swift-nio
IntegrationTests/tests_04_performance/test_01_resources/test_bytebuffer_lots_of_rw.swift
1
2634
//===----------------------------------------------------------------------===// // // This source file is part of the SwiftNIO open source project // // Copyright (c) 2017-2021 Apple Inc. and the SwiftNIO project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of SwiftNIO project authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// import Dispatch import NIOCore func run(identifier: String) { measure(identifier: identifier) { let dispatchData = ("A" as StaticString).withUTF8Buffer { ptr in DispatchData(bytes: UnsafeRawBufferPointer(ptr)) } var buffer = ByteBufferAllocator().buffer(capacity: 7 * 1000) let foundationData = "A".data(using: .utf8)! let substring = Substring("A") @inline(never) func doWrites(buffer: inout ByteBuffer, dispatchData: DispatchData, substring: Substring) { /* these ones are zero allocations */ // buffer.writeBytes(foundationData) // see SR-7542 buffer.writeBytes([0x41]) buffer.writeBytes("A".utf8) buffer.writeString("A") buffer.writeStaticString("A") buffer.writeInteger(0x41, as: UInt8.self) /* those down here should be one allocation each (on Linux) */ buffer.writeBytes(dispatchData) // see https://bugs.swift.org/browse/SR-9597 /* these here are one allocation on all platforms */ buffer.writeSubstring(substring) } @inline(never) func doReads(buffer: inout ByteBuffer) { /* these ones are zero allocations */ let val = buffer.readInteger(as: UInt8.self) precondition(0x41 == val, "\(val!)") var slice = buffer.readSlice(length: 1) let sliceVal = slice!.readInteger(as: UInt8.self) precondition(0x41 == sliceVal, "\(sliceVal!)") buffer.withUnsafeReadableBytes { ptr in precondition(ptr[0] == 0x41) } /* those down here should be one allocation each */ let arr = buffer.readBytes(length: 1) precondition([0x41] == arr!, "\(arr!)") let str = buffer.readString(length: 1) precondition("A" == str, "\(str!)") } for _ in 0..<1000 { doWrites(buffer: &buffer, dispatchData: dispatchData, substring: substring) doReads(buffer: &buffer) } return buffer.readableBytes } }
apache-2.0
0d57828fd921a3b110336d0a2bb00b0b
38.909091
99
0.5653
4.695187
false
false
false
false
Chaosspeeder/YourGoals
YourGoals/UI/Controller/GoalDetailViewController.swift
1
10006
// // GoalDetailViewController.swift // YourGoals // // Created by André Claaßen on 24.10.17. // Copyright © 2017 André Claaßen. All rights reserved. // import UIKit import CoreData enum GoalDetailViewControllerMode { case tasksMode case habitsMode } protocol GoalDetailViewControllerDelegate { func goalChanged() func commitmentChanged() } /// show a goal and all of its tasks in detail. this controller enables you to add tasks and habits to your goal class GoalDetailViewController: UIViewController, EditActionableViewControllerDelegate, EditGoalFormControllerDelegate, ActionableTableViewDelegate { @IBOutlet weak var editGoalButton: UIButton! // container and constraints for animating this view @IBOutlet internal weak var contentContainerView: UIView! @IBOutlet internal weak var containerLeadingConstraint: NSLayoutConstraint! @IBOutlet internal weak var containerTrailingConstraint: NSLayoutConstraint! @IBOutlet internal weak var containerTopConstraint: NSLayoutConstraint! @IBOutlet internal weak var containerBottomConstraint: NSLayoutConstraint! @IBOutlet internal var headerHeightConstraint: NSLayoutConstraint! // view for presenting tasks and habits @IBOutlet internal weak var goalContentView: GoalContentView! @IBOutlet internal weak var tasksView: ActionableTableView! @IBOutlet private weak var toggleHabitsButton: UIButton! @IBOutlet weak var addNewActionableButton: UIButton! @IBOutlet weak var buttonView: UIView! @IBOutlet weak var closerButton: UIButton! /// Header Image Height var goal:Goal! var tasksOrdered: [Task]! var editActionable:Actionable? = nil let manager = GoalsStorageManager.defaultStorageManager var delegate:GoalDetailViewControllerDelegate? var reorderTableView: LongPressReorderTableView! var mode = GoalDetailViewControllerMode.tasksMode fileprivate func configure(goal:Goal) throws { // Do any additional setup after loading the view. self.goal = goal try self.goalContentView.show(goal: goal, forDate: Date(), goalIsActive: goal.isActive(forDate: Date()), backburnedGoals: goal.backburnedGoals, manager: self.manager) } override func viewDidLoad() { do { super.viewDidLoad() try configure(goal: self.goal) self.configureActionButtons(forMode: mode) self.configureTableView(forMode: mode) let swipeDown = UISwipeGestureRecognizer(target: self, action: #selector(handleGesture)) swipeDown.direction = .down self.view.addGestureRecognizer(swipeDown) } catch let error { self.showNotification(forError: error) } } func convertControllerModeToType(mode: GoalDetailViewControllerMode) -> ActionableType { switch mode { case .habitsMode: return .habit case .tasksMode: return .task } } func dataSourceForMode(_ mode: GoalDetailViewControllerMode) -> ActionableDataSource { let actionableType = convertControllerModeToType(mode: mode) return ActionableDataSourceProvider(manager: self.manager).dataSource(forGoal: self.goal, andType: actionableType) } func configureTableView(forMode mode: GoalDetailViewControllerMode) { let dataSource = dataSourceForMode(mode) self.tasksView.configure(manager: self.manager, dataSource: dataSource,delegate: self) } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) tasksView.reload() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @objc func handleGesture(gesture: UISwipeGestureRecognizer) -> Void { if gesture.direction == UISwipeGestureRecognizer.Direction.down { self.dismiss(animated: true, completion: nil) } } // override var prefersStatusBarHidden: Bool { return true } @IBAction func closeButtonDidPress(_ sender: Any) { dismiss(animated: true, completion: nil) } // MARK: - Navigation /// set the parameter for the actionable detail from the state of the current detail view controlelr /// /// - Parameter parameter: parameter block for the EditActionableViewControlle fileprivate func setEditActionableViewControllerParameter(parameter: EditActionableViewControllerParameter) { // make parameter variable var parameter = parameter parameter.goal = self.goal parameter.delegate = self parameter.editActionable = self.editActionable parameter.manager = self.manager switch mode { case .tasksMode: parameter.editActionableType = .task case .habitsMode: parameter.editActionableType = .habit } parameter.commitParameter() self.editActionable = nil } /// In a storyboard-based application, /// you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { guard let identifier = segue.identifier else { assertionFailure("no identifier set in segue \(segue)") return } switch identifier { case "presentEditActionable": let parameter = (segue.destination as! UINavigationController).topViewController! as! EditActionableViewControllerParameter setEditActionableViewControllerParameter(parameter: parameter) return case "presentEditGoal": var parameter = (segue.destination as! UINavigationController).topViewController! as! EditGoalSegueParameter parameter.delegate = self parameter.editGoal = self.goal parameter.commit() default: assertionFailure("couldn't prepare segue with destination: \(segue)") } } func refreshView() throws { self.tasksView.reload() try self.configure(goal: self.goal) } // MARK: - EditActionableViewControllerDelegate func createNewActionable(actionableInfo: ActionableInfo) throws { let goalComposer = GoalComposer(manager: self.manager) self.goal = try goalComposer.create(actionableInfo: actionableInfo, toGoal: goal).goal try self.refreshView() } func updateActionable(actionable: Actionable, updateInfo: ActionableInfo) throws { let goalComposer = GoalComposer(manager: self.manager) self.goal = try goalComposer.update(actionable: actionable, withInfo: updateInfo, forDate: Date()) try self.refreshView() } func deleteActionable(actionable: Actionable) throws { let goalComposer = GoalComposer(manager: self.manager) self.goal = try goalComposer.delete(actionable: actionable) try self.refreshView() } // MARK: - EditGoalFormControllerDelegate func createNewGoal(goalInfo: GoalInfo) { assertionFailure("this function") } func update(goal: Goal, withGoalInfo goalInfo: GoalInfo) { do { let goalUpdater = GoalUpdater(manager: self.manager) try goalUpdater.update(goal: goal, withGoalInfo: goalInfo) self.delegate?.goalChanged() try configure(goal: goal) } catch let error { self.showNotification(forError: error) } } func delete(goal: Goal) { do { let goalDeleter = GoalDeleter(manager: self.manager) try goalDeleter.delete(goal: goal) self.delegate?.goalChanged() } catch let error { self.showNotification(forError: error) } } func dismissController() { self.dismiss(animated: true, completion: nil) } // MARK: - tasks view delegate /// request for editing a task /// /// - Parameter task: the task func requestForEdit(actionable: Actionable) { self.editActionable = actionable performSegue(withIdentifier: "presentEditActionable", sender: self) } func goalChanged(goal: Goal) { do { self.goal = goal try self.configure(goal: goal) self.delegate?.goalChanged() } catch let error { self.showNotification(forError: error) } } func progressChanged(actionable: Actionable) { self.delegate?.goalChanged() } func configureActionButtons(forMode mode: GoalDetailViewControllerMode) { switch mode { case .habitsMode: self.addNewActionableButton.setTitle("Add Habit", for: .normal) self.toggleHabitsButton.setTitle("Show Tasks", for: .normal) case .tasksMode: self.addNewActionableButton.setTitle("Add Task", for: .normal) self.toggleHabitsButton.setTitle("Show Habits", for: .normal) } } /// toggle between habits and tasks and reload the table view @IBAction func toggleHabitsAction(_ sender: Any) { if self.mode == .tasksMode { self.mode = .habitsMode } else { self.mode = .tasksMode } configureActionButtons(forMode: self.mode) configureTableView(forMode: self.mode) } func commitmentChanged() { self.delegate?.goalChanged() } // MARK: - UI Events @IBAction func addNewActionableTouched(_ sender: Any) { self.editActionable = nil performSegue(withIdentifier: "presentEditActionable", sender: self) } @IBAction func editButtonTouched(_ sender: Any) { performSegue(withIdentifier: "presentEditGoal", sender: self) } }
lgpl-3.0
9a2da916a71a6a399014778a4fbe31e5
34.091228
174
0.659734
5.274789
false
false
false
false
zybug/firefox-ios
Client/Frontend/Browser/BrowserTrayAnimators.swift
2
15856
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import UIKit class TrayToBrowserAnimator: NSObject, UIViewControllerAnimatedTransitioning { func animateTransition(transitionContext: UIViewControllerContextTransitioning) { if let bvc = transitionContext.viewControllerForKey(UITransitionContextToViewControllerKey) as? BrowserViewController, let tabTray = transitionContext.viewControllerForKey(UITransitionContextFromViewControllerKey) as? TabTrayController { transitionFromTray(tabTray, toBrowser: bvc, usingContext: transitionContext) } } func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval { return 0.4 } } private extension TrayToBrowserAnimator { func transitionFromTray(tabTray: TabTrayController, toBrowser bvc: BrowserViewController, usingContext transitionContext: UIViewControllerContextTransitioning) { guard let container = transitionContext.containerView() else { return } guard let selectedTab = bvc.tabManager.selectedTab else { return } // Bug 1205464 - Top Sites tiles blow up or shrink after rotating // Force the BVC's frame to match the tab trays since for some reason on iOS 9 the UILayoutContainer in // the UINavigationController doesn't rotate the presenting view controller let os = NSProcessInfo().operatingSystemVersion switch (os.majorVersion, os.minorVersion, os.patchVersion) { case (9, _, _): bvc.view.frame = UIWindow().frame default: break } let tabManager = bvc.tabManager let displayedTabs = selectedTab.isPrivate ? tabManager.privateTabs : tabManager.normalTabs guard let expandFromIndex = displayedTabs.indexOf(selectedTab) else { return } // Hide browser components bvc.toggleSnackBarVisibility(show: false) toggleWebViewVisibility(show: false, usingTabManager: bvc.tabManager) bvc.homePanelController?.view.hidden = true // Take a snapshot of the collection view that we can scale/fade out. We don't need to wait for screen updates since it's already rendered on the screen let tabCollectionViewSnapshot = tabTray.collectionView.snapshotViewAfterScreenUpdates(false) tabTray.collectionView.alpha = 0 tabCollectionViewSnapshot.frame = tabTray.collectionView.frame container.insertSubview(tabCollectionViewSnapshot, aboveSubview: tabTray.view) // Create a fake cell to use for the upscaling animation let startingFrame = calculateCollapsedCellFrameUsingCollectionView(tabTray.collectionView, atIndex: expandFromIndex) let cell = createTransitionCellFromBrowser(bvc.tabManager.selectedTab, withFrame: startingFrame) cell.backgroundHolder.layer.cornerRadius = 0 container.insertSubview(bvc.view, aboveSubview: tabCollectionViewSnapshot) container.insertSubview(cell, aboveSubview: bvc.view) // Flush any pending layout/animation code in preperation of the animation call container.layoutIfNeeded() let finalFrame = calculateExpandedCellFrameFromBVC(bvc) bvc.footer.alpha = shouldDisplayFooterForBVC(bvc) ? 1 : 0 bvc.urlBar.isTransitioning = true // Re-calculate the starting transforms for header/footer views in case we switch orientation resetTransformsForViews([bvc.header, bvc.headerBackdrop, bvc.readerModeBar, bvc.footer, bvc.footerBackdrop]) transformHeaderFooterForBVC(bvc, toFrame: startingFrame, container: container) UIView.animateWithDuration(self.transitionDuration(transitionContext), delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 0, options: UIViewAnimationOptions.CurveEaseInOut, animations: { // Scale up the cell and reset the transforms for the header/footers cell.frame = finalFrame container.layoutIfNeeded() cell.title.transform = CGAffineTransformMakeTranslation(0, -cell.title.frame.height) resetTransformsForViews([bvc.header, bvc.footer, bvc.readerModeBar, bvc.footerBackdrop, bvc.headerBackdrop]) bvc.urlBar.updateAlphaForSubviews(1) tabCollectionViewSnapshot.transform = CGAffineTransformMakeScale(0.9, 0.9) tabCollectionViewSnapshot.alpha = 0 // Push out the navigation bar buttons let buttonOffset = tabTray.addTabButton.frame.width + TabTrayControllerUX.ToolbarButtonOffset tabTray.addTabButton.transform = CGAffineTransformTranslate(CGAffineTransformIdentity, buttonOffset , 0) tabTray.settingsButton.transform = CGAffineTransformTranslate(CGAffineTransformIdentity, -buttonOffset , 0) if #available(iOS 9, *) { tabTray.togglePrivateMode.transform = CGAffineTransformTranslate(CGAffineTransformIdentity, buttonOffset , 0) } }, completion: { finished in // Remove any of the views we used for the animation cell.removeFromSuperview() tabCollectionViewSnapshot.removeFromSuperview() bvc.footer.alpha = 1 bvc.startTrackingAccessibilityStatus() bvc.toggleSnackBarVisibility(show: true) toggleWebViewVisibility(show: true, usingTabManager: bvc.tabManager) bvc.homePanelController?.view.hidden = false bvc.urlBar.isTransitioning = false transitionContext.completeTransition(true) }) } } class BrowserToTrayAnimator: NSObject, UIViewControllerAnimatedTransitioning { func animateTransition(transitionContext: UIViewControllerContextTransitioning) { if let bvc = transitionContext.viewControllerForKey(UITransitionContextFromViewControllerKey) as? BrowserViewController, let tabTray = transitionContext.viewControllerForKey(UITransitionContextToViewControllerKey) as? TabTrayController { transitionFromBrowser(bvc, toTabTray: tabTray, usingContext: transitionContext) } } func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval { return 0.4 } } private extension BrowserToTrayAnimator { func transitionFromBrowser(bvc: BrowserViewController, toTabTray tabTray: TabTrayController, usingContext transitionContext: UIViewControllerContextTransitioning) { guard let container = transitionContext.containerView() else { return } guard let selectedTab = bvc.tabManager.selectedTab else { return } let tabManager = bvc.tabManager let displayedTabs = selectedTab.isPrivate ? tabManager.privateTabs : tabManager.normalTabs guard let scrollToIndex = displayedTabs.indexOf(selectedTab) else { return } // Insert tab tray below the browser and force a layout so the collection view can get it's frame right container.insertSubview(tabTray.view, belowSubview: bvc.view) // Force subview layout on the collection view so we can calculate the correct end frame for the animation tabTray.view.layoutSubviews() tabTray.collectionView.scrollToItemAtIndexPath(NSIndexPath(forItem: scrollToIndex, inSection: 0), atScrollPosition: .CenteredVertically, animated: false) // Build a tab cell that we will use to animate the scaling of the browser to the tab let expandedFrame = calculateExpandedCellFrameFromBVC(bvc) let cell = createTransitionCellFromBrowser(bvc.tabManager.selectedTab, withFrame: expandedFrame) cell.backgroundHolder.layer.cornerRadius = TabTrayControllerUX.CornerRadius cell.innerStroke.hidden = true // Take a snapshot of the collection view to perform the scaling/alpha effect let tabCollectionViewSnapshot = tabTray.collectionView.snapshotViewAfterScreenUpdates(true) tabCollectionViewSnapshot.frame = tabTray.collectionView.frame tabCollectionViewSnapshot.transform = CGAffineTransformMakeScale(0.9, 0.9) tabCollectionViewSnapshot.alpha = 0 tabTray.view.addSubview(tabCollectionViewSnapshot) container.addSubview(cell) cell.layoutIfNeeded() cell.title.transform = CGAffineTransformMakeTranslation(0, -cell.title.frame.size.height) // Hide views we don't want to show during the animation in the BVC bvc.homePanelController?.view.hidden = true bvc.toggleSnackBarVisibility(show: false) toggleWebViewVisibility(show: false, usingTabManager: bvc.tabManager) bvc.urlBar.isTransitioning = true // Since we are hiding the collection view and the snapshot API takes the snapshot after the next screen update, // the screenshot ends up being blank unless we set the collection view hidden after the screen update happens. // To work around this, we dispatch the setting of collection view to hidden after the screen update is completed. dispatch_async(dispatch_get_main_queue()) { tabTray.collectionView.hidden = true let finalFrame = calculateCollapsedCellFrameUsingCollectionView(tabTray.collectionView, atIndex: scrollToIndex) UIView.animateWithDuration(self.transitionDuration(transitionContext), delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 0, options: UIViewAnimationOptions.CurveEaseInOut, animations: { cell.frame = finalFrame cell.title.transform = CGAffineTransformIdentity cell.layoutIfNeeded() transformHeaderFooterForBVC(bvc, toFrame: finalFrame, container: container) bvc.urlBar.updateAlphaForSubviews(0) bvc.footer.alpha = 0 tabCollectionViewSnapshot.alpha = 1 var viewsToReset: [UIView?] = [tabCollectionViewSnapshot, tabTray.addTabButton, tabTray.settingsButton] if #available(iOS 9, *) { viewsToReset.append(tabTray.togglePrivateMode) } resetTransformsForViews(viewsToReset) }, completion: { finished in // Remove any of the views we used for the animation cell.removeFromSuperview() tabCollectionViewSnapshot.removeFromSuperview() tabTray.collectionView.hidden = false bvc.toggleSnackBarVisibility(show: true) toggleWebViewVisibility(show: true, usingTabManager: bvc.tabManager) bvc.homePanelController?.view.hidden = false bvc.stopTrackingAccessibilityStatus() bvc.urlBar.isTransitioning = false transitionContext.completeTransition(true) }) } } } private func transformHeaderFooterForBVC(bvc: BrowserViewController, toFrame finalFrame: CGRect, container: UIView) { let footerForTransform = footerTransform(bvc.footer.frame, toFrame: finalFrame, container: container) let headerForTransform = headerTransform(bvc.header.frame, toFrame: finalFrame, container: container) bvc.footer.transform = footerForTransform bvc.footerBackdrop.transform = footerForTransform bvc.header.transform = headerForTransform bvc.readerModeBar?.transform = headerForTransform bvc.headerBackdrop.transform = headerForTransform } private func footerTransform(var frame: CGRect, toFrame finalFrame: CGRect, container: UIView) -> CGAffineTransform { frame = container.convertRect(frame, toView: container) let endY = CGRectGetMaxY(finalFrame) - (frame.size.height / 2) let endX = CGRectGetMidX(finalFrame) let translation = CGPoint(x: endX - CGRectGetMidX(frame), y: endY - CGRectGetMidY(frame)) let scaleX = finalFrame.width / frame.width var transform = CGAffineTransformIdentity transform = CGAffineTransformTranslate(transform, translation.x, translation.y) transform = CGAffineTransformScale(transform, scaleX, scaleX) return transform } private func headerTransform(var frame: CGRect, toFrame finalFrame: CGRect, container: UIView) -> CGAffineTransform { frame = container.convertRect(frame, toView: container) let endY = CGRectGetMinY(finalFrame) + (frame.size.height / 2) let endX = CGRectGetMidX(finalFrame) let translation = CGPoint(x: endX - CGRectGetMidX(frame), y: endY - CGRectGetMidY(frame)) let scaleX = finalFrame.width / frame.width var transform = CGAffineTransformIdentity transform = CGAffineTransformTranslate(transform, translation.x, translation.y) transform = CGAffineTransformScale(transform, scaleX, scaleX) return transform } //MARK: Private Helper Methods private func calculateCollapsedCellFrameUsingCollectionView(collectionView: UICollectionView, atIndex index: Int) -> CGRect { if let attr = collectionView.collectionViewLayout.layoutAttributesForItemAtIndexPath(NSIndexPath(forItem: index, inSection: 0)) { return collectionView.convertRect(attr.frame, toView: collectionView.superview) } else { return CGRectZero } } private func calculateExpandedCellFrameFromBVC(bvc: BrowserViewController) -> CGRect { var frame = bvc.webViewContainer.frame // If we're navigating to a home panel and we were expecting to show the toolbar, add more height to end frame since // there is no toolbar for home panels if !bvc.shouldShowFooterForTraitCollection(bvc.traitCollection) { return frame } else if AboutUtils.isAboutURL(bvc.tabManager.selectedTab?.url) { frame.size.height += UIConstants.ToolbarHeight } return frame } private func shouldDisplayFooterForBVC(bvc: BrowserViewController) -> Bool { return bvc.shouldShowFooterForTraitCollection(bvc.traitCollection) && !AboutUtils.isAboutURL(bvc.tabManager.selectedTab?.url) } private func toggleWebViewVisibility(show show: Bool, usingTabManager tabManager: TabManager) { for i in 0..<tabManager.count { if let tab = tabManager[i] { tab.webView?.hidden = !show } } } private func resetTransformsForViews(views: [UIView?]) { for view in views { // Reset back to origin view?.transform = CGAffineTransformIdentity } } private func transformToolbarsToFrame(toolbars: [UIView?], toRect endRect: CGRect) { for toolbar in toolbars { // Reset back to origin toolbar?.transform = CGAffineTransformIdentity // Transform from origin to where we want them to end up if let toolbarFrame = toolbar?.frame { toolbar?.transform = CGAffineTransformMakeRectToRect(toolbarFrame, toFrame: endRect) } } } private func createTransitionCellFromBrowser(browser: Browser?, withFrame frame: CGRect) -> TabCell { let cell = TabCell(frame: frame) cell.background.image = browser?.screenshot cell.titleText.text = browser?.displayTitle if let browser = browser where browser.isPrivate { cell.style = .Dark } if let favIcon = browser?.displayFavicon { cell.favicon.sd_setImageWithURL(NSURL(string: favIcon.url)!) } else { var defaultFavicon = UIImage(named: "defaultFavicon") if browser?.isPrivate ?? false { defaultFavicon = defaultFavicon?.imageWithRenderingMode(.AlwaysTemplate) cell.favicon.image = defaultFavicon cell.favicon.tintColor = (browser?.isPrivate ?? false) ? UIColor.whiteColor() : UIColor.darkGrayColor() } else { cell.favicon.image = defaultFavicon } } return cell }
mpl-2.0
cec612ad3be677c1a8af1900a9d60bfa
47.638037
168
0.715691
5.814448
false
false
false
false
anzfactory/QiitaCollection
QiitaCollection/CommentListViewController.swift
1
14585
// // CommentListViewController.swift // QiitaCollection // // Created by ANZ on 2015/02/28. // Copyright (c) 2015年 anz. All rights reserved. // import UIKit class CommentListViewController: BaseViewController, UITableViewDataSource, UITableViewDelegate { enum InputStatus { case None, Writing, Confirm } // MARK: UI @IBOutlet weak var tableView: BaseTableView! @IBOutlet weak var comment: UITextView! @IBOutlet weak var constraintCommentHeight: NSLayoutConstraint! // MARK: プロパティ var displayEntryId: String = "" var displayEntryTitle: String = "" var openTextView: Bool = false var inputStatus: InputStatus = .None var targetComment: CommentEntity? = nil // MARK: ライフサイクル override func viewDidLoad() { super.viewDidLoad() self.comment.backgroundColor = UIColor.backgroundSub() self.comment.textColor = UIColor.textBase() self.comment.hidden = true self.constraintCommentHeight.constant = 0.0 self.title = "コメント" self.tableView.estimatedRowHeight = 104 self.tableView.rowHeight = UITableViewAutomaticDimension self.tableView.dataSource = self self.tableView.delegate = self self.tableView.setupRefreshControl { () -> Void in self.refresh() } self.setupNavigationBar() NSNotificationCenter.defaultCenter().addObserver(self, selector: "receiveKeyboardShowNotification:", name: UIKeyboardWillShowNotification, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: "receiveKeyboardDidShowNotification:", name: UIKeyboardDidShowNotification, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: "receiveKeyboardHideNotification:", name: UIKeyboardWillHideNotification, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: "receiveKeyboardDidHideNotification:", name: UIKeyboardDidHideNotification, object: nil) } deinit { NSNotificationCenter.defaultCenter().removeObserver(self) } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) if !self.isBeingPresented() && !self.isMovingToParentViewController() { return } if self.displayEntryId.isEmpty { fatalError("required display entry id...") } self.refresh() } // MARK: メソッド func setupNavigationBar() { if self.openTextView { let edit: UIBarButtonItem = UIBarButtonItem(image: UIImage(named: "bar_item_check"), style: UIBarButtonItemStyle.Plain, target: self, action: "tapCheck") edit.tintColor = UIColor.tintAttention() self.navigationItem.rightBarButtonItem = edit } else { let edit: UIBarButtonItem = UIBarButtonItem(image: UIImage(named: "bar_item_pencil"), style: UIBarButtonItemStyle.Plain, target: self, action: "tapEdit") self.navigationItem.rightBarButtonItem = edit } } func refresh() { self.tableView.page = 1 self.load() } func load() { NSNotificationCenter.defaultCenter().postNotificationName(QCKeys.Notification.ShowLoadingWave.rawValue, object: nil) self.account.comments(self.tableView.page, entryId: self.displayEntryId) { (total, items) -> Void in if total == 0 { Toast.show("コメントが投稿されていません…", style: JFMinimalNotificationStytle.StyleInfo) // 1件しかなかったコメントを削除した場合はこっちにくるから、 // クリアしょりをいれとく self.tableView.clearItems() } else { self.tableView.loadedItems(total, items: items, isAppendable: nil) } NSNotificationCenter.defaultCenter().postNotificationName(QCKeys.Notification.HideLoadingWave.rawValue, object: nil) } } func tapThumb(cell: CommentTableViewCell) { let entity: CommentEntity = self.tableView.items[cell.tag] as! CommentEntity let vc: UserDetailViewController = self.storyboard?.instantiateViewControllerWithIdentifier("UserDetailVC") as! UserDetailViewController vc.displayUserId = entity.postUser.id NSNotificationCenter.defaultCenter().postNotificationName(QCKeys.Notification.PushViewController.rawValue, object: vc) } func tapEdit() { self.prepareComment("") } func tapCheck() { if !self.openTextView { return } self.inputStatus = .Confirm self.comment.resignFirstResponder() } func tapCommentEdit(cell: CommentTableViewCell) { if self.account is QiitaAccount == false { return } let entity: CommentEntity = self.tableView.items[cell.tag] as! CommentEntity if (self.account as! QiitaAccount).canCommentEdit(entity.postUser.id) == false { println("can not edit") return } // 編集なのか、削除なのか let params = [ QCKeys.AlertController.Style.rawValue : UIAlertControllerStyle.ActionSheet.rawValue, QCKeys.AlertController.Title.rawValue : "選んで下さい", QCKeys.AlertController.Description.rawValue: "コメントを編集しますか?削除しますか??", QCKeys.AlertController.Actions.rawValue : [ UIAlertAction(title: "編集", style: UIAlertActionStyle.Default, handler: { (action) -> Void in self.prepareComment(entity.body) }), UIAlertAction(title: "削除", style: UIAlertActionStyle.Default, handler: { (action) -> Void in self.confirmDeleteComment() }), UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel, handler: { (action) -> Void in // なにもしない }) ] ] self.targetComment = entity NSNotificationCenter.defaultCenter().postNotificationName(QCKeys.Notification.ShowAlertController.rawValue, object: self, userInfo: params as [NSObject : AnyObject]) } func prepareComment(defaultComment: String) { if self.openTextView { return } self.openTextView = true self.comment.text = defaultComment.removeExceptionUnicode() self.comment.becomeFirstResponder() } func openCommentField(keyboardHeight: CGFloat) { self.inputStatus = .Writing self.comment.hidden = false self.constraintCommentHeight.constant = self.tableView.bounds.size.height - keyboardHeight UIView.animateWithDuration(0.5, animations: { () -> Void in self.view.layoutIfNeeded() }) } func fullscreenComment() { self.constraintCommentHeight.constant = self.tableView.bounds.size.height UIView.animateWithDuration(0.3, animations: { () -> Void in self.view.layoutIfNeeded() }) } func dismissCommentField() { self.constraintCommentHeight.constant = 0.0 UIView.animateWithDuration(0.3, animations: { () -> Void in self.view.layoutIfNeeded() }) { (finished) -> Void in self.comment.hidden = true self.inputStatus = .None self.openTextView = false self.setupNavigationBar() } } func postComment() { if let qiitaAccount = self.account as? QiitaAccount { if self.comment.text.isEmpty { Toast.show("コメントを入力してください...", style: JFMinimalNotificationStytle.StyleWarning) return } let completion = {(isError: Bool) -> Void in if isError { Toast.show("コメントできませんでした...", style: JFMinimalNotificationStytle.StyleError) return } self.fin() } if let comm = self.targetComment { qiitaAccount.commentEdit(comm.id, text: self.comment.text, completion: completion) } else { qiitaAccount.comment(self.displayEntryId, text: self.comment.text, completion: completion) } } } func confirmDeleteComment() { if self.targetComment == nil { return } let params = [ QCKeys.AlertView.Title.rawValue : "確認", QCKeys.AlertView.Message.rawValue: "コメントを削除してもよいですか?", QCKeys.AlertView.NoTitle.rawValue: "Cancel", QCKeys.AlertView.YesAction.rawValue: AlertViewSender(action: { () -> Void in self.deleteComent() }, title: "OK") ] NSNotificationCenter.defaultCenter().postNotificationName(QCKeys.Notification.ShowAlertYesNo.rawValue, object: nil, userInfo: params) } func deleteComent() { if let qiitaAccount = self.account as? QiitaAccount { if let comm = self.targetComment { qiitaAccount.deleteComment(comm.id, completion: { (isError) -> Void in if isError { Toast.show("削除できませんでした...", style: JFMinimalNotificationStytle.StyleError) return } self.fin() }) } } } func fin() { self.targetComment = nil self.refresh() } // MARK: UITableViewDataSource func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.tableView.items.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell: CommentTableViewCell = tableView.dequeueReusableCellWithIdentifier("CELL") as! CommentTableViewCell cell.account = self.account cell.tag = indexPath.row let entity: CommentEntity = self.tableView.items[indexPath.row] as! CommentEntity cell.action = {(c: CommentTableViewCell) -> Void in self.tapThumb(c) return } cell.editCommentAction = {(c: CommentTableViewCell) -> Void in self.tapCommentEdit(c) } cell.showComment(entity) return cell } // MARK: UITableViewDelegate func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return 30.0 } func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) { if self.tableView.page != NSNotFound && indexPath.row + 1 == self.tableView.items.count { self.load() } } func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let headerView: UIView = UIView(frame: CGRect(x: 0, y: 0, width: self.tableView.bounds.size.width, height: 30.0)) headerView.backgroundColor = UIColor.backgroundSub(0.8) let headerTitle: UILabel = UILabel(frame: CGRect(x: 8, y: 8, width: self.tableView.bounds.size.width - 16, height: 14.0)) headerTitle.lineBreakMode = NSLineBreakMode.ByTruncatingMiddle headerTitle.textColor = UIColor.textBase() headerTitle.font = UIFont.systemFontOfSize(12.0) headerTitle.text = self.displayEntryTitle + "のコメント一覧" headerView.addSubview(headerTitle) headerTitle.addConstraintFromLeft(8.0, toRight: 8.0) headerTitle.addConstraintFromTop(8.0, toBottom: 8.0) return headerView } // MARK: NSNotification func receiveKeyboardShowNotification(notification: NSNotification) { if let userInfo = notification.userInfo { if let keyboard = userInfo[UIKeyboardFrameEndUserInfoKey] as? NSValue { let keyBoardRect: CGRect = keyboard.CGRectValue() self.openCommentField(keyBoardRect.size.height) } } } func receiveKeyboardDidShowNotification(notification: NSNotification) { self.setupNavigationBar() } func receiveKeyboardHideNotification(notification: NSNotification) { if self.inputStatus != .Confirm { return } self.fullscreenComment() } func receiveKeyboardDidHideNotification(notification: NSNotification) { if self.inputStatus != .Confirm { return } let args = [ QCKeys.AlertController.Style.rawValue : UIAlertControllerStyle.Alert.rawValue, QCKeys.AlertController.Title.rawValue : "確認", QCKeys.AlertController.Description.rawValue: "この内容でコメントしてもよいですか?", QCKeys.AlertController.Actions.rawValue : [ UIAlertAction(title: "OK", style: UIAlertActionStyle.Destructive, handler: { (action) -> Void in self.inputStatus = .None self.dismissCommentField() self.postComment() }), UIAlertAction(title: "やめる", style: UIAlertActionStyle.Default, handler: { (action) -> Void in // 編集終了 self.inputStatus = .None self.dismissCommentField() return }), UIAlertAction(title: "再編集", style: UIAlertActionStyle.Default, handler: { (action) -> Void in self.inputStatus = .Writing self.comment.becomeFirstResponder() return }) ] ] NSNotificationCenter.defaultCenter().postNotificationName(QCKeys.Notification.ShowAlertController.rawValue, object: self, userInfo: args as [NSObject : AnyObject]) } }
mit
f54e4bb5f198ccf02c6af229cce9eb4b
36.562334
173
0.60257
5.254545
false
false
false
false
mcgraw/tomorrow
Tomorrow/IGILabel.swift
1
5304
// // IGILabel.swift // Tomorrow // // Created by David McGraw on 1/24/15. // Copyright (c) 2015 David McGraw. All rights reserved. // import UIKit import Spring import pop class IGILabel: SpringLabel { @IBOutlet weak var layoutConstraint: NSLayoutConstraint? @IBOutlet weak var spacingConstraint: NSLayoutConstraint? weak var viewToReveal: UIView? var tempDismissValue: Int32? // MARK: Jump Button Animation /** Move button to location :param: constant location offset :param: delayStart time to begin */ func jumpAnimationToConstant(constant: Int, delayStart: Double) { // sink into the screen, anticipate the jump let sink = POPBasicAnimation(propertyNamed: kPOPLayerScaleXY) sink.toValue = NSValue(CGPoint: CGPointMake(0.95, 0.95)) sink.beginTime = CACurrentMediaTime() + delayStart layer.pop_addAnimation(sink, forKey: "sink") // scale up, jump! let jump = POPSpringAnimation(propertyNamed: kPOPLayerScaleXY) jump.toValue = NSValue(CGPoint: CGPointMake(1.8, 1.8)) jump.beginTime = CACurrentMediaTime() + delayStart + 0.2 layer.pop_addAnimation(jump, forKey: "jump") let move = POPBasicAnimation(propertyNamed: kPOPLayerPositionY) move.toValue = constant move.beginTime = CACurrentMediaTime() + delayStart + 0.2 move.duration = 0.8 layer.pop_addAnimation(move, forKey: "move") // move to the top of the screen let fall = POPSpringAnimation(propertyNamed: kPOPLayerScaleXY) fall.toValue = NSValue(CGPoint: CGPointMake(1.0, 1.0)) fall.beginTime = CACurrentMediaTime() + delayStart + 0.45 layer.pop_addAnimation(fall, forKey: "fall") // spacingConstraint?.active = false } // MARK: Reveal func revealView(#constant: Int) { var anim = POPSpringAnimation(propertyNamed: kPOPLayoutConstraintConstant) anim.springBounciness = 2 anim.springSpeed = 1 anim.toValue = NSNumber(int: Int32(constant)) layoutConstraint?.pop_addAnimation(anim, forKey: "movement") UIView.animateWithDuration(1.0, animations: { self.alpha = 1.0 }) } func revealViewWithDelay(#constant: Int, delay: CFTimeInterval) { var anim = POPSpringAnimation(propertyNamed: kPOPLayoutConstraintConstant) anim.beginTime = CACurrentMediaTime() + delay anim.springBounciness = 2 anim.springSpeed = 1 anim.toValue = NSNumber(int: Int32(constant)) anim.name = "reveal-delay" anim.delegate = self layoutConstraint?.pop_addAnimation(anim, forKey: "movement") } func revealViewWithDelay(#constant: Int, delay: CFTimeInterval, view: UIView) { // reveal this view after the animation plays viewToReveal = view var anim = POPSpringAnimation(propertyNamed: kPOPLayoutConstraintConstant) anim.beginTime = CACurrentMediaTime() + delay anim.springBounciness = 2 anim.springSpeed = 1 anim.toValue = NSNumber(int: Int32(constant)) anim.name = "reveal-delay" anim.delegate = self layoutConstraint?.pop_addAnimation(anim, forKey: "movement") } // MARK: Dismiss func dismissView(#constant: Int) { tempDismissValue = Int32(constant) var anim = POPSpringAnimation(propertyNamed: kPOPLayoutConstraintConstant) anim.springBounciness = 2 anim.springSpeed = 1 anim.toValue = NSNumber(int: Int32(layoutConstraint!.constant + 10)) anim.name = "dismiss" anim.delegate = self layoutConstraint?.pop_addAnimation(anim, forKey: "movement") } func dismissViewWithDelay(#constant: Int, delay: CFTimeInterval) { tempDismissValue = Int32(constant) var anim = POPSpringAnimation(propertyNamed: kPOPLayoutConstraintConstant) anim.beginTime = CACurrentMediaTime() + delay anim.springBounciness = 2 anim.springSpeed = 1 anim.toValue = NSNumber(int: Int32(constant)) anim.name = "dismiss-delay" anim.delegate = self layoutConstraint?.pop_addAnimation(anim, forKey: "movement") } // MARK: POP Delegate func pop_animationDidStart(anim: POPAnimation!) { if anim.name == "reveal-delay" { UIView.animateWithDuration(0.5, animations: { if let inputView = self.viewToReveal { inputView.alpha = 1.0 } else { self.alpha = 1.0 } }) } } func pop_animationDidReachToValue(anim: POPAnimation!) { if anim.name == "dismiss" { var anim = POPSpringAnimation(propertyNamed: kPOPLayoutConstraintConstant) anim.springBounciness = 2 anim.springSpeed = 1 anim.toValue = NSNumber(int: tempDismissValue!) // should not be nil! layoutConstraint?.pop_addAnimation(anim, forKey: "movement") UIView.animateWithDuration(1.0, animations: { self.alpha = 0.0 }) } } }
bsd-2-clause
1270898851dcb94b947db244b4d5487b
34.125828
86
0.623303
4.915663
false
false
false
false
belatrix/iOSAllStars
AllStarsV2/AllStarsV2/iPhone/Classes/Profile/Categories/CategoriesViewController.swift
1
3575
// // CategoriesViewController.swift // AllStarsV2 // // Created by Kenyi Rodriguez Vergara on 2/08/17. // Copyright © 2017 Kenyi Rodriguez Vergara. All rights reserved. // import UIKit class CategoriesViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { @IBOutlet weak var tlbCategories: UITableView! @IBOutlet weak var loadingView : CDMLoadingView! var categoryCellSelected : CategoryTableViewCell! var objUser : UserBE! var arrayCategories = [CategoryBE]() //MARK: - UITableViewDelegate, UITableViewDataSource func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.arrayCategories.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cellIdentifier = "CategoryTableViewCell" let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as! CategoryTableViewCell cell.objCategory = self.arrayCategories[indexPath.row] return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) self.categoryCellSelected = tableView.cellForRow(at: indexPath) as! CategoryTableViewCell self.performSegue(withIdentifier: "CategoryDetailViewController", sender: self.arrayCategories[indexPath.row]) } //MARK: - WebService func listCategories(){ if self.arrayCategories.count == 0 { self.loadingView.iniciarLoading(conMensaje: "get_category_list".localized, conAnimacion: true) } CategoryBC.listCategories(toUser: self.objUser, withSuccessful: { (arrayCategories) in if arrayCategories.count > 0 { self.arrayCategories = arrayCategories self.tlbCategories.reloadSections(IndexSet(integer: 0), with: .automatic) self.loadingView.detenerLoading() } else { self.loadingView.mostrarError(conMensaje: "no_categories".localized, conOpcionReintentar: false) } }) { (title, message) in self.loadingView.mostrarError(conMensaje: message, conOpcionReintentar: false) } } override func viewDidLoad() { super.viewDidLoad() self.tlbCategories.estimatedRowHeight = 30 self.tlbCategories.rowHeight = UITableViewAutomaticDimension } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.listCategories() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "CategoryDetailViewController" { let controller = segue.destination as! CategoryDetailViewController controller.objCategory = sender as! CategoryBE controller.objUser = self.objUser } } }
apache-2.0
de940c368b3a5d306934c098b354a305
31.788991
122
0.641858
5.398792
false
false
false
false
Rostmen/TimelineController
RZTimelineCollection/RZTimelineCollectionLayout.swift
1
10548
// // RZTimelineCollectionLayout.swift // RZTimelineCollection // // Created by Rostyslav Kobizsky on 12/18/14. // Copyright (c) 2014 Rozdoum. All rights reserved. // import UIKit let kPostCollectionViewAvatarSizeDefault: CGFloat = 30 let RZCollectionElementKindTimeLine = "CollectionElementKindTimeLine" class RZTimelineCollectionLayout: UICollectionViewFlowLayout { private var _postsCache: NSCache! override var collectionView: RZPostCollectionView? { get { return super.collectionView as? RZPostCollectionView } } var postFont: UIFont = UIFont.preferredFontForTextStyle(UIFontTextStyleBody) var postImageAssetWidth = UIImage.rz_postCompactImage()?.size.width var postContainerLeftRigthMargin: CGFloat = 30 var postTextViewFrameInsets = UIEdgeInsetsMake(0, 0, 0, 6) var postTextViewFrameTextContainerInsents = UIEdgeInsetsMake(7, 14, 7, 14) var avatarSize = CGSize(width: kPostCollectionViewAvatarSizeDefault, height: kPostCollectionViewAvatarSizeDefault) var visibleIndexPaths = NSMutableSet() var timelineInsets = UIEdgeInsets(top: 0, left: 20, bottom: 0, right: 0) var timelineXPosition: CGFloat = 0 private var _decorationViewsCache: NSCache! private var _dynamicAnimator: UIDynamicAnimator! private func configureFlowLayout() { scrollDirection = UICollectionViewScrollDirection.Vertical sectionInset = UIEdgeInsetsMake(10, 4, 10, 4) minimumLineSpacing = 4 _postsCache = NSCache() _postsCache.name = "RZTimelineCollectionLayout.postsCache" _postsCache.countLimit = 200 _decorationViewsCache = NSCache() _decorationViewsCache.name = "RZTimelineCollectionLayout.decorationsCache" _decorationViewsCache.countLimit = 10 //_dynamicAnimator = UIDynamicAnimator(collectionViewLayout: self) } override init() { super.init() configureFlowLayout() } required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) configureFlowLayout() } override func awakeFromNib() { configureFlowLayout() } override class func layoutAttributesClass() -> AnyClass { return RZPostCollectionViewLayoutAttribures.self } func itemWidth() -> CGFloat { return collectionView!.frame.size.width - sectionInset.left - sectionInset.right - timelineInsets.left - timelineXPosition } override func prepareLayout() { super.prepareLayout() } override func finalizeCollectionViewUpdates() { for subview in collectionView!.subviews as [UIView] { if subview is RZGridline { subview.removeFromSuperview() } } collectionView!.reloadData() } override func layoutAttributesForElementsInRect(rect: CGRect) -> [AnyObject]? { var superLayoutAttributesForElementsInRect = super.layoutAttributesForElementsInRect(rect) if var attributesInRect = superLayoutAttributesForElementsInRect as? [UICollectionViewLayoutAttributes] { let timelineAttributes = layoutAttributesForSupplementaryViewOfKind(RZCollectionElementKindTimeLine, atIndexPath: NSIndexPath(forItem: 0, inSection: 0)) attributesInRect.append(timelineAttributes) for attributesItem in attributesInRect { if attributesItem.representedElementCategory == UICollectionElementCategory.Cell { configurePostCellLayoutAttributes(attributesItem as RZPostCollectionViewLayoutAttribures) } else { attributesItem.frame = CGRect(x: timelineXPosition + timelineInsets.left, y: collectionView!.contentOffset.y, width: 1, height: collectionView!.frame.size.height) attributesItem.zIndex = 0 } } return attributesInRect } return superLayoutAttributesForElementsInRect } func configurePostCellLayoutAttributes(layoutAttributes: RZPostCollectionViewLayoutAttribures) { let indexPath = layoutAttributes.indexPath let postSize = cellSizeForItemAtIndexPath(indexPath) layoutAttributes.postContainerViewWidth = postSize.width layoutAttributes.textViewFrameInsets = postTextViewFrameInsets layoutAttributes.textViewTextContainerInsets = postTextViewFrameTextContainerInsents layoutAttributes.postFont = postFont layoutAttributes.avatarViewSize = avatarSize layoutAttributes.cellTopLabelHeight = (collectionView?.delegate as RZPostCollectionViewDelegateFlowLayout).collectionView(collectionView!, layout: self , heightForCellTopLabelAtIndexPath: indexPath) layoutAttributes.cellBottomLabelHeight = (collectionView?.delegate as RZPostCollectionViewDelegateFlowLayout).collectionView(collectionView!, layout: self , heightForCellBottomLabelAtIndexPath: indexPath) layoutAttributes.frame = CGRect( x: timelineXPosition + timelineInsets.left - (avatarSize.width / 2), y: CGRectGetMinY(layoutAttributes.frame), width: CGRectGetWidth(layoutAttributes.frame), height: CGRectGetHeight(layoutAttributes.frame)) layoutAttributes.zIndex = 100 } override func layoutAttributesForItemAtIndexPath(indexPath: NSIndexPath) -> UICollectionViewLayoutAttributes! { let customAttributes = super.layoutAttributesForItemAtIndexPath(indexPath) as RZPostCollectionViewLayoutAttribures if (customAttributes.representedElementCategory == UICollectionElementCategory.Cell) { configurePostCellLayoutAttributes(customAttributes) } return customAttributes } override func layoutAttributesForSupplementaryViewOfKind(elementKind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionViewLayoutAttributes! { if let attributes = _decorationViewsCache.objectForKey(elementKind) as? UICollectionViewLayoutAttributes { return attributes } else { let attributes = UICollectionViewLayoutAttributes(forSupplementaryViewOfKind: elementKind, withIndexPath: NSIndexPath(forItem: 0, inSection: 0)) _decorationViewsCache.setObject(attributes, forKey: elementKind) return attributes } } override func shouldInvalidateLayoutForBoundsChange(newBounds: CGRect) -> Bool { return true } func sizeForItemAtIndexPath(indexPath: NSIndexPath) -> CGSize { let size = cellSizeForItemAtIndexPath(indexPath) let attributes = layoutAttributesForItemAtIndexPath(indexPath) as RZPostCollectionViewLayoutAttribures var finalHeight = size.height finalHeight += attributes.cellTopLabelHeight finalHeight += attributes.cellBottomLabelHeight return CGSize(width: itemWidth(), height: finalHeight) } override func prepareForCollectionViewUpdates(updateItems: [AnyObject]!) { super.prepareForCollectionViewUpdates(updateItems) NSArray(array: updateItems).enumerateObjectsUsingBlock { (updateItemObj, index, stop) -> Void in if let updateItem = updateItemObj as? UICollectionViewUpdateItem { if updateItem.updateAction == UICollectionUpdateAction.Insert { let collectionViewHeight = CGRectGetHeight(self.collectionView!.bounds) let attributes = RZPostCollectionViewLayoutAttribures(forCellWithIndexPath: updateItem.indexPathAfterUpdate) if attributes.representedElementCategory == UICollectionElementCategory.Cell { self.configurePostCellLayoutAttributes(attributes) } attributes.frame = CGRect( x: self.timelineXPosition + self.timelineInsets.left, y: collectionViewHeight + CGRectGetHeight(attributes.frame), width: CGRectGetWidth(attributes.frame), height: CGRectGetHeight(attributes.frame)) } } } } func resetLayout() { _postsCache.removeAllObjects() _decorationViewsCache.removeAllObjects() } func cellSizeForItemAtIndexPath(indexPath: NSIndexPath) -> CGSize { let post = (collectionView?.dataSource as RZPostCollectionViewDataSource).collectionView(collectionView!, postDataForIndexPath: indexPath) if let cachedSize = _postsCache.objectForKey(post.hash) as? NSValue { return cachedSize.CGSizeValue() } else { var finalSize = CGSizeZero if post.media != nil { finalSize = post.media!.mediaViewDisplaySize } else { // from the cell xibs, there is a 0 point space between avatar and bubble let spaceBetweenAvatarAndBody: CGFloat = 0 let horizontalContainerInsets = postTextViewFrameTextContainerInsents.left + postTextViewFrameTextContainerInsents.right let horizontalFrameInsets = postTextViewFrameInsets.left + postTextViewFrameInsets.right let horizontalInsetsTotal = horizontalContainerInsets + horizontalFrameInsets + spaceBetweenAvatarAndBody - timelineXPosition - timelineInsets.left let maximumTextWidth = self.itemWidth() - avatarSize.width - postContainerLeftRigthMargin - horizontalInsetsTotal let stringRect = postFont.rectOfString(post.text!, constrainedToWidth: maximumTextWidth) let stringSize = CGRectIntegral(stringRect).size let verticalContainerInsets = postTextViewFrameTextContainerInsents.top + postTextViewFrameTextContainerInsents.bottom let verticalFrameInsets = postTextViewFrameInsets.top + postTextViewFrameInsets.bottom let verticalInsets = verticalContainerInsets + verticalFrameInsets + 2 let finalWidth = max(stringSize.width + horizontalInsetsTotal, postImageAssetWidth!)// + 2 finalSize = CGSize(width: finalWidth, height: stringSize.height + verticalInsets) } _postsCache.setObject(NSValue(CGSize: finalSize), forKey: post.hash) return finalSize } } }
apache-2.0
791521f705544c4056b9451741e1425d
44.86087
212
0.688377
6.563783
false
false
false
false
mubstimor/smartcollaborationvapor
Sources/App/Controllers/InjuryController.swift
1
3369
// // InjuryController.swift // SmartCollaborationVapor // // Created by Timothy Mubiru on 01/03/2017. // // import Vapor import HTTP final class InjuryController { func addRoutes(drop: Droplet){ // let injuries = drop.grouped("injuries") let injuries = drop.grouped(BasicAuthMiddleware(), StaticInfo.protect).grouped("api").grouped("injuries") injuries.get(handler: index) injuries.post(handler: create) injuries.get(Injury.self, handler: show) injuries.patch(Injury.self, handler: update) injuries.get(Injury.self, "treatments", handler: treatmentsIndex) } func index(request: Request) throws -> ResponseRepresentable { return try Injury.all().makeNode().converted(to: JSON.self) } func create(request: Request) throws -> ResponseRepresentable { var injury = try request.injury() try injury.save() return injury } func show(request: Request, injury: Injury) throws -> ResponseRepresentable { return injury } func delete(request: Request, injury: Injury) throws -> ResponseRepresentable { try injury.delete() return JSON([:]) } func clear(request: Request) throws -> ResponseRepresentable { try Injury.query().delete() return JSON([]) } func update(request: Request, injury: Injury) throws -> ResponseRepresentable { let new = try request.injury() var injury = injury injury.name = new.name injury.player_id = new.player_id injury.situation = new.situation injury.time_of_injury = new.time_of_injury injury.injured_body_part = new.injured_body_part injury.is_contact_injury = new.is_contact_injury injury.playing_surface = new.playing_surface injury.weather_conditions = new.weather_conditions injury.estimated_absence_period = new.estimated_absence_period injury.club_id = new.club_id injury.specialist_id = new.specialist_id try injury.save() return injury } func replace(request: Request, injury: Injury) throws -> ResponseRepresentable { try injury.delete() return try create(request: request) } // func makeResource() -> Resource<Injury> { // return Resource( // index: index, // store: create, // show: show, // replace: replace, // modify: update, // destroy: delete, // clear: clear // ) // } func treatmentsIndex(request: Request, injury: Injury) throws -> ResponseRepresentable { var response: [Node] = [] let children = try injury.treatments() for treatment in children { let specialist_id = treatment.specialist_id let specialist = try Specialist.find(specialist_id!) let object = try Node(node: [ "treatment": treatment, "specialist": specialist?.name ]) response += object } return try JSON(node: response.makeNode()) } } extension Request { func injury() throws -> Injury { guard let json = json else { throw Abort.badRequest } return try Injury(node: json) } }
mit
a9cf1647f5ebd0732cdea68aa6141f79
29.351351
113
0.5981
4.409686
false
false
false
false
february29/Learning
swift/ReactiveCocoaDemo/Pods/RxCocoa/RxCocoa/Traits/ControlProperty.swift
93
4940
// // ControlProperty.swift // RxCocoa // // Created by Krunoslav Zaher on 8/28/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // #if !RX_NO_MODULE import RxSwift #endif /// Protocol that enables extension of `ControlProperty`. public protocol ControlPropertyType : ObservableType, ObserverType { /// - returns: `ControlProperty` interface func asControlProperty() -> ControlProperty<E> } /** Trait for `Observable`/`ObservableType` that represents property of UI element. Sequence of values only represents initial control value and user initiated value changes. Programatic value changes won't be reported. It's properties are: - it never fails - `shareReplay(1)` behavior - it's stateful, upon subscription (calling subscribe) last element is immediately replayed if it was produced - it will `Complete` sequence on control being deallocated - it never errors out - it delivers events on `MainScheduler.instance` **The implementation of `ControlProperty` will ensure that sequence of values is being subscribed on main scheduler (`subscribeOn(ConcurrentMainScheduler.instance)` behavior).** **It is implementor's responsibility to make sure that that all other properties enumerated above are satisfied.** **If they aren't, then using this trait communicates wrong properties and could potentially break someone's code.** **In case `values` observable sequence that is being passed into initializer doesn't satisfy all enumerated properties, please don't use this unit.** */ public struct ControlProperty<PropertyType> : ControlPropertyType { public typealias E = PropertyType let _values: Observable<PropertyType> let _valueSink: AnyObserver<PropertyType> /// Initializes control property with a observable sequence that represents property values and observer that enables /// binding values to property. /// /// - parameter values: Observable sequence that represents property values. /// - parameter valueSink: Observer that enables binding values to control property. /// - returns: Control property created with a observable sequence of values and an observer that enables binding values /// to property. public init<V: ObservableType, S: ObserverType>(values: V, valueSink: S) where E == V.E, E == S.E { _values = values.subscribeOn(ConcurrentMainScheduler.instance) _valueSink = valueSink.asObserver() } /// Subscribes an observer to control property values. /// /// - parameter observer: Observer to subscribe to property values. /// - returns: Disposable object that can be used to unsubscribe the observer from receiving control property values. public func subscribe<O : ObserverType>(_ observer: O) -> Disposable where O.E == E { return _values.subscribe(observer) } /// `ControlEvent` of user initiated value changes. Every time user updates control value change event /// will be emitted from `changed` event. /// /// Programatic changes to control value won't be reported. /// /// It contains all control property values except for first one. /// /// The name only implies that sequence element will be generated once user changes a value and not that /// adjacent sequence values need to be different (e.g. because of interaction between programatic and user updates, /// or for any other reason). public var changed: ControlEvent<PropertyType> { get { return ControlEvent(events: _values.skip(1)) } } /// - returns: `Observable` interface. public func asObservable() -> Observable<E> { return _values } /// - returns: `ControlProperty` interface. public func asControlProperty() -> ControlProperty<E> { return self } /// Binds event to user interface. /// /// - In case next element is received, it is being set to control value. /// - In case error is received, DEBUG buids raise fatal error, RELEASE builds log event to standard output. /// - In case sequence completes, nothing happens. public func on(_ event: Event<E>) { switch event { case .error(let error): bindingErrorToInterface(error) case .next: _valueSink.on(event) case .completed: _valueSink.on(event) } } } extension ControlPropertyType where E == String? { /// Transforms control property of type `String?` into control property of type `String`. public var orEmpty: ControlProperty<String> { let original: ControlProperty<String?> = self.asControlProperty() let values: Observable<String> = original._values.map { $0 ?? "" } let valueSink: AnyObserver<String> = original._valueSink.mapObserver { $0 } return ControlProperty<String>(values: values, valueSink: valueSink) } }
mit
080a24fa8c6e98a60584d36863815b97
39.154472
124
0.694068
4.948898
false
false
false
false
ifLab/WeCenterMobile-iOS
WeCenterMobile/View/Question/QuestionCell.swift
3
2416
// // QuestionCell.swift // WeCenterMobile // // Created by Darren Liu on 15/4/28. // Copyright (c) 2015年 Beijing Information Science and Technology University. All rights reserved. // import UIKit class QuestionCell: UITableViewCell { @IBOutlet weak var questionTitleLabel: UILabel! @IBOutlet weak var questionBodyLabel: UILabel! @IBOutlet weak var userNameLabel: UILabel! @IBOutlet weak var dateLabel: UILabel! @IBOutlet weak var userButton: UIButton! @IBOutlet weak var questionButton: UIButton! @IBOutlet weak var userAvatarView: MSRRoundedImageView! @IBOutlet weak var userContainerView: UIView! @IBOutlet weak var questionContainerView: UIView! @IBOutlet weak var containerView: UIView! @IBOutlet weak var separator: UIView! lazy var dateFormatter: NSDateFormatter = { let f = NSDateFormatter() f.timeZone = NSTimeZone.localTimeZone() f.dateFormat = "yyyy-MM-dd HH:mm:ss" return f }() override func awakeFromNib() { super.awakeFromNib() msr_scrollView?.delaysContentTouches = false let theme = SettingsManager.defaultManager.currentTheme containerView.msr_borderColor = theme.borderColorA separator.backgroundColor = theme.borderColorA for v in [userContainerView, questionContainerView] { v.backgroundColor = theme.backgroundColorB } for v in [userButton, questionButton] { v.msr_setBackgroundImageWithColor(theme.highlightColor, forState: .Highlighted) } for v in [userNameLabel, questionTitleLabel] { v.textColor = theme.titleTextColor } dateLabel.textColor = theme.footnoteTextColor questionBodyLabel.textColor = theme.subtitleTextColor } func update(question question: Question) { questionTitleLabel.text = question.title questionBodyLabel.text = question.body?.wc_plainString ?? "" userNameLabel.text = question.user?.name ?? "匿名用户" if let date = question.date { dateLabel.text = dateFormatter.stringFromDate(date) } else { dateLabel.text = "" } userAvatarView.wc_updateWithUser(question.user) userButton.msr_userInfo = question.user questionButton.msr_userInfo = question setNeedsLayout() layoutIfNeeded() } }
gpl-2.0
86fe12f9f3f9f439fad0f5c79dee54ef
34.910448
99
0.673732
5.119149
false
false
false
false
SwiftGen/SwiftGen
Sources/SwiftGen/Commands/Template/Template Doc.swift
1
1350
// // SwiftGen // Copyright © 2022 SwiftGen // MIT Licence // import AppKit import ArgumentParser import SwiftGenCLI extension Commands.Template { struct Doc: ParsableCommand { static let configuration = CommandConfiguration(abstract: "Open the documentation for templates on GitHub.") @Argument(help: "The name of the parser the template is for, like `xcassets`") var parser: ParserCLI? @Argument(help: "The name of the template to find, like `swift5` or `flat-swift5`") var template: String? func validate() throws { guard let template = template else { return } guard let parser = parser else { throw ValidationError("Must have parser for template `\(template)`") } guard TemplateRef.name(template).isBundled(forParser: parser) else { throw ValidationError(""" If provided, the 2nd argument must be the name of a bundled template for the given parser """) } } func run() throws { var path = "templates/" if let parser = parser { path += "\(parser.name)/" if let template = template { path += "\(template).md" } } let url = gitHubDocURL(version: Version.swiftgen, path: path) logMessage(.info, "Opening documentation: \(url)") NSWorkspace.shared.open(url) } } }
mit
befa027467cfc001f23819252b9096e7
26.530612
112
0.638251
4.496667
false
false
false
false
nathawes/swift
stdlib/public/core/StringBridge.swift
6
21702
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// import SwiftShims /// Effectively an untyped NSString that doesn't require foundation. @usableFromInline internal typealias _CocoaString = AnyObject #if _runtime(_ObjC) // Swift's String bridges NSString via this protocol and these // variables, allowing the core stdlib to remain decoupled from // Foundation. @objc private protocol _StringSelectorHolder : _NSCopying { @objc var length: Int { get } @objc var hash: UInt { get } @objc(characterAtIndex:) func character(at offset: Int) -> UInt16 @objc(getCharacters:range:) func getCharacters( _ buffer: UnsafeMutablePointer<UInt16>, range aRange: _SwiftNSRange ) @objc(_fastCStringContents:) func _fastCStringContents( _ requiresNulTermination: Int8 ) -> UnsafePointer<CChar>? @objc(_fastCharacterContents) func _fastCharacterContents() -> UnsafePointer<UInt16>? @objc(getBytes:maxLength:usedLength:encoding:options:range:remainingRange:) func getBytes(_ buffer: UnsafeMutableRawPointer?, maxLength maxBufferCount: Int, usedLength usedBufferCount: UnsafeMutablePointer<Int>?, encoding: UInt, options: UInt, range: _SwiftNSRange, remaining leftover: UnsafeMutablePointer<_SwiftNSRange>?) -> Int8 @objc(compare:options:range:locale:) func compare(_ string: _CocoaString, options: UInt, range: _SwiftNSRange, locale: AnyObject?) -> Int @objc(newTaggedNSStringWithASCIIBytes_:length_:) func createTaggedString(bytes: UnsafePointer<UInt8>, count: Int) -> AnyObject? } /* Passing a _CocoaString through _objc() lets you call ObjC methods that the compiler doesn't know about, via the protocol above. In order to get good performance, you need a double indirection like this: func a -> _objc -> func a' because any refcounting @_effects on 'a' will be lost when _objc breaks ARC's knowledge that the _CocoaString and _StringSelectorHolder are the same object. */ @inline(__always) private func _objc(_ str: _CocoaString) -> _StringSelectorHolder { return unsafeBitCast(str, to: _StringSelectorHolder.self) } @_effects(releasenone) private func _copyNSString(_ str: _StringSelectorHolder) -> _CocoaString { return str.copy(with: nil) } @usableFromInline // @testable @_effects(releasenone) internal func _stdlib_binary_CFStringCreateCopy( _ source: _CocoaString ) -> _CocoaString { return _copyNSString(_objc(source)) } @_effects(readonly) private func _NSStringLen(_ str: _StringSelectorHolder) -> Int { return str.length } @usableFromInline // @testable @_effects(readonly) internal func _stdlib_binary_CFStringGetLength( _ source: _CocoaString ) -> Int { if let len = getConstantTaggedCocoaContents(source)?.utf16Length { return len } return _NSStringLen(_objc(source)) } @_effects(readonly) internal func _isNSString(_ str:AnyObject) -> Bool { if getConstantTaggedCocoaContents(str) != nil { return true } return _swift_stdlib_isNSString(str) != 0 } @_effects(readonly) private func _NSStringCharactersPtr(_ str: _StringSelectorHolder) -> UnsafeMutablePointer<UTF16.CodeUnit>? { return UnsafeMutablePointer(mutating: str._fastCharacterContents()) } @usableFromInline // @testable @_effects(readonly) internal func _stdlib_binary_CFStringGetCharactersPtr( _ source: _CocoaString ) -> UnsafeMutablePointer<UTF16.CodeUnit>? { return _NSStringCharactersPtr(_objc(source)) } @_effects(releasenone) private func _NSStringGetCharacters( from source: _StringSelectorHolder, range: Range<Int>, into destination: UnsafeMutablePointer<UTF16.CodeUnit> ) { source.getCharacters(destination, range: _SwiftNSRange( location: range.startIndex, length: range.count) ) } /// Copies a slice of a _CocoaString into contiguous storage of sufficient /// capacity. @_effects(releasenone) internal func _cocoaStringCopyCharacters( from source: _CocoaString, range: Range<Int>, into destination: UnsafeMutablePointer<UTF16.CodeUnit> ) { _NSStringGetCharacters(from: _objc(source), range: range, into: destination) } @_effects(readonly) private func _NSStringGetCharacter( _ target: _StringSelectorHolder, _ position: Int ) -> UTF16.CodeUnit { return target.character(at: position) } @_effects(readonly) internal func _cocoaStringSubscript( _ target: _CocoaString, _ position: Int ) -> UTF16.CodeUnit { return _NSStringGetCharacter(_objc(target), position) } @_effects(releasenone) private func _NSStringCopyUTF8( _ o: _StringSelectorHolder, into bufPtr: UnsafeMutableBufferPointer<UInt8> ) -> Int? { let ptr = bufPtr.baseAddress._unsafelyUnwrappedUnchecked let len = o.length var remainingRange = _SwiftNSRange(location: 0, length: 0) var usedLen = 0 let success = 0 != o.getBytes( ptr, maxLength: bufPtr.count, usedLength: &usedLen, encoding: _cocoaUTF8Encoding, options: 0, range: _SwiftNSRange(location: 0, length: len), remaining: &remainingRange ) if success && remainingRange.length == 0 { return usedLen } return nil } @_effects(releasenone) internal func _cocoaStringCopyUTF8( _ target: _CocoaString, into bufPtr: UnsafeMutableBufferPointer<UInt8> ) -> Int? { return _NSStringCopyUTF8(_objc(target), into: bufPtr) } @_effects(readonly) private func _NSStringUTF8Count( _ o: _StringSelectorHolder, range: Range<Int> ) -> Int? { var remainingRange = _SwiftNSRange(location: 0, length: 0) var usedLen = 0 let success = 0 != o.getBytes( UnsafeMutablePointer<UInt8>(Builtin.inttoptr_Word(0._builtinWordValue)), maxLength: 0, usedLength: &usedLen, encoding: _cocoaUTF8Encoding, options: 0, range: _SwiftNSRange(location: range.startIndex, length: range.count), remaining: &remainingRange ) if success && remainingRange.length == 0 { return usedLen } return nil } @_effects(readonly) internal func _cocoaStringUTF8Count( _ target: _CocoaString, range: Range<Int> ) -> Int? { if range.isEmpty { return 0 } return _NSStringUTF8Count(_objc(target), range: range) } @_effects(readonly) private func _NSStringCompare( _ o: _StringSelectorHolder, _ other: _CocoaString ) -> Int { let range = _SwiftNSRange(location: 0, length: o.length) let options = UInt(2) /* NSLiteralSearch*/ return o.compare(other, options: options, range: range, locale: nil) } @_effects(readonly) internal func _cocoaStringCompare( _ string: _CocoaString, _ other: _CocoaString ) -> Int { return _NSStringCompare(_objc(string), other) } @_effects(readonly) internal func _cocoaHashString( _ string: _CocoaString ) -> UInt { return _swift_stdlib_CFStringHashNSString(string) } @_effects(readonly) internal func _cocoaHashASCIIBytes( _ bytes: UnsafePointer<UInt8>, length: Int ) -> UInt { return _swift_stdlib_CFStringHashCString(bytes, length) } // These "trampolines" are effectively objc_msgSend_super. // They bypass our implementations to use NSString's. @_effects(readonly) internal func _cocoaCStringUsingEncodingTrampoline( _ string: _CocoaString, _ encoding: UInt ) -> UnsafePointer<UInt8>? { return _swift_stdlib_NSStringCStringUsingEncodingTrampoline(string, encoding) } @_effects(releasenone) internal func _cocoaGetCStringTrampoline( _ string: _CocoaString, _ buffer: UnsafeMutablePointer<UInt8>, _ maxLength: Int, _ encoding: UInt ) -> Int8 { return Int8(_swift_stdlib_NSStringGetCStringTrampoline( string, buffer, maxLength, encoding)) } // // Conversion from NSString to Swift's native representation. // private var kCFStringEncodingASCII: _swift_shims_CFStringEncoding { @inline(__always) get { return 0x0600 } } private var kCFStringEncodingUTF8: _swift_shims_CFStringEncoding { @inline(__always) get { return 0x8000100 } } internal enum _KnownCocoaString { case storage case shared case cocoa #if !(arch(i386) || arch(arm) || arch(wasm32)) case tagged #endif #if arch(arm64) case constantTagged #endif @inline(__always) init(_ str: _CocoaString) { #if !(arch(i386) || arch(arm)) if _isObjCTaggedPointer(str) { #if arch(arm64) if let _ = getConstantTaggedCocoaContents(str) { self = .constantTagged } else { self = .tagged } #else self = .tagged #endif return } #endif switch unsafeBitCast(_swift_classOfObjCHeapObject(str), to: UInt.self) { case unsafeBitCast(__StringStorage.self, to: UInt.self): self = .storage case unsafeBitCast(__SharedStringStorage.self, to: UInt.self): self = .shared default: self = .cocoa } } } #if !(arch(i386) || arch(arm)) // Resiliently write a tagged _CocoaString's contents into a buffer. // TODO: move this to the Foundation overlay and reimplement it with // _NSTaggedPointerStringGetBytes @_effects(releasenone) // @opaque internal func _bridgeTagged( _ cocoa: _CocoaString, intoUTF8 bufPtr: UnsafeMutableBufferPointer<UInt8> ) -> Int? { _internalInvariant(_isObjCTaggedPointer(cocoa)) return _cocoaStringCopyUTF8(cocoa, into: bufPtr) } #endif @_effects(readonly) private func _NSStringASCIIPointer(_ str: _StringSelectorHolder) -> UnsafePointer<UInt8>? { // TODO(String bridging): Is there a better interface here? Ideally we'd be // able to ask for UTF8 rather than just ASCII return str._fastCStringContents(0)?._asUInt8 } @_effects(readonly) // @opaque private func _withCocoaASCIIPointer<R>( _ str: _CocoaString, requireStableAddress: Bool, work: (UnsafePointer<UInt8>) -> R? ) -> R? { #if !(arch(i386) || arch(arm)) if _isObjCTaggedPointer(str) { if let ptr = getConstantTaggedCocoaContents(str)?.asciiContentsPointer { return work(ptr) } if requireStableAddress { return nil // tagged pointer strings don't support _fastCStringContents } let tmp = _StringGuts(_SmallString(taggedCocoa: str)) return tmp.withFastUTF8 { work($0.baseAddress._unsafelyUnwrappedUnchecked) } } #endif defer { _fixLifetime(str) } if let ptr = _NSStringASCIIPointer(_objc(str)) { return work(ptr) } return nil } @_effects(readonly) // @opaque internal func withCocoaASCIIPointer<R>( _ str: _CocoaString, work: (UnsafePointer<UInt8>) -> R? ) -> R? { return _withCocoaASCIIPointer(str, requireStableAddress: false, work: work) } @_effects(readonly) internal func stableCocoaASCIIPointer(_ str: _CocoaString) -> UnsafePointer<UInt8>? { return _withCocoaASCIIPointer(str, requireStableAddress: true, work: { $0 }) } private enum CocoaStringPointer { case ascii(UnsafePointer<UInt8>) case utf8(UnsafePointer<UInt8>) case utf16(UnsafePointer<UInt16>) case none } @_effects(readonly) private func _getCocoaStringPointer( _ cfImmutableValue: _CocoaString ) -> CocoaStringPointer { if let ascii = stableCocoaASCIIPointer(cfImmutableValue) { return .ascii(ascii) } if let utf16Ptr = _stdlib_binary_CFStringGetCharactersPtr(cfImmutableValue) { return .utf16(utf16Ptr) } return .none } #if arch(arm64) //11000000..payload..111 private var constantTagMask:UInt { 0b1111_1111_1000_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000_0111 } private var expectedConstantTagValue:UInt { 0b1100_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000_0111 } #endif @inline(__always) private func formConstantTaggedCocoaString( untaggedCocoa: _CocoaString ) -> AnyObject? { #if !arch(arm64) return nil #else let constantPtr:UnsafeRawPointer = Builtin.reinterpretCast(untaggedCocoa) // Check if what we're pointing to is actually a valid tagged constant guard _swift_stdlib_dyld_is_objc_constant_string(constantPtr) == 1 else { return nil } let retaggedPointer = UInt(bitPattern: constantPtr) | expectedConstantTagValue return unsafeBitCast(retaggedPointer, to: AnyObject.self) #endif } @inline(__always) private func getConstantTaggedCocoaContents(_ cocoaString: _CocoaString) -> (utf16Length: Int, asciiContentsPointer: UnsafePointer<UInt8>, untaggedCocoa: _CocoaString)? { #if !arch(arm64) return nil #else guard _isObjCTaggedPointer(cocoaString) else { return nil } let taggedValue = unsafeBitCast(cocoaString, to: UInt.self) guard taggedValue & constantTagMask == expectedConstantTagValue else { return nil } let payloadMask = ~constantTagMask let payload = taggedValue & payloadMask let ivarPointer = UnsafePointer<_swift_shims_builtin_CFString>( bitPattern: payload )! guard _swift_stdlib_dyld_is_objc_constant_string( UnsafeRawPointer(ivarPointer) ) == 1 else { return nil } let length = ivarPointer.pointee.length let isUTF16Mask:UInt = 0x0000_0000_0000_0004 //CFStringFlags bit 4: isUnicode let isASCII = ivarPointer.pointee.flags & isUTF16Mask == 0 precondition(isASCII) // we don't currently support non-ASCII here let contentsPtr = ivarPointer.pointee.str return ( utf16Length: Int(length), asciiContentsPointer: contentsPtr, untaggedCocoa: Builtin.reinterpretCast(ivarPointer) ) #endif } @usableFromInline @_effects(releasenone) // @opaque internal func _bridgeCocoaString(_ cocoaString: _CocoaString) -> _StringGuts { switch _KnownCocoaString(cocoaString) { case .storage: return _unsafeUncheckedDowncast( cocoaString, to: __StringStorage.self).asString._guts case .shared: return _unsafeUncheckedDowncast( cocoaString, to: __SharedStringStorage.self).asString._guts #if !(arch(i386) || arch(arm)) case .tagged: return _StringGuts(_SmallString(taggedCocoa: cocoaString)) #if arch(arm64) case .constantTagged: let taggedContents = getConstantTaggedCocoaContents(cocoaString)! return _StringGuts( cocoa: taggedContents.untaggedCocoa, providesFastUTF8: false, //TODO: if contentsPtr is UTF8 compatible, use it isASCII: true, length: taggedContents.utf16Length ) #endif #endif case .cocoa: // "Copy" it into a value to be sure nobody will modify behind // our backs. In practice, when value is already immutable, this // just does a retain. // // TODO: Only in certain circumstances should we emit this call: // 1) If it's immutable, just retain it. // 2) If it's mutable with no associated information, then a copy must // happen; might as well eagerly bridge it in. // 3) If it's mutable with associated information, must make the call let immutableCopy = _stdlib_binary_CFStringCreateCopy(cocoaString) #if !(arch(i386) || arch(arm)) if _isObjCTaggedPointer(immutableCopy) { return _StringGuts(_SmallString(taggedCocoa: immutableCopy)) } #endif let (fastUTF8, isASCII): (Bool, Bool) switch _getCocoaStringPointer(immutableCopy) { case .ascii(_): (fastUTF8, isASCII) = (true, true) case .utf8(_): (fastUTF8, isASCII) = (true, false) default: (fastUTF8, isASCII) = (false, false) } let length = _stdlib_binary_CFStringGetLength(immutableCopy) return _StringGuts( cocoa: immutableCopy, providesFastUTF8: fastUTF8, isASCII: isASCII, length: length) } } extension String { @_spi(Foundation) public init(_cocoaString: AnyObject) { self._guts = _bridgeCocoaString(_cocoaString) } } @_effects(releasenone) private func _createNSString( _ receiver: _StringSelectorHolder, _ ptr: UnsafePointer<UInt8>, _ count: Int, _ encoding: UInt32 ) -> AnyObject? { return receiver.createTaggedString(bytes: ptr, count: count) } @_effects(releasenone) private func _createCFString( _ ptr: UnsafePointer<UInt8>, _ count: Int, _ encoding: UInt32 ) -> AnyObject? { return _createNSString( unsafeBitCast(__StringStorage.self as AnyClass, to: _StringSelectorHolder.self), ptr, count, encoding ) } extension String { @_effects(releasenone) public // SPI(Foundation) func _bridgeToObjectiveCImpl() -> AnyObject { _connectOrphanedFoundationSubclassesIfNeeded() // Smol ASCII a) may bridge to tagged pointers, b) can't contain a BOM if _guts.isSmallASCII { let maybeTagged = _guts.asSmall.withUTF8 { bufPtr in return _createCFString( bufPtr.baseAddress._unsafelyUnwrappedUnchecked, bufPtr.count, kCFStringEncodingUTF8 ) } if let tagged = maybeTagged { return tagged } } if _guts.isSmall { // We can't form a tagged pointer String, so grow to a non-small String, // and bridge that instead. Also avoids CF deleting any BOM that may be // present var copy = self // TODO: small capacity minimum is lifted, just need to make native copy._guts.grow(_SmallString.capacity + 1) _internalInvariant(!copy._guts.isSmall) return copy._bridgeToObjectiveCImpl() } if _guts._object.isImmortal { // TODO: We'd rather emit a valid ObjC object statically than create a // shared string class instance. let gutsCountAndFlags = _guts._object._countAndFlags return __SharedStringStorage( immortal: _guts._object.fastUTF8.baseAddress!, countAndFlags: _StringObject.CountAndFlags( sharedCount: _guts.count, isASCII: gutsCountAndFlags.isASCII)) } _internalInvariant(_guts._object.hasObjCBridgeableObject, "Unknown non-bridgeable object case") let result = _guts._object.objCBridgeableObject return formConstantTaggedCocoaString(untaggedCocoa: result) ?? result } } // Note: This function is not intended to be called from Swift. The // availability information here is perfunctory; this function isn't considered // part of the Stdlib's Swift ABI. @available(macOS 10.15.4, iOS 13.4, watchOS 6.2, tvOS 13.4, *) @_cdecl("_SwiftCreateBridgedString") @usableFromInline internal func _SwiftCreateBridgedString_DoNotCall( bytes: UnsafePointer<UInt8>, length: Int, encoding: _swift_shims_CFStringEncoding ) -> Unmanaged<AnyObject> { let bufPtr = UnsafeBufferPointer(start: bytes, count: length) let str:String switch encoding { case kCFStringEncodingUTF8: str = String(decoding: bufPtr, as: Unicode.UTF8.self) case kCFStringEncodingASCII: str = String(decoding: bufPtr, as: Unicode.ASCII.self) default: fatalError("Unsupported encoding in shim") } return Unmanaged<AnyObject>.passRetained(str._bridgeToObjectiveCImpl()) } // At runtime, this class is derived from `__SwiftNativeNSStringBase`, // which is derived from `NSString`. // // The @_swift_native_objc_runtime_base attribute // This allows us to subclass an Objective-C class and use the fast Swift // memory allocator. @objc @_swift_native_objc_runtime_base(__SwiftNativeNSStringBase) class __SwiftNativeNSString { @objc internal init() {} deinit {} } // Called by the SwiftObject implementation to get the description of a value // as an NSString. @_silgen_name("swift_stdlib_getDescription") public func _getDescription<T>(_ x: T) -> AnyObject { return String(reflecting: x)._bridgeToObjectiveCImpl() } @_silgen_name("swift_stdlib_NSStringFromUTF8") @usableFromInline //this makes the symbol available to the runtime :( @available(macOS 10.15.4, iOS 13.4, watchOS 6.2, tvOS 13.4, *) internal func _NSStringFromUTF8(_ s: UnsafePointer<UInt8>, _ len: Int) -> AnyObject { return String( decoding: UnsafeBufferPointer(start: s, count: len), as: UTF8.self )._bridgeToObjectiveCImpl() } #else // !_runtime(_ObjC) internal class __SwiftNativeNSString { internal init() {} deinit {} } #endif // Special-case Index <-> Offset converters for bridging and use in accelerating // the UTF16View in general. extension StringProtocol { @_specialize(where Self == String) @_specialize(where Self == Substring) public // SPI(Foundation) func _toUTF16Offset(_ idx: Index) -> Int { return self.utf16.distance(from: self.utf16.startIndex, to: idx) } @_specialize(where Self == String) @_specialize(where Self == Substring) public // SPI(Foundation) func _toUTF16Index(_ offset: Int) -> Index { return self.utf16.index(self.utf16.startIndex, offsetBy: offset) } @_specialize(where Self == String) @_specialize(where Self == Substring) public // SPI(Foundation) func _toUTF16Offsets(_ indices: Range<Index>) -> Range<Int> { let lowerbound = _toUTF16Offset(indices.lowerBound) let length = self.utf16.distance( from: indices.lowerBound, to: indices.upperBound) return Range( uncheckedBounds: (lower: lowerbound, upper: lowerbound + length)) } @_specialize(where Self == String) @_specialize(where Self == Substring) public // SPI(Foundation) func _toUTF16Indices(_ range: Range<Int>) -> Range<Index> { let lowerbound = _toUTF16Index(range.lowerBound) let upperbound = _toUTF16Index(range.lowerBound + range.count) return Range(uncheckedBounds: (lower: lowerbound, upper: upperbound)) } } extension String { public // @testable / @benchmarkable func _copyUTF16CodeUnits( into buffer: UnsafeMutableBufferPointer<UInt16>, range: Range<Int> ) { _internalInvariant(buffer.count >= range.count) let indexRange = self._toUTF16Indices(range) self.utf16._nativeCopy(into: buffer, alignedRange: indexRange) } }
apache-2.0
b77093082c07cb713c13487bda9c289c
28.327027
108
0.708829
4.061763
false
false
false
false
roambotics/swift
test/expr/cast/as_coerce.swift
4
7222
// RUN: %target-typecheck-verify-swift -enable-objc-interop // Test the use of 'as' for type coercion (which requires no checking). @objc protocol P1 { func foo() } class A : P1 { @objc func foo() { } } @objc class B : A { func bar() { } } func doFoo() {} func test_coercion(_ a: A, b: B) { // Coercion to a protocol type let x = a as P1 x.foo() // Coercion to a superclass type let y = b as A y.foo() } class C : B { } class D : C { } func prefer_coercion(_ c: inout C) { let d = c as! D c = d } // Coerce literals var i32 = 1 as Int32 var i8 = -1 as Int8 // Coerce to a superclass with generic parameter inference class C1<T> { func f(_ x: T) { } } class C2<T> : C1<Int> { } var c2 = C2<()>() var c1 = c2 as C1 c1.f(5) @objc protocol P {} class CC : P {} let cc: Any = CC() if cc is P { doFoo() } if let p = cc as? P { doFoo() _ = p } // Test that 'as?' coercion fails. let strImplicitOpt: String! = nil _ = strImplicitOpt as? String // expected-warning{{conditional downcast from 'String?' to 'String' does nothing}}{{19-30=}} class C3 {} class C4 : C3 {} class C5 {} var c: AnyObject = C3() // XXX TODO: Constant-folding should generate an error about 'C3' not being convertible to 'C4' //if let castX = c as! C4? {} // XXX TODO: Only suggest replacing 'as' with 'as!' if it would fix the error. C3() as C4 // expected-error {{'C3' is not convertible to 'C4'}} // expected-note@-1 {{did you mean to use 'as!' to force downcast?}} {{6-8=as!}} C3() as C5 // expected-error {{cannot convert value of type 'C3' to type 'C5' in coercion}} // Diagnostic shouldn't include @lvalue in type of c3. var c3 = C3() // XXX TODO: This should not suggest `as!` c3 as C4 // expected-error {{'C3' is not convertible to 'C4'}} // expected-note@-1{{did you mean to use 'as!' to force downcast?}} {{4-6=as!}} // <rdar://problem/19495142> Various incorrect diagnostics for explicit type conversions 1 as Double as Float // expected-error{{cannot convert value of type 'Double' to type 'Float' in coercion}} 1 as Int as String // expected-error{{cannot convert value of type 'Int' to type 'String' in coercion}} Double(1) as Double as String // expected-error{{cannot convert value of type 'Double' to type 'String' in coercion}} ["awd"] as [Int] // expected-error{{cannot convert value of type 'String' to expected element type 'Int'}} ([1, 2, 1.0], 1) as ([String], Int) // expected-error@-1 2 {{cannot convert value of type 'Int' to expected element type 'String'}} // expected-error@-2 {{cannot convert value of type 'Double' to expected element type 'String'}} [[1]] as [[String]] // expected-error{{cannot convert value of type 'Int' to expected element type 'String'}} (1, 1.0) as (Int, Int) // expected-error{{cannot convert value of type '(Int, Double)' to type '(Int, Int)' in coercion}} (1.0, 1, "asd") as (String, Int, Float) // expected-error{{cannot convert value of type '(Double, Int, String)' to type '(String, Int, Float)' in coercion}} (1, 1.0, "a", [1, 23]) as (Int, Double, String, [String]) // expected-error@-1 2 {{cannot convert value of type 'Int' to expected element type 'String'}} _ = [1] as! [String] // OK _ = [(1, (1, 1))] as! [(Int, (String, Int))] // OK // <rdar://problem/19495253> Incorrect diagnostic for explicitly casting to the same type _ = "hello" as! String // expected-warning{{forced cast of 'String' to same type has no effect}} {{13-24=}} // <rdar://problem/19499340> QoI: Nimble as -> as! changes not covered by Fix-Its func f(_ x : String) {} f("what" as Any as String) // expected-error {{'Any' is not convertible to 'String'}} // expected-note@-1{{did you mean to use 'as!' to force downcast?}} {{17-19=as!}} f(1 as String) // expected-error{{cannot convert value of type 'Int' to type 'String' in coercion}} // <rdar://problem/19650402> Swift compiler segfaults while running the annotation tests let s : AnyObject = C3() s as C3 // expected-error{{'AnyObject' is not convertible to 'C3'}} // expected-note@-1{{did you mean to use 'as!' to force downcast?}} {{3-5=as!}} // https://github.com/apple/swift/issues/48579 protocol P_48579 {} do { func f1() -> Any {} func f2() {} _ = f1 is P_48579 // expected-warning {{cast from '() -> Any' to unrelated type 'any P_48579' always fails}} // expected-note {{did you mean to call 'f1' with '()'?}}{{9-9=()}} _ = f1 as! P_48579 // expected-warning {{cast from '() -> Any' to unrelated type 'any P_48579' always fails}} // expected-note {{did you mean to call 'f1' with '()'?}}{{9-9=()}} _ = f1 as? P_48579 // expected-warning {{cast from '() -> Any' to unrelated type 'any P_48579' always fails}} // expected-note {{did you mean to call 'f1' with '()'}}{{9-9=()}} _ = f2 is P_48579 // expected-warning {{cast from '() -> ()' to unrelated type 'any P_48579' always fails}} _ = f2 as! P_48579 // expected-warning {{cast from '() -> ()' to unrelated type 'any P_48579' always fails}} _ = f2 as? P_48579 // expected-warning {{cast from '() -> ()' to unrelated type 'any P_48579' always fails}} _ = f1 as! AnyObject // expected-warning {{forced cast from '() -> Any' to 'AnyObject' always succeeds; did you mean to use 'as'?}} _ = f1 as? AnyObject // expected-warning {{conditional cast from '() -> Any' to 'AnyObject' always succeeds}} _ = f2 as! Any // expected-warning {{forced cast from '() -> ()' to 'Any' always succeeds; did you mean to use 'as'?}} _ = f2 as? Any // expected-warning {{conditional cast from '() -> ()' to 'Any' always succeeds}} func test1<T: P_48579>(_: T.Type) { _ = f1 is T // expected-warning {{cast from '() -> Any' to unrelated type 'T' always fails}} // expected-note {{did you mean to call 'f1' with '()'?}}{{11-11=()}} _ = f1 as! T // expected-warning {{cast from '() -> Any' to unrelated type 'T' always fails}} // expected-note {{did you mean to call 'f1' with '()'?}}{{11-11=()}} _ = f1 as? T // expected-warning {{cast from '() -> Any' to unrelated type 'T' always fails}} // expected-note {{did you mean to call 'f1' with '()'?}}{{11-11=()}} _ = f2 is T // expected-warning {{cast from '() -> ()' to unrelated type 'T' always fails}} _ = f2 as! T // expected-warning {{cast from '() -> ()' to unrelated type 'T' always fails}} _ = f2 as? T // expected-warning {{cast from '() -> ()' to unrelated type 'T' always fails}} } func test2<U>(_: U.Type) { _ = f1 as! U // Okay _ = f1 as? U // Okay _ = f2 as! U // Okay _ = f2 as? U // Okay } } // https://github.com/apple/swift/issues/56297 let any: Any = 1 if let int = any as Int { // expected-error {{'Any' is not convertible to 'Int'}} // expected-note@-1 {{did you mean to use 'as?' to conditionally downcast?}} {{18-20=as?}} } let _ = any as Int // expected-error {{'Any' is not convertible to 'Int'}} // expected-note@-1 {{did you mean to use 'as!' to force downcast?}} {{13-15=as!}} let _: Int = any as Int // expected-error {{'Any' is not convertible to 'Int'}} // expected-note@-1 {{did you mean to use 'as!' to force downcast?}} {{18-20=as!}} let _: Int? = any as Int // expected-error {{'Any' is not convertible to 'Int'}} // expected-note@-1 {{did you mean to use 'as?' to conditionally downcast?}} {{19-21=as?}}
apache-2.0
cde1a9fff0bcdd571a3cfe8336d3febe
42.769697
179
0.627389
3.228431
false
false
false
false
Scorocode/scorocode-SDK-swift
ScorocodeTests/TestSCUpdate.swift
1
4912
// // TestUpdate.swift // SC // // Created by Alexey Kuznetsov on 27/12/2016. // Copyright © 2016 Prof-IT Group OOO. All rights reserved. // import XCTest class TestSCUpdate: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testOperators() { var update = SCUpdate() let op1 = SCUpdateOperator.push(name: "fieldName1", value: SCString("A"), each: false) update.addOperator(op1) let op2 = SCUpdateOperator.push(name: "fieldName2", value: SCString("b"), each: true) update.addOperator(op2) XCTAssertEqual(update.operators, [op1, op2]) } func testAddOperator() { var update = SCUpdate() let op1 = SCUpdateOperator.push(name: "fieldName1", value: SCString("A"), each: false) update.addOperator(op1) XCTAssertEqual(update.operators.last!, op1) } func testSet() { var update = SCUpdate() update.set(["fieldName": SCString("A")]) XCTAssertEqual(update.operators.last!, SCUpdateOperator.set(["fieldName": SCString("A")])) } func testPush() { var update = SCUpdate() update.push("fieldName", SCString("A")) XCTAssertEqual(update.operators.last!, SCUpdateOperator.push(name: "fieldName", value: SCString("A"), each: false)) } func testPushEach() { var update = SCUpdate() update.pushEach("fieldName", SCString("A")) XCTAssertEqual(update.operators, [SCUpdateOperator]()) update.pushEach("fieldName", SCArray([SCString("A")])) XCTAssertEqual(update.operators.last!, SCUpdateOperator.push(name: "fieldName", value: SCArray([SCString("A")]), each: true)) } // TODO: Pull func testPull() { var update = SCUpdate() update.pull("fieldName", SCString("A")) XCTAssertEqual(update.operators.last!, SCUpdateOperator.pull("fieldName", SCString("A"))) } func testPullAll() { var update = SCUpdate() update.pullAll("fieldName", SCString("A")) XCTAssertEqual(update.operators, [SCUpdateOperator]()) update.pullAll("fieldName", SCArray([SCString("A")])) XCTAssertEqual(update.operators.last!, SCUpdateOperator.pullAll("fieldName", SCArray([SCString("A")]))) } func testAddToSet() { var update = SCUpdate() update.addToSet("fieldName", SCString("A")) XCTAssertEqual(update.operators.last!, SCUpdateOperator.addToSet(name: "fieldName", value: SCString("A"), each: false)) } func testAddToSetEach() { var update = SCUpdate() update.addToSetEach("fieldName", SCString("A")) XCTAssertEqual(update.operators.last!, SCUpdateOperator.addToSet(name: "fieldName", value: SCString("A"), each: true)) } func testPop() { var update = SCUpdate() update.pop("fieldName", 0) XCTAssertEqual(update.operators, [SCUpdateOperator]()) update.pop("fieldName", 1) XCTAssertEqual(update.operators.last!, SCUpdateOperator.pop("fieldName", 1)) } func testInc() { var update = SCUpdate() update.inc("fieldName", SCString("A")) XCTAssertEqual(update.operators, [SCUpdateOperator]()) update.inc("fieldName", SCInt(1)) XCTAssertEqual(update.operators.last!, SCUpdateOperator.inc("fieldName", SCInt(1))) } func testCurrentDate() { var update = SCUpdate() update.currentDate("fieldName", typeSpec: "wrong") XCTAssertEqual(update.operators, [SCUpdateOperator]()) update.currentDate("fieldName", typeSpec: "date") XCTAssertEqual(update.operators.last!, SCUpdateOperator.currentDate("fieldName", "date")) } func testMul() { var update = SCUpdate() update.mul("fieldName", SCString("A")) XCTAssertEqual(update.operators, [SCUpdateOperator]()) update.mul("fieldName", SCInt(5)) XCTAssertEqual(update.operators.last!, SCUpdateOperator.mul("fieldName", SCInt(5))) } func testMin() { var update = SCUpdate() update.min("fieldName", SCInt(5)) XCTAssertEqual(update.operators.last!, SCUpdateOperator.min("fieldName", SCInt(5))) } func testMax() { var update = SCUpdate() update.max("fieldName", SCInt(5)) XCTAssertEqual(update.operators.last!, SCUpdateOperator.max("fieldName", SCInt(5))) } }
mit
8e7ac6a9d934c15d801fbd4e6119a3f9
31.523179
133
0.604358
4.681602
false
true
false
false
Zeitblick/Zeitblick-iOS
Zeitblick/vendor/Spring/Misc.swift
1
7935
// The MIT License (MIT) // // Copyright (c) 2015 Meng To ([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. import UIKit public extension String { public var length: Int { return self.characters.count } public func toURL() -> NSURL? { return NSURL(string: self) } } public func htmlToAttributedString(text: String) -> NSAttributedString! { let htmlData = text.data(using: String.Encoding.utf8, allowLossyConversion: false) let htmlString: NSAttributedString? do { htmlString = try NSAttributedString(data: htmlData!, options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType], documentAttributes: nil) } catch _ { htmlString = nil } return htmlString } public func degreesToRadians(degrees: CGFloat) -> CGFloat { return degrees * CGFloat(M_PI / 180) } public func delay(delay:Double, closure: @escaping ()->()) { DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + Double(Int64(delay * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC), execute: closure) } public func imageFromURL(_ Url: String) -> UIImage { let url = Foundation.URL(string: Url) let data = try? Data(contentsOf: url!) return UIImage(data: data!)! } public extension UIColor { convenience init(hex: String) { var red: CGFloat = 0.0 var green: CGFloat = 0.0 var blue: CGFloat = 0.0 var alpha: CGFloat = 1.0 var hex: String = hex if hex.hasPrefix("#") { let index = hex.index(hex.startIndex, offsetBy: 1) hex = hex.substring(from: index) } let scanner = Scanner(string: hex) var hexValue: CUnsignedLongLong = 0 if scanner.scanHexInt64(&hexValue) { switch (hex.characters.count) { case 3: red = CGFloat((hexValue & 0xF00) >> 8) / 15.0 green = CGFloat((hexValue & 0x0F0) >> 4) / 15.0 blue = CGFloat(hexValue & 0x00F) / 15.0 case 4: red = CGFloat((hexValue & 0xF000) >> 12) / 15.0 green = CGFloat((hexValue & 0x0F00) >> 8) / 15.0 blue = CGFloat((hexValue & 0x00F0) >> 4) / 15.0 alpha = CGFloat(hexValue & 0x000F) / 15.0 case 6: red = CGFloat((hexValue & 0xFF0000) >> 16) / 255.0 green = CGFloat((hexValue & 0x00FF00) >> 8) / 255.0 blue = CGFloat(hexValue & 0x0000FF) / 255.0 case 8: red = CGFloat((hexValue & 0xFF000000) >> 24) / 255.0 green = CGFloat((hexValue & 0x00FF0000) >> 16) / 255.0 blue = CGFloat((hexValue & 0x0000FF00) >> 8) / 255.0 alpha = CGFloat(hexValue & 0x000000FF) / 255.0 default: print("Invalid RGB string, number of characters after '#' should be either 3, 4, 6 or 8", terminator: "") } } else { print("Scan hex error") } self.init(red:red, green:green, blue:blue, alpha:alpha) } } public func rgbaToUIColor(red: CGFloat, green: CGFloat, blue: CGFloat, alpha: CGFloat) -> UIColor { return UIColor(red: red, green: green, blue: blue, alpha: alpha) } public func UIColorFromRGB(rgbValue: UInt) -> UIColor { return UIColor( red: CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0, green: CGFloat((rgbValue & 0x00FF00) >> 8) / 255.0, blue: CGFloat(rgbValue & 0x0000FF) / 255.0, alpha: CGFloat(1.0) ) } public func stringFromDate(date: NSDate, format: String) -> String { let dateFormatter = DateFormatter() dateFormatter.dateFormat = format return dateFormatter.string(from: date as Date) } public func dateFromString(date: String, format: String) -> Date { let dateFormatter = DateFormatter() dateFormatter.dateFormat = format if let date = dateFormatter.date(from: date) { return date } else { return Date(timeIntervalSince1970: 0) } } public func randomStringWithLength (len : Int) -> NSString { let letters : NSString = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" let randomString : NSMutableString = NSMutableString(capacity: len) for _ in 0 ..< len { let length = UInt32 (letters.length) let rand = arc4random_uniform(length) randomString.appendFormat("%C", letters.character(at: Int(rand))) } return randomString } public func timeAgoSinceDate(date: Date, numericDates: Bool) -> String { let calendar = Calendar.current let unitFlags = Set<Calendar.Component>(arrayLiteral: Calendar.Component.minute, Calendar.Component.hour, Calendar.Component.day, Calendar.Component.weekOfYear, Calendar.Component.month, Calendar.Component.year, Calendar.Component.second) let now = Date() let dateComparison = now.compare(date) var earliest: Date var latest: Date switch dateComparison { case .orderedAscending: earliest = now latest = date default: earliest = date latest = now } let components: DateComponents = calendar.dateComponents(unitFlags, from: earliest, to: latest) guard let year = components.year, let month = components.month, let weekOfYear = components.weekOfYear, let day = components.day, let hour = components.hour, let minute = components.minute, let second = components.second else { fatalError() } if (year >= 2) { return "\(year)y" } else if (year >= 1) { if (numericDates){ return "1y" } else { return "1y" } } else if (month >= 2) { return "\(month * 4)w" } else if (month >= 1) { if (numericDates){ return "4w" } else { return "4w" } } else if (weekOfYear >= 2) { return "\(weekOfYear)w" } else if (weekOfYear >= 1){ if (numericDates){ return "1w" } else { return "1w" } } else if (day >= 2) { return "\(components.day)d" } else if (day >= 1){ if (numericDates){ return "1d" } else { return "1d" } } else if (hour >= 2) { return "\(hour)h" } else if (hour >= 1){ if (numericDates){ return "1h" } else { return "1h" } } else if (minute >= 2) { return "\(minute)m" } else if (minute >= 1){ if (numericDates){ return "1m" } else { return "1m" } } else if (second >= 3) { return "\(second)s" } else { return "now" } }
gpl-3.0
691c7ed451375c993b816d4a3693feb9
32.910256
242
0.589666
4.187335
false
false
false
false
alexandresoliveira/IosSwiftExamples
CardApp/CardApp/ViewController.swift
1
2768
// // ViewController.swift // CardApp // // Created by Alexandre Salvador de Oliveira on 13/01/2018. // Copyright © 2018 Alexandre Salvador de Oliveira. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var scroll: UIScrollView! @IBOutlet weak var greenView: UIView! @IBOutlet weak var purpleView: UIView! @IBOutlet weak var blueView: UIView! override func viewDidLoad() { super.viewDidLoad() addCardViews() addActionViews() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } private func addCardViews() { let margins = scroll.layoutMarginsGuide var lastCardView: CardView? = nil for _ in 0...8 { let cardView: CardView = CardView() cardView.backgroundColor = UIColor.white scroll.addSubview(cardView) cardView.translatesAutoresizingMaskIntoConstraints = false cardView.heightAnchor.constraint(equalToConstant: 150).isActive = true cardView.widthAnchor.constraint(equalToConstant: scroll.bounds.width - 32).isActive = true cardView.centerXAnchor.constraint(equalTo: margins.centerXAnchor).isActive = true if lastCardView != nil { cardView.topAnchor.constraint(equalTo: (lastCardView?.bottomAnchor)!, constant: 16.0).isActive = true } else { cardView.topAnchor.constraint(equalTo: scroll.topAnchor, constant: 8.0).isActive = true } lastCardView = cardView } let newHeightScroll: CGFloat = 150.0 * 10 scroll.contentSize = CGSize(width: scroll.bounds.width, height: newHeightScroll) } private func addActionViews() { let tapG = UITapGestureRecognizer(target: self, action: #selector(ViewController.tapGreen)) greenView.addGestureRecognizer(tapG) let tapP = UITapGestureRecognizer(target: self, action: #selector(ViewController.tapPurple)) purpleView.addGestureRecognizer(tapP) let tapB = UITapGestureRecognizer(target: self, action: #selector(ViewController.tapBlue)) blueView.addGestureRecognizer(tapB) } @objc func tapGreen() { alert("Green Tap") } @objc func tapPurple() { alert("Purple Tap") } @objc func tapBlue() { alert("Blue Tap") } private func alert(_ msg: String) { let alert = UIAlertController(title: "Alert", message: msg, preferredStyle: UIAlertControllerStyle.alert) alert.addAction(UIAlertAction(title: "Click", style: UIAlertActionStyle.default, handler: nil)) self.present(alert, animated: true, completion: nil) } }
gpl-3.0
103462f37802037b775b3f4b742b1059
34.935065
117
0.656306
4.994585
false
false
false
false
crossroadlabs/Boilerplate
Tests/BoilerplateTests/NullTests.swift
1
2531
// // NullTests.swift // Boilerplate // // Created by Daniel Leping on 17/06/2016. // Copyright © 2016 Crossroad Labs, LTD. All rights reserved. // import XCTest import Foundation import Result import Boilerplate enum Nullable { case yesnull case nonull case somemore } extension Nullable : NullEquatable { } func ==(lhs:Nullable, rhs:Null) -> Bool { switch lhs { case .yesnull: return true default: return false } } class NullTests: XCTestCase { let yesnull:Nullable? = .yesnull let nonull:Nullable? = .nonull let somemore:Nullable? = .somemore let actualnil:Nullable? = nil let snil:String? = nil let snnil:String? = "" func testNull() { XCTAssert(Nullable.yesnull == .null) XCTAssert(Nullable.yesnull == nil) XCTAssertFalse(Nullable.nonull == .null) XCTAssertFalse(Nullable.nonull == nil) XCTAssertFalse(Nullable.somemore == .null) XCTAssertFalse(Nullable.somemore == nil) } func testNotNull() { XCTAssertFalse(Nullable.yesnull != .null) XCTAssertFalse(Nullable.yesnull != nil) XCTAssert(Nullable.nonull != .null) XCTAssert(Nullable.nonull != nil) XCTAssert(Nullable.somemore != .null) XCTAssert(Nullable.somemore != nil) } func testOptional() { XCTAssert(snil == nil) XCTAssert(snil == .null) XCTAssert(snnil != nil) XCTAssert(snnil != .null) XCTAssertFalse(snil != nil) XCTAssertFalse(snil != .null) XCTAssertFalse(snnil == nil) XCTAssertFalse(snnil == .null) } func testOptionalNull() { XCTAssert(yesnull == .null) //XCTAssert(yesnull == nil) XCTAssert(actualnil == .null) //XCTAssert(actualnil == nil) XCTAssertFalse(nonull == .null) //XCTAssertFalse(nonull == nil) XCTAssertFalse(somemore == .null) //XCTAssertFalse(somemore == nil) } func testOptionalNotNull() { XCTAssertFalse(yesnull != .null) XCTAssertFalse(actualnil != .null) XCTAssert(nonull != .null) XCTAssert(somemore != .null) } } #if os(Linux) extension NullTests { static var allTests : [(String, (NullTests) -> () throws -> Void)] { return [ ("testNull", testNull), ("testNotNull", testNotNull), ("testOptionalNull", testOptionalNull), ("testOptionalNotNull", testOptionalNotNull), ] } } #endif
apache-2.0
d27cd96d19ce0d35553abf0bbac9332b
23.095238
69
0.601581
4.252101
false
true
false
false
anthonyprograms/SwiftStructures
SwiftTests/AVLTest.swift
10
4563
// // AVLTest.swift // SwiftStructures // // Created by Wayne Bishop on 9/23/14. // Copyright (c) 2014 Arbutus Software Inc. All rights reserved. // import UIKit import XCTest /* An AVL Tree is another name for a balanced binary search tree*/ class AVLTest: XCTestCase { //called before each test invocation override func setUp() { super.setUp() } //essay documentation - single right rotation - O(n) func testAVLEssayExample() { let numberList : Array<Int> = [29, 26, 23] //build and balance model self.buildAVLTree(numberList) } //input for a balanced avl tree - O(log n) func testAVLBalancedTree() { let numberList : Array<Int> = [8, 5, 10, 3, 12, 9, 6, 16] //build and balance model self.buildAVLTree(numberList) } //input for multiple right rotations - O(n) func testAVLRotationRight() { let numberList: Array<Int> = [29, 26, 23, 20, 19] //build and balance model self.buildAVLTree(numberList) } //input for multiple left rotations - O(n) func testAVLRotationLeft() { let numberList: Array<Int> = [19, 20, 23, 26, 29] //build and balance model self.buildAVLTree(numberList) } //input for left and right rotations - 0(n) func testAVLRotationLeftAndRight() { let numberList: Array<Int> = [19, 20, 21, 26, 16, 12] //build and balance model self.buildAVLTree(numberList) } //MARK: Closure Tests //update tree values with function func testAVLTraverseFunction() { var avlTest = self.buildClosureTree() //invoke formula function avlTest.traverse(traverseFormula) } //update avl values with closure expression func testAVLTraverseExpression() { var avlTest = self.buildClosureTree() var didFail: Bool = false /* notes: for this test, the didFail variable is known to be 'captured' by the closure expression. this technique allows a single variable to be used. */ avlTest.traverse { (node: AVLTree<Int>) -> Int in var results = node.key! + node.height if node.height > 0 && node.key! == results { didFail = true } return results } XCTAssertFalse(didFail, "..closure update failed..") } //update avl values with closure function func traverseFormula(node: AVLTree<Int>) -> Int { var results = node.key! + node.height if node.height > 0 && node.key! == results { XCTFail("closure update failed..") } return results } //MARK: Helper Functions //helper function - build and balance bst func buildAVLTree(numberList: Array<Int>) { //test for new instance var avlTest: AVLTree<Int> = AVLTree<Int>() XCTAssertNotNil(avlTest, "avl instance not created..") //build the tree list for number in numberList { println("adding \(number) to avl tree...") avlTest.addNode(number) } //traverse the completed tree avlTest.traverse() //tree balance check XCTAssertTrue(avlTest.isTreeBalanced(), "tree is unbalanced..") } //helper function - build specific model to be traversed with closures func buildClosureTree() -> AVLTree<Int> { //test for new instance var avlTest: AVLTree<Int> = AVLTree<Int>() XCTAssertNotNil(avlTest, "avl instance not created..") //provide a balanced list let numberList : Array<Int> = [8, 5, 10, 3, 12, 9, 6, 16] //build the tree list for number in numberList { println("adding \(number) to avl tree...") avlTest.addNode(number) } //tree balance check XCTAssertTrue(avlTest.isTreeBalanced(), "tree is unbalanced..") return avlTest } }
mit
4425be37930d231053ad83ed27d900b3
21.043478
103
0.522244
5.030871
false
true
false
false
chrisjmendez/swift-exercises
Walkthroughs/BWW/Pods/BWWalkthrough/Pod/Classes/BWWalkthroughPageViewController.swift
1
6383
/* The MIT License (MIT) Copyright (c) 2015 Yari D'areglia @bitwaker Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ import UIKit public enum WalkthroughAnimationType:String{ case Linear = "Linear" case Curve = "Curve" case Zoom = "Zoom" case InOut = "InOut" init(_ name:String){ if let tempSelf = WalkthroughAnimationType(rawValue: name){ self = tempSelf }else{ self = .Linear } } } public class BWWalkthroughPageViewController: UIViewController, BWWalkthroughPage { private var animation:WalkthroughAnimationType = .Linear private var subsWeights:[CGPoint] = Array() private var notAnimatableViews:[Int] = [] // Array of views' tags that should not be animated during the scroll/transition // MARK: Inspectable Properties // Edit these values using the Attribute inspector or modify directly the "User defined runtime attributes" in IB @IBInspectable var speed:CGPoint = CGPoint(x: 0.0, y: 0.0); // Note if you set this value via Attribute inspector it can only be an Integer (change it manually via User defined runtime attribute if you need a Float) @IBInspectable var speedVariance:CGPoint = CGPoint(x: 0.0, y: 0.0) // Note if you set this value via Attribute inspector it can only be an Integer (change it manually via User defined runtime attribute if you need a Float) @IBInspectable var animationType:String { set(value){ self.animation = WalkthroughAnimationType(rawValue: value)! } get{ return self.animation.rawValue } } @IBInspectable var animateAlpha:Bool = false @IBInspectable var staticTags:String { // A comma separated list of tags that you don't want to animate during the transition/scroll set(value){ self.notAnimatableViews = value.componentsSeparatedByString(",").map{Int($0)!} } get{ return notAnimatableViews.map{String($0)}.joinWithSeparator(",") } } // MARK: BWWalkthroughPage Implementation override public func viewDidLoad() { super.viewDidLoad() self.view.layer.masksToBounds = true subsWeights = Array() for v in view.subviews{ speed.x += speedVariance.x speed.y += speedVariance.y if !notAnimatableViews.contains(v.tag) { subsWeights.append(speed) } } } public func walkthroughDidScroll(position: CGFloat, offset: CGFloat) { for(var i = 0; i < subsWeights.count ;i++){ // Perform Transition/Scale/Rotate animations switch animation{ case .Linear: animationLinear(i, offset) case .Zoom: animationZoom(i, offset) case .Curve: animationCurve(i, offset) case .InOut: animationInOut(i, offset) } // Animate alpha if(animateAlpha){ animationAlpha(i, offset) } } } // MARK: Animations (WIP) private func animationAlpha(index:Int, var _ offset:CGFloat){ let cView = view.subviews[index] if(offset > 1.0){ offset = 1.0 + (1.0 - offset) } cView.alpha = (offset) } private func animationCurve(index:Int, _ offset:CGFloat){ var transform = CATransform3DIdentity let x:CGFloat = (1.0 - offset) * 10 transform = CATransform3DTranslate(transform, (pow(x,3) - (x * 25)) * subsWeights[index].x, (pow(x,3) - (x * 20)) * subsWeights[index].y, 0 ) applyTransform(index, transform: transform) } private func animationZoom(index:Int, _ offset:CGFloat){ var transform = CATransform3DIdentity var tmpOffset = offset if(tmpOffset > 1.0){ tmpOffset = 1.0 + (1.0 - tmpOffset) } let scale:CGFloat = (1.0 - tmpOffset) transform = CATransform3DScale(transform, 1 - scale , 1 - scale, 1.0) applyTransform(index, transform: transform) } private func animationLinear(index:Int, _ offset:CGFloat){ var transform = CATransform3DIdentity let mx:CGFloat = (1.0 - offset) * 100 transform = CATransform3DTranslate(transform, mx * subsWeights[index].x, mx * subsWeights[index].y, 0 ) applyTransform(index, transform: transform) } private func animationInOut(index:Int, _ offset:CGFloat){ var transform = CATransform3DIdentity //var x:CGFloat = (1.0 - offset) * 20 var tmpOffset = offset if(tmpOffset > 1.0){ tmpOffset = 1.0 + (1.0 - tmpOffset) } transform = CATransform3DTranslate(transform, (1.0 - tmpOffset) * subsWeights[index].x * 100, (1.0 - tmpOffset) * subsWeights[index].y * 100, 0) applyTransform(index, transform: transform) } private func applyTransform(index:Int, transform:CATransform3D){ let subview = view.subviews[index] if !notAnimatableViews.contains(subview.tag){ view.subviews[index].layer.transform = transform } } }
mit
52e1a9a620db4a4180ffafdbbf8303f5
35.901734
230
0.624315
4.672767
false
false
false
false
twobitlabs/AnalyticsKit
Providers/mParticle/AnalyticsKitMParticleProvider.swift
1
4726
import Foundation import mParticle_Apple_SDK let AKMParticleEventType = "mParticleEventType" public class AnalyticsKitMParticleProvider: NSObject, AnalyticsKitProvider { let defaultEventType: MPEventType @objc(initWithOptions:defaultEventType:) public init(options: MParticleOptions, defaultEventType: MPEventType = .other) { self.defaultEventType = defaultEventType MParticle.sharedInstance().start(with: options) } @objc(initWithKey:secret:defaultEventType:installationType:environment:proxyAppDelegate:) public init(key: String, secret: String, defaultEventType: MPEventType = .other, installationType: MPInstallationType = .autodetect, environment: MPEnvironment = .autoDetect, proxyAppDelegate: Bool = false) { self.defaultEventType = defaultEventType let options = MParticleOptions(key: key, secret: secret) options.installType = installationType options.environment = environment options.proxyAppDelegate = proxyAppDelegate MParticle.sharedInstance().start(with: options) } public func applicationWillEnterForeground() {} public func applicationDidEnterBackground() {} public func applicationWillTerminate() {} public func uncaughtException(_ exception: NSException) {} // Logging public func logScreen(_ screenName: String) { MParticle.sharedInstance().logScreen(screenName, eventInfo: nil) } public func logScreen(_ screenName: String, withProperties properties: [String: Any]) { MParticle.sharedInstance().logScreen(screenName, eventInfo: properties) } public func logEvent(_ event: String) { MParticle.sharedInstance().logEvent(event, eventType: defaultEventType, eventInfo: nil) } public func logEvent(_ event: String, withProperties properties: [String: Any]) { MParticle.sharedInstance().logEvent(event, eventType: extractEventTypeFromProperties(properties), eventInfo: properties) } public func logEvent(_ event: String, withProperty key: String, andValue value: String) { logEvent(event, withProperties: [key: value]) } public func logEvent(_ event: String, timed: Bool) { if timed { if let event = MPEvent(name: event, type: defaultEventType) { MParticle.sharedInstance().beginTimedEvent(event) } } else { logEvent(event) } } public func logEvent(_ event: String, withProperties properties: [String: Any], timed: Bool) { if timed { if let mpEvent = MPEvent(name: event, type: extractEventTypeFromProperties(properties)) { mpEvent.customAttributes = properties MParticle.sharedInstance().beginTimedEvent(mpEvent) } } else { logEvent(event, withProperties: properties) } } public func endTimedEvent(_ event: String, withProperties properties: [String: Any]) { if let event = MParticle.sharedInstance().event(withName: event) { if properties.count > 0 { // Replace the parameters if parameters are passed event.customAttributes = properties } // The mParticle SDK's endTimedEvent call became asynchronous in 7.3.0, // so calling event(withName:) immediately after calling endTimedEvent is likely to still return an event. // https://github.com/mParticle/mparticle-apple-sdk/commit/ead0fc8 MParticle.sharedInstance().endTimedEvent(event) } } public func logError(_ name: String, message: String?, properties: [String: Any]?, exception: NSException?) { if let exception = exception { MParticle.sharedInstance().logException(exception) } else { logError(name, message: message, properties: properties, error: nil) } } public func logError(_ name: String, message: String?, properties: [String: Any]?, error: Error?) { var eventInfo = [String: Any]() if let message = message { eventInfo["message"] = message } if let error = error { eventInfo["error"] = error.localizedDescription } if let properties = properties { eventInfo.merge(properties) { (current, _) in current } } MParticle.sharedInstance().logError(name, eventInfo: eventInfo) } fileprivate func extractEventTypeFromProperties(_ properties: [String: Any]) -> MPEventType { if let value = properties[AKMParticleEventType] as? UInt, let eventType = MPEventType(rawValue: value) { return eventType } return defaultEventType } }
mit
48bcfe62635d4fbfc0b5463f37bc6934
40.45614
212
0.665468
5.103672
false
false
false
false
taqun/TodoEver
TodoEver/Classes/Model/Managed/TDEMTask.swift
1
1211
// // TDEMTask.swift // TodoEver // // Created by taqun on 2015/06/02. // Copyright (c) 2015年 envoixapp. All rights reserved. // import UIKit import CoreData import SWXMLHash @objc(TDEMTask) class TDEMTask: NSManagedObject { @NSManaged var title: String @NSManaged var isChecked: Bool @NSManaged var index: Int /* * Public Method */ func parseData(index:Int, data: XMLIndexer) { self.index = index if let titleValue = data.element?.text { self.title = titleValue } if var checkedValue = data["en-todo"].element?.attributes["checked"] { if checkedValue == "true" { self.isChecked = true } else { self.isChecked = false } } else { self.isChecked = false } } /* * Getter, Setter */ var htmlString: String { get { if self.isChecked { return "<div><en-todo checked=\"\(self.isChecked)\"></en-todo>\(self.title)</div>" } else { return "<div><en-todo></en-todo>\(self.title)</div>" } } } }
mit
cd25b83767fe1d96ac99b3a8f4c8390d
20.589286
98
0.507031
4.333333
false
false
false
false
valitovaza/NewsAP
NewsAP/Article/ArticleResponse.swift
1
965
struct ArticleResponse { let status: ResponseStatus let source: String let sortBy: SortType let articles: [Article] } extension ArticleResponse { static let statusKey = "status" static let sourceKey = "source" static let sortByKey = "sortBy" static let articlesKey = "articles" init?(_ dict: [String: Any]) { guard let statusString = dict[ArticleResponse.statusKey] as? String, let status = ResponseStatus(rawValue: statusString), let source = dict[ArticleResponse.sourceKey] as? String, let sortByString = dict[ArticleResponse.sortByKey] as? String, let sortBy = SortType(rawValue: sortByString), let articles = dict[ArticleResponse.articlesKey] as? [[String: Any]] else { return nil } self.status = status self.source = source self.sortBy = sortBy self.articles = articles.flatMap{Article($0)} } }
mit
4c54d76dc6af01fc51eba70ac5f230f3
34.740741
87
0.637306
4.551887
false
false
false
false
Antondomashnev/Sourcery
SourceryTests/Stub/Performance-Code/Kiosk/App/MarkdownParser.swift
2
711
import Foundation import XNGMarkdownParser import Artsy_UIFonts class MarkdownParser: XNGMarkdownParser { override init() { super.init() paragraphFont = UIFont.serifFont(withSize: 16) linkFontName = UIFont.serifItalicFont(withSize: 16).fontName boldFontName = UIFont.serifBoldFont(withSize: 16).fontName italicFontName = UIFont.serifItalicFont(withSize: 16).fontName shouldParseLinks = false let paragraphStyle = NSMutableParagraphStyle() paragraphStyle.minimumLineHeight = 16 topAttributes = [ NSParagraphStyleAttributeName: paragraphStyle, NSForegroundColorAttributeName: UIColor.black ] } }
mit
430c3efb151f12112e2a30c7e9b9c14c
28.625
70
0.699015
5.554688
false
false
false
false
TarangKhanna/Inspirator
WorkoutMotivation/PullToRefreshView.swift
2
8548
// // PullToRefreshConst.swift // PullToRefreshSwift // // Created by Yuji Hato on 12/11/14. // import UIKit public class PullToRefreshView: UIView { enum PullToRefreshState { case Normal case Pulling case Refreshing } // MARK: Variables let contentOffsetKeyPath = "contentOffset" var kvoContext = "" private var options: PullToRefreshOption! private var backgroundView: UIView! private var arrow: UIImageView! private var indicator: UIActivityIndicatorView! private var scrollViewBounces: Bool = false private var scrollViewInsets: UIEdgeInsets = UIEdgeInsetsZero private var previousOffset: CGFloat = 0 private var refreshCompletion: (() -> ()) = {} var state: PullToRefreshState = PullToRefreshState.Normal { didSet { if self.state == oldValue { return } switch self.state { case .Normal: stopAnimating() case .Refreshing: startAnimating() default: break } } } // MARK: UIView override init(frame: CGRect) { super.init(frame: frame) } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } convenience init(options: PullToRefreshOption, frame: CGRect, refreshCompletion :(() -> ())) { self.init(frame: frame) self.options = options self.refreshCompletion = refreshCompletion self.backgroundView = UIView(frame: CGRectMake(0, 0, frame.size.width, frame.size.height)) self.backgroundView.backgroundColor = self.options.backgroundColor self.backgroundView.autoresizingMask = UIViewAutoresizing.FlexibleWidth self.addSubview(backgroundView) self.arrow = UIImageView(frame: CGRectMake(0, 0, 30, 30)) self.arrow.autoresizingMask = [.FlexibleLeftMargin, .FlexibleRightMargin] self.arrow.image = UIImage(named: PullToRefreshConst.imageName, inBundle: NSBundle(forClass: self.dynamicType), compatibleWithTraitCollection: nil) self.addSubview(arrow) self.indicator = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.Gray) self.indicator.bounds = self.arrow.bounds self.indicator.autoresizingMask = self.arrow.autoresizingMask self.indicator.hidesWhenStopped = true self.indicator.color = options.indicatorColor self.addSubview(indicator) self.autoresizingMask = .FlexibleWidth } public override func layoutSubviews() { super.layoutSubviews() self.arrow.center = CGPointMake(self.frame.size.width / 2, self.frame.size.height / 2) self.indicator.center = self.arrow.center } public override func willMoveToSuperview(superView: UIView!) { superview?.removeObserver(self, forKeyPath: contentOffsetKeyPath, context: &kvoContext) if let scrollView = superView as? UIScrollView { scrollView.addObserver(self, forKeyPath: contentOffsetKeyPath, options: .Initial, context: &kvoContext) } } deinit { if let scrollView = superview as? UIScrollView { scrollView.removeObserver(self, forKeyPath: contentOffsetKeyPath, context: &kvoContext) } } // MARK: KVO public override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<()>) { if (context == &kvoContext && keyPath == contentOffsetKeyPath) { if let scrollView = object as? UIScrollView { // Debug //println(scrollView.contentOffset.y) let offsetWithoutInsets = self.previousOffset + self.scrollViewInsets.top // Update the content inset for fixed section headers if self.options.fixedSectionHeader && self.state == .Refreshing { if (scrollView.contentOffset.y > 0) { scrollView.contentInset = UIEdgeInsetsZero; } return } // Alpha set if PullToRefreshConst.alpha { var alpha = fabs(offsetWithoutInsets) / (self.frame.size.height + 30) if alpha > 0.8 { alpha = 0.8 } self.arrow.alpha = alpha } // Backgroundview frame set if PullToRefreshConst.fixedTop { if PullToRefreshConst.height < fabs(offsetWithoutInsets) { self.backgroundView.frame.size.height = fabs(offsetWithoutInsets) } else { self.backgroundView.frame.size.height = PullToRefreshConst.height } } else { self.backgroundView.frame.size.height = PullToRefreshConst.height + fabs(offsetWithoutInsets) self.backgroundView.frame.origin.y = -fabs(offsetWithoutInsets) } // Pulling State Check if (offsetWithoutInsets < -self.frame.size.height) { // pulling or refreshing if (scrollView.dragging == false && self.state != .Refreshing) { self.state = .Refreshing } else if (self.state != .Refreshing) { self.arrowRotation() self.state = .Pulling } } else if (self.state != .Refreshing && offsetWithoutInsets < 0) { // normal self.arrowRotationBack() } self.previousOffset = scrollView.contentOffset.y } } else { super.observeValueForKeyPath(keyPath, ofObject: object, change: change, context: context) } } // MARK: private private func startAnimating() { self.indicator.startAnimating() self.arrow.hidden = true if let scrollView = superview as? UIScrollView { scrollViewBounces = scrollView.bounces scrollViewInsets = scrollView.contentInset var insets = scrollView.contentInset insets.top += self.frame.size.height scrollView.contentOffset.y = self.previousOffset scrollView.bounces = false UIView.animateWithDuration(PullToRefreshConst.animationDuration, delay: 0, options:[], animations: { scrollView.contentInset = insets scrollView.contentOffset = CGPointMake(scrollView.contentOffset.x, -insets.top) }, completion: {finished in if self.options.autoStopTime != 0 { let time = dispatch_time(DISPATCH_TIME_NOW, Int64(self.options.autoStopTime * Double(NSEC_PER_SEC))) dispatch_after(time, dispatch_get_main_queue()) { self.state = .Normal } } self.refreshCompletion() }) } } private func stopAnimating() { self.indicator.stopAnimating() self.arrow.transform = CGAffineTransformIdentity self.arrow.hidden = false if let scrollView = superview as? UIScrollView { scrollView.bounces = self.scrollViewBounces UIView.animateWithDuration(PullToRefreshConst.animationDuration, animations: { () -> Void in scrollView.contentInset = self.scrollViewInsets }) { (Bool) -> Void in } } } private func arrowRotation() { UIView.animateWithDuration(0.2, delay: 0, options:[], animations: { // -0.0000001 for the rotation direction control self.arrow.transform = CGAffineTransformMakeRotation(CGFloat(M_PI-0.0000001)) }, completion:nil) } private func arrowRotationBack() { UIView.animateWithDuration(0.2, delay: 0, options:[], animations: { self.arrow.transform = CGAffineTransformIdentity }, completion:nil) } }
apache-2.0
f06ee647f83504a89488c0a29ba05d9d
38.03653
162
0.57183
5.811013
false
false
false
false
PureSwift/Bluetooth
Sources/BluetoothGATT/GAPUUIDList.swift
2
3602
// // GAPUUIDList.swift // Bluetooth // // Created by Alsey Coleman Miller on 8/25/18. // Copyright © 2018 PureSwift. All rights reserved. // import Foundation /// GAP UUID List internal struct GAPUUIDList <Element: GAPUUIDElement> { internal var uuids: [Element] internal init(uuids: [Element]) { self.uuids = uuids } internal init?(data: Data) { let elementSize = MemoryLayout<Element>.size var uuids = [Element]() uuids.reserveCapacity(data.count / elementSize) var index = 0 while index < data.count { guard index + elementSize <= data.count else { return nil } let valueData = data.subdataNoCopy(in: data.startIndex + index ..< data.startIndex + index + elementSize) let value = Element(littleEndian: Element(data: valueData)!) index += elementSize uuids.append(value) } self.uuids = uuids } } extension GAPUUIDList: DataConvertible { static func += <T: DataContainer> (data: inout T, value: GAPUUIDList) { value.forEach { data += $0.littleEndian } } var dataLength: Int { return MemoryLayout<Element>.size * uuids.count } } // MARK: - Sequence extension GAPUUIDList: Sequence { public func makeIterator() -> IndexingIterator<GAPUUIDList<Element>> { return IndexingIterator(_elements: self) } } // MARK: - Collection extension GAPUUIDList: Collection { subscript(index: Int) -> Element { return uuids[index] } func index(after index: Int) -> Int { return index + 1 } var startIndex: Int { return 0 } var endIndex: Int { return uuids.count } } // MARK: - Supporting Types internal protocol GAPUUIDElement: UnsafeDataConvertible { init? <T: DataContainer> (data: T) init(littleEndian: Self) var littleEndian: Self { get } static func += (data: inout LowEnergyAdvertisingData, value: Self) } extension UInt16: GAPUUIDElement { init? <T: DataContainer> (data: T) { guard data.count == MemoryLayout<UInt16>.size else { return nil } self.init(bytes: (data[0], data[1])) } } extension UInt32: GAPUUIDElement { init? <T: DataContainer> (data: T) { guard data.count == MemoryLayout<UInt32>.size else { return nil } self.init(bytes: (data[0], data[1], data[2], data[3])) } } extension UInt128: GAPUUIDElement { init? <T: DataContainer> (data: T) { guard data.count == MemoryLayout<UInt128>.size else { return nil } self.init(bytes: (data[0], data[1], data[2], data[3], data[4], data[5], data[6], data[7], data[8], data[9], data[10], data[11], data[12], data[13], data[14], data[15])) } }
mit
441a223bcf7308c7661921b0149efadd
21.791139
117
0.474313
4.953232
false
false
false
false
bitboylabs/selluv-ios
selluv-ios/selluv-ios/Classes/Base/Vender/Box/BoxType.swift
1
1238
// Copyright (c) 2014 Rob Rix. All rights reserved. // MARK: BoxType /// The type conformed to by all boxes. public protocol BoxType { /// The type of the wrapped value. associatedtype Value /// Initializes an intance of the type with a value. init(_ value: Value) /// The wrapped value. var value: Value { get } } /// The type conformed to by mutable boxes. public protocol MutableBoxType: BoxType { /// The (mutable) wrapped value. var value: Value { get set } } // MARK: Equality /// Equality of `BoxType`s of `Equatable` types. /// /// We cannot declare that e.g. `Box<T: Equatable>` conforms to `Equatable`, so this is a relatively ad hoc definition. public func == <B: BoxType> (lhs: B, rhs: B) -> Bool where B.Value: Equatable { return lhs.value == rhs.value } /// Inequality of `BoxType`s of `Equatable` types. /// /// We cannot declare that e.g. `Box<T: Equatable>` conforms to `Equatable`, so this is a relatively ad hoc definition. public func != <B: BoxType> (lhs: B, rhs: B) -> Bool where B.Value: Equatable { return lhs.value != rhs.value } // MARK: Map /// Maps the value of a box into a new box. public func map<B: BoxType, C: BoxType>(v: B, f: (B.Value) -> C.Value) -> C { return C(f(v.value)) }
mit
018eafa03f685d5b0ffdc11a72f1a0f9
25.913043
119
0.668013
3.257895
false
false
false
false
February12/YLPhotoBrowser
YLPhotoBrowser/ViewController.swift
1
6633
// // ViewController.swift // YLPhotoBrowser // // Created by yl on 2017/7/25. // Copyright © 2017年 February12. All rights reserved. // import UIKit class ViewController: UIViewController { fileprivate var collectionView:UICollectionView! fileprivate var dataArray = [String]() var imageView:UIImageView! var imageView1:UIImageView! override func viewDidLoad() { super.viewDidLoad() dataArray += ["1.png","2.png","3.gif"] dataArray += ["http://ww2.sinaimg.cn/bmiddle/72635b6agw1eyqehvujq1j218g0p0qai.jpg", "http://ww2.sinaimg.cn/bmiddle/e67669aagw1f1v6w3ya5vj20hk0qfq86.jpg", "http://ww3.sinaimg.cn/bmiddle/61e36371gw1f1v6zegnezg207p06fqv6.gif", "http://ww4.sinaimg.cn/bmiddle/7f02d774gw1f1dxhgmh3mj20cs1tdaiv.jpg"] let layout = UICollectionViewFlowLayout() layout.itemSize = CGSize(width: 90, height: 90) layout.minimumInteritemSpacing = 0 layout.minimumLineSpacing = 10 collectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: layout) collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "cell") collectionView.backgroundColor = UIColor.clear collectionView.delegate = self collectionView.dataSource = self view.addSubview(collectionView) collectionView.addConstraints(toItem: view, edgeInsets: .init(top: 64, left: 0, bottom: 0, right: 0)) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @objc func tap() { print("点击") } } // MARK: - UICollectionViewDelegate,UICollectionViewDataSource extension ViewController:UICollectionViewDelegate,UICollectionViewDataSource { func numberOfSections(in collectionView: UICollectionView) -> Int { return 1 } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return dataArray.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) for view in cell.subviews { view.removeFromSuperview() } let imageView = UIImageView.init(frame: cell.bounds) imageView.tag = 100 if indexPath.row <= 2 { let imageName = dataArray[indexPath.row] if indexPath.row == 2 { let path = Bundle.main.path(forResource: imageName, ofType: nil) let data = try! Data.init(contentsOf: URL.init(fileURLWithPath: path!)) imageView.image = UIImage.yl_gifWithData(data) }else { imageView.image = UIImage.init(named: imageName) } }else { let url = dataArray[indexPath.row] imageView.kf.setImage(with: URL.init(string: url)) } cell.addSubview(imageView) return cell } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { let photoBrowser = YLPhotoBrowser.init(indexPath.row, self) // 用白色 遮挡 原来的图 photoBrowser.originalCoverViewBG = UIColor.white // 非矩形图片需要实现(比如聊天界面带三角形的图片) 默认是矩形图片 photoBrowser.getTransitionImageView = { (currentIndex: Int,image: UIImage?, isBack: Bool) -> UIView? in return nil } // 每张图片上的 View 视图 photoBrowser.getViewOnTheBrowser = { [weak self] (currentIndex: Int) -> UIView? in let view = UIView() view.backgroundColor = UIColor.clear let label = UILabel() label.text = "第 \(currentIndex) 张" label.textColor = UIColor.red view.addSubview(label) // label 约束 label.addConstraints(attributes: [.centerX,.top], toItem: view, attributes: nil, constants: [0,40]) label.backgroundColor = UIColor.blue label.isUserInteractionEnabled = true label.addGestureRecognizer(UITapGestureRecognizer.init(target: self, action: #selector(ViewController.tap))) return view } present(photoBrowser, animated: true, completion: nil) } } // MARK: - YLPhotoBrowserDelegate extension ViewController: YLPhotoBrowserDelegate { func epPhotoBrowserGetPhotoCount() -> Int { return dataArray.count } func epPhotoBrowserGetPhotoByCurrentIndex(_ currentIndex: Int) -> YLPhoto { var photo: YLPhoto? if let cell = collectionView.cellForItem(at: IndexPath.init(row: currentIndex, section: 0)) { let frame = collectionView.convert(cell.frame, to: collectionView.superview) if currentIndex <= 2 { let imageName = dataArray[currentIndex] var image:UIImage? if currentIndex == 2 { // gif let path = Bundle.main.path(forResource: imageName, ofType: nil) let data = try! Data.init(contentsOf: URL.init(fileURLWithPath: path!)) image = UIImage.yl_gifWithData(data) }else { // 非 gif image = UIImage.init(named: imageName) } photo = YLPhoto.addImage(image, imageUrl: nil, frame: frame) }else { let url = dataArray[currentIndex] // 最佳 let imageView:UIImageView? = cell.viewWithTag(100) as! UIImageView? // photo = YLPhoto.addImage(imageView?.image, imageUrl: url, frame: frame) // 其次 photo = YLPhoto.addImage(nil, imageUrl: url, frame: frame) } } return photo! } }
mit
3ec6004f3662c494950ac0a0c0da9e8e
32.587629
121
0.566759
5.171429
false
false
false
false
Polidea/RxBluetoothKit
Tests/Autogenerated/_BluetoothError.generated.swift
1
10172
import Foundation import CoreBluetooth @testable import RxBluetoothKit /// Bluetooth error which can be emitted by RxBluetoothKit created observables. enum _BluetoothError: Error { /// Emitted when the object that is the source of Observable was destroyed and event was emitted nevertheless. /// To mitigate it dispose all of your subscriptions before deinitializing /// object that created Observables that subscriptions are made to. case destroyed // Emitted when `_CentralManager.scanForPeripherals` called and there is already ongoing scan case scanInProgress // Emitted when `_PeripheralManager.startAdvertising` called and there is already ongoing advertisement case advertisingInProgress case advertisingStartFailed(Error) // States case bluetoothUnsupported case bluetoothUnauthorized case bluetoothPoweredOff case bluetoothInUnknownState case bluetoothResetting // _Peripheral case peripheralIsAlreadyObservingConnection(_Peripheral) @available(*, deprecated, renamed: "_BluetoothError.peripheralIsAlreadyObservingConnection") case peripheralIsConnectingOrAlreadyConnected(_Peripheral) case peripheralConnectionFailed(_Peripheral, Error?) case peripheralDisconnected(_Peripheral, Error?) case peripheralRSSIReadFailed(_Peripheral, Error?) // Services case servicesDiscoveryFailed(_Peripheral, Error?) case includedServicesDiscoveryFailed(_Peripheral, Error?) case addingServiceFailed(CBServiceMock, Error?) // Characteristics case characteristicsDiscoveryFailed(_Service, Error?) case characteristicWriteFailed(_Characteristic, Error?) case characteristicReadFailed(_Characteristic, Error?) case characteristicNotifyChangeFailed(_Characteristic, Error?) case characteristicSetNotifyValueFailed(_Characteristic, Error?) // Descriptors case descriptorsDiscoveryFailed(_Characteristic, Error?) case descriptorWriteFailed(_Descriptor, Error?) case descriptorReadFailed(_Descriptor, Error?) // L2CAP case openingL2CAPChannelFailed(_Peripheral, Error?) case publishingL2CAPChannelFailed(CBL2CAPPSM, Error?) // Unknown case unknownWriteType } extension _BluetoothError: CustomStringConvertible { /// Human readable description of bluetooth error var description: String { switch self { case .destroyed: return """ The object that is the source of this Observable was destroyed. It's programmer's error, please check documentation of error for more details """ case .scanInProgress: return """ Tried to scan for peripheral when there is already ongoing scan. You can have only 1 ongoing scanning, please check documentation of _CentralManager for more details """ case .advertisingInProgress: return """ Tried to advertise when there is already advertising ongoing. You can have only 1 ongoing advertising, please check documentation of _PeripheralManager for more details """ case let .advertisingStartFailed(err): return "Start advertising error occured: \(err.localizedDescription)" case .bluetoothUnsupported: return "Bluetooth is unsupported" case .bluetoothUnauthorized: return "Bluetooth is unauthorized" case .bluetoothPoweredOff: return "Bluetooth is powered off" case .bluetoothInUnknownState: return "Bluetooth is in unknown state" case .bluetoothResetting: return "Bluetooth is resetting" // _Peripheral case .peripheralIsAlreadyObservingConnection, .peripheralIsConnectingOrAlreadyConnected: return """ _Peripheral connection is already being observed. You cannot try to establishConnection to peripheral when you have ongoing connection (previously establishConnection subscription was not disposed). """ case let .peripheralConnectionFailed(_, err): return "Connection error has occured: \(err?.localizedDescription ?? "-")" case let .peripheralDisconnected(_, err): return "Connection error has occured: \(err?.localizedDescription ?? "-")" case let .peripheralRSSIReadFailed(_, err): return "RSSI read failed : \(err?.localizedDescription ?? "-")" // Services case let .servicesDiscoveryFailed(_, err): return "Services discovery error has occured: \(err?.localizedDescription ?? "-")" case let .includedServicesDiscoveryFailed(_, err): return "Included services discovery error has occured: \(err?.localizedDescription ?? "-")" case let .addingServiceFailed(_, err): return "Adding _PeripheralManager service error has occured: \(err?.localizedDescription ?? "-")" // Characteristics case let .characteristicsDiscoveryFailed(_, err): return "Characteristics discovery error has occured: \(err?.localizedDescription ?? "-")" case let .characteristicWriteFailed(_, err): return "_Characteristic write error has occured: \(err?.localizedDescription ?? "-")" case let .characteristicReadFailed(_, err): return "_Characteristic read error has occured: \(err?.localizedDescription ?? "-")" case let .characteristicNotifyChangeFailed(_, err): return "_Characteristic notify change error has occured: \(err?.localizedDescription ?? "-")" case let .characteristicSetNotifyValueFailed(_, err): return "_Characteristic isNotyfing value change error has occured: \(err?.localizedDescription ?? "-")" // Descriptors case let .descriptorsDiscoveryFailed(_, err): return "_Descriptor discovery error has occured: \(err?.localizedDescription ?? "-")" case let .descriptorWriteFailed(_, err): return "_Descriptor write error has occured: \(err?.localizedDescription ?? "-")" case let .descriptorReadFailed(_, err): return "_Descriptor read error has occured: \(err?.localizedDescription ?? "-")" case let .openingL2CAPChannelFailed(_, err): return "Opening L2CAP channel error has occured: \(err?.localizedDescription ?? "-")" case let .publishingL2CAPChannelFailed(_, err): return "Publishing L2CAP channel error has occured: \(err?.localizedDescription ?? "-")" // Unknown case .unknownWriteType: return "Unknown write type" } } } extension _BluetoothError { init?(state: BluetoothState) { switch state { case .unsupported: self = .bluetoothUnsupported case .unauthorized: self = .bluetoothUnauthorized case .poweredOff: self = .bluetoothPoweredOff case .unknown: self = .bluetoothInUnknownState case .resetting: self = .bluetoothResetting default: return nil } } } extension _BluetoothError: Equatable {} // swiftlint:disable cyclomatic_complexity func == (lhs: _BluetoothError, rhs: _BluetoothError) -> Bool { switch (lhs, rhs) { case (.scanInProgress, .scanInProgress): return true case (.advertisingInProgress, .advertisingInProgress): return true case (.advertisingStartFailed, .advertisingStartFailed): return true // States case (.bluetoothUnsupported, .bluetoothUnsupported): return true case (.bluetoothUnauthorized, .bluetoothUnauthorized): return true case (.bluetoothPoweredOff, .bluetoothPoweredOff): return true case (.bluetoothInUnknownState, .bluetoothInUnknownState): return true case (.bluetoothResetting, .bluetoothResetting): return true // Services case let (.servicesDiscoveryFailed(l, _), .servicesDiscoveryFailed(r, _)): return l == r case let (.includedServicesDiscoveryFailed(l, _), .includedServicesDiscoveryFailed(r, _)): return l == r case let (.addingServiceFailed(l, _), .addingServiceFailed(r, _)): return l == r // Peripherals case let (.peripheralIsAlreadyObservingConnection(l), .peripheralIsAlreadyObservingConnection(r)): return l == r case let (.peripheralIsConnectingOrAlreadyConnected(l), .peripheralIsConnectingOrAlreadyConnected(r)): return l == r case let (.peripheralIsAlreadyObservingConnection(l), .peripheralIsConnectingOrAlreadyConnected(r)): return l == r case let (.peripheralIsConnectingOrAlreadyConnected(l), .peripheralIsAlreadyObservingConnection(r)): return l == r case let (.peripheralConnectionFailed(l, _), .peripheralConnectionFailed(r, _)): return l == r case let (.peripheralDisconnected(l, _), .peripheralDisconnected(r, _)): return l == r case let (.peripheralRSSIReadFailed(l, _), .peripheralRSSIReadFailed(r, _)): return l == r // Characteristics case let (.characteristicsDiscoveryFailed(l, _), .characteristicsDiscoveryFailed(r, _)): return l == r case let (.characteristicWriteFailed(l, _), .characteristicWriteFailed(r, _)): return l == r case let (.characteristicReadFailed(l, _), .characteristicReadFailed(r, _)): return l == r case let (.characteristicNotifyChangeFailed(l, _), .characteristicNotifyChangeFailed(r, _)): return l == r case let (.characteristicSetNotifyValueFailed(l, _), .characteristicSetNotifyValueFailed(r, _)): return l == r // Descriptors case let (.descriptorsDiscoveryFailed(l, _), .descriptorsDiscoveryFailed(r, _)): return l == r case let (.descriptorWriteFailed(l, _), .descriptorWriteFailed(r, _)): return l == r case let (.descriptorReadFailed(l, _), .descriptorReadFailed(r, _)): return l == r // L2CAP case let (.openingL2CAPChannelFailed(l, _), .openingL2CAPChannelFailed(r, _)): return l == r case let (.publishingL2CAPChannelFailed(l, _), .publishingL2CAPChannelFailed(r, _)): return l == r // Unknown case (.unknownWriteType, .unknownWriteType): return true default: return false } } // swiftlint:enable cyclomatic_complexity
apache-2.0
45b9ac10a0818e9375555c0cd801b194
50.897959
120
0.691801
5.879769
false
false
false
false
wikimedia/wikipedia-ios
Wikipedia/Code/ArticleLocationCollectionViewController.swift
1
9895
import UIKit class ArticleLocationCollectionViewController: ColumnarCollectionViewController, DetailPresentingFromContentGroup { var articleURLs: [URL] { didSet { collectionView.reloadData() } } let dataStore: MWKDataStore fileprivate let locationManager = LocationManager() private var feedFunnelContext: FeedFunnelContext? private var previewedIndexPath: IndexPath? let contentGroupIDURIString: String? required init(articleURLs: [URL], dataStore: MWKDataStore, contentGroup: WMFContentGroup?, theme: Theme) { self.articleURLs = articleURLs self.dataStore = dataStore contentGroupIDURIString = contentGroup?.objectID.uriRepresentation().absoluteString super.init() self.theme = theme if contentGroup != nil { self.feedFunnelContext = FeedFunnelContext(contentGroup) } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) not supported") } override func viewDidLoad() { super.viewDidLoad() layoutManager.register(ArticleLocationCollectionViewCell.self, forCellWithReuseIdentifier: ArticleLocationCollectionViewCell.identifier, addPlaceholder: true) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) locationManager.delegate = self if locationManager.isAuthorized { locationManager.startMonitoringLocation() } } override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) locationManager.delegate = nil locationManager.stopMonitoringLocation() if isMovingFromParent, let context = feedFunnelContext { FeedFunnel.shared.logFeedCardClosed(for: context, maxViewed: maxViewed) } } func articleURL(at indexPath: IndexPath) -> URL { return articleURLs[indexPath.item] } override func collectionView(_ collectionView: UICollectionView, estimatedHeightForItemAt indexPath: IndexPath, forColumnWidth columnWidth: CGFloat) -> ColumnarCollectionViewLayoutHeightEstimate { var estimate = ColumnarCollectionViewLayoutHeightEstimate(precalculated: false, height: 150) guard let placeholderCell = layoutManager.placeholder(forCellWithReuseIdentifier: ArticleLocationCollectionViewCell.identifier) as? ArticleLocationCollectionViewCell else { return estimate } placeholderCell.layoutMargins = layout.itemLayoutMargins configure(cell: placeholderCell, forItemAt: indexPath, layoutOnly: true) estimate.height = placeholderCell.sizeThatFits(CGSize(width: columnWidth, height: UIView.noIntrinsicMetric), apply: false).height estimate.precalculated = true return estimate } override func metrics(with size: CGSize, readableWidth: CGFloat, layoutMargins: UIEdgeInsets) -> ColumnarCollectionViewLayoutMetrics { return ColumnarCollectionViewLayoutMetrics.tableViewMetrics(with: size, readableWidth: readableWidth, layoutMargins: layoutMargins) } // MARK: - CollectionViewFooterDelegate override func collectionViewFooterButtonWasPressed(_ collectionViewFooter: CollectionViewFooter) { navigationController?.popViewController(animated: true) } // MARK: ArticlePreviewingDelegate override func shareArticlePreviewActionSelected(with articleController: ArticleViewController, shareActivityController: UIActivityViewController) { guard let context = feedFunnelContext else { super.shareArticlePreviewActionSelected(with: articleController, shareActivityController: shareActivityController) return } super.shareArticlePreviewActionSelected(with: articleController, shareActivityController: shareActivityController) FeedFunnel.shared.logFeedDetailShareTapped(for: context, index: previewedIndexPath?.item, midnightUTCDate: context.midnightUTCDate) } override func readMoreArticlePreviewActionSelected(with articleController: ArticleViewController) { guard let context = feedFunnelContext else { super.readMoreArticlePreviewActionSelected(with: articleController) return } articleController.wmf_removePeekableChildViewControllers() push(articleController, context: context, index: previewedIndexPath?.item, animated: true) } override func saveArticlePreviewActionSelected(with articleController: ArticleViewController, didSave: Bool, articleURL: URL) { guard let context = feedFunnelContext else { super.saveArticlePreviewActionSelected(with: articleController, didSave: didSave, articleURL: articleURL) return } if didSave { ReadingListsFunnel.shared.logSaveInFeed(context: context, articleURL: articleURL, index: previewedIndexPath?.item) } else { ReadingListsFunnel.shared.logUnsaveInFeed(context: context, articleURL: articleURL, index: previewedIndexPath?.item) } } func updateLocationOnVisibleCells() { for cell in collectionView.visibleCells { guard let locationCell = cell as? ArticleLocationCollectionViewCell else { continue } locationCell.update(userLocation: locationManager.location, heading: locationManager.heading) } } } // MARK: - UICollectionViewDataSource extension ArticleLocationCollectionViewController { override func numberOfSections(in collectionView: UICollectionView) -> Int { return 1 } var numberOfItems: Int { return articleURLs.count } override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return numberOfItems } private func configure(cell: UICollectionViewCell, forItemAt indexPath: IndexPath, layoutOnly: Bool) { guard let cell = cell as? ArticleLocationCollectionViewCell else { return } let url = articleURL(at: indexPath) guard let article = dataStore.fetchArticle(with: url) else { return } var userLocation: CLLocation? var userHeading: CLHeading? if locationManager.isUpdating { userLocation = locationManager.location userHeading = locationManager.heading } cell.articleLocation = article.location cell.update(userLocation: userLocation, heading: userHeading) cell.configure(article: article, displayType: .pageWithLocation, index: indexPath.row, theme: theme, layoutOnly: layoutOnly) } override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: ArticleLocationCollectionViewCell.identifier, for: indexPath) configure(cell: cell, forItemAt: indexPath, layoutOnly: false) return cell } } // MARK: - LocationManagerDelegate extension ArticleLocationCollectionViewController: LocationManagerDelegate { func locationManager(_ locationManager: LocationManagerProtocol, didUpdate location: CLLocation) { updateLocationOnVisibleCells() } func locationManager(_ locationManager: LocationManagerProtocol, didUpdate heading: CLHeading) { updateLocationOnVisibleCells() } func locationManager(_ locationManager: LocationManagerProtocol, didUpdateAuthorized authorized: Bool) { if authorized { locationManager.startMonitoringLocation() } } } // MARK: - UICollectionViewDelegate extension ArticleLocationCollectionViewController { func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { if let context = feedFunnelContext { FeedFunnel.shared.logArticleInFeedDetailReadingStarted(for: context, index: indexPath.item, maxViewed: maxViewed) } navigate(to: articleURLs[indexPath.item]) } } // MARK: - CollectionViewContextMenuShowing extension ArticleLocationCollectionViewController: CollectionViewContextMenuShowing { func articleViewController(for indexPath: IndexPath) -> ArticleViewController? { let articleURL = articleURL(at: indexPath) let articleViewController = ArticleViewController(articleURL: articleURL, dataStore: dataStore, theme: theme) return articleViewController } func previewingViewController(for indexPath: IndexPath, at location: CGPoint) -> UIViewController? { guard let articleViewController = articleViewController(for: indexPath) else { return nil } let articleURL = articleViewController.articleURL articleViewController.articlePreviewingDelegate = self articleViewController.wmf_addPeekableChildViewController(for: articleURL, dataStore: dataStore, theme: theme) if let context = feedFunnelContext { FeedFunnel.shared.logArticleInFeedDetailPreviewed(for: context, index: indexPath.item) } previewedIndexPath = indexPath return articleViewController } var poppingIntoVCCompletion: () -> Void { return { if let context = self.feedFunnelContext { FeedFunnel.shared.logArticleInFeedDetailReadingStarted(for: context, index: self.previewedIndexPath?.item, maxViewed: self.maxViewed) } } } } // MARK: - Reading lists event logging extension ArticleLocationCollectionViewController: EventLoggingEventValuesProviding { var eventLoggingCategory: EventLoggingCategory { return .places } var eventLoggingLabel: EventLoggingLabel? { return nil } }
mit
8a35ef33ac284218e30a3ec35e831185
41.467811
200
0.718343
6.338885
false
false
false
false
schrockblock/eson
Pod/Classes/Eson.swift
1
19164
// // Eson.swift // Pods // // Created by Elliot Schrock on 1/25/16. // // import UIKit public protocol EsonKeyMapper { static func esonPropertyNameToKeyMap() -> [String:String] } public protocol Deserializer { func nameOfClass() -> String func valueForObject(_ object: AnyObject) -> AnyObject? } public protocol Serializer { func objectForValue(_ value: AnyObject?) -> AnyObject?; func exampleValue() -> AnyObject; } open class IntSerializer: Serializer { open func objectForValue(_ value: AnyObject?) -> AnyObject? { return value } open func exampleValue() -> AnyObject { return Int() as AnyObject } } open class BoolSerializer: Serializer { open func objectForValue(_ value: AnyObject?) -> AnyObject? { return value } open func exampleValue() -> AnyObject { return Bool() as AnyObject } } open class ISODateDeserializer: Deserializer { public init() {} public func nameOfClass() -> String { return "Date" } public func valueForObject(_ object: AnyObject) -> AnyObject? { if let string = object as? String { let formatter = DateFormatter() formatter.calendar = Calendar(identifier: .iso8601) formatter.locale = Locale(identifier: "en_US_POSIX") formatter.timeZone = TimeZone(secondsFromGMT: 0) formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss'Z'" let date = formatter.date(from: string) return date as AnyObject } return nil } } open class Eson: NSObject { open var shouldConvertSnakeCase = true open var serializers: [Serializer]! = [Serializer]() open var deserializers: [Deserializer]! = [Deserializer]() public init(shouldConvertSnakeCase: Bool = true) { super.init() self.shouldConvertSnakeCase = shouldConvertSnakeCase self.serializers?.append(IntSerializer()) self.serializers?.append(BoolSerializer()) } open func toJsonDictionary(_ object: AnyObject) -> [String: AnyObject]? { if object is Dictionary<String, Any> { return object as? [String : AnyObject] } var json = [String: AnyObject]() var keyMap = [String:String]() if type(of: object).responds(to: Selector(("esonPropertyNameToKeyMap"))) { keyMap = (type(of: object) as! EsonKeyMapper.Type).esonPropertyNameToKeyMap() } let children = childrenOfClass(object) for child in children { let propertyName = child.label! var value = child.value as AnyObject let subMirror = Mirror(reflecting: child.value) var hasAValue: Bool = true if subMirror.displayStyle == .optional { if subMirror.children.count == 0 { hasAValue = false }else{ value = subMirror.children.first!.value as AnyObject } } if hasAValue { let propertyValue = value var isSerialized = false for serializer in self.serializers { if type(of: propertyValue) === type(of: serializer.exampleValue()) { var key = shouldConvertSnakeCase ? convertToSnakeCase(propertyName) : propertyName if let mappedKey = keyMap[propertyName] { key = mappedKey } json[key] = serializer.objectForValue(propertyValue) isSerialized = true break; } } if !isSerialized { let key = shouldConvertSnakeCase ? convertToSnakeCase(propertyName) : propertyName //There are SO MANY types of strings whose dynamicType does NOT equal String().dynamicType, //so, I'm just outright testing for it here if propertyValue is String { json[key] = propertyValue }else if propertyValue is NSArray { json[key] = toJsonArray(propertyValue as? [AnyObject]) as AnyObject? }else{ json[key] = toJsonDictionary(propertyValue) as AnyObject? } } } } return json } open func fromJsonDictionary<T: NSObject>(_ jsonDictionary: [String: AnyObject]?, clazz: T.Type) -> T? { let object = clazz.init() var keyMap = [String:String]() if type(of: object).responds(to: Selector(("esonPropertyNameToKeyMap"))) { keyMap = (type(of: object) as! EsonKeyMapper.Type).esonPropertyNameToKeyMap() } if let json = jsonDictionary { for key: String in json.keys{ let propertyKey = transformPropertyKey(key, keyMap) if object.responds(to: Selector(propertyKey)) { let propertyClassName = propertyTypeStringForName(object, name: propertyKey)! var isDeserialized = false if let deserializer = deserializer(for: propertyClassName) { isDeserialized = true if json[key] is NSNull { continue } else { if let value = deserializer.valueForObject(json[key]!), !(value is NSNull) { object.setValue(value, forKey: propertyKey) } else { continue } } } if !isDeserialized { if let jsonValue = json[key] { if jsonValue.isKind(of: NSDictionary.self) { handleDictionary(object: object, propertyKey: propertyKey, json: json, key: key) }else if jsonValue.isKind(of: NSArray.self) { handleArray(object: object, propertyKey: propertyKey, json: json, key: key) }else if !(json[key] is NSNull) { setValueOfObject(object, value: json[key]!, key: propertyKey) } } } } } } return object } open func toJsonArray(_ array: [AnyObject]?) -> [[String: AnyObject]]? { var result = [[String: AnyObject]]() if let objectArray = array { for object in objectArray { result.append(toJsonDictionary(object)!) } } return result } open func fromJsonArray<T: NSObject>(_ array: [[String: AnyObject]]?, clazz: T.Type) -> [T]? { var result = [T]() if let jsonArray = array { if let deserializer = deserializer(for: String(describing: T.self)) { result = fromJsonArray(using: deserializer, jsonArray, clazz: T.self)! }else{ for json in jsonArray { result.append(fromJsonDictionary(json, clazz: clazz)!) } } } return result } //MARK: non-public methods func fromJsonArray<T: NSObject>(using deserializer: Deserializer, _ jsonArray: [[String: AnyObject]], clazz: T.Type) -> [T]? { var result = [T]() for json in jsonArray { result.append(deserializer.valueForObject(json as AnyObject) as! T) } return result } func deserializer(for propertyClassName: String?) -> Deserializer? { for deserializer in self.deserializers! { let nameOfClass = deserializer.nameOfClass() if propertyClassName == nameOfClass { return deserializer } } return nil } func transformPropertyKey(_ key: String, _ keyMap: [String: String]) -> String { var propertyKey = shouldConvertSnakeCase ? convertToCamelCase(key) : key for propertyName in keyMap.keys { if keyMap[propertyName] == key { propertyKey = propertyName break; } } return propertyKey } func handleDictionary(object: NSObject, propertyKey: String, json: [String: AnyObject], key: String) { if let mirror = propertyMirrorFor(object, name: propertyKey) { var typeName: String? = String(describing: mirror.subjectType) if mirror.displayStyle == .optional { typeName = unwrappedClassName(typeName) } if typeName?.characters.count > 29 && (typeName?.substring(to: (typeName?.index((typeName?.startIndex)!, offsetBy: 29))!).contains("ImplicitlyUnwrappedOptional<"))! { typeName = unwrappedImplicitClassName(typeName) } let mirrorClass: AnyClass? = typeClass(typeName: typeName!) if mirrorClass == nil { if let isDict = typeName?.hasPrefix("Dictionary"), isDict { setValueOfObject(object, value: json[key]!, key: propertyKey) } } else { let mirrorType: NSObject.Type = mirrorClass.self as! NSObject.Type if mirrorType.init() is NSDictionary { setValueOfObject(object, value: json[key]!, key: propertyKey) }else{ setValueOfObject(object, value: fromJsonDictionary(json[key] as? [String: AnyObject], clazz: mirrorType)!, key: propertyKey) } } }else{ setValueOfObject(object, value: json[key]!, key: propertyKey) } } func handleArray(object: NSObject, propertyKey: String, json: [String: AnyObject], key: String) { let array = json[key] as! NSArray if array.count > 0 { let value = array[0] as AnyObject if value.isKind(of: NSDictionary.self) { if let mirror = propertyMirrorFor(object, name: propertyKey) { var typeName: String? if mirror.displayStyle == .optional { typeName = unwrappedClassName(String(describing: mirror.subjectType)) typeName = unwrappedArrayElementClassName(typeName) }else{ typeName = unwrappedArrayElementClassName(String(describing: mirror.subjectType)) } let mirrorClass: AnyClass? = typeClass(typeName: typeName!) if mirrorClass == nil { if let isDict = typeName?.hasPrefix("Dictionary"), isDict { setValueOfObject(object, value: json[key]!, key: propertyKey) } } else { let mirrorType: NSObject.Type = mirrorClass.self as! NSObject.Type if mirrorType.init() is NSDictionary { setValueOfObject(object, value: json[key]!, key: propertyKey) }else if let deserializer = deserializer(for: typeName) { setValueOfObject(object, value: fromJsonArray(using: deserializer, (json[key] as? [[String: AnyObject]])!, clazz: mirrorType)! as AnyObject, key: propertyKey) }else{ setValueOfObject(object, value: fromJsonArray(json[key] as? [[String: AnyObject]], clazz: mirrorType)! as AnyObject, key: propertyKey) } } }else{ setValueOfObject(object, value: json[key]!, key: propertyKey) } }else{ setValueOfObject(object, value: json[key]!, key: propertyKey) } } } func typeClass(typeName: String) -> AnyClass? { var mirrorClass: AnyClass? = NSClassFromString(typeName) if mirrorClass == nil { var appName = Bundle.main.object(forInfoDictionaryKey: "CFBundleName") as! String appName = appName.replacingOccurrences(of: " ", with: "_") mirrorClass = NSClassFromString(appName + "." + typeName) } return mirrorClass } func setValueOfObject(_ object: AnyObject, value: AnyObject, key: String) { if object.responds(to: Selector(key)) { object.setValue(value, forKey: key) }else{ let ivar: Ivar = class_getInstanceVariable(type(of: object), key) let fieldOffset = ivar_getOffset(ivar) // Pointer arithmetic to get a pointer to the field let pointerToInstance = Unmanaged.passUnretained(object).toOpaque() switch value { case is Int: let pointerToField = unsafeBitCast(pointerToInstance + fieldOffset, to: UnsafeMutablePointer<Int?>.self) // Set the value using the pointer pointerToField.pointee = value as? Int break case is Bool: let pointerToField = unsafeBitCast(pointerToInstance + fieldOffset, to: UnsafeMutablePointer<Bool?>.self) // Set the value using the pointer pointerToField.pointee = value as? Bool break default: break } } } func childrenOfClass(_ object: AnyObject) -> [(label: String?, value: Any)] { let mirror = Mirror(reflecting: object) var children = [(label: String?, value: Any)]() let mirrorChildrenCollection = AnyRandomAccessCollection(mirror.children)! children += mirrorChildrenCollection var currentMirror = mirror while let superclassChildren = currentMirror.superclassMirror?.children { let randomCollection = AnyRandomAccessCollection(superclassChildren) if let collection = randomCollection { children += collection } currentMirror = currentMirror.superclassMirror! } return children } func propertyTypeForName(_ object: NSObject, name: String) -> Any.Type? { return propertyMirrorFor(object, name: name)?.subjectType } func propertyMirrorFor(_ object: NSObject, name: String) -> Mirror? { let children = childrenOfClass(object) for child in children { let propertyName = child.label! if propertyName == name { return Mirror(reflecting: child.value) } } return nil } func propertyTypeStringForName(_ object: NSObject, name: String) -> String? { var propertyTypeString: String? = "" if let mirror = propertyMirrorFor(object, name: name) { if mirror.displayStyle == .optional { propertyTypeString = unwrappedClassName(String(describing: mirror.subjectType)) } else { propertyTypeString = String(describing: mirror.subjectType) } } // let children = childrenOfClass(object) // // for child in children { // let propertyName = child.label! // if propertyName == name { // propertyType = unwrappedClassName(String(describing: type(of: (child.value) as AnyObject))) // } // } return propertyTypeString } func unwrappedClassName(_ string: String?) -> String? { var unwrappedClassName: String? = string if string?.characters.count > 9 { if (string?.substring(to: (string?.characters.index((string?.startIndex)!, offsetBy: 9))!))! == "Optional<" { unwrappedClassName = string?.substring(to: (string?.characters.index((string?.startIndex)!, offsetBy: (string?.characters.count)! - 1))!) unwrappedClassName = unwrappedClassName?.substring(from: (unwrappedClassName?.characters.index((unwrappedClassName?.startIndex)!, offsetBy: 9))!) } } return unwrappedClassName } func unwrappedImplicitClassName(_ string: String?) -> String? { var unwrappedClassName: String? = string if string?.characters.count > 29 { if (string?.substring(to: (string?.characters.index((string?.startIndex)!, offsetBy: 28))!))! == "ImplicitlyUnwrappedOptional<" { unwrappedClassName = string?.substring(to: (string?.characters.index((string?.startIndex)!, offsetBy: (string?.characters.count)! - 1))!) unwrappedClassName = unwrappedClassName?.substring(from: (unwrappedClassName?.characters.index((unwrappedClassName?.startIndex)!, offsetBy: 28))!) } } return unwrappedClassName } func unwrappedArrayElementClassName(_ string: String?) -> String? { var unwrappedClassName: String? = string if string?.characters.count > 6 { if (string?.substring(to: (string?.characters.index((string?.startIndex)!, offsetBy: 6))!))! == "Array<" { unwrappedClassName = string?.substring(to: (string?.characters.index((string?.startIndex)!, offsetBy: (string?.characters.count)! - 1))!) unwrappedClassName = unwrappedClassName?.substring(from: (unwrappedClassName?.characters.index((unwrappedClassName?.startIndex)!, offsetBy: 6))!) } } return unwrappedClassName } func convertToCamelCase(_ string: String) -> String { let stringArray = string.characters.split(separator: "_") let capStringArray = stringArray.map{String($0).capitalized} var camelCaseString = capStringArray.joined(separator: "") camelCaseString = camelCaseString.characters.first.map {String($0).lowercased()}! + camelCaseString.substring(from: camelCaseString.characters.index(after: camelCaseString.startIndex)) return camelCaseString } func convertToSnakeCase(_ string: String) -> String { var snakeCaseString = string while let range = snakeCaseString.rangeOfCharacter(from: CharacterSet.uppercaseLetters) { let substring = snakeCaseString.substring(with: range) snakeCaseString.replaceSubrange(range, with: "_\(substring.lowercased())") } return snakeCaseString } } fileprivate func < <T : Comparable>(lhs: T?, rhs: T?) -> Bool { switch (lhs, rhs) { case let (l?, r?): return l < r case (nil, _?): return true default: return false } } fileprivate func > <T : Comparable>(lhs: T?, rhs: T?) -> Bool { switch (lhs, rhs) { case let (l?, r?): return l > r default: return rhs < lhs } }
mit
609b77e24fef4469d2fb851d3bbe12b9
40.751634
192
0.557451
5.42275
false
false
false
false
michael-yuji/YSMessagePack
YSMessagePack/Classes/parse.swift
2
6327
// // parse.swift // MessagePack2.0 // // Created by yuuji on 4/3/16. // Copyright © 2016 yuuji. All rights reserved. // import Foundation private func parsePackedArray(_ bytes: ByteArray, atIndex index: Int, count: Int) -> size_t { var bytes = bytes bytes.removeFirst(index) var length: size_t = 0 try! _ = parseData(messagePackedBytes: bytes, specific_amount: count, dataLengthOutput: &length) return length } private func parsePackedMap(_ bytes: ByteArray, atIndex index: Int, count: Int) -> size_t { var bytes = bytes bytes.removeFirst(index) var length: size_t = 0 try! _ = parseData(messagePackedBytes: bytes, specific_amount: count * 2, dataLengthOutput: &length) return length } public func parseData(messagePackedBytes byte_array: ByteArray, specific_amount amount: Int? = nil, dataLengthOutput len: inout Int) throws -> [(Range<Int>, DataTypes)] { var itemMarks = [(Range<Int>, DataTypes)]() var i: Int = 0 let _singleByteSize = 1 let _8bitDataSize = 1 let _16bitDataSize = 2 let _32bitDataSize = 4 let _64bitDataSize = 8 while (i < byte_array.count) { var shift: size_t!, dataSize: size_t! var type: DataTypes = .fixstr let _fixStrDataMarkupSize = size_t(byte_array[i] ^ 0b101_00000)/MemoryLayout<UInt8>.size let _fixArrayDataCount = size_t(byte_array[i] ^ 0b1001_0000)/MemoryLayout<UInt8>.size let _fixMapCount = size_t(byte_array[i] ^ 0b1000_0000)/MemoryLayout<UInt8>.size let _8bitMarkupDataSize = byte_array.count - (i+1) >= 1 ? size_t(byte_array[i + 1]) : 0// (i + 1) : the next byte of prefix byte, which is the size byte let _16bitMarkupDataSize = byte_array.count - (i+2) >= 2 ? byte_array[i+1]._16bitValue(jointWith: byte_array[i+2]) : 0 let _32bitMarkupDataSize = byte_array.count - (i+3) >= 3 ? byte_array[i+1]._32bitValue(joinWith: byte_array[i+2], and: byte_array[i+3]) : 0 switch byte_array[i] { //Nil case 0xc0: type = .`nil` dataSize = _singleByteSize case 0xc2: type = .bool dataSize = _singleByteSize case 0xc3: type = .bool dataSize = _singleByteSize //bool case 0xc2, 0xc3: type = .bool ; dataSize = _singleByteSize //bin case 0xc4: type = .bin8 ; dataSize = _8bitMarkupDataSize case 0xc5: type = .bin16 ; dataSize = _16bitMarkupDataSize case 0xc6: type = .bin32 ; dataSize = _32bitMarkupDataSize //float case 0xca: type = .float32 ; dataSize = _32bitDataSize case 0xcb: type = .float64 ; dataSize = _64bitDataSize //uint case 0xcc: type = .uInt8 ; dataSize = _8bitDataSize case 0xcd: type = .uInt16 ; dataSize = _16bitDataSize case 0xce: type = .uInt32 ; dataSize = _32bitDataSize case 0xcf: type = .uInt64 ; dataSize = _64bitDataSize //int case 0...0b01111111: type = .fixInt ; dataSize = _singleByteSize case 0b11100000..<0b11111111: type = .fixNegativeInt ; dataSize = _singleByteSize case 0xd0: type = .int8 ; dataSize = _8bitDataSize case 0xd1: type = .int16 ; dataSize = _16bitDataSize case 0xd2: type = .int32 ; dataSize = _32bitDataSize case 0xd3: type = .int64 ; dataSize = _64bitDataSize //String case 0b101_00000...0b101_11111: type = .fixstr ; dataSize = _fixStrDataMarkupSize case 0xd9: type = .str8bit; dataSize = _8bitMarkupDataSize case 0xda: type = .str16bit; dataSize = _16bitMarkupDataSize case 0xdb: type = .str32bit; dataSize = _32bitMarkupDataSize //array case 0b10010000...0b10011111: let count = _fixArrayDataCount dataSize = parsePackedArray(byte_array, atIndex: i + 1, count: count) type = .fixarray case 0xdc: let count = _16bitMarkupDataSize dataSize = parsePackedArray(byte_array, atIndex: i + 1 + 2, count: count) type = .array16 case 0xdd: let count = _32bitMarkupDataSize dataSize = parsePackedArray(byte_array, atIndex: i + 1 + 4, count: count) type = .array32 //map case 0b10000000...0b10001111: let count = _fixMapCount dataSize = parsePackedMap(byte_array, atIndex: i + 1, count: count) type = .fixmap case 0xde: let count = _16bitMarkupDataSize dataSize = parsePackedMap(byte_array, atIndex: i + 1 + 2, count: count) type = .map16 case 0xdf: let count = _32bitMarkupDataSize dataSize = parsePackedMap(byte_array, atIndex: i + 1 + 4, count: count) type = .map32 default: throw UnpackingError.unknownDataTypeUndifinedPrefix } shift = try type.getDataPrefixSize() // let rawDataRange = Range<Int>(start: i , end:i + shift + dataSize) let rawDataRange = Range<Int>(i..<i+shift+dataSize) itemMarks.append((rawDataRange, type)) i += dataSize + shift //when `packedObject` stored enough values or entered an infinity loop because of bad data, break if (amount != nil && itemMarks.count == amount) || (dataSize + shift) == 0 { if (dataSize + shift == 0) { throw UnpackingError.invaildDataFormat } break } } // len = i return itemMarks }
bsd-2-clause
89ff66e362a41a61d28854a36cd614af
36.654762
168
0.528612
4.137345
false
false
false
false
MoMoWan/IQKeyboardManager
Demo/Swift_Demo/ViewController/ExampleTableViewController.swift
12
2174
// // ExampleTableViewController.swift // IQKeyboardManager // // Created by InfoEnum02 on 20/04/15. // Copyright (c) 2015 Iftekhar. All rights reserved. // import UIKit class ExampleTableViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 10 } func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { if ((indexPath.row % 2) == 0) { return 40 } else { return 150 } } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let identifier = "\(indexPath.section) \(indexPath.row)" var cell = tableView.dequeueReusableCellWithIdentifier(identifier) if cell == nil { cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: identifier) cell?.backgroundColor = UIColor.clearColor() cell?.selectionStyle = UITableViewCellSelectionStyle.None let contentView : UIView! = cell?.contentView if ((indexPath.row % 2) == 0) { let textField = UITextField(frame: CGRectMake(5,5,contentView.frame.size.width-10,30)) textField.autoresizingMask = [UIViewAutoresizing.FlexibleBottomMargin, UIViewAutoresizing.FlexibleTopMargin, UIViewAutoresizing.FlexibleWidth] textField.placeholder = identifier textField.backgroundColor = UIColor.clearColor() textField.borderStyle = UITextBorderStyle.RoundedRect cell?.contentView.addSubview(textField) } else { let textView = UITextView(frame: CGRectInset(contentView.bounds, 5, 5)) textView.autoresizingMask = [UIViewAutoresizing.FlexibleHeight, UIViewAutoresizing.FlexibleWidth] textView.text = "Sample Text" cell?.contentView.addSubview(textView) } } return cell! } }
mit
0943c69e4eb56c5b1086c81eb4f18adb
35.847458
158
0.635695
5.891599
false
false
false
false
Ashok28/Kingfisher
Tests/KingfisherTests/DiskStorageTests.swift
2
9510
// // DiskStorageTests.swift // Kingfisher // // Created by Wei Wang on 2018/11/12. // // 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. import XCTest @testable import Kingfisher extension String: DataTransformable { public func toData() throws -> Data { return data(using: .utf8)! } public static func fromData(_ data: Data) throws -> String { return String(data: data, encoding: .utf8)! } public static var empty: String { return "" } } class DiskStorageTests: XCTestCase { var storage: DiskStorage.Backend<String>! override func setUp() { super.setUp() let uuid = UUID().uuidString let config = DiskStorage.Config(name: "test-\(uuid)", sizeLimit: 5) storage = try! DiskStorage.Backend<String>(config: config) } override func tearDown() { try! storage.removeAll(skipCreatingDirectory: true) super.tearDown() } func testStoreAndGet() { XCTAssertFalse(storage.isCached(forKey: "1")) try! storage.store(value: "1", forKey: "1") XCTAssertTrue(storage.isCached(forKey: "1")) let value = try! storage.value(forKey: "1") XCTAssertEqual(value, "1") } func testRemove() { XCTAssertFalse(storage.isCached(forKey: "1")) try! storage.store(value: "1", forKey: "1") try! storage.remove(forKey: "1") XCTAssertFalse(storage.isCached(forKey: "1")) } func testRemoveAll() { try! storage.store(value: "1", forKey: "1") try! storage.store(value: "2", forKey: "2") try! storage.store(value: "3", forKey: "3") try! storage.removeAll() XCTAssertFalse(storage.isCached(forKey: "1")) XCTAssertFalse(storage.isCached(forKey: "2")) XCTAssertFalse(storage.isCached(forKey: "3")) } func testTotalSize() { var size = try! storage.totalSize() XCTAssertEqual(size, 0) try! storage.store(value: "1", forKey: "1") size = try! storage.totalSize() XCTAssertEqual(size, 1) } func testSetExpiration() { let now = Date() try! storage.store(value: "1", forKey: "1", expiration: .seconds(1)) XCTAssertTrue(storage.isCached(forKey: "1", referenceDate: now)) XCTAssertFalse(storage.isCached(forKey: "1", referenceDate: now.addingTimeInterval(5))) } func testConfigExpiration() { let now = Date() storage.config.expiration = .seconds(1) try! storage.store(value: "1", forKey: "1") XCTAssertTrue(storage.isCached(forKey: "1", referenceDate: now)) XCTAssertFalse(storage.isCached(forKey: "1", referenceDate: now.addingTimeInterval(5))) } func testExtendExpirationByAccessing() { let exp = expectation(description: #function) let now = Date() try! storage.store(value: "1", forKey: "1", expiration: .seconds(2)) XCTAssertTrue(storage.isCached(forKey: "1")) XCTAssertFalse(storage.isCached(forKey: "1", referenceDate: now.addingTimeInterval(5))) delay(1) { let v = try! self.storage.value(forKey: "1") XCTAssertNotNil(v) // The meta extending happens on its own queue. self.storage.metaChangingQueue.async { XCTAssertTrue(self.storage.isCached(forKey: "1", referenceDate: now.addingTimeInterval(3))) XCTAssertFalse(self.storage.isCached(forKey: "1", referenceDate: now.addingTimeInterval(10))) exp.fulfill() } } waitForExpectations(timeout: 2, handler: nil) } func testNotExtendExpirationByAccessing() { let exp = expectation(description: #function) let now = Date() try! storage.store(value: "1", forKey: "1", expiration: .seconds(2)) XCTAssertTrue(storage.isCached(forKey: "1")) XCTAssertFalse(storage.isCached(forKey: "1", referenceDate: now.addingTimeInterval(3))) delay(1) { let v = try! self.storage.value(forKey: "1", extendingExpiration: .none) XCTAssertNotNil(v) // The meta extending happens on its own queue. self.storage.metaChangingQueue.async { XCTAssertFalse(self.storage.isCached(forKey: "1", referenceDate: now.addingTimeInterval(3))) XCTAssertFalse(self.storage.isCached(forKey: "1", referenceDate: now.addingTimeInterval(10))) exp.fulfill() } } waitForExpectations(timeout: 2, handler: nil) } func testRemoveExpired() { let expiration = StorageExpiration.seconds(1) try! storage.store(value: "1", forKey: "1", expiration: expiration) try! storage.store(value: "2", forKey: "2", expiration: expiration) try! storage.store(value: "3", forKey: "3") let urls = try! self.storage.removeExpiredValues(referenceDate: Date().addingTimeInterval(2)) XCTAssertEqual(urls.count, 2) XCTAssertTrue(self.storage.isCached(forKey: "3")) } func testRemoveSizeExceeded() { let count = 10 for i in 0..<count { let s = String(i) try! storage.store(value: s, forKey: s) } let urls = try! storage.removeSizeExceededValues() XCTAssertTrue(urls.count < count) XCTAssertTrue(urls.count > 0) } func testConfigUsesHashedFileName() { let key = "test" // hashed fileName storage.config.usesHashedFileName = true let hashedFileName = storage.cacheFileName(forKey: key) XCTAssertNotEqual(hashedFileName, key) // validation md5 hash of the key XCTAssertEqual(hashedFileName, key.kf.md5) // fileName without hash storage.config.usesHashedFileName = false let originalFileName = storage.cacheFileName(forKey: key) XCTAssertEqual(originalFileName, key) } func testConfigUsesHashedFileNameWithAutoExt() { let key = "test.gif" // hashed fileName storage.config.usesHashedFileName = true storage.config.autoExtAfterHashedFileName = true let hashedFileName = storage.cacheFileName(forKey: key) XCTAssertNotEqual(hashedFileName, key) // validation md5 hash of the key XCTAssertEqual(hashedFileName, key.kf.md5 + ".gif") // fileName without hash storage.config.usesHashedFileName = false let originalFileName = storage.cacheFileName(forKey: key) XCTAssertEqual(originalFileName, key) } func testConfigUsesHashedFileNameWithAutoExtAndProcessor() { // The key of an image with processor will be as this format. let key = "test.jpeg@abc" // hashed fileName storage.config.usesHashedFileName = true storage.config.autoExtAfterHashedFileName = true let hashedFileName = storage.cacheFileName(forKey: key) XCTAssertNotEqual(hashedFileName, key) // validation md5 hash of the key XCTAssertEqual(hashedFileName, key.kf.md5 + ".jpeg") // fileName without hash storage.config.usesHashedFileName = false let originalFileName = storage.cacheFileName(forKey: key) XCTAssertEqual(originalFileName, key) } func testFileMetaOrder() { let urls = [URL(string: "test1")!, URL(string: "test2")!, URL(string: "test3")!] let now = Date() let file1 = DiskStorage.FileMeta( fileURL: urls[0], lastAccessDate: now, estimatedExpirationDate: now.addingTimeInterval(1), isDirectory: false, fileSize: 1) let file2 = DiskStorage.FileMeta( fileURL: urls[1], lastAccessDate: now.addingTimeInterval(1), estimatedExpirationDate: now.addingTimeInterval(2), isDirectory: false, fileSize: 1) let file3 = DiskStorage.FileMeta( fileURL: urls[2], lastAccessDate: now.addingTimeInterval(2), estimatedExpirationDate: now.addingTimeInterval(3), isDirectory: false, fileSize: 1) let ordered = [file2, file1, file3].sorted(by: DiskStorage.FileMeta.lastAccessDate) XCTAssertTrue(ordered[0].lastAccessDate! > ordered[1].lastAccessDate!) XCTAssertTrue(ordered[1].lastAccessDate! > ordered[2].lastAccessDate!) } }
mit
86342b9c691b0f41ac459ca2d1b9be14
35.576923
109
0.640904
4.490085
false
true
false
false
TTVS/NightOut
Clubber/UserModel.swift
1
1411
// // UserModel.swift // Clubber // // Created by Terra on 13/10/2015. // Copyright © 2015 Dino Media Asia. All rights reserved. // import Foundation class UserModel: NSObject { let user_email: String let user_password: String let user_password_confirmation: String let user_first_name: String let user_last_name: String // Must be one of: Guest, Manager, Admin, Organizer, VIP let user_type: String let user_image: String let user_description: String let user_location: String let user_contact_number: String init(userEmail: String?, userPassword: String?, userPasswordConfirmation: String?, userFirstName: String?, userLastName: String?, userType: String?, userImage: String?, userDescription: String?, userLocation: String?, userContactNumber: String?) { self.user_email = userEmail ?? "" self.user_password = userPassword ?? "" self.user_password_confirmation = userPasswordConfirmation ?? "" self.user_first_name = userFirstName ?? "" self.user_last_name = userLastName ?? "" self.user_type = userType ?? "" self.user_image = userImage ?? "" self.user_description = userDescription ?? "" self.user_location = userLocation ?? "" self.user_contact_number = userContactNumber ?? "" } }
apache-2.0
394af030d179ebb0539d7378e1830294
15.785714
249
0.62695
4.420063
false
false
false
false
AliSoftware/SwiftGen
Sources/SwiftGenCLI/OutputDestination.swift
1
1050
// // SwiftGen // Copyright © 2020 SwiftGen // MIT Licence // import Commander import PathKit public enum OutputDestination: ArgumentConvertible { case console case file(Path) public init(parser: ArgumentParser) throws { guard let path = parser.shift() else { throw ArgumentError.missingValue(argument: nil) } self = .file(Path(path)) } public var description: String { switch self { case .console: return "(stdout)" case .file(let path): return path.description } } } extension OutputDestination { public func write( content: String, onlyIfChanged: Bool = false, logger: (LogLevel, String) -> Void = logMessage ) throws { switch self { case .console: print(content) case .file(let path): if try onlyIfChanged && path.exists && path.read(.utf8) == content { logMessage(.info, "Not writing the file as content is unchanged") return } try path.write(content) logMessage(.info, "File written: \(path)") } } }
mit
7e9c564c85a528a83272a789ceca95ac
20.408163
74
0.635844
4.129921
false
false
false
false
TabletopAssistant/DiceKit
TomeOfKnowledge.playground/Pages/Dice.xcplaygroundpage/Contents.swift
1
2253
//: # DiceKit //: //: DiceKit is a Swift framework for expressing and evaluating [dice notation](https://en.wikipedia.org/wiki/Dice_notation) (e.g., `d20`, `4d6+4`, `3d8×10+2`), which is commonly used in tabletop role-playing games. //: ## Importing //: //: To use DiceKit you need to import the `DiceKit` module in your files. //: //: > **Note:** //: > If the import below is failing with `No such module 'DiceKit'`, then you need to make sure to open the playground in a workspace that has the DiceKit project in it, build the DiceKit scheme, and then possibly execute the playground again. ([Apple Help](https://developer.apple.com/library/ios/recipes/Playground_Help/Chapters/ImportingaFrameworkIntoaPlayground.html)) import DiceKit //: ## Dice //: //: The `Die` type is used to represent an n-sided die. It defaults to 6 sides. let d6 = Die() let d4 = Die(sides: 4) //: There is also a convenience function for making `Die` more naturally. let d8 = d(8) //: Rolling a die will produce a `Die.Roll`, which represents the result of the roll. let d6Result = d6.roll() let d4Result = d4.roll() //: It holds the numeric result of the roll in the `value` property. let d6Value = d6Result.value let d4Value = d4Result.value //: It also holds the `Die` that was used to produce it in the `die` property. //: This associates the value to the type of die that produced it. d6Result.die == d6 d4Result.die == Die(sides: 4) //: If you really want flexibility in the way dice work, you can assign new rollers to the `Die.roller` property. Rollers define the range of outcomes that a die can have. When you roll a die, the result is made by passing that die's `sides` property to the roller. The default is `signedClosedRoller`, which can have a positive or negative number of sides. Another available roller is `unsignedRoller`, which will cause the dice to return 0 when sides <= 0. Die.roller = Die.unsignedRoller let unsignedDie = d(-10) let unsignedResult = unsignedDie.roll() let unsignedValue = unsignedResult.value //: Now that we have a grasp on single dice, let's explore [expressions](Expressions), which allows for combining dice and constants with various operations such as multiplication and addition. //: //: --- //: //: [Next](@next)
apache-2.0
7686cf38e35a6d4737ad0ca1b61f8287
47.956522
458
0.730462
3.697865
false
false
false
false
team-pie/DDDKit
DDDKit/Classes/DDDGeometry.swift
1
3276
// // DDDGeometry.swift // DDDKit // // Created by Guillaume Sabran on 9/28/16. // Copyright © 2016 Guillaume Sabran. All rights reserved. // import Foundation import GLKit /** Represents the 3D shape of an object */ public class DDDGeometry { var vertexArrayObject = GLuint() private var vertexIndicesBufferID = GLuint() private var vertexBufferID = GLuint() private var vertexTexCoordID = GLuint() private var vertexTexCoordAttributeIndex: GLuint! /// Positions in the 3d space public let vertices: [GLKVector3] /// (optional) positions in a 2d space that describe the mapping between the vertices and their positions in the texture public let texCoords: [GLKVector2]? /// The order in which triangles (described by 3 vertices) should be drawn. public let indices: [UInt16] var numVertices: Int { return vertices.count } /** Creates a new geometry - Parameter vertices: positions in the 3d space - Parameter texCoords: (optional) positions in a 2d space that describe the mapping between the vertices and their positions in the texture - Parameter indices: the order in which triangles (described by 3 vertices) should be drawn. */ public init( indices: [UInt16], vertices: [GLKVector3], texCoords: [GLKVector2]? = nil ) { self.indices = indices self.vertices = vertices self.texCoords = texCoords } private var hasSetUp = false /// create the vertex buffers func setUpIfNotAlready(for program: DDDShaderProgram) { if hasSetUp { return } // glGenVertexArrays(1, &vertexArrayObject) glBindVertexArray(vertexArrayObject) //Indices glGenBuffers(1, &vertexIndicesBufferID); glBindBuffer(GLenum(GL_ELEMENT_ARRAY_BUFFER), vertexIndicesBufferID); glBufferData(GLenum(GL_ELEMENT_ARRAY_BUFFER), indices.count * MemoryLayout<UInt16>.size, indices, GLenum(GL_STATIC_DRAW)); // Vertex let flatVert = vertices .map({ return [$0.x, $0.y, $0.z] }) .flatMap({ return $0 }) .map({ return GLfloat($0) }) glGenBuffers(1, &vertexBufferID); glBindBuffer(GLenum(GL_ARRAY_BUFFER), vertexBufferID); glBufferData(GLenum(GL_ARRAY_BUFFER), flatVert.count*MemoryLayout<GLfloat>.size, flatVert, GLenum(GL_STATIC_DRAW)); glEnableVertexAttribArray(GLuint(GLKVertexAttrib.position.rawValue)); glVertexAttribPointer(GLuint(GLKVertexAttrib.position.rawValue), 3, GLenum(GL_FLOAT), GLboolean(GL_FALSE), GLsizei(MemoryLayout<GLfloat>.size*3), nil); // Texture Coordinates if let texCoords = texCoords { let flatCoords = texCoords .map({ return [$0.y, $0.x] }) .flatMap({ return $0 }) .map({ return GLfloat($0) }) vertexTexCoordAttributeIndex = program.indexFor(attributeNamed: "texCoord") glGenBuffers(1, &vertexTexCoordID); glBindBuffer(GLenum(GL_ARRAY_BUFFER), vertexTexCoordID); glBufferData(GLenum(GL_ARRAY_BUFFER), flatCoords.count*MemoryLayout<GLfloat>.size, flatCoords, GLenum(GL_DYNAMIC_DRAW)); glEnableVertexAttribArray(vertexTexCoordAttributeIndex); glVertexAttribPointer(vertexTexCoordAttributeIndex, 2, GLenum(GL_FLOAT), GLboolean(GL_FALSE), GLsizei(MemoryLayout<GLfloat>.size*2), nil); } hasSetUp = true } /// set the geometry to be used as this one func prepareToUse() { glBindVertexArray(vertexArrayObject) } func reset() { hasSetUp = false } }
mit
73b915e38e7a3495407a3314dea828db
31.75
153
0.739237
3.659218
false
false
false
false
CodeLuca/StampWatch
iOS/Upload Live/Item.swift
1
859
// // Item.swift // Upload Live // // Created by Ben Gray on 21/02/2015. // Copyright (c) 2015 Graypfruit. All rights reserved. // import UIKit import CoreLocation class Item: NSObject { var name: NSString! var location: CLLocationCoordinate2D! var locationDescription: NSString! var date: NSNumber! var museumLocation: NSString! var id: NSString! var imageId: NSString! var collected: Bool = false init(name : NSString, location : CLLocationCoordinate2D, locationDescription: NSString, date: NSNumber, museumLocation: NSString, id: NSString, imageId: NSString) { self.name = name self.location = location self.locationDescription = locationDescription self.date = date self.museumLocation = museumLocation self.id = id self.imageId = imageId } }
mit
117ad190d25f14ffd9598130bbb2ecb1
25.84375
168
0.672875
4.295
false
false
false
false
tavultesoft/keymanweb
ios/engine/KMEI/KeymanEngine/Classes/Queries/Queries+LexicalModel.swift
1
3568
// // Queries+LexicalModel.swift // KeymanEngine // // Created by Joshua Horton on 7/8/20. // Copyright © 2020 SIL International. All rights reserved. // import Foundation extension Queries { public class LexicalModel { public struct Result: Decodable { let id: String let name: String let version: String let languages: [String] let packageFilename: String let description: String let minKeymanVersion: String enum CodingKeys: String, CodingKey { case id case name case version case languages case packageFilename case minKeymanVersion case description } var models: [InstallableLexicalModel] { return languages.map { modelFor(languageID: $0)! } } func modelFor(languageID: String) -> InstallableLexicalModel? { if languages.contains(languageID) { return InstallableLexicalModel(id: id, name: name, languageID: languageID, version: version, isCustom: false) } else { return nil } } } private static let MODEL_ENDPOINT = URLComponents(string: "\(KeymanHosts.API_KEYMAN_COM)/model")! public static func fetch(forLanguageCode bcp47: String, fetchCompletion: @escaping JSONQueryCompletionBlock<[Result]>) { fetch(forLanguageCode: bcp47, withSession: URLSession.shared, fetchCompletion: fetchCompletion) } internal static func fetch(forLanguageCode bcp47: String, withSession session: URLSession, fetchCompletion: @escaping JSONQueryCompletionBlock<[Result]>) { // Step 1: build the query var urlComponents = MODEL_ENDPOINT urlComponents.queryItems = [URLQueryItem(name: "q", value: "bcp47:\(bcp47)")] SentryManager.breadcrumbAndLog("Querying package versions through API endpoint: \(urlComponents.url!)") // Step 2: configure the completion closure. let completionClosure = Queries.jsonDataTaskCompletionAdapter(resultType: [Result].self, completionBlock: fetchCompletion) // Step 3: run the actual query, letting the prepared completion closure take care of the rest. let task = session.dataTask(with: urlComponents.url!, completionHandler: completionClosure) task.resume() } /** * Returns an array of package keys containing models that support the specified language. */ public static func fetchModels(forLanguageCode bcp47: String, fetchCompletion: @escaping ([(InstallableLexicalModel, URL)]?, Error?) -> Void) { fetchModels(forLanguageCode: bcp47, withSession: URLSession.shared, fetchCompletion: fetchCompletion) } internal static func fetchModels(forLanguageCode bcp47: String, withSession session: URLSession, fetchCompletion: @escaping ([(InstallableLexicalModel, URL)]?, Error?) -> Void) { Queries.LexicalModel.fetch(forLanguageCode: bcp47, withSession: session) { result, error in if let error = error { fetchCompletion(nil, error) return } guard let result = result, result.count > 0 else { fetchCompletion([], nil) return } // There are valid packages for the language code - send off the report! fetchCompletion(result.map { ($0.modelFor(languageID: bcp47)!, URL.init(string: $0.packageFilename)!) }, nil) } } } }
apache-2.0
b54d51a5191dea06dd8cd4f6c40add09
36.15625
128
0.642837
5.125
false
false
false
false
apple/swift-tools-support-core
Sources/TSCUtility/Triple.swift
1
8941
/* 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 http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for Swift project authors */ import protocol Foundation.CustomNSError import var Foundation.NSLocalizedDescriptionKey import TSCBasic /// Triple - Helper class for working with Destination.target values /// /// Used for parsing values such as x86_64-apple-macosx10.10 into /// set of enums. For os/arch/abi based conditions in build plan. /// /// @see Destination.target /// @see https://github.com/apple/swift-llvm/blob/stable/include/llvm/ADT/Triple.h /// public struct Triple: Encodable, Equatable { public let tripleString: String public let arch: Arch public let vendor: Vendor public let os: OS public let abi: ABI public let osVersion: String? public let abiVersion: String? public enum Error: Swift.Error { case badFormat(triple: String) case unknownArch(arch: String) case unknownOS(os: String) } public enum Arch: String, Encodable { case x86_64 case x86_64h case i686 case powerpc case powerpc64le case s390x case aarch64 case amd64 case armv7 case armv6 case armv5 case arm case arm64 case arm64e case wasm32 case riscv64 case mips case mipsel case mips64 case mips64el } public enum Vendor: String, Encodable { case unknown case apple } public enum OS: String, Encodable, CaseIterable { case darwin case macOS = "macosx" case linux case windows case wasi case openbsd } public enum ABI: Encodable, Equatable, RawRepresentable { case unknown case android case other(name: String) public init?(rawValue: String) { if rawValue.hasPrefix(ABI.android.rawValue) { self = .android } else if let version = rawValue.firstIndex(where: { $0.isNumber }) { self = .other(name: String(rawValue[..<version])) } else { self = .other(name: rawValue) } } public var rawValue: String { switch self { case .android: return "android" case .other(let name): return name case .unknown: return "unknown" } } public static func ==(lhs: ABI, rhs: ABI) -> Bool { switch (lhs, rhs) { case (.unknown, .unknown): return true case (.android, .android): return true case let (.other(lhsName), .other(rhsName)): return lhsName == rhsName default: return false } } } public init(_ string: String) throws { let components = string.split(separator: "-").map(String.init) guard components.count == 3 || components.count == 4 else { throw Error.badFormat(triple: string) } guard let arch = Arch(rawValue: components[0]) else { throw Error.unknownArch(arch: components[0]) } let vendor = Vendor(rawValue: components[1]) ?? .unknown guard let os = Triple.parseOS(components[2]) else { throw Error.unknownOS(os: components[2]) } let osVersion = Triple.parseVersion(components[2]) let abi = components.count > 3 ? Triple.ABI(rawValue: components[3]) : nil let abiVersion = components.count > 3 ? Triple.parseVersion(components[3]) : nil self.tripleString = string self.arch = arch self.vendor = vendor self.os = os self.osVersion = osVersion self.abi = abi ?? .unknown self.abiVersion = abiVersion } fileprivate static func parseOS(_ string: String) -> OS? { var candidates = OS.allCases.map{ (name: $0.rawValue, value: $0) } // LLVM target triples support this alternate spelling as well. candidates.append((name: "macos", value: .macOS)) return candidates.first(where: { string.hasPrefix($0.name) })?.value } fileprivate static func parseVersion(_ string: String) -> String? { let candidate = String(string.drop(while: { $0.isLetter })) if candidate != string && !candidate.isEmpty { return candidate } return nil } public func isAndroid() -> Bool { return os == .linux && abi == .android } public func isDarwin() -> Bool { return vendor == .apple || os == .macOS || os == .darwin } public func isLinux() -> Bool { return os == .linux } public func isWindows() -> Bool { return os == .windows } public func isWASI() -> Bool { return os == .wasi } public func isOpenBSD() -> Bool { return os == .openbsd } /// Returns the triple string for the given platform version. /// /// This is currently meant for Apple platforms only. public func tripleString(forPlatformVersion version: String) -> String { precondition(isDarwin()) return String(self.tripleString.dropLast(self.osVersion?.count ?? 0)) + version } public static let macOS = try! Triple("x86_64-apple-macosx") /// Determine the versioned host triple using the Swift compiler. public static func getHostTriple(usingSwiftCompiler swiftCompiler: AbsolutePath) -> Triple { // Call the compiler to get the target info JSON. let compilerOutput: String do { let result = try Process.popen(args: swiftCompiler.pathString, "-print-target-info") compilerOutput = try result.utf8Output().spm_chomp() } catch { // FIXME: Remove the macOS special-casing once the latest version of Xcode comes with // a Swift compiler that supports -print-target-info. #if os(macOS) return .macOS #else fatalError("Failed to get target info (\(error))") #endif } // Parse the compiler's JSON output. let parsedTargetInfo: JSON do { parsedTargetInfo = try JSON(string: compilerOutput) } catch { fatalError("Failed to parse target info (\(error)).\nRaw compiler output: \(compilerOutput)") } // Get the triple string from the parsed JSON. let tripleString: String do { tripleString = try parsedTargetInfo.get("target").get("triple") } catch { fatalError("Target info does not contain a triple string (\(error)).\nTarget info: \(parsedTargetInfo)") } // Parse the triple string. do { return try Triple(tripleString) } catch { fatalError("Failed to parse triple string (\(error)).\nTriple string: \(tripleString)") } } public static func ==(lhs: Triple, rhs: Triple) -> Bool { return lhs.arch == rhs.arch && lhs.vendor == rhs.vendor && lhs.os == rhs.os && lhs.abi == rhs.abi && lhs.osVersion == rhs.osVersion && lhs.abiVersion == rhs.abiVersion } } extension Triple { /// The file prefix for dynamcic libraries public var dynamicLibraryPrefix: String { switch os { case .windows: return "" default: return "lib" } } /// The file extension for dynamic libraries (eg. `.dll`, `.so`, or `.dylib`) public var dynamicLibraryExtension: String { switch os { case .darwin, .macOS: return ".dylib" case .linux, .openbsd: return ".so" case .windows: return ".dll" case .wasi: return ".wasm" } } public var executableExtension: String { switch os { case .darwin, .macOS: return "" case .linux, .openbsd: return "" case .wasi: return ".wasm" case .windows: return ".exe" } } /// The file extension for static libraries. public var staticLibraryExtension: String { return ".a" } /// The file extension for Foundation-style bundle. public var nsbundleExtension: String { switch os { case .darwin, .macOS: return ".bundle" default: // See: https://github.com/apple/swift-corelibs-foundation/blob/master/Docs/FHS%20Bundles.md return ".resources" } } } extension Triple.Error: CustomNSError { public var errorUserInfo: [String : Any] { return [NSLocalizedDescriptionKey: "\(self)"] } }
apache-2.0
0965cc7004c6f467cd296ad88fc19fd2
29.206081
175
0.580919
4.550127
false
false
false
false
mrdepth/Neocom
Legacy/Neocom/Neocom/NCFittingLoadout.swift
2
5748
// // NCLoadout.swift // Neocom // // Created by Artem Shimanski on 11.01.17. // Copyright © 2017 Artem Shimanski. All rights reserved. // import UIKit import CoreData import EVEAPI import Dgmpp class NCFittingLoadoutItem: NSObject, NSSecureCoding { let typeID: Int var count: Int let identifier: Int? public static var supportsSecureCoding: Bool { return true } init(type: DGMType, count: Int = 1) { self.typeID = type.typeID self.count = count self.identifier = type.identifier super.init() } init(typeID: Int, count: Int, identifier: Int? = nil) { self.typeID = typeID self.count = count self.identifier = identifier super.init() } required init?(coder aDecoder: NSCoder) { typeID = aDecoder.decodeInteger(forKey: "typeID") count = aDecoder.containsValue(forKey: "count") ? aDecoder.decodeInteger(forKey: "count") : 1 if let s = (aDecoder.decodeObject(forKey: "identifier") as? String) { identifier = Int(s) ?? s.hashValue } else if let n = (aDecoder.decodeObject(forKey: "identifier") as? NSNumber) { identifier = n.intValue } else { identifier = nil } super.init() } func encode(with aCoder: NSCoder) { aCoder.encode(typeID, forKey: "typeID") if count != 1 { aCoder.encode(count, forKey: "count") } aCoder.encode(identifier, forKey: "identifier") } public static func ==(lhs: NCFittingLoadoutItem, rhs: NCFittingLoadoutItem) -> Bool { return lhs.hashValue == rhs.hashValue } override var hash: Int { return [typeID, count].hashValue } } class NCFittingLoadoutModule: NCFittingLoadoutItem { let state: DGMModule.State let charge: NCFittingLoadoutItem? let socket: Int init(module: DGMModule) { state = module.preferredState if let charge = module.charge { self.charge = NCFittingLoadoutItem(type: charge, count: max(module.charges, 1)) } else { self.charge = nil } socket = module.socket super.init(type: module) } init(typeID: Int, count: Int, identifier: Int?, state: DGMModule.State = .active, charge: NCFittingLoadoutItem? = nil, socket: Int = -1) { self.state = state self.charge = charge self.socket = socket super.init(typeID: typeID, count: count, identifier: identifier) } required init?(coder aDecoder: NSCoder) { state = DGMModule.State(rawValue: aDecoder.decodeInteger(forKey: "state")) ?? .unknown charge = aDecoder.decodeObject(forKey: "charge") as? NCFittingLoadoutItem socket = aDecoder.containsValue(forKey: "socket") ? aDecoder.decodeInteger(forKey: "socket") : -1 super.init(coder: aDecoder) } override func encode(with aCoder: NSCoder) { super.encode(with: aCoder) aCoder.encode(state.rawValue, forKey: "state") aCoder.encode(charge, forKey: "charge") aCoder.encode(socket, forKey: "socket") } override var hash: Int { return [typeID, count, state.rawValue, charge?.typeID ?? 0].hashValue } } class NCFittingLoadoutDrone: NCFittingLoadoutItem { let isActive: Bool let isKamikaze: Bool let squadronTag: Int init(typeID: Int, count: Int, identifier: Int?, isActive: Bool = true, squadronTag: Int = -1) { self.isActive = isActive self.squadronTag = squadronTag self.isKamikaze = false super.init(typeID: typeID, count: count, identifier: identifier) } init(drone: DGMDrone) { self.isActive = drone.isActive self.isKamikaze = drone.isKamikaze self.squadronTag = drone.squadronTag super.init(type: drone) } required init?(coder aDecoder: NSCoder) { isActive = aDecoder.containsValue(forKey: "isActive") ? aDecoder.decodeBool(forKey: "isActive") : true isKamikaze = aDecoder.containsValue(forKey: "isKamikaze") ? aDecoder.decodeBool(forKey: "isKamikaze") : false squadronTag = aDecoder.containsValue(forKey: "squadronTag") ? aDecoder.decodeInteger(forKey: "squadronTag") : -1 super.init(coder: aDecoder) } override func encode(with aCoder: NSCoder) { super.encode(with: aCoder) if !isActive { aCoder.encode(isActive, forKey: "isActive") } if !isKamikaze { aCoder.encode(isKamikaze, forKey: "isKamikaze") } aCoder.encode(squadronTag, forKey: "squadronTag") } override var hash: Int { return [typeID, count, isActive ? 1 : 0].hashValue } } public class NCFittingLoadout: NSObject, NSSecureCoding { var modules: [DGMModule.Slot: [NCFittingLoadoutModule]]? var drones: [NCFittingLoadoutDrone]? var cargo: [NCFittingLoadoutItem]? var implants: [NCFittingLoadoutItem]? var boosters: [NCFittingLoadoutItem]? override init() { super.init() } public static var supportsSecureCoding: Bool { return true } public required init?(coder aDecoder: NSCoder) { modules = [DGMModule.Slot: [NCFittingLoadoutModule]]() for (key, value) in aDecoder.decodeObject(forKey: "modules") as? [Int: [NCFittingLoadoutModule]] ?? [:] { guard let key = DGMModule.Slot(rawValue: key) else {continue} modules?[key] = value } drones = aDecoder.decodeObject(forKey: "drones") as? [NCFittingLoadoutDrone] cargo = aDecoder.decodeObject(forKey: "cargo") as? [NCFittingLoadoutItem] implants = aDecoder.decodeObject(forKey: "implants") as? [NCFittingLoadoutItem] boosters = aDecoder.decodeObject(forKey: "boosters") as? [NCFittingLoadoutItem] super.init() } public func encode(with aCoder: NSCoder) { var dic = [Int: [NCFittingLoadoutModule]]() for (key, value) in modules ?? [:] { dic[key.rawValue] = value } aCoder.encode(dic, forKey:"modules") if drones?.count ?? 0 > 0 { aCoder.encode(drones, forKey: "drones") } if cargo?.count ?? 0 > 0 { aCoder.encode(cargo, forKey: "cargo") } if implants?.count ?? 0 > 0 { aCoder.encode(implants, forKey: "implants") } if boosters?.count ?? 0 > 0 { aCoder.encode(boosters, forKey: "boosters") } } }
lgpl-2.1
860a6853a3f83cc350fb5bf6b420433a
26.629808
139
0.703845
3.49787
false
false
false
false
khizkhiz/swift
test/Parse/consecutive_statements.swift
5
1918
// RUN: %target-parse-verify-swift func statement_starts() { var f : Int -> () f = { (x : Int) -> () in } f(0) f (0) f // expected-error{{expression resolves to an unused l-value}} (0) var a = [1,2,3] a[0] = 1 a [0] = 1 a // expected-error{{expression resolves to an unused l-value}} [0, 1, 2] } // Within a function func test(i: inout Int, j: inout Int) { // Okay let q : Int; i = j; j = i; _ = q if i != j { i = j } // Errors i = j j = i // expected-error{{consecutive statements}} {{8-8=;}} let r : Int i = j // expected-error{{consecutive statements}} {{14-14=;}} let s : Int let t : Int // expected-error{{consecutive statements}} {{14-14=;}} _ = r; _ = s; _ = t } struct X { // In a sequence of declarations. var a, b : Int func d() -> Int {} // expected-error{{consecutive declarations}} {{17-17=;}} var prop : Int { return 4 } var other : Float // expected-error{{consecutive declarations}} {{4-4=;}} // Within property accessors subscript(i: Int) -> Float { get { var x = i x = i + x return Float(x) // expected-error{{consecutive statements}} {{16-16=;}} expected-error{{consecutive statements}} {{26-26=;}} } set { var x = i x = i + 1 // expected-error{{consecutive statements}} {{16-16=;}} _ = x } } } class C { // In a sequence of declarations. var a, b : Int func d() -> Int {} // expected-error{{consecutive declarations}} {{17-17=;}} init() { a = 0 b = 0 } } protocol P { func a() func b() // expected-error{{consecutive declarations}} {{11-11=;}} } enum Color { case Red case Blue // expected-error{{consecutive declarations}} {{11-11=;}} func a() {} func b() {} // expected-error{{consecutive declarations}} {{14-14=;}} } // At the top level var i, j : Int i = j j = i // expected-error{{consecutive statements}} {{15-15=;}} expected-error{{consecutive statements}} {{21-21=;}}
apache-2.0
ecfcb8b8816251f2ba0385bf3d1c8a72
25.638889
150
0.574035
3.261905
false
false
false
false
themonki/onebusaway-iphone
Carthage/Checkouts/swift-protobuf/Sources/SwiftProtobuf/Google_Protobuf_Any+Extensions.swift
1
5231
// Sources/SwiftProtobuf/Google_Protobuf_Any+Extensions.swift - Well-known Any type // // Copyright (c) 2014 - 2017 Apple Inc. and the project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See LICENSE.txt for license information: // https://github.com/apple/swift-protobuf/blob/master/LICENSE.txt // // ----------------------------------------------------------------------------- /// /// Extends the `Google_Protobuf_Any` type with various custom behaviors. /// // ----------------------------------------------------------------------------- // Explicit import of Foundation is necessary on Linux, // don't remove unless obsolete on all platforms import Foundation public let defaultAnyTypeURLPrefix: String = "type.googleapis.com" extension Google_Protobuf_Any { /// Initialize an Any object from the provided message. /// /// This corresponds to the `pack` operation in the C++ API. /// /// Unlike the C++ implementation, the message is not immediately /// serialized; it is merely stored until the Any object itself /// needs to be serialized. This design avoids unnecessary /// decoding/recoding when writing JSON format. /// /// - Parameters: /// - partial: If `false` (the default), this method will check /// `Message.isInitialized` before encoding to verify that all required /// fields are present. If any are missing, this method throws /// `BinaryEncodingError.missingRequiredFields`. /// - typePrefix: The prefix to be used when building the `type_url`. /// Defaults to "type.googleapis.com". /// - Throws: `BinaryEncodingError.missingRequiredFields` if `partial` is /// false and `message` wasn't fully initialized. public init( message: Message, partial: Bool = false, typePrefix: String = defaultAnyTypeURLPrefix ) throws { if !partial && !message.isInitialized { throw BinaryEncodingError.missingRequiredFields } self.init() typeURL = buildTypeURL(forMessage:message, typePrefix: typePrefix) _storage.state = .message(message) } /// Creates a new `Google_Protobuf_Any` by decoding the given string /// containing a serialized message in Protocol Buffer text format. /// /// - Parameters: /// - textFormatString: The text format string to decode. /// - extensions: An `ExtensionMap` used to look up and decode any /// extensions in this message or messages nested within this message's /// fields. /// - Throws: an instance of `TextFormatDecodingError` on failure. public init( textFormatString: String, extensions: ExtensionMap? = nil ) throws { self.init() if !textFormatString.isEmpty { if let data = textFormatString.data(using: String.Encoding.utf8) { try data.withUnsafeBytes { (bytes: UnsafePointer<UInt8>) in var textDecoder = try TextFormatDecoder( messageType: Google_Protobuf_Any.self, utf8Pointer: bytes, count: data.count, extensions: extensions) try decodeTextFormat(decoder: &textDecoder) if !textDecoder.complete { throw TextFormatDecodingError.trailingGarbage } } } } } /// Returns true if this `Google_Protobuf_Any` message contains the given /// message type. /// /// The check is performed by looking at the passed `Message.Type` and the /// `typeURL` of this message. /// /// - Parameter type: The concrete message type. /// - Returns: True if the receiver contains the given message type. public func isA<M: Message>(_ type: M.Type) -> Bool { return _storage.isA(type) } #if swift(>=4.2) public func hash(into hasher: inout Hasher) { _storage.hash(into: &hasher) } #else // swift(>=4.2) public var hashValue: Int { return _storage.hashValue } #endif // swift(>=4.2) } extension Google_Protobuf_Any { internal func textTraverse(visitor: inout TextFormatEncodingVisitor) { _storage.textTraverse(visitor: &visitor) try! unknownFields.traverse(visitor: &visitor) } } extension Google_Protobuf_Any: _CustomJSONCodable { // Custom text format decoding support for Any objects. // (Note: This is not a part of any protocol; it's invoked // directly from TextFormatDecoder whenever it sees an attempt // to decode an Any object) internal mutating func decodeTextFormat( decoder: inout TextFormatDecoder ) throws { // First, check if this uses the "verbose" Any encoding. // If it does, and we have the type available, we can // eagerly decode the contained Message object. if let url = try decoder.scanner.nextOptionalAnyURL() { try _uniqueStorage().decodeTextFormat(typeURL: url, decoder: &decoder) } else { // This is not using the specialized encoding, so we can use the // standard path to decode the binary value. try decodeMessage(decoder: &decoder) } } internal func encodedJSONString(options: JSONEncodingOptions) throws -> String { return try _storage.encodedJSONString(options: options) } internal mutating func decodeJSON(from decoder: inout JSONDecoder) throws { try _uniqueStorage().decodeJSON(from: &decoder) } }
apache-2.0
d7a5693e45d0597085c5e84cb2c877d6
36.099291
83
0.668323
4.529004
false
false
false
false
xwu/swift
test/Sema/diag_type_conversion.swift
8
3063
// RUN: %target-typecheck-verify-swift %clang-importer-sdk // REQUIRES: objc_interop import Foundation func foo1(_ a: [Int]) {} func foo2(_ a : UnsafePointer<Int>) {} func foo4(_ a : UnsafeMutablePointer<Int>) {} func foo3 () { let j = 3 foo2(j) // expected-error {{cannot convert value of type 'Int' to expected argument type 'UnsafePointer<Int>'}} {{none}} foo4(j) // expected-error {{cannot convert value of type 'Int' to expected argument type 'UnsafeMutablePointer<Int>'}} {{none}} var i = 3 foo2(i) // expected-error {{cannot convert value of type 'Int' to expected argument type 'UnsafePointer<Int>'}} {{8-8=&}} foo4(i) // expected-error {{cannot convert value of type 'Int' to expected argument type 'UnsafeMutablePointer<Int>'}} {{8-8=&}} foo2(1) // expected-error {{cannot convert value of type 'Int' to expected argument type 'UnsafePointer<Int>'}} {{none}} foo4(1) // expected-error {{cannot convert value of type 'Int' to expected argument type 'UnsafeMutablePointer<Int>'}} {{none}} } class A {} class B : A {} func foo5(b : B) {} func foo6(a : A) { foo5(b : a) // expected-error {{cannot convert value of type 'A' to expected argument type 'B'}} {{13-13= as! B}} } func foo7(b : [B]) {} func foo8(a : [A]) { // TODO(diagnostics): Since `A` and `B` are related it would make sense to suggest forced downcast. foo7(b : a) // expected-error {{cannot convert value of type '[A]' to expected argument type '[B]'}} // expected-note@-1 {{arguments to generic parameter 'Element' ('A' and 'B') are expected to be equal}} } protocol P1 {} struct S1 : P1 {} func foo9(s : S1) {} func foo10(p : P1) { foo9(s : p) // expected-error {{cannot convert value of type 'P1' to expected argument type 'S1'}} {{13-13= as! S1}} } func foo11(a : [AnyHashable]) {} func foo12(b : [NSObject]) { foo11(a : b) } func foo13(a : [AnyHashable : Any]) {} func foo14(b : [NSObject : AnyObject]) { foo13(a : b) } // Add a minimal test for inout-to-pointer conversion involving a // generic function with a protocol constraint of Equatable. infix operator =*= : ComparisonPrecedence func =*= <T : Equatable>(lhs: T, rhs: T) -> Bool { return lhs == rhs } func =*= <T : Equatable>(lhs: T?, rhs: T?) -> Bool { return lhs == rhs } class C {} var o = C() var p: UnsafeMutablePointer<C>? = nil _ = p =*= &o func rdar25963182(_ bytes: [UInt8] = nil) {} // expected-error@-1 {{nil default argument value cannot be converted to type}} // SR-13262 struct SR13262_S {} func SR13262(_ x: Int) {} func SR13262_Int(_ x: Int) -> Int { 0 } func SR13262_SF(_ x: Int) -> SR13262_S { SR13262_S() } func testSR13262(_ arr: [Int]) { for x in arr where SR13262(x) {} // expected-error {{cannot convert value of type '()' to expected condition type 'Bool'}} for x in arr where SR13262_Int(x) {} // expected-error {{type 'Int' cannot be used as a boolean; test for '!= 0' instead}} {{22-22=(}} {{36-36= != 0)}} for x in arr where SR13262_SF(x) {} // expected-error {{cannot convert value of type 'SR13262_S' to expected condition type 'Bool'}} }
apache-2.0
2c5287a2c65ac7f36661273558625c17
34.206897
154
0.651322
3.244703
false
false
false
false
ioveracker/oscon-swift
Basics.playground/Contents.swift
1
14047
import UIKit //: Variables and constants var str = "Hello, playground!" let constString = "Hello, constant" // Always use let unless you need a var //: Optional Values var optionalString : String? optionalString = "Hello" if let stringThatHasAValue = optionalString { println("It has a value.") } else { println("It doesn't have a value.") } // Can also coalesce null values with ??, just like C# // Unwrap an optional with ?, e.g. optionalString?.someMethod() // DANGEROUSLY unwrap with !, e.g. optionalString!.someMethod(), WILL CRASH if nil //: Arrays var arrayOfInts = [1, 2, 3, 4, 5] //: Dictionaries var niftyDictionary = [ "Greeting": "Hello", "Farewell": "Goodbye" ] var numberDictionary = [ 1: "one", 2: "two" ] // Note: maps as NSObject: String var mixedKeys = [ 1: "one", "two": 2 ] //: For loops for number in arrayOfInts { println("Number: \(number)") } for (key, value) in niftyDictionary { println("Key: \(key) = \(value)") } //: Tuples var grocery = ("Beans", 1.99) grocery.0 grocery.1 //: Typealias typealias GroceryType = (String, Float) var fancyGroceryType : GroceryType = ("Beans", 1.99) fancyGroceryType.0 fancyGroceryType.1 typealias GroceryTypeWithNames = (name: String, price: Float) var fancierGroceryType : GroceryTypeWithNames = ("Beans", 1.99) fancierGroceryType.name fancierGroceryType.price //: Sets var mySet : Set = [1, 2, 3, 4, 5] // Note: must use Set type or it will default to Array mySet.insert(5) // Sets enforce unique values //: Switch var number = 42 switch number { case 0: println("It's zero!") fallthrough // Falls through into case 1 case 1: println("It's one") default: // Switch must either be exhaustive or include a default println("It's something else") } switch number { case 0...10: // inclusive println("It's between 0 and 10") case 11..<20: // not inclusive println("It's between 11 and 19") default: println("It's 20 or more") } switch grocery { case ("Beans", _): // Underscore means you don't care what the price is. println("It's beans!") case ("Tomatoes", let price): // Capture specific tuple member println("Tomatoes cost \(price)") case (_, 0.0...100.0): // Case matching a pattern println("Price is between 0 and 100") default: println("It's something else.") } //: Ifs if "one".uppercaseString == "ONE" { println("Hi.") } if ("two".uppercaseString == "TWO") { println("'if' can also use parens, but doesn't have to.") } //: Functions func doSomething() { println("Hello!") } doSomething() func returnAValue() -> Int { return 42 } returnAValue() func withParams(name: String) { println("Hello, \(name)") } withParams("Isaac") func optionalParams(name: String?) { println("Hello, \(name!)") } optionalParams("Isaac") //optionalParams(nil) func namedParameters(name: String, withNumber number: Int) { println("\(name): \(number)") } namedParameters("Isaac", withNumber: 42) var funcVar = returnAValue funcVar() // Functions can return functions func createAdder(numberToAdd : Int) -> Int -> Int { func theAdder(aNumber : Int) -> Int { return aNumber + numberToAdd } return theAdder } var addTwo = createAdder(2) addTwo(40) //: Closures var addThree = { (number) in number + 3 } addThree(39) arrayOfInts.sorted( { (first, second) in return first < second }) // Can also omit parameter names // Can put it after arrayOfInts.sorted(){$0 < $1} //: Extensions (mixins) // CGPoint is a C struct var myPoint = CGPoint() myPoint.x = 2 myPoint.y = 3 // Extend to include length() extension CGPoint { func length() -> CGFloat { return sqrt(self.x * self.x + self.y * self.y) } } myPoint.length() // You can even extend basic types like Int extension Int { func double() -> Int { return self * 2 } } 2.double() // Operator Overloading (must be at the top level, not part of an extension) func +(left: CGPoint, right: CGPoint) -> CGPoint { return CGPoint(x: left.x + right.x, y: left.y + right.y) } let anotherPoint = CGPoint(x: 3, y: 4) myPoint + anotherPoint //: Classes // Must provide either an initializer OR properties must be optional OR provide default value // Access modifiers: (can apply at class level and/or property & function level) // public - everything can access // internal - everything within the same module can access // private - only this class can access // class WebBrowser { // Properties var currentWebsite : String = "about:blank" var windowTitle : String { willSet { println("Window title is about to change from \(windowTitle) to \(newValue)") } didSet { println("Window title did change from \(oldValue) to \(windowTitle)") } } var lastResponseCode : Int? // Computed property var numberOfAdsOnCurrentPage : Int { // Walk the DOM and cout ad elements return 241503 } // get/set var numberOfOpenTabs : Int { get { // Count tabs return 3 } set { // close or open tabs then continue } } // Can declare properties as weak references (note: must be optional) weak var button : UIButton? init(browserName: String) { windowTitle = "Welcome to \(browserName)" } deinit { // Goodbye! // Note: Swift does not have a garbage collector. // The compiler does reference counting for you. } } var opera = WebBrowser(browserName: "opera") opera.currentWebsite opera.windowTitle opera.lastResponseCode opera.numberOfAdsOnCurrentPage var anotherBrowser = opera anotherBrowser.windowTitle = "Firefox" opera.windowTitle // Note that this type of assignment uses the same memory address class PrivateModeBrowser : WebBrowser { var privacyLevel : Float override init(browserName: String) { privacyLevel = 1.0 // Must be initialized before super.init super.init(browserName: browserName) } } //: Structures // Do not need to provide initializer, default values, or optionals // Compiler provides an initializer with all vars included // Are value types // struct Square { var size : Float var color : UIColor var area : Float { get { return size * size } set { size = sqrt(newValue) } } // Can declare functions within structs, but by default they cannot mutate self // unless the `mutating` modifier is included. // Use sparingly. mutating func changeColor() { let colors = [UIColor.redColor(), UIColor.greenColor()] let randomColor = colors[Int(rand()) % colors.count] self.color = randomColor } } var mySquare = Square(size: 2.0, color: UIColor.yellowColor()) var otherSquare = mySquare otherSquare.size = 6.0 mySquare.size mySquare.area = 9 mySquare.size //: Generics class Tree<T : Equatable> { // Can 'qualify' types, just like C# var data : T var children : [Tree<T>] = [] init(data: T) { self.data = data } func addChild(data : T) -> Tree<T> { let newNode = Tree(data: data) children.append(newNode) return newNode } func containsData(dataToFind : T) -> Bool { if (self.data == dataToFind) { return true } for childNode in self.children { if childNode.containsData(dataToFind) { return true } } return false } } let numberTree = Tree(data: 5) numberTree.addChild(2) numberTree.addChild(7).addChild(4) let stringTree = Tree(data: "hello") //: Enumerations /* Traditional enum: enum CompassDirection { North = 0, South, East, West } */ enum CompassDirection /* : Int */{ // Not backed by integer by default case North case South case East case West } var theWall = CompassDirection.North theWall = .South switch theWall { case .North: println("The wall is north.") default: () // default cannot be empty } // Enum backed by String enum HTTPVerb : String { case GET = "GET" case POST = "POST" } var myHTTPRequest = HTTPVerb.GET myHTTPRequest.rawValue enum Planet : Int { case Mercury = 1 case Venus /* = 2 */ // assignment after first is optional case Earth case Mars case Jupiter case Saturn case Uranus case Neptune } // Can create using raw value instead of enum 'case' var myPlanet = Planet(rawValue: 3) // Enums can also have different values enum Beverage { case Tea(milk: Bool, sugars: Int) case Coffee(milk: Bool, sugars: Int) case Soda(name: String) } var myDrink = Beverage.Coffee(milk: true, sugars: 0) switch myDrink { case .Coffee(true, let sugars): println("It's coffee with milk and \(sugars) sugar(s)") case .Coffee(true, 2): println("It's coffee, but with milk and 2 sugars") case .Coffee: println("It's coffee, black") default: () } //: Custom Operators // Double type does not provide an operator for exponents, so let's create one. // 💁 would be a great emoji for this but apparently it doesn't work infix operator ** { associativity left precedence 160 } func **(left: Double, right: Double) -> Double { return pow(left, right) } 2.4 ** 3.14 prefix operator +++ {} // defined before infix so no need to set precedence prefix func +++(inout int: Int) -> Int { return int + 2 } var a = 1 +++a var b = +++a + 1 a b //: Literal convertibles var anArray = [1, 2, 3] var aSet : Set = [1, 2, 3] // This array is converted into a Set automatically struct Regex { let pattern : String let options : NSRegularExpressionOptions private var matcher : NSRegularExpression? { return NSRegularExpression(pattern: self.pattern, options: self.options, error: nil) } init(pattern: String, options: NSRegularExpressionOptions = NSRegularExpressionOptions.CaseInsensitive) { self.pattern = pattern self.options = options } func match(string: String, options: NSMatchingOptions = nil) -> Bool { return self.matcher?.numberOfMatchesInString(string, options: options, range: NSMakeRange(0, string.lengthOfBytesUsingEncoding(NSUTF8StringEncoding))) != 0; } } let myRegex = Regex(pattern: "foo") myRegex.match("foo bar") // Can use Swift literal convertibles to make this declaration nicer. extension Regex : StringLiteralConvertible { typealias UnicodeScalarLiteralType = StringLiteralType typealias ExtendedGraphemeClusterLiteralType = StringLiteralType init(stringLiteral value: StringLiteralType) { self.pattern = value self.options = .CaseInsensitive } init(unicodeScalarLiteral value: UnicodeScalarLiteralType) { self.pattern = value self.options = .CaseInsensitive } init(extendedGraphemeClusterLiteral value: ExtendedGraphemeClusterLiteralType) { self.pattern = value self.options = .CaseInsensitive } } // Now we can init a regex like this: let nicerRegex : Regex = "foo" nicerRegex.match("foo bar") //: File Access let fileManager = NSFileManager.defaultManager() var documentsDirectory = fileManager.URLsForDirectory(NSSearchPathDirectory.DocumentDirectory, inDomains: NSSearchPathDomainMask.UserDomainMask).first as? NSURL println(documentsDirectory!) let fileContents = "I am the very model of a modern major general" if let destinationURL = documentsDirectory?.URLByAppendingPathComponent("penzance.txt") { fileContents.writeToURL(destinationURL, atomically: true, encoding: NSUTF8StringEncoding, error: nil) } //: Autoclosure // In Objective-C (and C), we will commonly use the pre-processor to guard certain blocks of code with #ifdef, e.g.: // #ifdef DEBUG // [self doSomethingIfDebugBuild] // #endif // Swift doesn't have a preprocessor, so we use the assert function. // Note: uncommenting this section will cause the playground to crash. //assert(1 == 1, "Math is broken if this is false") // //// Implementation of this function uses the @autoclosure keyword. Something like this: //let debugMode = true //func myAssert(predicate: @autoclosure () -> Bool) { // if debugMode == true { // if predicate() == false { // abort() // } // } //} //myAssert(1 == 1) //: String Operations var helloPlayground = "Hello, playground" helloPlayground.componentsSeparatedByString(" ") helloPlayground.uppercaseString helloPlayground.lowercaseString helloPlayground.hasPrefix("Hello") helloPlayground.hasSuffix("playground") helloPlayground.rangeOfString("playground") helloPlayground.rangeOfString("PlaYGrOund", options: .CaseInsensitiveSearch) count(helloPlayground) //: Number Formatter let numberFormatter = NSNumberFormatter() numberFormatter.numberStyle = .CurrencyStyle numberFormatter.stringFromNumber(23.42) numberFormatter.roundingIncrement = 0.5 numberFormatter.stringFromNumber(23.42) numberFormatter.roundingIncrement = 0.0 numberFormatter.numberStyle = .DecimalStyle numberFormatter.stringFromNumber(10294701972) //: Mass Formatter let massFormatter = NSMassFormatter() massFormatter.stringFromKilograms(0.5) //: Length formatter let lengthFormatter = NSLengthFormatter() lengthFormatter.stringFromMeters(100) //: Data Formatter let dataFormatter = NSByteCountFormatter() dataFormatter.stringFromByteCount(2000000) //: Map, reduce, and filter let source = [1, 2, 4, 8] let mapped = source.map({ $0 * 2 }) // 1 + 2 + 4 + 8 let reduced = source.reduce(0, combine: { (currentValue, nextValue) -> Int in return currentValue + nextValue }) // Shorter alternative let shortClosure = source.reduce(0, combine: +) println(shortClosure) let filtered = source.filter({ $0 % 4 == 0 }) println(filtered) let sorted = source.sorted({ $0 > $1 }) println(sorted)
unlicense
dffcf97349cd62190951f71cbf0e785b
22.524288
164
0.667474
4.003421
false
false
false
false
Jeffchiucp/Swift_PlayGrounds
5-Arrays.playground/Contents.swift
1
3213
import UIKit /*: # Arrays Time to dive into arrays! In case you do not know what an array is, an array is an ordered list of items of the same type. Let's look at some examples! */ let groceryList: [String] = ["eggs", "milk"] /*: This is how you declare and initalize an array. The array type is defined as [<type of items in array>], like above where the type of groceryList is defined as [String]. For that reason, groceryList is an array of Strings. There are languages where you can have an array of objects with different types, but in Swift, you have to specify the type of the objects that will be stored in the array, and all objects in the array have to be of that type. */ /*: As you learned before in the section on type inference, Swift is smart enough to realize that your variable is an array and it's of type [String]. */ let groceryListWithInferredType = ["eggs", "milk"] /*: To initialize an empty array: */ let emptyArray = [String]() /*: In many cases, it is important to find out the number of items in your array. You can find the number of items easily by looking at the array's `count` property. */ let numberOfItems = groceryList.count print("the grocery list contains \(numberOfItems) items.") //: Notice that, just like Java's .length property, this is not a property, not a method. /*: Sometimes you just want to know whether the array is empty or not: */ if groceryList.isEmpty { print("The grocery list is empty!") } else { print("The grocery list is not empty!") } /*: If you notice, the above variables are defined with the let keyword, which makes these arrays immutable (unchangeable). You cannot change these arrays at all in any way, so they stay as they are throughout the program. Uncomment the line below to see what happens when you try to add an item to the immutable array. */ //groceryList.append("bread") /*: It says `Immutable value of type '[String]' only has mutating members named 'append' As you can see, `.count` and `.isEmpty` work with immutable arrays without any problems. Let's now define a mutable array to see what features are available when working with mutable arrays: */ var mutableGroceryList = ["eggs", "milk"] /*: To add an item to the end of the array, you can use the append method: */ mutableGroceryList.append("yogurt") /*: If you want to add an item to somewhere in the middle of the array, you can specify the index at which you want to insert an item and all the items that follow the newly added item will shift. Notice how after adding "chips", "yogurt" is shifted to the next index. */ mutableGroceryList.insert("chips", atIndex: 2) /*: To combine 2 mutable arrays together: */ mutableGroceryList += ["cheese", "ice cream"] /*: To retrieve values from the array, subscript syntax is used, where you pass in the index of the item you are trying to retrieve. Keep in mind that arrays are zero-indexed (i.e. first item's index is 0, second item's index is 1, etc.) */ var item = mutableGroceryList[0] /*: Challenge: try to retrieve last item in the array */ /*: Of course, you have the ability to remove an item. This will return the removed item. */ let removedItem = mutableGroceryList.removeAtIndex(0)
mit
2f5b5f4b3be8dd6916b0682906fe716a
32.46875
449
0.737006
4.026316
false
false
false
false
brentsimmons/Evergreen
Account/Sources/Account/NewsBlur/Internals/NewsBlurAPICaller+Internal.swift
1
5821
// // NewsBlurAPICaller+Internal.swift // Account // // Created by Anh Quang Do on 2020-03-21. // Copyright (c) 2020 Ranchero Software, LLC. All rights reserved. // import Foundation import RSWeb protocol NewsBlurDataConvertible { var asData: Data? { get } } enum NewsBlurError: LocalizedError { case general(message: String) case invalidParameter case unknown var errorDescription: String? { switch self { case .general(let message): return message case .invalidParameter: return "There was an invalid parameter passed" case .unknown: return "An unknown error occurred" } } } // MARK: - Interact with endpoints extension NewsBlurAPICaller { // GET endpoint, discard response func requestData( endpoint: String, completion: @escaping (Result<Void, Error>) -> Void ) { let callURL = baseURL.appendingPathComponent(endpoint) requestData(callURL: callURL, completion: completion) } // GET endpoint func requestData<R: Decodable>( endpoint: String, resultType: R.Type, dateDecoding: JSONDecoder.DateDecodingStrategy = .iso8601, keyDecoding: JSONDecoder.KeyDecodingStrategy = .useDefaultKeys, completion: @escaping (Result<(HTTPURLResponse, R?), Error>) -> Void ) { let callURL = baseURL.appendingPathComponent(endpoint) requestData( callURL: callURL, resultType: resultType, dateDecoding: dateDecoding, keyDecoding: keyDecoding, completion: completion ) } // POST to endpoint, discard response func sendUpdates( endpoint: String, payload: NewsBlurDataConvertible, completion: @escaping (Result<Void, Error>) -> Void ) { let callURL = baseURL.appendingPathComponent(endpoint) sendUpdates(callURL: callURL, payload: payload, completion: completion) } // POST to endpoint func sendUpdates<R: Decodable>( endpoint: String, payload: NewsBlurDataConvertible, resultType: R.Type, dateDecoding: JSONDecoder.DateDecodingStrategy = .iso8601, keyDecoding: JSONDecoder.KeyDecodingStrategy = .useDefaultKeys, completion: @escaping (Result<(HTTPURLResponse, R?), Error>) -> Void ) { let callURL = baseURL.appendingPathComponent(endpoint) sendUpdates( callURL: callURL, payload: payload, resultType: resultType, dateDecoding: dateDecoding, keyDecoding: keyDecoding, completion: completion ) } } // MARK: - Interact with URLs extension NewsBlurAPICaller { // GET URL with params, discard response func requestData( callURL: URL?, completion: @escaping (Result<Void, Error>) -> Void ) { guard let callURL = callURL else { completion(.failure(TransportError.noURL)) return } let request = URLRequest(url: callURL, credentials: credentials) transport.send(request: request) { result in if self.suspended { completion(.failure(TransportError.suspended)) return } switch result { case .success: completion(.success(())) case .failure(let error): completion(.failure(error)) } } } // GET URL with params func requestData<R: Decodable>( callURL: URL?, resultType: R.Type, dateDecoding: JSONDecoder.DateDecodingStrategy = .iso8601, keyDecoding: JSONDecoder.KeyDecodingStrategy = .useDefaultKeys, completion: @escaping (Result<(HTTPURLResponse, R?), Error>) -> Void ) { guard let callURL = callURL else { completion(.failure(TransportError.noURL)) return } let request = URLRequest(url: callURL, credentials: credentials) transport.send( request: request, resultType: resultType, dateDecoding: dateDecoding, keyDecoding: keyDecoding ) { result in if self.suspended { completion(.failure(TransportError.suspended)) return } switch result { case .success(let response): completion(.success(response)) case .failure(let error): completion(.failure(error)) } } } // POST to URL with params, discard response func sendUpdates( callURL: URL?, payload: NewsBlurDataConvertible, completion: @escaping (Result<Void, Error>) -> Void ) { guard let callURL = callURL else { completion(.failure(TransportError.noURL)) return } var request = URLRequest(url: callURL, credentials: credentials) request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: HTTPRequestHeader.contentType) request.httpBody = payload.asData transport.send(request: request, method: HTTPMethod.post) { result in if self.suspended { completion(.failure(TransportError.suspended)) return } switch result { case .success: completion(.success(())) case .failure(let error): completion(.failure(error)) } } } // POST to URL with params func sendUpdates<R: Decodable>( callURL: URL?, payload: NewsBlurDataConvertible, resultType: R.Type, dateDecoding: JSONDecoder.DateDecodingStrategy = .iso8601, keyDecoding: JSONDecoder.KeyDecodingStrategy = .useDefaultKeys, completion: @escaping (Result<(HTTPURLResponse, R?), Error>) -> Void ) { guard let callURL = callURL else { completion(.failure(TransportError.noURL)) return } guard let data = payload.asData else { completion(.failure(NewsBlurError.invalidParameter)) return } var request = URLRequest(url: callURL, credentials: credentials) request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: HTTPRequestHeader.contentType) transport.send( request: request, method: HTTPMethod.post, data: data, resultType: resultType, dateDecoding: dateDecoding, keyDecoding: keyDecoding ) { result in if self.suspended { completion(.failure(TransportError.suspended)) return } switch result { case .success(let response): completion(.success(response)) case .failure(let error): completion(.failure(error)) } } } }
mit
476d4af84c4bf81ba9b7307c648f7195
23.665254
106
0.711562
3.909335
false
false
false
false
kstaring/swift
validation-test/compiler_crashers_fixed/00180-szone-free-definite-size.swift
11
1037
// 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 class x<ji>: y { init(u: ji) { kj. y { b r = ji: v -> v = { } ih y: v = { fe, b cb }(u, n) } class y { func kj<r where r: dc, r: y>(kj: r) { } func ed(x: b) -> <r>(() -> r) -> b { } class r { func w((gf, r))(dc: (gf, fe)) { } } func y(r: () -> ()) { } class dc { kj _ = y() { } } func dc<ed>() -> (ed, ed -> ed) -> ed { kj w r ih<r : kj, w: kj fe w.n == r.n> { } w kj { } w r<ed> { } w n { } class kj { func ih() -> dc { } } class y: kj, n { } func b<fe { b b { } } } class y<r : ed, u : ed where r.ed == u> : n { } class y<r, u> { } protocol ed { } protocol n { } protocol ed : y { func y
apache-2.0
de40198fddf0fbe3e0a3203692c6d47c
16.283333
78
0.525554
2.554187
false
false
false
false
overtake/TelegramSwift
Telegram-Mac/ModalPreviewViews.swift
1
15397
// // StickerPreviewModalController.swift // Telegram // // Created by keepcoder on 02/02/2017. // Copyright © 2017 Telegram. All rights reserved. // import Cocoa import TGUIKit import TelegramCore import Postbox import SwiftSignalKit class StickerPreviewModalView : View, ModalPreviewControllerView { fileprivate let imageView:TransformImageView = TransformImageView() fileprivate let textView:TextView = TextView() private let fetchDisposable = MetaDisposable() required init(frame frameRect: NSRect) { super.init(frame: frameRect) addSubview(imageView) addSubview(textView) textView.backgroundColor = .clear imageView.setFrameSize(100,100) self.background = .clear } deinit { fetchDisposable.dispose() } override func layout() { super.layout() imageView.center() } func update(with reference: QuickPreviewMedia, context: AccountContext, animated: Bool) -> Void { if let reference = reference.fileReference { let size = reference.media.dimensions?.size.aspectFitted(NSMakeSize(min(300, frame.size.width), min(300, frame.size.height))) ?? frame.size imageView.set(arguments: TransformImageArguments(corners: ImageCorners(), imageSize: size, boundingSize: size, intrinsicInsets: NSEdgeInsets())) imageView.frame = NSMakeRect(0, frame.height - size.height, size.width, size.height) if animated { imageView.layer?.animateScaleSpring(from: 0.5, to: 1.0, duration: 0.2) } imageView.setSignal(chatMessageSticker(postbox: context.account.postbox, file: reference, small: false, scale: backingScaleFactor, fetched: true), clearInstantly: true, animate:true) let layout = TextViewLayout(.initialize(string: reference.media.stickerText?.fixed, color: nil, font: .normal(30.0))) layout.measure(width: .greatestFiniteMagnitude) textView.update(layout) textView.centerX() if animated { textView.layer?.animateScaleSpring(from: 0.5, to: 1.0, duration: 0.2) } needsLayout = true } } func getContentView() -> NSView { return imageView } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } } class GifPreviewModalView : View, ModalPreviewControllerView { fileprivate var player:GIFContainerView = GIFContainerView() required init(frame frameRect: NSRect) { super.init(frame: frameRect) addSubview(player) player.setFrameSize(100,100) self.background = .clear } override func layout() { super.layout() player.center() } func getContentView() -> NSView { return player } func update(with reference: QuickPreviewMedia, context: AccountContext, animated: Bool) -> Void { if let reference = reference.fileReference { if animated { let current = self.player current.layer?.animateAlpha(from: 1, to: 0, duration: 0.2, removeOnCompletion: false, completion: { [weak current] completed in if completed { current?.removeFromSuperview() } }) } else { self.player.removeFromSuperview() } self.player = GIFContainerView() self.player.layer?.borderWidth = 0 self.player.layer?.cornerRadius = .cornerRadius addSubview(self.player) let size = reference.media.dimensions?.size.aspectFitted(NSMakeSize(frame.size.width, frame.size.height - 40)) ?? frame.size let iconSignal: Signal<ImageDataTransformation, NoError> iconSignal = chatMessageSticker(postbox: context.account.postbox, file: reference, small: false, scale: backingScaleFactor) player.update(with: reference, size: size, viewSize: size, context: context, table: nil, iconSignal: iconSignal) player.frame = NSMakeRect(0, frame.height - size.height, size.width, size.height) if animated { player.layer?.animateAlpha(from: 0, to: 1, duration: 0.2) } needsLayout = true } } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } } class ImagePreviewModalView : View, ModalPreviewControllerView { fileprivate var imageView:TransformImageView = TransformImageView() required init(frame frameRect: NSRect) { super.init(frame: frameRect) addSubview(imageView) self.background = .clear } override func layout() { super.layout() imageView.center() } func getContentView() -> NSView { return imageView } func update(with reference: QuickPreviewMedia, context: AccountContext, animated: Bool) -> Void { if let reference = reference.imageReference { let current = self.imageView if animated { current.layer?.animateAlpha(from: 1, to: 0, duration: 0.2, removeOnCompletion: false, completion: { [weak current] completed in if completed { current?.removeFromSuperview() } }) } else { current.removeFromSuperview() } self.imageView = TransformImageView() self.imageView.layer?.borderWidth = 0 addSubview(self.imageView) let size = frame.size let dimensions = largestImageRepresentation(reference.media.representations)?.dimensions.size ?? size let arguments = TransformImageArguments(corners: ImageCorners(radius: .cornerRadius), imageSize: dimensions.fitted(size), boundingSize: dimensions.fitted(size), intrinsicInsets: NSEdgeInsets(), resizeMode: .none) self.imageView.setSignal(signal: cachedMedia(media: reference.media, arguments: arguments, scale: backingScaleFactor, positionFlags: nil), clearInstantly: false) let updateImageSignal = chatMessagePhoto(account: context.account, imageReference: reference, scale: backingScaleFactor, synchronousLoad: true) self.imageView.setSignal(updateImageSignal, animate: false) self.imageView.set(arguments: arguments) imageView.setFrameSize(arguments.imageSize) if animated { imageView.layer?.animateScaleSpring(from: 0.5, to: 1.0, duration: 0.2) } needsLayout = true } } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } } class VideoPreviewModalView : View, ModalPreviewControllerView { fileprivate var playerView:ChatVideoAutoplayView? required init(frame frameRect: NSRect) { super.init(frame: frameRect) self.background = .clear } override func layout() { super.layout() playerView?.view.center() } func getContentView() -> NSView { return playerView?.view ?? self } func update(with reference: QuickPreviewMedia, context: AccountContext, animated: Bool) -> Void { if let reference = reference.fileReference { let currentView = self.playerView?.view if animated { currentView?.layer?.animateAlpha(from: 1, to: 0, duration: 0.2, removeOnCompletion: false, completion: { [weak currentView] completed in if completed { currentView?.removeFromSuperview() } }) } else { currentView?.removeFromSuperview() } self.playerView = ChatVideoAutoplayView(mediaPlayer: MediaPlayer(postbox: context.account.postbox, reference: reference.resourceReference(reference.media.resource), streamable: reference.media.isStreamable, video: true, preferSoftwareDecoding: false, enableSound: true, volume: 1.0, fetchAutomatically: true), view: MediaPlayerView(backgroundThread: true)) guard let playerView = self.playerView else { return } addSubview(playerView.view) let size = frame.size let dimensions = reference.media.dimensions?.size ?? size playerView.view.setFrameSize(dimensions.fitted(size)) playerView.mediaPlayer.attachPlayerView(playerView.view) playerView.mediaPlayer.play() needsLayout = true } } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } } class AnimatedStickerPreviewModalView : View, ModalPreviewControllerView { private let loadResourceDisposable = MetaDisposable() fileprivate let textView:TextView = TextView() required init(frame frameRect: NSRect) { super.init(frame: frameRect) self.background = .clear addSubview(textView) textView.backgroundColor = .clear } private var player: LottiePlayerView? private var effectView: LottiePlayerView? private let dataDisposable = MetaDisposable() override func layout() { super.layout() //player.center() } func getContentView() -> NSView { return player ?? self } override func viewDidMoveToWindow() { } deinit { self.loadResourceDisposable.dispose() self.dataDisposable.dispose() } func update(with reference: QuickPreviewMedia, context: AccountContext, animated: Bool) -> Void { if let reference = reference.fileReference { self.player?.removeFromSuperview() self.player = nil let dimensions = reference.media.dimensions?.size var size = NSMakeSize(frame.width - 80, frame.height - 80) if reference.media.premiumEffect != nil { size = NSMakeSize(200, 200) } if let dimensions = dimensions { size = dimensions.aspectFitted(size) } self.player = LottiePlayerView(frame: NSMakeRect(0, 0, size.width, size.height)) addSubview(self.player!) guard let player = self.player else { return } player.center() let mediaId = reference.media.id let data: Signal<MediaResourceData, NoError> if let resource = reference.media.resource as? LocalBundleResource { data = Signal { subscriber in if let path = Bundle.main.path(forResource: resource.name, ofType: resource.ext), let data = try? Data(contentsOf: URL(fileURLWithPath: path), options: [.mappedRead]) { subscriber.putNext(MediaResourceData(path: path, offset: 0, size: Int64(data.count), complete: true)) subscriber.putCompletion() } return EmptyDisposable } } else { data = context.account.postbox.mediaBox.resourceData(reference.media.resource, attemptSynchronously: true) } self.loadResourceDisposable.set((data |> map { resourceData -> Data? in if resourceData.complete, let data = try? Data(contentsOf: URL(fileURLWithPath: resourceData.path), options: [.mappedIfSafe]) { if reference.media.isWebm { return resourceData.path.data(using: .utf8)! } return data } return nil } |> deliverOnMainQueue).start(next: { [weak player] data in if let data = data { let type: LottieAnimationType if reference.media.isWebm { type = .webm } else if reference.media.mimeType == "image/webp" { type = .webp } else { type = .lottie } player?.set(LottieAnimation(compressed: data, key: LottieAnimationEntryKey(key: .media(mediaId), size: size), type: type, cachePurpose: .none)) } else { player?.set(nil) } })) if animated { player.layer?.animateAlpha(from: 0, to: 1, duration: 0.2) } let layout = TextViewLayout(.initialize(string: reference.media.stickerText?.fixed ?? reference.media.customEmojiText?.fixed, color: nil, font: .normal(30.0))) layout.measure(width: .greatestFiniteMagnitude) textView.update(layout) textView.centerX() if animated { textView.layer?.animateScaleSpring(from: 0.5, to: 1.0, duration: 0.2) } if let effect = reference.media.premiumEffect { var animationSize = NSMakeSize(size.width * 1.5, size.height * 1.5) if let dimensions = reference.media.dimensions?.size { animationSize = dimensions.aspectFitted(animationSize) } let signal: Signal<LottieAnimation?, NoError> = context.account.postbox.mediaBox.resourceData(effect.resource) |> filter { $0.complete } |> take(1) |> map { data in if data.complete, let data = try? Data(contentsOf: URL(fileURLWithPath: data.path)) { return LottieAnimation(compressed: data, key: .init(key: .bundle("_premium_\(reference.media.fileId)"), size: animationSize, backingScale: Int(System.backingScale)), cachePurpose: .none, playPolicy: .loop) } else { return nil } } |> deliverOnMainQueue let current: LottiePlayerView if let view = effectView { current = view } else { current = LottiePlayerView(frame: animationSize.bounds) self.effectView = current } addSubview(current, positioned: .above, relativeTo: self.player) current.centerY(x: player.frame.maxX - current.frame.width + 19, addition: -1.5) dataDisposable.set(signal.start(next: { [weak current] animation in current?.set(animation) })) } else if let view = effectView { performSubviewRemoval(view, animated: true) self.effectView = nil } } } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
gpl-2.0
bc4e1d93075a77ffc12c1dc4d9b83db2
37.780856
368
0.577553
5.287088
false
false
false
false
rsmoz/swift-package-manager
Sources/PackageDescription/Package.swift
1
4399
/* This source file is part of the Swift.org open source project Copyright 2015 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 Swift project authors */ #if os(Linux) import Glibc #else import Darwin.C #endif /// A TOML representation of an element. protocol TOMLConvertible { /// Return a TOML representation. func toTOML() -> String } /// The description for a complete package. public final class Package { /// The description for a package dependency. public class Dependency { public let versionRange: Range<Version> public let url: String init(_ url: String, _ versionRange: Range<Version>) { self.url = url self.versionRange = versionRange } public class func Package(url url: String, versions: Range<Version>) -> Dependency { return Dependency(url, versions) } public class func Package(url url: String, majorVersion: Int) -> Dependency { return Dependency(url, Version(majorVersion, 0, 0)..<Version(majorVersion + 1, 0, 0)) } public class func Package(url url: String, majorVersion: Int, minor: Int) -> Dependency { return Dependency(url, Version(majorVersion, minor, 0)..<Version(majorVersion, minor + 1, 0)) } public class func Package(url url: String, _ version: Version) -> Dependency { return Dependency(url, version...version) } } /// The name of the package, if specified. public let name: String? /// The list of targets. public var targets: [Target] /// The list of dependencies. public var dependencies: [Dependency] /// The list of test dependencies. They aren't exposed to a parent Package public var testDependencies: [Dependency] /// The list of folders to exclude. public var exclude: [String] /// Construct a package. public init(name: String? = nil, targets: [Target] = [], dependencies: [Dependency] = [], testDependencies: [Dependency] = [], exclude: [String] = []) { self.name = name self.targets = targets self.dependencies = dependencies self.testDependencies = testDependencies self.exclude = exclude // Add custom exit handler to cause package to be dumped at exit, if requested. // // FIXME: This doesn't belong here, but for now is the mechanism we use // to get the interpreter to dump the package when attempting to load a // manifest. if getenv("SWIFT_DUMP_PACKAGE") != nil { dumpPackageAtExit(self) } } } // MARK: TOMLConvertible extension Package.Dependency: TOMLConvertible { public func toTOML() -> String { return "[\"\(url)\", \"\(versionRange.startIndex)\", \"\(versionRange.endIndex)\"]," } } extension Package: TOMLConvertible { public func toTOML() -> String { var result = "" result += "[package]\n" if let name = self.name { result += "name = \"\(name)\"\n" } result += "dependencies = [" for dependency in dependencies { result += dependency.toTOML() } result += "]\n" result += "testDependencies = [" for dependency in testDependencies { result += dependency.toTOML() } result += "]\n" result += "\n" + "exclude = \(exclude)" + "\n" for target in targets { result += "[[package.targets]]\n" result += target.toTOML() } return result } } // MARK: Equatable extension Package : Equatable { } public func ==(lhs: Package, rhs: Package) -> Bool { return (lhs.name == rhs.name && lhs.targets == rhs.targets && lhs.dependencies == rhs.dependencies) } extension Package.Dependency : Equatable { } public func ==(lhs: Package.Dependency, rhs: Package.Dependency) -> Bool { return lhs.url == rhs.url && lhs.versionRange == rhs.versionRange } // MARK: Package Dumping private var thePackageToDump: Package? = nil private func dumpPackageAtExit(package: Package) { func dump() { print(thePackageToDump!.toTOML()) } thePackageToDump = package atexit(dump) }
apache-2.0
a8877f1e9ad38b96f1a6f17f6c4dd68c
29.548611
156
0.619459
4.470528
false
false
false
false
ello/ello-ios
Sources/Controllers/Editorials/Cells/EditorialTitledCell.swift
1
3010
//// /// EditorialTitledCell.swift // import SnapKit class EditorialTitledCell: EditorialCellContent { let titleLabel = StyledLabel(style: .editorialHeader) let authorLabel = StyledLabel(style: .editorialHeader) let subtitleWebView = ElloWebView() var subtitleHeightConstraint: Constraint? enum TitlePlacement { case `default` case inStream } var titlePlacement: TitlePlacement = .default { didSet { let top: CGFloat switch titlePlacement { case .default: top = Size.defaultMargin.top case .inStream: top = Size.postStreamLabelMargin } titleLabel.snp.updateConstraints { make in make.top.equalTo(editorialContentView).offset(top) } } } override func style() { super.style() titleLabel.isMultiline = true authorLabel.isMultiline = false subtitleWebView.scrollView.isScrollEnabled = false } override func prepareForReuse() { super.prepareForReuse() titlePlacement = .default } override func updateConfig() { super.updateConfig() titleLabel.text = config.title authorLabel.text = config.author if let html = config.subtitle { let wrappedHtml = StreamTextCellHTML.editorialHTML(html) subtitleWebView.loadHTMLString(wrappedHtml, baseURL: URL(string: "/")) } else { subtitleWebView.loadHTMLString("", baseURL: URL(string: "/")) } } override func bindActions() { super.bindActions() subtitleWebView.delegate = self } override func arrange() { super.arrange() editorialContentView.addSubview(titleLabel) editorialContentView.addSubview(authorLabel) editorialContentView.addSubview(subtitleWebView) titleLabel.snp.makeConstraints { make in make.top.leading.trailing.equalTo(editorialContentView).inset(Size.defaultMargin) } authorLabel.snp.makeConstraints { make in make.leading.trailing.equalTo(editorialContentView).inset(Size.defaultMargin) make.top.equalTo(titleLabel.snp.bottom).offset(3) } } } extension EditorialTitledCell: UIWebViewDelegate { func webView( _ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebView.NavigationType ) -> Bool { if let scheme = request.url?.scheme, scheme == "default" { tappedEditorial() return false } else { return ElloWebViewHelper.handle(request: request, origin: self) } } func webViewDidFinishLoad(_ webView: UIWebView) { if let actualHeight = webView.windowContentSize()?.height, let constraint = subtitleHeightConstraint { constraint.update(offset: actualHeight) } } }
mit
1cc44bf46b8aa8462a5ca4be3a6b65bf
26.87037
93
0.621262
5.318021
false
false
false
false
LocationKit/LocationKitSampleApps
CurrentPlace/CurrentPlace/ViewController.swift
1
1130
// // ViewController.swift // CurrentPlace // // Created by Victor Quinn on 11/20/15. // Copyright (c) 2015 SocialRadar. All rights reserved. // import UIKit class ViewController: UIViewController { let locationManager = LKLocationManager() @IBOutlet weak var placeLabel: UILabel! override func viewDidLoad() { super.viewDidLoad() self.placeLabel.text = "Place undetermined" #if DEBUG locationManager.debug = true #endif locationManager.apiToken = "your_api_token_here" locationManager.startUpdatingLocation() } @IBAction func whereAmI(sender: UIButton) { locationManager.requestPlace { (place: LKPlacemark?, error: NSError?) -> Void in if let place = place { self.placeLabel.text = "\(place.subThoroughfare!) \(place.thoroughfare!), \(place.locality!), \(place.administrativeArea!)" } else if error != nil { print("Uh oh, got an error: \(error)") } else { self.placeLabel.text = "Place could not be determined" } } } }
mit
b4417fc511f2ab8cdbf52eb1e907bbbb
25.904762
139
0.606195
4.556452
false
false
false
false
JasperMeurs/UIColor-Hex-Swift
Example/UIColor-Hex-Swift/ViewController.swift
1
1352
// // ViewController.swift // UIColor-Hex-Swift // // Created by Frederik Jacques on 05/30/2015. // Copyright (c) 05/30/2015 Frederik Jacques. All rights reserved. // import UIKit import UIColor_Hex_Swift class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. let colors = ["#0", "3f", "123", "00ff00", "12345699"] var yPosition = 40 for (index, colorString) in enumerate(colors){ let square = UIView(frame: CGRect(x: 0, y: 0, width: 20, height: 20)) let color = UIColor.colorWithCSS( colorString ) square.backgroundColor = color square.center = CGPoint(x: Int(view.center.x), y: yPosition) view.addSubview(square) yPosition += Int(square.bounds.height) + 5 } var v = UIView (frame: CGRect(x: 0, y: 0, width: 20, height: 20)) v.backgroundColor = UIColor.colorWithHex(0xff0000) v.center = CGPoint(x: 50, y: 200) view.addSubview(v) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
7a3a32e4296cd279b7b86e35812ee93b
27.765957
81
0.579882
4.225
false
false
false
false
SirapatBoonyasiwapong/grader
Sources/App/Models/GroupEvent.swift
1
1484
import Foundation import FluentProvider final class GroupEvent: Model, NodeRepresentable { var groupID: Identifier var eventID: Identifier var classroom: Parent<GroupEvent, Group> { return parent(id: groupID) } var events: Parent<GroupEvent, Event> { return parent(id: eventID) } let storage = Storage() init(row: Row) throws { groupID = try row.get("group_id") eventID = try row.get("event_id") } init(groupID: Identifier, eventID: Identifier) { self.groupID = groupID self.eventID = eventID } func makeRow() throws -> Row { var row = Row() try row.set("group_id", groupID) try row.set("event_id", eventID) return row } func makeNode(in context: Context?) throws -> Node { let events = try self.events.get() return try Node(node: [ "id": id!.string!, "groupID": groupID, "eventID": eventID, "events": events.makeNode(in: context)]) } } extension GroupEvent: Preparation { static func prepare(_ database: Database) throws { try database.create(self) { builder in builder.id() builder.parent(Group.self, optional: false) builder.parent(Event.self, optional: false) } } static func revert(_ database: Database) throws { try database.delete(self) } }
mit
9e2f92b89c4e89c6409cf27b3131e9df
24.152542
56
0.568733
4.390533
false
false
false
false
tidwall/SwiftWebSocket
Source/WebSocket.swift
1
69102
/* * SwiftWebSocket (websocket.swift) * * Copyright (C) Josh Baker. All Rights Reserved. * Contact: @tidwall, [email protected] * * This software may be modified and distributed under the terms * of the MIT license. See the LICENSE file for details. * */ import Foundation private let windowBufferSize = 0x2000 private class Payload { var ptr : UnsafeMutableRawPointer var cap : Int var len : Int init(){ len = 0 cap = windowBufferSize ptr = malloc(cap) } deinit{ free(ptr) } var count : Int { get { return len } set { if newValue > cap { while cap < newValue { cap *= 2 } ptr = realloc(ptr, cap) } len = newValue } } func append(_ bytes: UnsafePointer<UInt8>, length: Int){ let prevLen = len count = len+length memcpy(ptr+prevLen, bytes, length) } var array : [UInt8] { get { var array = [UInt8](repeating: 0, count: count) memcpy(&array, ptr, count) return array } set { count = 0 append(newValue, length: newValue.count) } } var nsdata : Data { get { return Data(bytes: ptr.assumingMemoryBound(to: UInt8.self), count: count) } set { count = 0 append((newValue as NSData).bytes.bindMemory(to: UInt8.self, capacity: newValue.count), length: newValue.count) } } var buffer : UnsafeBufferPointer<UInt8> { get { return UnsafeBufferPointer<UInt8>(start: ptr.assumingMemoryBound(to: UInt8.self), count: count) } set { count = 0 append(newValue.baseAddress!, length: newValue.count) } } } private enum OpCode : UInt8, CustomStringConvertible { case `continue` = 0x0, text = 0x1, binary = 0x2, close = 0x8, ping = 0x9, pong = 0xA var isControl : Bool { switch self { case .close, .ping, .pong: return true default: return false } } var description : String { switch self { case .`continue`: return "Continue" case .text: return "Text" case .binary: return "Binary" case .close: return "Close" case .ping: return "Ping" case .pong: return "Pong" } } } /// The WebSocketEvents struct is used by the events property and manages the events for the WebSocket connection. public struct WebSocketEvents { /// An event to be called when the WebSocket connection's readyState changes to .Open; this indicates that the connection is ready to send and receive data. public var open : ()->() = {} /// An event to be called when the WebSocket connection's readyState changes to .Closed. public var close : (_ code : Int, _ reason : String, _ wasClean : Bool)->() = {(code, reason, wasClean) in} /// An event to be called when an error occurs. public var error : (_ error : Error)->() = {(error) in} /// An event to be called when a message is received from the server. public var message : (_ data : Any)->() = {(data) in} /// An event to be called when a pong is received from the server. public var pong : (_ data : Any)->() = {(data) in} /// An event to be called when the WebSocket process has ended; this event is guarenteed to be called once and can be used as an alternative to the "close" or "error" events. public var end : (_ code : Int, _ reason : String, _ wasClean : Bool, _ error : Error?)->() = {(code, reason, wasClean, error) in} } /// The WebSocketBinaryType enum is used by the binaryType property and indicates the type of binary data being transmitted by the WebSocket connection. public enum WebSocketBinaryType : CustomStringConvertible { /// The WebSocket should transmit [UInt8] objects. case uInt8Array /// The WebSocket should transmit NSData objects. case nsData /// The WebSocket should transmit UnsafeBufferPointer<UInt8> objects. This buffer is only valid during the scope of the message event. Use at your own risk. case uInt8UnsafeBufferPointer public var description : String { switch self { case .uInt8Array: return "UInt8Array" case .nsData: return "NSData" case .uInt8UnsafeBufferPointer: return "UInt8UnsafeBufferPointer" } } } /// The WebSocketReadyState enum is used by the readyState property to describe the status of the WebSocket connection. @objc public enum WebSocketReadyState : Int, CustomStringConvertible { /// The connection is not yet open. case connecting = 0 /// The connection is open and ready to communicate. case open = 1 /// The connection is in the process of closing. case closing = 2 /// The connection is closed or couldn't be opened. case closed = 3 fileprivate var isClosed : Bool { switch self { case .closing, .closed: return true default: return false } } /// Returns a string that represents the ReadyState value. public var description : String { switch self { case .connecting: return "Connecting" case .open: return "Open" case .closing: return "Closing" case .closed: return "Closed" } } } private let defaultMaxWindowBits = 15 /// The WebSocketCompression struct is used by the compression property and manages the compression options for the WebSocket connection. public struct WebSocketCompression { /// Used to accept compressed messages from the server. Default is true. public var on = false /// request no context takeover. public var noContextTakeover = false /// request max window bits. public var maxWindowBits = defaultMaxWindowBits } /// The WebSocketService options are used by the services property and manages the underlying socket services. public struct WebSocketService : OptionSet { public typealias RawValue = UInt var value: UInt = 0 init(_ value: UInt) { self.value = value } public init(rawValue value: UInt) { self.value = value } public init(nilLiteral: ()) { self.value = 0 } public static var allZeros: WebSocketService { return self.init(0) } static func fromMask(_ raw: UInt) -> WebSocketService { return self.init(raw) } public var rawValue: UInt { return self.value } /// No services. public static var None: WebSocketService { return self.init(0) } /// Allow socket to handle VoIP. public static var VoIP: WebSocketService { return self.init(1 << 0) } /// Allow socket to handle video. public static var Video: WebSocketService { return self.init(1 << 1) } /// Allow socket to run in background. public static var Background: WebSocketService { return self.init(1 << 2) } /// Allow socket to handle voice. public static var Voice: WebSocketService { return self.init(1 << 3) } } private let atEndDetails = "streamStatus.atEnd" private let timeoutDetails = "The operation couldn’t be completed. Operation timed out" private let timeoutDuration : CFTimeInterval = 30 public enum WebSocketError : Error, CustomStringConvertible { case memory case needMoreInput case invalidHeader case invalidAddress case network(String) case libraryError(String) case payloadError(String) case protocolError(String) case invalidResponse(String) case invalidCompressionOptions(String) public var description : String { switch self { case .memory: return "Memory" case .needMoreInput: return "NeedMoreInput" case .invalidAddress: return "InvalidAddress" case .invalidHeader: return "InvalidHeader" case let .invalidResponse(details): return "InvalidResponse(\(details))" case let .invalidCompressionOptions(details): return "InvalidCompressionOptions(\(details))" case let .libraryError(details): return "LibraryError(\(details))" case let .protocolError(details): return "ProtocolError(\(details))" case let .payloadError(details): return "PayloadError(\(details))" case let .network(details): return "Network(\(details))" } } public var details : String { switch self { case .invalidResponse(let details): return details case .invalidCompressionOptions(let details): return details case .libraryError(let details): return details case .protocolError(let details): return details case .payloadError(let details): return details case .network(let details): return details default: return "" } } } private class UTF8 { var text : String = "" var count : UInt32 = 0 // number of bytes var procd : UInt32 = 0 // number of bytes processed var codepoint : UInt32 = 0 // the actual codepoint var bcount = 0 init() { text = "" } func append(_ byte : UInt8) throws { if count == 0 { if byte <= 0x7F { text.append(String(UnicodeScalar(byte))) return } if byte == 0xC0 || byte == 0xC1 { throw WebSocketError.payloadError("invalid codepoint: invalid byte") } if byte >> 5 & 0x7 == 0x6 { count = 2 } else if byte >> 4 & 0xF == 0xE { count = 3 } else if byte >> 3 & 0x1F == 0x1E { count = 4 } else { throw WebSocketError.payloadError("invalid codepoint: frames") } procd = 1 codepoint = (UInt32(byte) & (0xFF >> count)) << ((count-1) * 6) return } if byte >> 6 & 0x3 != 0x2 { throw WebSocketError.payloadError("invalid codepoint: signature") } codepoint += UInt32(byte & 0x3F) << ((count-procd-1) * 6) if codepoint > 0x10FFFF || (codepoint >= 0xD800 && codepoint <= 0xDFFF) { throw WebSocketError.payloadError("invalid codepoint: out of bounds") } procd += 1 if procd == count { if codepoint <= 0x7FF && count > 2 { throw WebSocketError.payloadError("invalid codepoint: overlong") } if codepoint <= 0xFFFF && count > 3 { throw WebSocketError.payloadError("invalid codepoint: overlong") } procd = 0 count = 0 text.append(String.init(describing: UnicodeScalar(codepoint)!)) } return } func append(_ bytes : UnsafePointer<UInt8>, length : Int) throws { if length == 0 { return } if count == 0 { var ascii = true for i in 0 ..< length { if bytes[i] > 0x7F { ascii = false break } } if ascii { text += NSString(bytes: bytes, length: length, encoding: String.Encoding.ascii.rawValue)! as String bcount += length return } } for i in 0 ..< length { try append(bytes[i]) } bcount += length } var completed : Bool { return count == 0 } static func bytes(_ string : String) -> [UInt8]{ let data = string.data(using: String.Encoding.utf8)! return [UInt8](UnsafeBufferPointer<UInt8>(start: (data as NSData).bytes.bindMemory(to: UInt8.self, capacity: data.count), count: data.count)) } static func string(_ bytes : [UInt8]) -> String{ if let str = NSString(bytes: bytes, length: bytes.count, encoding: String.Encoding.utf8.rawValue) { return str as String } return "" } } private class Frame { var inflate = false var code = OpCode.continue var utf8 = UTF8() var payload = Payload() var statusCode = UInt16(0) var finished = true static func makeClose(_ statusCode: UInt16, reason: String) -> Frame { let f = Frame() f.code = .close f.statusCode = statusCode f.utf8.text = reason return f } func copy() -> Frame { let f = Frame() f.code = code f.utf8.text = utf8.text f.payload.buffer = payload.buffer f.statusCode = statusCode f.finished = finished f.inflate = inflate return f } } private class Delegate : NSObject, StreamDelegate { @objc func stream(_ aStream: Stream, handle eventCode: Stream.Event){ manager.signal() } } @_silgen_name("zlibVersion") private func zlibVersion() -> OpaquePointer @_silgen_name("deflateInit2_") private func deflateInit2(_ strm : UnsafeMutableRawPointer, level : CInt, method : CInt, windowBits : CInt, memLevel : CInt, strategy : CInt, version : OpaquePointer, stream_size : CInt) -> CInt @_silgen_name("deflateInit_") private func deflateInit(_ strm : UnsafeMutableRawPointer, level : CInt, version : OpaquePointer, stream_size : CInt) -> CInt @_silgen_name("deflateEnd") private func deflateEnd(_ strm : UnsafeMutableRawPointer) -> CInt @_silgen_name("deflate") private func deflate(_ strm : UnsafeMutableRawPointer, flush : CInt) -> CInt @_silgen_name("inflateInit2_") private func inflateInit2(_ strm : UnsafeMutableRawPointer, windowBits : CInt, version : OpaquePointer, stream_size : CInt) -> CInt @_silgen_name("inflateInit_") private func inflateInit(_ strm : UnsafeMutableRawPointer, version : OpaquePointer, stream_size : CInt) -> CInt @_silgen_name("inflate") private func inflateG(_ strm : UnsafeMutableRawPointer, flush : CInt) -> CInt @_silgen_name("inflateEnd") private func inflateEndG(_ strm : UnsafeMutableRawPointer) -> CInt private func zerror(_ res : CInt) -> Error? { var err = "" switch res { case 0: return nil case 1: err = "stream end" case 2: err = "need dict" case -1: err = "errno" case -2: err = "stream error" case -3: err = "data error" case -4: err = "mem error" case -5: err = "buf error" case -6: err = "version error" default: err = "undefined error" } return WebSocketError.payloadError("zlib: \(err): \(res)") } private struct z_stream { var next_in : UnsafePointer<UInt8>? = nil var avail_in : CUnsignedInt = 0 var total_in : CUnsignedLong = 0 var next_out : UnsafeMutablePointer<UInt8>? = nil var avail_out : CUnsignedInt = 0 var total_out : CUnsignedLong = 0 var msg : UnsafePointer<CChar>? = nil var state : OpaquePointer? = nil var zalloc : OpaquePointer? = nil var zfree : OpaquePointer? = nil var opaque : OpaquePointer? = nil var data_type : CInt = 0 var adler : CUnsignedLong = 0 var reserved : CUnsignedLong = 0 } private class Inflater { var windowBits = 0 var strm = z_stream() var tInput = [[UInt8]]() var inflateEnd : [UInt8] = [0x00, 0x00, 0xFF, 0xFF] var bufferSize = windowBufferSize var buffer = malloc(windowBufferSize) init?(windowBits : Int){ if buffer == nil { return nil } self.windowBits = windowBits let ret = inflateInit2(&strm, windowBits: -CInt(windowBits), version: zlibVersion(), stream_size: CInt(MemoryLayout<z_stream>.size)) if ret != 0 { return nil } } deinit{ _ = inflateEndG(&strm) free(buffer) } func inflate(_ bufin : UnsafePointer<UInt8>, length : Int, final : Bool) throws -> (p : UnsafeMutablePointer<UInt8>, n : Int){ var buf = buffer var bufsiz = bufferSize var buflen = 0 for i in 0 ..< 2{ if i == 0 { strm.avail_in = CUnsignedInt(length) strm.next_in = UnsafePointer<UInt8>(bufin) } else { if !final { break } strm.avail_in = CUnsignedInt(inflateEnd.count) strm.next_in = UnsafePointer<UInt8>(inflateEnd) } while true { strm.avail_out = CUnsignedInt(bufsiz) strm.next_out = buf?.assumingMemoryBound(to: UInt8.self) _ = inflateG(&strm, flush: 0) let have = bufsiz - Int(strm.avail_out) bufsiz -= have buflen += have if strm.avail_out != 0{ break } if bufsiz == 0 { bufferSize *= 2 let nbuf = realloc(buffer, bufferSize) if nbuf == nil { throw WebSocketError.payloadError("memory") } buffer = nbuf buf = buffer?.advanced(by: Int(buflen)) bufsiz = bufferSize - buflen } } } return (buffer!.assumingMemoryBound(to: UInt8.self), buflen) } } private class Deflater { var windowBits = 0 var memLevel = 0 var strm = z_stream() var bufferSize = windowBufferSize var buffer = malloc(windowBufferSize) init?(windowBits : Int, memLevel : Int){ if buffer == nil { return nil } self.windowBits = windowBits self.memLevel = memLevel let ret = deflateInit2(&strm, level: 6, method: 8, windowBits: -CInt(windowBits), memLevel: CInt(memLevel), strategy: 0, version: zlibVersion(), stream_size: CInt(MemoryLayout<z_stream>.size)) if ret != 0 { return nil } } deinit{ _ = deflateEnd(&strm) free(buffer) } /*func deflate(_ bufin : UnsafePointer<UInt8>, length : Int, final : Bool) -> (p : UnsafeMutablePointer<UInt8>, n : Int, err : NSError?){ return (nil, 0, nil) }*/ } /// WebSocketDelegate is an Objective-C alternative to WebSocketEvents and is used to delegate the events for the WebSocket connection. @objc public protocol WebSocketDelegate { /// A function to be called when the WebSocket connection's readyState changes to .Open; this indicates that the connection is ready to send and receive data. func webSocketOpen() /// A function to be called when the WebSocket connection's readyState changes to .Closed. func webSocketClose(_ code: Int, reason: String, wasClean: Bool) /// A function to be called when an error occurs. func webSocketError(_ error: NSError) /// A function to be called when a message (string) is received from the server. @objc optional func webSocketMessageText(_ text: String) /// A function to be called when a message (binary) is received from the server. @objc optional func webSocketMessageData(_ data: Data) /// A function to be called when a pong is received from the server. @objc optional func webSocketPong() /// A function to be called when the WebSocket process has ended; this event is guarenteed to be called once and can be used as an alternative to the "close" or "error" events. @objc optional func webSocketEnd(_ code: Int, reason: String, wasClean: Bool, error: NSError?) } /// WebSocket objects are bidirectional network streams that communicate over HTTP. RFC 6455. private class InnerWebSocket: Hashable { var id : Int var mutex = pthread_mutex_t() let request : URLRequest! let subProtocols : [String]! var frames : [Frame] = [] var delegate : Delegate var inflater : Inflater! var deflater : Deflater! var outputBytes : UnsafeMutablePointer<UInt8>? var outputBytesSize : Int = 0 var outputBytesStart : Int = 0 var outputBytesLength : Int = 0 var inputBytes : UnsafeMutablePointer<UInt8>? var inputBytesSize : Int = 0 var inputBytesStart : Int = 0 var inputBytesLength : Int = 0 var createdAt = CFAbsoluteTimeGetCurrent() var connectionTimeout = false var eclose : ()->() = {} var _eventQueue : DispatchQueue? = DispatchQueue.main var _subProtocol = "" var _compression = WebSocketCompression() var _allowSelfSignedSSL = false var _services = WebSocketService.None var _event = WebSocketEvents() var _eventDelegate: WebSocketDelegate? var _binaryType = WebSocketBinaryType.uInt8Array var _readyState = WebSocketReadyState.connecting var _networkTimeout = TimeInterval(-1) var url : String { return request.url!.description } var subProtocol : String { get { return privateSubProtocol } } var privateSubProtocol : String { get { lock(); defer { unlock() }; return _subProtocol } set { lock(); defer { unlock() }; _subProtocol = newValue } } var compression : WebSocketCompression { get { lock(); defer { unlock() }; return _compression } set { lock(); defer { unlock() }; _compression = newValue } } var allowSelfSignedSSL : Bool { get { lock(); defer { unlock() }; return _allowSelfSignedSSL } set { lock(); defer { unlock() }; _allowSelfSignedSSL = newValue } } var services : WebSocketService { get { lock(); defer { unlock() }; return _services } set { lock(); defer { unlock() }; _services = newValue } } var event : WebSocketEvents { get { lock(); defer { unlock() }; return _event } set { lock(); defer { unlock() }; _event = newValue } } var eventDelegate : WebSocketDelegate? { get { lock(); defer { unlock() }; return _eventDelegate } set { lock(); defer { unlock() }; _eventDelegate = newValue } } var eventQueue : DispatchQueue? { get { lock(); defer { unlock() }; return _eventQueue; } set { lock(); defer { unlock() }; _eventQueue = newValue } } var binaryType : WebSocketBinaryType { get { lock(); defer { unlock() }; return _binaryType } set { lock(); defer { unlock() }; _binaryType = newValue } } var readyState : WebSocketReadyState { get { return privateReadyState } } var privateReadyState : WebSocketReadyState { get { lock(); defer { unlock() }; return _readyState } set { lock(); defer { unlock() }; _readyState = newValue } } func copyOpen(_ request: URLRequest, subProtocols : [String] = []) -> InnerWebSocket{ let ws = InnerWebSocket(request: request, subProtocols: subProtocols, stub: false) ws.eclose = eclose ws.compression = compression ws.allowSelfSignedSSL = allowSelfSignedSSL ws.services = services ws.event = event ws.eventQueue = eventQueue ws.binaryType = binaryType return ws } var hashValue: Int { return id } func hash(into hasher: inout Hasher) { hasher.combine(id) } init(request: URLRequest, subProtocols : [String] = [], stub : Bool = false){ pthread_mutex_init(&mutex, nil) self.id = manager.nextId() self.request = request self.subProtocols = subProtocols self.outputBytes = UnsafeMutablePointer<UInt8>.allocate(capacity: windowBufferSize) self.outputBytesSize = windowBufferSize self.inputBytes = UnsafeMutablePointer<UInt8>.allocate(capacity: windowBufferSize) self.inputBytesSize = windowBufferSize self.delegate = Delegate() if stub{ manager.queue.asyncAfter(deadline: DispatchTime.now() + Double(0) / Double(NSEC_PER_SEC)){ _ = self } } else { manager.queue.asyncAfter(deadline: DispatchTime.now() + Double(0) / Double(NSEC_PER_SEC)){ manager.add(self) } } } deinit{ if outputBytes != nil { free(outputBytes) } if inputBytes != nil { free(inputBytes) } pthread_mutex_init(&mutex, nil) } @inline(__always) fileprivate func lock(){ pthread_mutex_lock(&mutex) } @inline(__always) fileprivate func unlock(){ pthread_mutex_unlock(&mutex) } fileprivate var dirty : Bool { lock() defer { unlock() } if exit { return false } if connectionTimeout { return true } if stage != .readResponse && stage != .handleFrames { return true } if rd.streamStatus == .opening && wr.streamStatus == .opening { return false; } if rd.streamStatus != .open || wr.streamStatus != .open { return true } if rd.streamError != nil || wr.streamError != nil { return true } if rd.hasBytesAvailable || frames.count > 0 || inputBytesLength > 0 { return true } if outputBytesLength > 0 && wr.hasSpaceAvailable{ return true } return false } enum Stage : Int { case openConn case readResponse case handleFrames case closeConn case end } var stage = Stage.openConn var rd : InputStream! var wr : OutputStream! var atEnd = false var closeCode = UInt16(0) var closeReason = "" var closeClean = false var closeFinal = false var finalError : Error? var exit = false var more = true func step(){ if exit { return } do { try stepBuffers(more) try stepStreamErrors() more = false switch stage { case .openConn: try openConn() stage = .readResponse case .readResponse: try readResponse() privateReadyState = .open fire { self.event.open() self.eventDelegate?.webSocketOpen() } stage = .handleFrames case .handleFrames: try stepOutputFrames() if closeFinal { privateReadyState = .closing stage = .closeConn return } let frame = try readFrame() switch frame.code { case .text: fire { self.event.message(frame.utf8.text) self.eventDelegate?.webSocketMessageText?(frame.utf8.text) } case .binary: fire { switch self.binaryType { case .uInt8Array: self.event.message(frame.payload.array) case .nsData: self.event.message(frame.payload.nsdata) // The WebSocketDelegate is necessary to add Objective-C compability and it is only possible to send binary data with NSData. self.eventDelegate?.webSocketMessageData?(frame.payload.nsdata) case .uInt8UnsafeBufferPointer: self.event.message(frame.payload.buffer) } } case .ping: let nframe = frame.copy() nframe.code = .pong lock() frames += [nframe] unlock() case .pong: fire { switch self.binaryType { case .uInt8Array: self.event.pong(frame.payload.array) case .nsData: self.event.pong(frame.payload.nsdata) case .uInt8UnsafeBufferPointer: self.event.pong(frame.payload.buffer) } self.eventDelegate?.webSocketPong?() } case .close: lock() frames += [frame] unlock() default: break } case .closeConn: if let error = finalError { self.event.error(error) self.eventDelegate?.webSocketError(error as NSError) } privateReadyState = .closed if rd != nil { closeConn() fire { self.eclose() self.event.close(Int(self.closeCode), self.closeReason, self.closeFinal) self.eventDelegate?.webSocketClose(Int(self.closeCode), reason: self.closeReason, wasClean: self.closeFinal) } } stage = .end case .end: fire { self.event.end(Int(self.closeCode), self.closeReason, self.closeClean, self.finalError) self.eventDelegate?.webSocketEnd?(Int(self.closeCode), reason: self.closeReason, wasClean: self.closeClean, error: self.finalError as NSError?) } exit = true manager.remove(self) } } catch WebSocketError.needMoreInput { more = true } catch { if finalError != nil { return } finalError = error if stage == .openConn || stage == .readResponse { stage = .closeConn } else { var frame : Frame? if let error = error as? WebSocketError{ switch error { case .network(let details): if details == atEndDetails{ stage = .closeConn frame = Frame.makeClose(1006, reason: "Abnormal Closure") atEnd = true finalError = nil } case .protocolError: frame = Frame.makeClose(1002, reason: "Protocol error") case .payloadError: frame = Frame.makeClose(1007, reason: "Payload error") default: break } } if frame == nil { frame = Frame.makeClose(1006, reason: "Abnormal Closure") } if let frame = frame { if frame.statusCode == 1007 { self.lock() self.frames = [frame] self.unlock() manager.signal() } else { manager.queue.asyncAfter(deadline: DispatchTime.now() + Double(0) / Double(NSEC_PER_SEC)){ self.lock() self.frames += [frame] self.unlock() manager.signal() } } } } } } func stepBuffers(_ more: Bool) throws { if rd != nil { if stage != .closeConn && rd.streamStatus == Stream.Status.atEnd { if atEnd { return; } throw WebSocketError.network(atEndDetails) } if more { while rd.hasBytesAvailable { var size = inputBytesSize while size-(inputBytesStart+inputBytesLength) < windowBufferSize { size *= 2 } if size > inputBytesSize { let ptr = realloc(inputBytes, size) if ptr == nil { throw WebSocketError.memory } inputBytes = ptr?.assumingMemoryBound(to: UInt8.self) inputBytesSize = size } let n = rd.read(inputBytes!+inputBytesStart+inputBytesLength, maxLength: inputBytesSize-inputBytesStart-inputBytesLength) if n > 0 { inputBytesLength += n } } } } if wr != nil && wr.hasSpaceAvailable && outputBytesLength > 0 { let n = wr.write(outputBytes!+outputBytesStart, maxLength: outputBytesLength) if n > 0 { outputBytesLength -= n if outputBytesLength == 0 { outputBytesStart = 0 } else { outputBytesStart += n } } } } func stepStreamErrors() throws { if finalError == nil { if connectionTimeout { throw WebSocketError.network(timeoutDetails) } if let error = rd?.streamError { throw WebSocketError.network(error.localizedDescription) } if let error = wr?.streamError { throw WebSocketError.network(error.localizedDescription) } } } func stepOutputFrames() throws { lock() defer { frames = [] unlock() } if !closeFinal { for frame in frames { try writeFrame(frame) if frame.code == .close { closeCode = frame.statusCode closeReason = frame.utf8.text closeFinal = true return } } } } @inline(__always) func fire(_ block: ()->()){ if let queue = eventQueue { queue.sync { block() } } else { block() } } var readStateSaved = false var readStateFrame : Frame? var readStateFinished = false var leaderFrame : Frame? func readFrame() throws -> Frame { var frame : Frame var finished : Bool if !readStateSaved { if leaderFrame != nil { frame = leaderFrame! finished = false leaderFrame = nil } else { frame = try readFrameFragment(nil) finished = frame.finished } if frame.code == .continue{ throw WebSocketError.protocolError("leader frame cannot be a continue frame") } if !finished { readStateSaved = true readStateFrame = frame readStateFinished = finished throw WebSocketError.needMoreInput } } else { frame = readStateFrame! finished = readStateFinished if !finished { let cf = try readFrameFragment(frame) finished = cf.finished if cf.code != .continue { if !cf.code.isControl { throw WebSocketError.protocolError("only ping frames can be interlaced with fragments") } leaderFrame = frame return cf } if !finished { readStateSaved = true readStateFrame = frame readStateFinished = finished throw WebSocketError.needMoreInput } } } if !frame.utf8.completed { throw WebSocketError.payloadError("incomplete utf8") } readStateSaved = false readStateFrame = nil readStateFinished = false return frame } func closeConn() { rd.remove(from: RunLoop.main, forMode: RunLoop.Mode.default) wr.remove(from: RunLoop.main, forMode: RunLoop.Mode.default) rd.delegate = nil wr.delegate = nil rd.close() wr.close() } func openConn() throws { var req = request! req.setValue("websocket", forHTTPHeaderField: "Upgrade") req.setValue("Upgrade", forHTTPHeaderField: "Connection") if req.value(forHTTPHeaderField: "User-Agent") == nil { req.setValue("SwiftWebSocket", forHTTPHeaderField: "User-Agent") } req.setValue("13", forHTTPHeaderField: "Sec-WebSocket-Version") if req.url == nil || req.url!.host == nil{ throw WebSocketError.invalidAddress } if req.url!.port == nil || req.url!.port! == 80 || req.url!.port! == 443 { req.setValue(req.url!.host!, forHTTPHeaderField: "Host") } else { req.setValue("\(req.url!.host!):\(req.url!.port!)", forHTTPHeaderField: "Host") } let origin = req.value(forHTTPHeaderField: "Origin") if origin == nil || origin! == ""{ req.setValue(req.url!.absoluteString, forHTTPHeaderField: "Origin") } if subProtocols.count > 0 { req.setValue(subProtocols.joined(separator: ","), forHTTPHeaderField: "Sec-WebSocket-Protocol") } if req.url!.scheme != "wss" && req.url!.scheme != "ws" { throw WebSocketError.invalidAddress } if compression.on { var val = "permessage-deflate" if compression.noContextTakeover { val += "; client_no_context_takeover; server_no_context_takeover" } val += "; client_max_window_bits" if compression.maxWindowBits != 0 { val += "; server_max_window_bits=\(compression.maxWindowBits)" } req.setValue(val, forHTTPHeaderField: "Sec-WebSocket-Extensions") } let security: TCPConnSecurity let port : Int if req.url!.scheme == "wss" { port = req.url!.port ?? 443 security = .negoticatedSSL } else { port = req.url!.port ?? 80 security = .none } var path = CFURLCopyPath(req.url! as CFURL) as String if path == "" { path = "/" } if let q = req.url!.query { if q != "" { path += "?" + q } } var reqs = "GET \(path) HTTP/1.1\r\n" for key in req.allHTTPHeaderFields!.keys { if let val = req.value(forHTTPHeaderField: key) { reqs += "\(key): \(val)\r\n" } } var keyb = [UInt32](repeating: 0, count: 4) for i in 0 ..< 4 { keyb[i] = arc4random() } let rkey = Data(bytes: UnsafePointer(keyb), count: 16).base64EncodedString(options: NSData.Base64EncodingOptions(rawValue: 0)) reqs += "Sec-WebSocket-Key: \(rkey)\r\n" reqs += "\r\n" var header = [UInt8]() for b in reqs.utf8 { header += [b] } let addr = ["\(req.url!.host!)", "\(port)"] if addr.count != 2 || Int(addr[1]) == nil { throw WebSocketError.invalidAddress } var (rdo, wro) : (InputStream?, OutputStream?) var readStream: Unmanaged<CFReadStream>? var writeStream: Unmanaged<CFWriteStream>? CFStreamCreatePairWithSocketToHost(nil, addr[0] as CFString, UInt32(Int(addr[1])!), &readStream, &writeStream); rdo = readStream!.takeRetainedValue() wro = writeStream!.takeRetainedValue() (rd, wr) = (rdo!, wro!) rd.setProperty(security.level, forKey: Stream.PropertyKey.socketSecurityLevelKey) wr.setProperty(security.level, forKey: Stream.PropertyKey.socketSecurityLevelKey) if services.contains(.VoIP) { rd.setProperty(StreamNetworkServiceTypeValue.voIP.rawValue, forKey: Stream.PropertyKey.networkServiceType) wr.setProperty(StreamNetworkServiceTypeValue.voIP.rawValue, forKey: Stream.PropertyKey.networkServiceType) } if services.contains(.Video) { rd.setProperty(StreamNetworkServiceTypeValue.video.rawValue, forKey: Stream.PropertyKey.networkServiceType) wr.setProperty(StreamNetworkServiceTypeValue.video.rawValue, forKey: Stream.PropertyKey.networkServiceType) } if services.contains(.Background) { rd.setProperty(StreamNetworkServiceTypeValue.background.rawValue, forKey: Stream.PropertyKey.networkServiceType) wr.setProperty(StreamNetworkServiceTypeValue.background.rawValue, forKey: Stream.PropertyKey.networkServiceType) } if services.contains(.Voice) { rd.setProperty(StreamNetworkServiceTypeValue.voice.rawValue, forKey: Stream.PropertyKey.networkServiceType) wr.setProperty(StreamNetworkServiceTypeValue.voice.rawValue, forKey: Stream.PropertyKey.networkServiceType) } if allowSelfSignedSSL { let prop: Dictionary<NSObject,NSObject> = [kCFStreamSSLPeerName: kCFNull, kCFStreamSSLValidatesCertificateChain: NSNumber(value: false)] rd.setProperty(prop, forKey: Stream.PropertyKey(rawValue: kCFStreamPropertySSLSettings as String as String)) wr.setProperty(prop, forKey: Stream.PropertyKey(rawValue: kCFStreamPropertySSLSettings as String as String)) } rd.delegate = delegate wr.delegate = delegate rd.schedule(in: RunLoop.main, forMode: RunLoop.Mode.default) wr.schedule(in: RunLoop.main, forMode: RunLoop.Mode.default) rd.open() wr.open() try write(header, length: header.count) } func write(_ bytes: UnsafePointer<UInt8>, length: Int) throws { if outputBytesStart+outputBytesLength+length > outputBytesSize { var size = outputBytesSize while outputBytesStart+outputBytesLength+length > size { size *= 2 } let ptr = realloc(outputBytes, size) if ptr == nil { throw WebSocketError.memory } outputBytes = ptr?.assumingMemoryBound(to: UInt8.self) outputBytesSize = size } memcpy(outputBytes!+outputBytesStart+outputBytesLength, bytes, length) outputBytesLength += length } func readResponse() throws { let end : [UInt8] = [ 0x0D, 0x0A, 0x0D, 0x0A ] let ptr = memmem(inputBytes!+inputBytesStart, inputBytesLength, end, 4) if ptr == nil { throw WebSocketError.needMoreInput } let buffer = inputBytes!+inputBytesStart let bufferCount = ptr!.assumingMemoryBound(to: UInt8.self)-(inputBytes!+inputBytesStart) let string = NSString(bytesNoCopy: buffer, length: bufferCount, encoding: String.Encoding.utf8.rawValue, freeWhenDone: false) as String? if string == nil { throw WebSocketError.invalidHeader } let header = string! var needsCompression = false var serverMaxWindowBits = 15 let clientMaxWindowBits = 15 var key = "" let trim : (String)->(String) = { (text) in return text.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)} let eqval : (String,String)->(String) = { (line, del) in return trim(line.components(separatedBy: del)[1]) } let lines = header.components(separatedBy: "\r\n") for i in 0 ..< lines.count { let line = trim(lines[i]) if i == 0 { if !line.hasPrefix("HTTP/1.1 101"){ throw WebSocketError.invalidResponse(line) } } else if line != "" { var value = "" if line.hasPrefix("\t") || line.hasPrefix(" ") { value = trim(line) } else { key = "" if let r = line.range(of: ":") { key = trim(String(line[..<r.lowerBound])) value = trim(String(line[r.upperBound...])) } } switch key.lowercased() { case "sec-websocket-subprotocol": privateSubProtocol = value case "sec-websocket-extensions": let parts = value.components(separatedBy: ";") for p in parts { let part = trim(p) if part == "permessage-deflate" { needsCompression = true } else if part.hasPrefix("server_max_window_bits="){ if let i = Int(eqval(line, "=")) { serverMaxWindowBits = i } } } default: break } } } if needsCompression { if serverMaxWindowBits < 8 || serverMaxWindowBits > 15 { throw WebSocketError.invalidCompressionOptions("server_max_window_bits") } if serverMaxWindowBits < 8 || serverMaxWindowBits > 15 { throw WebSocketError.invalidCompressionOptions("client_max_window_bits") } inflater = Inflater(windowBits: serverMaxWindowBits) if inflater == nil { throw WebSocketError.invalidCompressionOptions("inflater init") } deflater = Deflater(windowBits: clientMaxWindowBits, memLevel: 8) if deflater == nil { throw WebSocketError.invalidCompressionOptions("deflater init") } } inputBytesLength -= bufferCount+4 if inputBytesLength == 0 { inputBytesStart = 0 } else { inputBytesStart += bufferCount+4 } } class ByteReader { var start : UnsafePointer<UInt8> var end : UnsafePointer<UInt8> var bytes : UnsafePointer<UInt8> init(bytes: UnsafePointer<UInt8>, length: Int){ self.bytes = bytes start = bytes end = bytes+length } func readByte() throws -> UInt8 { if bytes >= end { throw WebSocketError.needMoreInput } let b = bytes.pointee bytes += 1 return b } var length : Int { return end - bytes } var position : Int { get { return bytes - start } set { bytes = start + newValue } } } var fragStateSaved = false var fragStatePosition = 0 var fragStateInflate = false var fragStateLen = 0 var fragStateFin = false var fragStateCode = OpCode.continue var fragStateLeaderCode = OpCode.continue var fragStateUTF8 = UTF8() var fragStatePayload = Payload() var fragStateStatusCode = UInt16(0) var fragStateHeaderLen = 0 var buffer = [UInt8](repeating: 0, count: windowBufferSize) var reusedPayload = Payload() func readFrameFragment(_ leader : Frame?) throws -> Frame { var inflate : Bool var len : Int var fin = false var code : OpCode var leaderCode : OpCode var utf8 : UTF8 var payload : Payload var statusCode : UInt16 var headerLen : Int var leader = leader let reader = ByteReader(bytes: inputBytes!+inputBytesStart, length: inputBytesLength) if fragStateSaved { // load state reader.position += fragStatePosition inflate = fragStateInflate len = fragStateLen fin = fragStateFin code = fragStateCode leaderCode = fragStateLeaderCode utf8 = fragStateUTF8 payload = fragStatePayload statusCode = fragStateStatusCode headerLen = fragStateHeaderLen fragStateSaved = false } else { var b = try reader.readByte() fin = b >> 7 & 0x1 == 0x1 let rsv1 = b >> 6 & 0x1 == 0x1 let rsv2 = b >> 5 & 0x1 == 0x1 let rsv3 = b >> 4 & 0x1 == 0x1 if inflater != nil && (rsv1 || (leader != nil && leader!.inflate)) { inflate = true } else if rsv1 || rsv2 || rsv3 { throw WebSocketError.protocolError("invalid extension") } else { inflate = false } code = OpCode.binary if let c = OpCode(rawValue: (b & 0xF)){ code = c } else { throw WebSocketError.protocolError("invalid opcode") } if !fin && code.isControl { throw WebSocketError.protocolError("unfinished control frame") } b = try reader.readByte() if b >> 7 & 0x1 == 0x1 { throw WebSocketError.protocolError("server sent masked frame") } var len64 = Int64(b & 0x7F) var bcount = 0 if b & 0x7F == 126 { bcount = 2 } else if len64 == 127 { bcount = 8 } if bcount != 0 { if code.isControl { throw WebSocketError.protocolError("invalid payload size for control frame") } len64 = 0 var i = bcount-1 while i >= 0 { b = try reader.readByte() len64 += Int64(b) << Int64(i*8) i -= 1 } } len = Int(len64) if code == .continue { if code.isControl { throw WebSocketError.protocolError("control frame cannot have the 'continue' opcode") } if leader == nil { throw WebSocketError.protocolError("continue frame is missing it's leader") } } if code.isControl { if leader != nil { leader = nil } if inflate { throw WebSocketError.protocolError("control frame cannot be compressed") } } statusCode = 0 if leader != nil { leaderCode = leader!.code utf8 = leader!.utf8 payload = leader!.payload } else { leaderCode = code utf8 = UTF8() payload = reusedPayload payload.count = 0 } if leaderCode == .close { if len == 1 { throw WebSocketError.protocolError("invalid payload size for close frame") } if len >= 2 { let b1 = try reader.readByte() let b2 = try reader.readByte() statusCode = (UInt16(b1) << 8) + UInt16(b2) len -= 2 if statusCode < 1000 || statusCode > 4999 || (statusCode >= 1004 && statusCode <= 1006) || (statusCode >= 1012 && statusCode <= 2999) { throw WebSocketError.protocolError("invalid status code for close frame") } } } headerLen = reader.position } let rlen : Int let rfin : Bool let chopped : Bool if reader.length+reader.position-headerLen < len { rlen = reader.length rfin = false chopped = true } else { rlen = len-reader.position+headerLen rfin = fin chopped = false } let bytes : UnsafeMutablePointer<UInt8> let bytesLen : Int if inflate { (bytes, bytesLen) = try inflater!.inflate(reader.bytes, length: rlen, final: rfin) } else { (bytes, bytesLen) = (UnsafeMutablePointer<UInt8>.init(mutating: reader.bytes), rlen) } reader.bytes += rlen if leaderCode == .text || leaderCode == .close { try utf8.append(bytes, length: bytesLen) } else { payload.append(bytes, length: bytesLen) } if chopped { // save state fragStateHeaderLen = headerLen fragStateStatusCode = statusCode fragStatePayload = payload fragStateUTF8 = utf8 fragStateLeaderCode = leaderCode fragStateCode = code fragStateFin = fin fragStateLen = len fragStateInflate = inflate fragStatePosition = reader.position fragStateSaved = true throw WebSocketError.needMoreInput } inputBytesLength -= reader.position if inputBytesLength == 0 { inputBytesStart = 0 } else { inputBytesStart += reader.position } let f = Frame() (f.code, f.payload, f.utf8, f.statusCode, f.inflate, f.finished) = (code, payload, utf8, statusCode, inflate, fin) return f } var head = [UInt8](repeating: 0, count: 0xFF) func writeFrame(_ f : Frame) throws { if !f.finished{ throw WebSocketError.libraryError("cannot send unfinished frames") } var hlen = 0 let b : UInt8 = 0x80 var deflate = false if deflater != nil { if f.code == .binary || f.code == .text { deflate = true // b |= 0x40 } } head[hlen] = b | f.code.rawValue hlen += 1 var payloadBytes : [UInt8] var payloadLen = 0 if f.utf8.text != "" { payloadBytes = UTF8.bytes(f.utf8.text) } else { payloadBytes = f.payload.array } payloadLen += payloadBytes.count if deflate { } var usingStatusCode = false if f.statusCode != 0 && payloadLen != 0 { payloadLen += 2 usingStatusCode = true } if payloadLen < 126 { head[hlen] = 0x80 | UInt8(payloadLen) hlen += 1 } else if payloadLen <= 0xFFFF { head[hlen] = 0x80 | 126 hlen += 1 var i = 1 while i >= 0 { head[hlen] = UInt8((UInt16(payloadLen) >> UInt16(i*8)) & 0xFF) hlen += 1 i -= 1 } } else { head[hlen] = UInt8((0x1 << 7) + 127) hlen += 1 var i = 7 while i >= 0 { head[hlen] = UInt8((UInt64(payloadLen) >> UInt64(i*8)) & 0xFF) hlen += 1 i -= 1 } } let r = arc4random() var maskBytes : [UInt8] = [UInt8(r >> 0 & 0xFF), UInt8(r >> 8 & 0xFF), UInt8(r >> 16 & 0xFF), UInt8(r >> 24 & 0xFF)] for i in 0 ..< 4 { head[hlen] = maskBytes[i] hlen += 1 } if payloadLen > 0 { if usingStatusCode { var sc = [UInt8(f.statusCode >> 8 & 0xFF), UInt8(f.statusCode >> 0 & 0xFF)] for i in 0 ..< 2 { sc[i] ^= maskBytes[i % 4] } head[hlen] = sc[0] hlen += 1 head[hlen] = sc[1] hlen += 1 for i in 2 ..< payloadLen { payloadBytes[i-2] ^= maskBytes[i % 4] } } else { for i in 0 ..< payloadLen { payloadBytes[i] ^= maskBytes[i % 4] } } } try write(head, length: hlen) try write(payloadBytes, length: payloadBytes.count) } func close(_ code : Int = 1000, reason : String = "Normal Closure") { let f = Frame() f.code = .close f.statusCode = UInt16(truncatingIfNeeded: code) f.utf8.text = reason sendFrame(f) } func sendFrame(_ f : Frame) { lock() frames += [f] unlock() manager.signal() } func send(_ message : Any) { let f = Frame() if let message = message as? String { f.code = .text f.utf8.text = message } else if let message = message as? [UInt8] { f.code = .binary f.payload.array = message } else if let message = message as? UnsafeBufferPointer<UInt8> { f.code = .binary f.payload.append(message.baseAddress!, length: message.count) } else if let message = message as? Data { f.code = .binary f.payload.nsdata = message } else { f.code = .text f.utf8.text = "\(message)" } sendFrame(f) } func ping() { let f = Frame() f.code = .ping sendFrame(f) } func ping(_ message : Any){ let f = Frame() f.code = .ping if let message = message as? String { f.payload.array = UTF8.bytes(message) } else if let message = message as? [UInt8] { f.payload.array = message } else if let message = message as? UnsafeBufferPointer<UInt8> { f.payload.append(message.baseAddress!, length: message.count) } else if let message = message as? Data { f.payload.nsdata = message } else { f.utf8.text = "\(message)" } sendFrame(f) } } private func ==(lhs: InnerWebSocket, rhs: InnerWebSocket) -> Bool { return lhs.id == rhs.id } private enum TCPConnSecurity { case none case negoticatedSSL var level: String { switch self { case .none: return StreamSocketSecurityLevel.none.rawValue case .negoticatedSSL: return StreamSocketSecurityLevel.negotiatedSSL.rawValue } } } // Manager class is used to minimize the number of dispatches and cycle through network events // using fewers threads. Helps tremendously with lowing system resources when many conncurrent // sockets are opened. private class Manager { var queue = DispatchQueue(label: "SwiftWebSocketInstance", attributes: []) var once = Int() var mutex = pthread_mutex_t() var cond = pthread_cond_t() var websockets = Set<InnerWebSocket>() var _nextId = 0 init(){ pthread_mutex_init(&mutex, nil) pthread_cond_init(&cond, nil) DispatchQueue(label: "SwiftWebSocket", attributes: []).async { var wss : [InnerWebSocket] = [] while true { var wait = true wss.removeAll() pthread_mutex_lock(&self.mutex) for ws in self.websockets { wss.append(ws) } for ws in wss { self.checkForConnectionTimeout(ws) if ws.dirty { pthread_mutex_unlock(&self.mutex) ws.step() pthread_mutex_lock(&self.mutex) wait = false } } if wait { _ = self.wait(250) } pthread_mutex_unlock(&self.mutex) } } } func checkForConnectionTimeout(_ ws : InnerWebSocket) { if ws.rd != nil && ws.wr != nil && (ws.rd.streamStatus == .opening || ws.wr.streamStatus == .opening) { let age = CFAbsoluteTimeGetCurrent() - ws.createdAt if age >= timeoutDuration { ws.connectionTimeout = true } } } func wait(_ timeInMs : Int) -> Int32 { var ts = timespec() var tv = timeval() gettimeofday(&tv, nil) ts.tv_sec = time(nil) + timeInMs / 1000; let v1 = Int(tv.tv_usec * 1000) let v2 = Int(1000 * 1000 * Int(timeInMs % 1000)) ts.tv_nsec = v1 + v2; ts.tv_sec += ts.tv_nsec / (1000 * 1000 * 1000); ts.tv_nsec %= (1000 * 1000 * 1000); return pthread_cond_timedwait(&self.cond, &self.mutex, &ts) } func signal(){ pthread_mutex_lock(&mutex) pthread_cond_signal(&cond) pthread_mutex_unlock(&mutex) } func add(_ websocket: InnerWebSocket) { pthread_mutex_lock(&mutex) websockets.insert(websocket) pthread_cond_signal(&cond) pthread_mutex_unlock(&mutex) } func remove(_ websocket: InnerWebSocket) { pthread_mutex_lock(&mutex) websockets.remove(websocket) pthread_cond_signal(&cond) pthread_mutex_unlock(&mutex) } func nextId() -> Int { pthread_mutex_lock(&mutex) defer { pthread_mutex_unlock(&mutex) } _nextId += 1 return _nextId } } private let manager = Manager() /// WebSocket objects are bidirectional network streams that communicate over HTTP. RFC 6455. @objcMembers open class WebSocket: NSObject { fileprivate var ws: InnerWebSocket fileprivate var id = manager.nextId() fileprivate var opened: Bool open override var hash: Int { return id } open override func isEqual(_ other: Any?) -> Bool { guard let other = other as? WebSocket else { return false } return self.id == other.id } /// Create a WebSocket connection to a URL; this should be the URL to which the WebSocket server will respond. public convenience init(_ url: String){ self.init(request: URLRequest(url: URL(string: url)!), subProtocols: []) } /// Create a WebSocket connection to a URL; this should be the URL to which the WebSocket server will respond. public convenience init(url: URL){ self.init(request: URLRequest(url: url), subProtocols: []) } /// Create a WebSocket connection to a URL; this should be the URL to which the WebSocket server will respond. Also include a list of protocols. public convenience init(_ url: String, subProtocols : [String]){ self.init(request: URLRequest(url: URL(string: url)!), subProtocols: subProtocols) } /// Create a WebSocket connection to a URL; this should be the URL to which the WebSocket server will respond. Also include a protocol. public convenience init(_ url: String, subProtocol : String){ self.init(request: URLRequest(url: URL(string: url)!), subProtocols: [subProtocol]) } /// Create a WebSocket connection from an NSURLRequest; Also include a list of protocols. public init(request: URLRequest, subProtocols : [String] = []){ let hasURL = request.url != nil opened = hasURL ws = InnerWebSocket(request: request, subProtocols: subProtocols, stub: !hasURL) super.init() // weak/strong pattern from: // http://stackoverflow.com/a/17105368/424124 // https://dhoerl.wordpress.com/2013/04/23/i-finally-figured-out-weakself-and-strongself/ ws.eclose = { [weak self] in if let strongSelf = self { strongSelf.opened = false } } } /// Create a WebSocket object with a deferred connection; the connection is not opened until the .open() method is called. public convenience override init(){ var request = URLRequest(url: URL(string: "http://apple.com")!) request.url = nil self.init(request: request, subProtocols: []) } /// The URL as resolved by the constructor. This is always an absolute URL. Read only. open var url : String{ return ws.url } /// A string indicating the name of the sub-protocol the server selected; this will be one of the strings specified in the protocols parameter when creating the WebSocket object. open var subProtocol : String{ return ws.subProtocol } /// The compression options of the WebSocket. open var compression : WebSocketCompression{ get { return ws.compression } set { ws.compression = newValue } } /// Allow for Self-Signed SSL Certificates. Default is false. open var allowSelfSignedSSL : Bool{ get { return ws.allowSelfSignedSSL } set { ws.allowSelfSignedSSL = newValue } } /// The services of the WebSocket. open var services : WebSocketService{ get { return ws.services } set { ws.services = newValue } } /// The events of the WebSocket. open var event : WebSocketEvents{ get { return ws.event } set { ws.event = newValue } } /// The queue for firing off events. default is main_queue open var eventQueue : DispatchQueue?{ get { return ws.eventQueue } set { ws.eventQueue = newValue } } /// A WebSocketBinaryType value indicating the type of binary data being transmitted by the connection. Default is .UInt8Array. open var binaryType : WebSocketBinaryType{ get { return ws.binaryType } set { ws.binaryType = newValue } } /// The current state of the connection; this is one of the WebSocketReadyState constants. Read only. open var readyState : WebSocketReadyState{ return ws.readyState } /// Opens a deferred or closed WebSocket connection to a URL; this should be the URL to which the WebSocket server will respond. open func open(_ url: String){ open(request: URLRequest(url: URL(string: url)!), subProtocols: []) } /// Opens a deferred or closed WebSocket connection to a URL; this should be the URL to which the WebSocket server will respond. open func open(nsurl url: URL){ open(request: URLRequest(url: url), subProtocols: []) } /// Opens a deferred or closed WebSocket connection to a URL; this should be the URL to which the WebSocket server will respond. Also include a list of protocols. open func open(_ url: String, subProtocols : [String]){ open(request: URLRequest(url: URL(string: url)!), subProtocols: subProtocols) } /// Opens a deferred or closed WebSocket connection to a URL; this should be the URL to which the WebSocket server will respond. Also include a protocol. open func open(_ url: String, subProtocol : String){ open(request: URLRequest(url: URL(string: url)!), subProtocols: [subProtocol]) } /// Opens a deferred or closed WebSocket connection from an NSURLRequest; Also include a list of protocols. open func open(request: URLRequest, subProtocols : [String] = []){ if opened{ return } opened = true ws = ws.copyOpen(request, subProtocols: subProtocols) } /// Opens a closed WebSocket connection from an NSURLRequest; Uses the same request and protocols as previously closed WebSocket open func open(){ open(request: ws.request, subProtocols: ws.subProtocols) } /** Closes the WebSocket connection or connection attempt, if any. If the connection is already closed or in the state of closing, this method does nothing. :param: code An integer indicating the status code explaining why the connection is being closed. If this parameter is not specified, a default value of 1000 (indicating a normal closure) is assumed. :param: reason A human-readable string explaining why the connection is closing. This string must be no longer than 123 bytes of UTF-8 text (not characters). */ open func close(_ code : Int = 1000, reason : String = "Normal Closure"){ if !opened{ return } opened = false ws.close(code, reason: reason) } /** Transmits message to the server over the WebSocket connection. :param: message The message to be sent to the server. */ open func send(_ message : Any){ if !opened{ return } ws.send(message) } /** Transmits a ping to the server over the WebSocket connection. :param: optional message The data to be sent to the server. */ open func ping(_ message : Any){ if !opened{ return } ws.ping(message) } /** Transmits a ping to the server over the WebSocket connection. */ open func ping(){ if !opened{ return } ws.ping() } } public func ==(lhs: WebSocket, rhs: WebSocket) -> Bool { return lhs.id == rhs.id } extension WebSocket { /// The events of the WebSocket using a delegate. @objc public var delegate : WebSocketDelegate? { get { return ws.eventDelegate } set { ws.eventDelegate = newValue } } /** Transmits message to the server over the WebSocket connection. :param: text The message (string) to be sent to the server. */ @objc public func send(text: String){ send(text) } /** Transmits message to the server over the WebSocket connection. :param: data The message (binary) to be sent to the server. */ @objc public func send(data: Data){ send(data) } }
mit
db8d53e241509973b06d68f8a5c4e733
36.493218
225
0.55288
4.936067
false
false
false
false
fvaldez/score_point_ios
scorePoint/LeaderBoardVC.swift
1
3064
// // LeaderBoardVC.swift // scorePoint // // Created by Adriana Gonzalez on 3/10/16. // Copyright © 2016 Adriana Gonzalez. All rights reserved. // import UIKit class LeaderBoardVC: UIViewController, UITableViewDataSource, UITableViewDelegate { var playersArray = ["Some Player", "Some Player", "Some Player", "Some Player"] @IBOutlet weak var searchBar: UISearchBar! @IBOutlet weak var tableView: UITableView! override func viewWillAppear(_ animated: Bool) { self.title = "Leaderboard" self.tabBarItem.title = "" } override func viewWillDisappear(_ animated: Bool) { self.title = "" } override func viewDidLoad() { super.viewDidLoad() self.tabBarItem.title = "" let backView = UIView(frame: self.tableView.bounds) backView.backgroundColor = UIColor.clear self.tableView.backgroundView = backView tableView.delegate = self tableView.dataSource = self let nibName = UINib(nibName: "RankCell", bundle:nil) self.tableView.register(nibName, forCellReuseIdentifier: "RankCell") searchBar.searchBarStyle = .minimal searchBar.isUserInteractionEnabled = false searchBar.backgroundColor = UIColor.white } func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return playersArray.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { // For testing purposes var name = "" switch(indexPath.row){ case 0: name = "badge-4" case 1: name = "badge-3" case 2: name = "badge-2" default: name = "badge-1" } let player = playersArray[indexPath.row] if let cell = tableView.dequeueReusableCell(withIdentifier: "RankCell") as? RankCell { cell.configureCell(player) cell.badgeImg.image = UIImage(named: name) cell.rankLbl.text = "\(indexPath.row+1)" cell.selectionStyle = .none return cell }else { let cell = RankCell() cell.badgeImg.image = UIImage(named: name) cell.rankLbl.text = "\(indexPath.row+1)" cell.configureCell(player) cell.selectionStyle = .none return cell } } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 80.0 } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let storyboard = UIStoryboard(name: "Main", bundle: nil) let vc = storyboard.instantiateViewController(withIdentifier: "VersusVC") self.navigationController?.pushViewController(vc, animated: true) //self.presentViewController(vc, animated: true, completion: nil) } }
mit
3d8103ea68a848987edde1c3f442a965
30.57732
100
0.617369
4.916533
false
false
false
false
eKasztany/4ania
ios/Queue/Pods/R.swift.Library/Library/Core/ColorResource.swift
3
1059
// // ColorResource.swift // R.swift.Library // // Created by Tom Lokhorst on 2016-03-13. // Copyright © 2016 Mathijs Kadijk. All rights reserved. // import Foundation public protocol ColorResourceType { /// Name of the color var name: String { get } /// Red componenent of color var red: CGFloat { get } /// Green componenent of color var green: CGFloat { get } /// Blue componenent of color var blue: CGFloat { get } /// Alpha componenent of color var alpha: CGFloat { get } } public struct ColorResource: ColorResourceType { /// Name of the color public let name: String /// Red componenent of color public let red: CGFloat /// Green componenent of color public let green: CGFloat /// Blue componenent of color public let blue: CGFloat /// Alpha componenent of color public let alpha: CGFloat public init(name: String, red: CGFloat, green: CGFloat, blue: CGFloat, alpha: CGFloat) { self.name = name self.red = red self.green = green self.blue = blue self.alpha = alpha } }
apache-2.0
9572dc8e22499010826c410f06efdab6
18.962264
90
0.672023
4.069231
false
false
false
false
bandit412/SwiftCodeCollection
MathUtilities/Math.swift
1
1498
// // Math.swift // MathUtilities // // Created by Allan Anderson on 07/11/2014. // Copyright (c) 2014 Allan Anderson. All rights reserved. // import Cocoa /* Some basic math functions */ func greatestCommonDenominator (_ numerator:Double, denominator:Double) -> Double{ if denominator != 0{ if numerator.truncatingRemainder(dividingBy: denominator) == 0{ return denominator } else { return greatestCommonDenominator(denominator, denominator: numerator.truncatingRemainder(dividingBy: denominator)) } } else { return Double.infinity } } func toDegrees (_ radians:Double) -> Double{ return radians * 180 / .pi } func toRadians (_ degrees:Double) -> Double{ return degrees * .pi / 180 } func quadraticPositive(_ a:Double, b:Double, c:Double) -> Double{ let b2 = b * b let ac4 = 4 * a * c let a2 = 2 * a let root = b2 - ac4 return (-1 * b + sqrt(root)) / a2 } func quadraticNegative(_ a:Double, b:Double, c:Double) -> Double{ let b2 = b * b let ac4 = 4 * a * c let a2 = 2 * a let root = b2 - ac4 return (-1 * b - sqrt(root)) / a2 } func createArray(_ rows:Int, columns:Int) -> [[Double]]{ var array2D = Array<Array<Double>>() for _ in 0...rows - 1 { array2D.append(Array(repeating: Double(), count: columns)) } for row in 0...rows - 1{ for _col in 0...columns - 1{ array2D[row][_col] = 0.0 } } return array2D }
gpl-3.0
61aceae69827a536982c6593b7c07bf0
22.40625
126
0.595461
3.483721
false
false
false
false
Eflet/Charts
ChartsRealm/Classes/Data/RealmScatterDataSet.swift
4
1612
// // RealmScatterDataSet.swift // Charts // // Created by Daniel Cohen Gindi on 23/2/15. // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/Charts // import Foundation import CoreGraphics import Charts import Realm import Realm.Dynamic public class RealmScatterDataSet: RealmLineScatterCandleRadarDataSet, IScatterChartDataSet { // The size the scatter shape will have public var scatterShapeSize = CGFloat(15.0) // The type of shape that is set to be drawn where the values are at // **default**: .Square public var scatterShape = ScatterChartDataSet.Shape.Square // The radius of the hole in the shape (applies to Square, Circle and Triangle) // **default**: 0.0 public var scatterShapeHoleRadius: CGFloat = 0.0 // Color for the hole in the shape. Setting to `nil` will behave as transparent. // **default**: nil public var scatterShapeHoleColor: NSUIColor? = nil // Custom path object to draw where the values are at. // This is used when shape is set to Custom. public var customScatterShape: CGPath? public override func initialize() { } // MARK: NSCopying public override func copyWithZone(zone: NSZone) -> AnyObject { let copy = super.copyWithZone(zone) as! RealmScatterDataSet copy.scatterShapeSize = scatterShapeSize copy.scatterShape = scatterShape copy.customScatterShape = customScatterShape return copy } }
apache-2.0
fd97d566c66b161bcd04438343ff1cce
26.338983
90
0.687965
4.71345
false
false
false
false
kingloveyy/SwiftBlog
SwiftBlog/SwiftBlog/Classes/UI/Main/MainTabBar.swift
1
1952
// // MainTabBar.swift // SwiftBlog // // Created by King on 15/3/19. // Copyright (c) 2015年 king. All rights reserved. // import UIKit class MainTabBar: UITabBar { /// 定义撰写微博按钮回调 var composeButtonClicked: (() -> ())? override func awakeFromNib() { super.awakeFromNib() self.addSubview(composeBtn!) } override func layoutSubviews() { super.layoutSubviews() setButtonFrame() } /// 设置按钮位子 func setButtonFrame() { let buttonCount = 5 let w = self.bounds.size.width / CGFloat(buttonCount) let h = self.bounds.size.height var index = 0 for view in self.subviews as! [UIView] { if view is UIControl && !(view is UIButton) { let frame = CGRectMake(w * CGFloat(index), 0, w, h) view.frame = frame index++ } if index == 2 { index++ } } composeBtn?.frame = CGRectMake(0, 0, w, h) composeBtn?.center = CGPointMake(self.center.x, h * 0.5) } lazy var composeBtn: UIButton? = { let btn = UIButton() btn.setImage(UIImage(named: "tabbar_compose_icon_add"), forState: UIControlState.Normal) btn.setImage(UIImage(named: "tabbar_compose_icon_add_highlighted"), forState: UIControlState.Highlighted) btn.setBackgroundImage(UIImage(named: "tabbar_compose_button"), forState: UIControlState.Normal) btn.setBackgroundImage(UIImage(named: "tabbar_compose_button_highlighted"), forState: UIControlState.Highlighted) btn.addTarget(self, action: "composeClick", forControlEvents: .TouchUpInside) return btn }() func composeClick() { if composeButtonClicked != nil { composeButtonClicked!() } } }
mit
2f118a595c92fbf57b09fe0d3452319a
26.797101
121
0.566215
4.577566
false
false
false
false
wilfreddekok/Antidote
Antidote/StringExtension.swift
1
2554
// 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 extension String { init(timeInterval: NSTimeInterval) { var timeInterval = timeInterval let hours = Int(timeInterval / 3600) timeInterval -= NSTimeInterval(hours * 3600) let minutes = Int(timeInterval / 60) timeInterval -= NSTimeInterval(minutes * 60) let seconds = Int(timeInterval) if hours > 0 { self.init(format: "%02d:%02d:%02d", hours, minutes, seconds) } else { self.init(format: "%02d:%02d", minutes, seconds) } } init(localized: String, _ arguments: CVarArgType...) { let format = NSLocalizedString(localized, tableName: nil, bundle: NSBundle.mainBundle(), value: "", comment: "") self.init(format: format, arguments: arguments) } init(localized: String, comment: String, _ arguments: CVarArgType...) { let format = NSLocalizedString(localized, tableName: nil, bundle: NSBundle.mainBundle(), value: "", comment: comment) self.init(format: format, arguments: arguments) } func substringToByteLength(length: Int, encoding: NSStringEncoding) -> String { guard length > 0 else { return "" } var substring = self as NSString while substring.lengthOfBytesUsingEncoding(encoding) > length { let newLength = substring.length - 1 guard newLength > 0 else { return "" } substring = substring.substringToIndex(newLength) } return substring as String } func stringSizeWithFont(font: UIFont) -> CGSize { return stringSizeWithFont(font, constrainedToSize:CGSize(width: CGFloat.max, height: CGFloat.max)) } func stringSizeWithFont(font: UIFont, constrainedToSize size: CGSize) -> CGSize { let boundingRect = (self as NSString).boundingRectWithSize( size, options: .UsesLineFragmentOrigin, attributes: [NSFontAttributeName : font], context: nil) return CGSize(width: ceil(boundingRect.size.width), height: ceil(boundingRect.size.height)) } subscript (r: Range<Int>) -> String { let start = startIndex.advancedBy(r.startIndex) let end = start.advancedBy(r.endIndex - r.startIndex) return self[start ..< end] } }
mpl-2.0
08e0d63b09a96b0f04ffe28402045d66
32.605263
125
0.62686
4.720887
false
false
false
false
OlegNovosad/Severenity
iOS/Severenity/Services/HealthService.swift
2
4613
// // HealthKitService.swift // Severenity // // Created by Yuriy Yasinskyy on 02.11.16. // Copyright © 2016 severenity. All rights reserved. // import UIKit import HealthKit class HealthService: NSObject { static let sharedInstance = HealthService() private var healthStore: HKHealthStore? // MARK: Init private override init() { super.init() if HKHealthStore.isHealthDataAvailable() { healthStore = HKHealthStore() var readTypes = Set<HKObjectType>() readTypes.insert(HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier.stepCount)!) readTypes.insert(HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier.distanceWalkingRunning)!) healthStore?.requestAuthorization(toShare: nil, read: readTypes) { (success, error) -> Void in if success { Log.info(message: "HealthKit authorized succesfully", sender: self) } else { Log.error(message: "HealthKit authorization failed: \(error)", sender: self) } } } else { Log.info(message: "HealthKit is not available", sender: self) } Log.info(message: "HealthKitService shared instance init did complete", sender: self) } // MARK: Methods for getting data from HealthKit func retrieveStepsCount(startDate: Date, endDate: Date, completion: @escaping (_ stepsRetrieved: Double) -> Void) { // Define the Step Quantity Type let stepsCount = HKQuantityType.quantityType(forIdentifier: HKQuantityTypeIdentifier.stepCount) // Set the Predicates & Interval let predicate = HKQuery.predicateForSamples(withStart: startDate, end: endDate, options: .strictStartDate) var interval = DateComponents() interval.day = 1 // Perform the Query let query = HKStatisticsCollectionQuery(quantityType: stepsCount!, quantitySamplePredicate: predicate, options: [.cumulativeSum], anchorDate: startDate, intervalComponents: interval) query.initialResultsHandler = { query, results, error in if error != nil { Log.error(message: "Cannot retrieve HealthKit steps data: \(error)", sender: self) return } if let myResults = results { var stepsCount = 0.0 myResults.enumerateStatistics(from: startDate, to: endDate) { statistics, stop in if let quantity = statistics.sumQuantity() { let steps = quantity.doubleValue(for: HKUnit.count()) stepsCount += steps } } completion(stepsCount) } } healthStore?.execute(query) } func retrieveWalkRunDistance(startDate: Date, endDate: Date, completion: @escaping (_ distanceRetrieved: Double) -> Void) { // Define the Distance Quantity Type let distance = HKQuantityType.quantityType(forIdentifier: HKQuantityTypeIdentifier.distanceWalkingRunning) // Set the Predicates & Interval let predicate = HKQuery.predicateForSamples(withStart: startDate, end: endDate, options: .strictStartDate) var interval = DateComponents() interval.day = 1 // Perform the Query let query = HKStatisticsCollectionQuery(quantityType: distance!, quantitySamplePredicate: predicate, options: [.cumulativeSum], anchorDate: startDate, intervalComponents: interval) query.initialResultsHandler = { query, results, error in if error != nil { Log.error(message: "Cannot retrieve HealthKit distance data: \(error)", sender: self) return } if let myResults = results { var totalDistance = 0.0 myResults.enumerateStatistics(from: startDate, to: endDate) { statistics, stop in if let quantity = statistics.sumQuantity() { let distance = quantity.doubleValue(for: HKUnit.mile()) totalDistance += distance } } completion(totalDistance) } } healthStore?.execute(query) } }
apache-2.0
a9cf0446db725c97709662e449112341
40.178571
127
0.579141
5.651961
false
false
false
false
Great-Li-Xin/Xcode
Apple Product Selector/Apple Product Selector/InformationViewController.swift
1
725
// // InformationViewController.swift // Apple Product Selector // // Created by 李欣 on 2017/9/23. // Copyright © 2017年 李欣. All rights reserved. // import Cocoa class InformationViewController: NSViewController { @IBOutlet weak var titleLabel: NSTextField! @IBOutlet weak var contentLabel: NSTextField! @IBOutlet weak var imageViewer: NSImageView! var _title = " " var _content = " " var _image = NSImage(named: NSImage.Name(rawValue: "")) override func viewDidLoad() { super.viewDidLoad() self.titleLabel.stringValue = _title self.contentLabel.stringValue = _content self.imageViewer!.image! = _image! // Do view setup here. } }
mit
01c91f29d7e02ecf9717309b4950b17f
24.5
59
0.659664
4.2
false
false
false
false
lorentey/GlueKit
Sources/ObservableSet.swift
1
8363
// // ObservableSet.swift // GlueKit // // Created by Károly Lőrentey on 2016-08-12. // Copyright © 2015–2017 Károly Lőrentey. // public typealias SetUpdate<Element: Hashable> = Update<SetChange<Element>> public typealias SetUpdateSource<Element: Hashable> = AnySource<Update<SetChange<Element>>> public protocol ObservableSetType: ObservableType where Change == SetChange<Element> { associatedtype Element typealias Base = Set<Element> var isBuffered: Bool { get } var count: Int { get } var value: Set<Element> { get } func contains(_ member: Element) -> Bool func isSubset(of other: Set<Element>) -> Bool func isSuperset(of other: Set<Element>) -> Bool var observableCount: AnyObservableValue<Int> { get } var anyObservableValue: AnyObservableValue<Base> { get } var anyObservableSet: AnyObservableSet<Element> { get } } extension ObservableSetType { public var isBuffered: Bool { return false } public var count: Int { return value.count } public func contains(_ member: Element) -> Bool { return value.contains(member) } public func isSubset(of other: Set<Element>) -> Bool { return value.isSubset(of: other) } public func isSuperset(of other: Set<Element>) -> Bool { return value.isSuperset(of: other) } public var isEmpty: Bool { return count == 0 } internal var valueUpdates: AnySource<ValueUpdate<Set<Element>>> { var value = self.value return self.updates.map { event in event.map { change in let old = value value.apply(change) return ValueChange(from: old, to: value) } }.buffered() } internal var countUpdates: AnySource<ValueUpdate<Int>> { var count = self.count return self.updates.map { update in update.map { change in let old = count count += numericCast(change.inserted.count - change.removed.count) return .init(from: old, to: count) } }.buffered() } public var observableCount: AnyObservableValue<Int> { return AnyObservableValue(getter: { self.count }, updates: self.countUpdates) } public var anyObservableValue: AnyObservableValue<Base> { return AnyObservableValue(getter: { self.value }, updates: self.valueUpdates) } public var anyObservableSet: AnyObservableSet<Element> { return AnyObservableSet(box: ObservableSetBox(self)) } } public struct AnyObservableSet<Element: Hashable>: ObservableSetType { public typealias Base = Set<Element> public typealias Change = SetChange<Element> let box: _AbstractObservableSet<Element> init(box: _AbstractObservableSet<Element>) { self.box = box } public var isBuffered: Bool { return box.isBuffered } public var count: Int { return box.count } public var value: Set<Element> { return box.value } public func contains(_ member: Element) -> Bool { return box.contains(member) } public func isSubset(of other: Set<Element>) -> Bool { return box.isSubset(of: other) } public func isSuperset(of other: Set<Element>) -> Bool { return box.isSuperset(of: other) } public func add<Sink: SinkType>(_ sink: Sink) where Sink.Value == Update<Change> { box.add(sink) } @discardableResult public func remove<Sink: SinkType>(_ sink: Sink) -> Sink where Sink.Value == Update<Change> { return box.remove(sink) } public var observableCount: AnyObservableValue<Int> { return box.observableCount } public var anyObservableValue: AnyObservableValue<Set<Element>> { return box.anyObservableValue } public var anyObservableSet: AnyObservableSet<Element> { return self } } open class _AbstractObservableSet<Element: Hashable>: ObservableSetType { public typealias Change = SetChange<Element> open var value: Set<Element> { abstract() } open func add<Sink: SinkType>(_ sink: Sink) where Sink.Value == Update<SetChange<Element>> { abstract() } @discardableResult open func remove<Sink: SinkType>(_ sink: Sink) -> Sink where Sink.Value == Update<SetChange<Element>> { abstract() } open var isBuffered: Bool { return false } open var count: Int { return value.count } open func contains(_ member: Element) -> Bool { return value.contains(member) } open func isSubset(of other: Set<Element>) -> Bool { return value.isSubset(of: other) } open func isSuperset(of other: Set<Element>) -> Bool { return value.isSuperset(of: other) } open var observableCount: AnyObservableValue<Int> { return AnyObservableValue(getter: { self.count }, updates: self.countUpdates) } open var anyObservableValue: AnyObservableValue<Set<Element>> { return AnyObservableValue(getter: { self.value }, updates: self.valueUpdates) } public final var anyObservableSet: AnyObservableSet<Element> { return AnyObservableSet(box: self) } } open class _BaseObservableSet<Element: Hashable>: _AbstractObservableSet<Element>, TransactionalThing { var _signal: TransactionalSignal<SetChange<Element>>? = nil var _transactionCount = 0 public final override func add<Sink: SinkType>(_ sink: Sink) where Sink.Value == Update<SetChange<Element>> { signal.add(sink) } @discardableResult public final override func remove<Sink: SinkType>(_ sink: Sink) -> Sink where Sink.Value == Update<SetChange<Element>> { return signal.remove(sink) } func activate() { // Do nothing } func deactivate() { // Do nothing } } final class ObservableSetBox<Contents: ObservableSetType>: _AbstractObservableSet<Contents.Element> { typealias Element = Contents.Element let contents: Contents init(_ contents: Contents) { self.contents = contents } override var isBuffered: Bool { return contents.isBuffered } override var count: Int { return contents.count } override var value: Set<Element> { return contents.value } override func contains(_ member: Element) -> Bool { return contents.contains(member) } override func isSubset(of other: Set<Element>) -> Bool { return contents.isSubset(of: other) } override func isSuperset(of other: Set<Element>) -> Bool { return contents.isSuperset(of: other) } override func add<Sink: SinkType>(_ sink: Sink) where Sink.Value == Update<SetChange<Element>> { contents.add(sink) } @discardableResult override func remove<Sink: SinkType>(_ sink: Sink) -> Sink where Sink.Value == Update<SetChange<Element>> { return contents.remove(sink) } override var observableCount: AnyObservableValue<Int> { return contents.observableCount } override var anyObservableValue: AnyObservableValue<Set<Element>> { return contents.anyObservableValue } } class ObservableConstantSet<Element: Hashable>: _AbstractObservableSet<Element> { let contents: Set<Element> init(_ contents: Set<Element>) { self.contents = contents } override var isBuffered: Bool { return true } override var count: Int { return contents.count } override var value: Set<Element> { return contents } override func contains(_ member: Element) -> Bool { return contents.contains(member) } override func isSubset(of other: Set<Element>) -> Bool { return contents.isSubset(of: other) } override func isSuperset(of other: Set<Element>) -> Bool { return contents.isSuperset(of: other) } override func add<Sink: SinkType>(_ sink: Sink) where Sink.Value == Update<SetChange<Element>> { // Do nothing } @discardableResult override func remove<Sink: SinkType>(_ sink: Sink) -> Sink where Sink.Value == Update<SetChange<Element>> { return sink } override var observableCount: AnyObservableValue<Int> { return AnyObservableValue.constant(contents.count) } override var anyObservableValue: AnyObservableValue<Set<Element>> { return AnyObservableValue.constant(contents) } } extension ObservableSetType { public static func constant(_ value: Set<Element>) -> AnyObservableSet<Element> { return ObservableConstantSet(value).anyObservableSet } public static func emptyConstant() -> AnyObservableSet<Element> { return constant([]) } }
mit
2f8dc8deeb3838e4117aab81ef3ab9b7
36.470852
124
0.684418
4.556161
false
false
false
false
wrutkowski/Lucid-Weather-Clock
Pods/Charts/Charts/Classes/Components/ChartLegend.swift
6
21518
// // ChartLegend.swift // Charts // // Created by Daniel Cohen Gindi on 24/2/15. // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/Charts // import Foundation import CoreGraphics #if !os(OSX) import UIKit #endif open class ChartLegend: ChartComponentBase { /// This property is deprecated - Use `position`, `horizontalAlignment`, `verticalAlignment`, `orientation`, `drawInside`, `direction`. @available(*, deprecated:1.0, message:"Use `position`, `horizontalAlignment`, `verticalAlignment`, `orientation`, `drawInside`, `direction`.") @objc(ChartLegendPosition) public enum Position: Int { case rightOfChart case rightOfChartCenter case rightOfChartInside case leftOfChart case leftOfChartCenter case leftOfChartInside case belowChartLeft case belowChartRight case belowChartCenter case aboveChartLeft case aboveChartRight case aboveChartCenter case piechartCenter } @objc(ChartLegendForm) public enum Form: Int { case square case circle case line } @objc(ChartLegendHorizontalAlignment) public enum HorizontalAlignment: Int { case left case center case right } @objc(ChartLegendVerticalAlignment) public enum VerticalAlignment: Int { case top case center case bottom } @objc(ChartLegendOrientation) public enum Orientation: Int { case horizontal case vertical } @objc(ChartLegendDirection) public enum Direction: Int { case leftToRight case rightToLeft } /// the legend colors array, each color is for the form drawn at the same index open var colors = [NSUIColor?]() // the legend text array. a nil label will start a group. open var labels = [String?]() internal var _extraColors = [NSUIColor?]() internal var _extraLabels = [String?]() /// colors that will be appended to the end of the colors array after calculating the legend. open var extraColors: [NSUIColor?] { return _extraColors; } /// labels that will be appended to the end of the labels array after calculating the legend. a nil label will start a group. open var extraLabels: [String?] { return _extraLabels; } /// Are the legend labels/colors a custom value or auto calculated? If false, then it's auto, if true, then custom. /// /// **default**: false (automatic legend) private var _isLegendCustom = false /// This property is deprecated - Use `position`, `horizontalAlignment`, `verticalAlignment`, `orientation`, `drawInside`, `direction`. @available(*, deprecated:1.0, message:"Use `position`, `horizontalAlignment`, `verticalAlignment`, `orientation`, `drawInside`, `direction`.") open var position: Position { get { if orientation == .vertical && horizontalAlignment == .center && verticalAlignment == .center { return .piechartCenter } else if orientation == .horizontal { if verticalAlignment == .top { return horizontalAlignment == .left ? .aboveChartLeft : (horizontalAlignment == .right ? .aboveChartRight : .aboveChartCenter) } else { return horizontalAlignment == .left ? .belowChartLeft : (horizontalAlignment == .right ? .belowChartRight : .belowChartCenter) } } else { if horizontalAlignment == .left { return verticalAlignment == .top && drawInside ? .leftOfChartInside : (verticalAlignment == .center ? .leftOfChartCenter : .leftOfChart) } else { return verticalAlignment == .top && drawInside ? .rightOfChartInside : (verticalAlignment == .center ? .rightOfChartCenter : .rightOfChart) } } } set { switch newValue { case .leftOfChart: fallthrough case .leftOfChartInside: fallthrough case .leftOfChartCenter: horizontalAlignment = .left verticalAlignment = newValue == .leftOfChartCenter ? .center : .top orientation = .vertical case .rightOfChart: fallthrough case .rightOfChartInside: fallthrough case .rightOfChartCenter: horizontalAlignment = .right verticalAlignment = newValue == .rightOfChartCenter ? .center : .top orientation = .vertical case .aboveChartLeft: fallthrough case .aboveChartCenter: fallthrough case .aboveChartRight: horizontalAlignment = newValue == .aboveChartLeft ? .left : (newValue == .aboveChartRight ? .right : .center) verticalAlignment = .top orientation = .horizontal case .belowChartLeft: fallthrough case .belowChartCenter: fallthrough case .belowChartRight: horizontalAlignment = newValue == .belowChartLeft ? .left : (newValue == .belowChartRight ? .right : .center) verticalAlignment = .bottom orientation = .horizontal case .piechartCenter: horizontalAlignment = .center verticalAlignment = .center orientation = .vertical } drawInside = newValue == .leftOfChartInside || newValue == .rightOfChartInside } } /// The horizontal alignment of the legend open var horizontalAlignment: HorizontalAlignment = HorizontalAlignment.left /// The vertical alignment of the legend open var verticalAlignment: VerticalAlignment = VerticalAlignment.bottom /// The orientation of the legend open var orientation: Orientation = Orientation.horizontal /// Flag indicating whether the legend will draw inside the chart or outside open var drawInside: Bool = false /// Flag indicating whether the legend will draw inside the chart or outside open var isDrawInsideEnabled: Bool { return drawInside } /// The text direction of the legend open var direction: Direction = Direction.leftToRight open var font: NSUIFont = NSUIFont.systemFont(ofSize: 10.0) open var textColor = NSUIColor.black open var form = Form.square open var formSize = CGFloat(8.0) open var formLineWidth = CGFloat(1.5) open var xEntrySpace = CGFloat(6.0) open var yEntrySpace = CGFloat(0.0) open var formToTextSpace = CGFloat(5.0) open var stackSpace = CGFloat(3.0) open var calculatedLabelSizes = [CGSize]() open var calculatedLabelBreakPoints = [Bool]() open var calculatedLineSizes = [CGSize]() public override init() { super.init() self.xOffset = 5.0 self.yOffset = 3.0 } public init(colors: [NSUIColor?], labels: [String?]) { super.init() self.colors = colors self.labels = labels } public init(colors: [NSObject], labels: [NSObject]) { super.init() self.colorsObjc = colors self.labelsObjc = labels } open func getMaximumEntrySize(_ font: NSUIFont) -> CGSize { var maxW = CGFloat(0.0) var maxH = CGFloat(0.0) var labels = self.labels for i in 0 ..< labels.count { if (labels[i] == nil) { continue } let size = (labels[i] as NSString!).size(attributes: [NSFontAttributeName: font]) if (size.width > maxW) { maxW = size.width } if (size.height > maxH) { maxH = size.height } } return CGSize( width: maxW + formSize + formToTextSpace, height: maxH ) } open func getLabel(_ index: Int) -> String? { return labels[index] } /// This function is deprecated - Please read `neededWidth`/`neededHeight` after `calculateDimensions` was called. @available(*, deprecated:1.0, message:"Please read `neededWidth`/`neededHeight` after `calculateDimensions` was called.") open func getFullSize(_ labelFont: NSUIFont) -> CGSize { return CGSize(width: neededWidth, height: neededHeight) } open var neededWidth = CGFloat(0.0) open var neededHeight = CGFloat(0.0) open var textWidthMax = CGFloat(0.0) open var textHeightMax = CGFloat(0.0) /// flag that indicates if word wrapping is enabled /// this is currently supported only for `orientation == Horizontal`. /// you may want to set maxSizePercent when word wrapping, to set the point where the text wraps. /// /// **default**: false open var wordWrapEnabled = true /// The maximum relative size out of the whole chart view in percent. /// If the legend is to the right/left of the chart, then this affects the width of the legend. /// If the legend is to the top/bottom of the chart, then this affects the height of the legend. /// /// **default**: 0.95 (95%) open var maxSizePercent: CGFloat = 0.95 open func calculateDimensions(labelFont: NSUIFont, viewPortHandler: ChartViewPortHandler) { let maxEntrySize = getMaximumEntrySize(labelFont) textWidthMax = maxEntrySize.width textHeightMax = maxEntrySize.height switch orientation { case .vertical: var maxWidth = CGFloat(0.0) var width = CGFloat(0.0) var maxHeight = CGFloat(0.0) let labelLineHeight = labelFont.lineHeight var labels = self.labels let count = labels.count var wasStacked = false for i in 0 ..< count { let drawingForm = colors[i] != nil if !wasStacked { width = 0.0 } if drawingForm { if wasStacked { width += stackSpace } width += formSize } if labels[i] != nil { let size = (labels[i] as NSString!).size(attributes: [NSFontAttributeName: labelFont]) if drawingForm && !wasStacked { width += formToTextSpace } else if wasStacked { maxWidth = max(maxWidth, width) maxHeight += labelLineHeight + yEntrySpace width = 0.0 wasStacked = false } width += size.width if (i < count - 1) { maxHeight += labelLineHeight + yEntrySpace } } else { wasStacked = true width += formSize if (i < count - 1) { width += stackSpace } } maxWidth = max(maxWidth, width) } neededWidth = maxWidth neededHeight = maxHeight case .horizontal: var labels = self.labels var colors = self.colors let labelCount = labels.count let labelLineHeight = labelFont.lineHeight let formSize = self.formSize let formToTextSpace = self.formToTextSpace let xEntrySpace = self.xEntrySpace let stackSpace = self.stackSpace let wordWrapEnabled = self.wordWrapEnabled let contentWidth: CGFloat = viewPortHandler.contentWidth * maxSizePercent // Prepare arrays for calculated layout if (calculatedLabelSizes.count != labelCount) { calculatedLabelSizes = [CGSize](repeating: CGSize(), count: labelCount) } if (calculatedLabelBreakPoints.count != labelCount) { calculatedLabelBreakPoints = [Bool](repeating: false, count: labelCount) } calculatedLineSizes.removeAll(keepingCapacity: true) // Start calculating layout let labelAttrs = [NSFontAttributeName: labelFont] var maxLineWidth: CGFloat = 0.0 var currentLineWidth: CGFloat = 0.0 var requiredWidth: CGFloat = 0.0 var stackedStartIndex: Int = -1 for i in 0 ..< labelCount { let drawingForm = colors[i] != nil calculatedLabelBreakPoints[i] = false if (stackedStartIndex == -1) { // we are not stacking, so required width is for this label only requiredWidth = 0.0 } else { // add the spacing appropriate for stacked labels/forms requiredWidth += stackSpace } // grouped forms have null labels if (labels[i] != nil) { calculatedLabelSizes[i] = (labels[i] as NSString!).size(attributes: labelAttrs) requiredWidth += drawingForm ? formToTextSpace + formSize : 0.0 requiredWidth += calculatedLabelSizes[i].width } else { calculatedLabelSizes[i] = CGSize() requiredWidth += drawingForm ? formSize : 0.0 if (stackedStartIndex == -1) { // mark this index as we might want to break here later stackedStartIndex = i } } if (labels[i] != nil || i == labelCount - 1) { let requiredSpacing = currentLineWidth == 0.0 ? 0.0 : xEntrySpace if (!wordWrapEnabled || // No word wrapping, it must fit. currentLineWidth == 0.0 || // The line is empty, it must fit. (contentWidth - currentLineWidth >= requiredSpacing + requiredWidth)) // It simply fits { // Expand current line currentLineWidth += requiredSpacing + requiredWidth } else { // It doesn't fit, we need to wrap a line // Add current line size to array calculatedLineSizes.append(CGSize(width: currentLineWidth, height: labelLineHeight)) maxLineWidth = max(maxLineWidth, currentLineWidth) // Start a new line calculatedLabelBreakPoints[stackedStartIndex > -1 ? stackedStartIndex : i] = true currentLineWidth = requiredWidth } if (i == labelCount - 1) { // Add last line size to array calculatedLineSizes.append(CGSize(width: currentLineWidth, height: labelLineHeight)) maxLineWidth = max(maxLineWidth, currentLineWidth) } } stackedStartIndex = labels[i] != nil ? -1 : stackedStartIndex } neededWidth = maxLineWidth neededHeight = labelLineHeight * CGFloat(calculatedLineSizes.count) + yEntrySpace * CGFloat(calculatedLineSizes.count == 0 ? 0 : (calculatedLineSizes.count - 1)) } } /// MARK: - Custom legend /// colors and labels that will be appended to the end of the auto calculated colors and labels after calculating the legend. /// (if the legend has already been calculated, you will need to call notifyDataSetChanged() to let the changes take effect) open func setExtra(colors: [NSUIColor?], labels: [String?]) { self._extraLabels = labels self._extraColors = colors } /// Sets a custom legend's labels and colors arrays. /// The colors count should match the labels count. /// * Each color is for the form drawn at the same index. /// * A nil label will start a group. /// * A nil color will avoid drawing a form, and a clearColor will leave a space for the form. /// This will disable the feature that automatically calculates the legend labels and colors from the datasets. /// Call `resetCustom(...)` to re-enable automatic calculation (and then `notifyDataSetChanged()` is needed). open func setCustom(colors: [NSUIColor?], labels: [String?]) { self.labels = labels self.colors = colors _isLegendCustom = true } /// Calling this will disable the custom legend labels (set by `setLegend(...)`). Instead, the labels will again be calculated automatically (after `notifyDataSetChanged()` is called). open func resetCustom() { _isLegendCustom = false } /// **default**: false (automatic legend) /// - returns: true if a custom legend labels and colors has been set open var isLegendCustom: Bool { return _isLegendCustom } /// MARK: - ObjC compatibility /// colors that will be appended to the end of the colors array after calculating the legend. open var extraColorsObjc: [NSObject] { return ChartUtils.bridgedObjCGetNSUIColorArray(swift: _extraColors); } /// labels that will be appended to the end of the labels array after calculating the legend. a nil label will start a group. open var extraLabelsObjc: [NSObject] { return ChartUtils.bridgedObjCGetStringArray(swift: _extraLabels); } /// the legend colors array, each color is for the form drawn at the same index /// (ObjC bridging functions, as Swift 1.2 does not bridge optionals in array to `NSNull`s) open var colorsObjc: [NSObject] { get { return ChartUtils.bridgedObjCGetNSUIColorArray(swift: colors); } set { self.colors = ChartUtils.bridgedObjCGetNSUIColorArray(objc: newValue); } } // the legend text array. a nil label will start a group. /// (ObjC bridging functions, as Swift 1.2 does not bridge optionals in array to `NSNull`s) open var labelsObjc: [NSObject] { get { return ChartUtils.bridgedObjCGetStringArray(swift: labels); } set { self.labels = ChartUtils.bridgedObjCGetStringArray(objc: newValue); } } /// colors and labels that will be appended to the end of the auto calculated colors and labels after calculating the legend. /// (if the legend has already been calculated, you will need to call `notifyDataSetChanged()` to let the changes take effect) open func setExtra(colors: [NSObject], labels: [NSObject]) { if (colors.count != labels.count) { fatalError("ChartLegend:setExtra() - colors array and labels array need to be of same size") } self._extraLabels = ChartUtils.bridgedObjCGetStringArray(objc: labels) self._extraColors = ChartUtils.bridgedObjCGetNSUIColorArray(objc: colors) } /// Sets a custom legend's labels and colors arrays. /// The colors count should match the labels count. /// * Each color is for the form drawn at the same index. /// * A nil label will start a group. /// * A nil color will avoid drawing a form, and a clearColor will leave a space for the form. /// This will disable the feature that automatically calculates the legend labels and colors from the datasets. /// Call `resetLegendToAuto(...)` to re-enable automatic calculation, and then if needed - call `notifyDataSetChanged()` on the chart to make it refresh the data. open func setCustom(colors: [NSObject], labels: [NSObject]) { if (colors.count != labels.count) { fatalError("ChartLegend:setCustom() - colors array and labels array need to be of same size") } self.labelsObjc = labels self.colorsObjc = colors _isLegendCustom = true } }
mit
641ae12f0e92626ae7b2dd0edc227bab
36.292894
188
0.555628
5.700132
false
false
false
false
moonknightskye/Luna
Luna/AR_BETA.swift
1
12683
// // AR.swift // Luna // // Created by Mart Civil on 2018/02/24. // Copyright © 2018年 salesforce.com. All rights reserved. // import Foundation import ARKit class AR_BETA { static let instance:AR_BETA = AR_BETA() var sceneView: ARSCNView! var touchpoint:ARHitTestResult? var ACCOUNT_ID:String? var PRIVATE_KEY:String? var MODEL_ID:String? init() {} func addClose() { let text:String = "" let font = UIFont(name: "HelveticaNeue-Thin", size: CGFloat(32)) let width = 100.0 let height = 100.0 let fontAttrs: [NSAttributedStringKey: Any] = [NSAttributedStringKey.font: font as Any] let renderer = UIGraphicsImageRenderer(size: CGSize(width: CGFloat(width), height: CGFloat(height))) let image = renderer.image { context in let color = UIColor.red.withAlphaComponent(CGFloat(0.75)) let rect = CGRect(x: (width * 0),y: (height * 0),width: (width * 1),height: (height * 1)) color.setFill() context.fill(rect) context.cgContext.setStrokeColor(UIColor.white.cgColor) text.draw(with: rect, options: .usesLineFragmentOrigin, attributes: fontAttrs, context: nil) } let box = SCNBox(width: 0.05, height: 0.05, length: 0.05, chamferRadius: 0) box.firstMaterial?.diffuse.contents = image //let plane = SCNPlane(width: 0.05, height: 0.05) //plane.firstMaterial?.diffuse.contents = image let node = SCNNode(geometry: box) node.position = SCNVector3(0, 0.03, -0.4) node.name = "CLOSE" sceneView.scene.rootNode.addChildNode(node) } func add3dClose() { let text = SCNText(string: "Tap box to Close", extrusionDepth: 1) let material = SCNMaterial() material.diffuse.contents = UIColor.red text.materials = [material] let node = SCNNode() node.position = SCNVector3(x:-0.1, y:-0.03, z:-0.4) node.scale = SCNVector3(x:0.002, y:0.002, z:0.002) node.geometry = text node.name = "CLOSE" sceneView.scene.rootNode.addChildNode(node) } func add3dText() { let text = SCNText(string: "Tap anywhere to predict image", extrusionDepth: 1) let material = SCNMaterial() material.diffuse.contents = UIColor.gray text.materials = [material] let node = SCNNode() node.position = SCNVector3(x:-0.18, y:-0.07, z:-0.55) node.scale = SCNVector3(x:0.002, y:0.002, z:0.002) node.geometry = text node.name = "3DTEXT" sceneView.scene.rootNode.addChildNode(node) } func getNode( text:String?="Hello, Stack Overflow." ) -> SCNNode{ //let text = "Hello, Stack Overflow." let font = UIFont(name: "HelveticaNeue-Thin", size: CGFloat(16)) let width = 200.0 let height = 200.0 let fontAttrs: [NSAttributedStringKey: Any] = [NSAttributedStringKey.font: font as Any] let renderer = UIGraphicsImageRenderer(size: CGSize(width: CGFloat(width), height: CGFloat(height))) let image = renderer.image { context in let color = UIColor.gray.withAlphaComponent(CGFloat(0.75)) let rect = CGRect(x: (width * 0.5),y: (height * 0.5),width: (width * 0.5),height: (height * 0.5)) color.setFill() context.fill(rect) context.cgContext.setStrokeColor(UIColor.white.cgColor) text!.draw(with: rect, options: .usesLineFragmentOrigin, attributes: fontAttrs, context: nil) } let plane = SCNPlane(width: CGFloat(0.15), height: CGFloat(0.15)) plane.firstMaterial?.diffuse.contents = image let node = SCNNode(geometry: plane) node.name = "EINSTEIN" return node } func addTapGestureToSceneView() { let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(self.didTap(withGestureRecognizer:))) sceneView.addGestureRecognizer(tapGestureRecognizer) } func run(accountId:String?=nil, privateKey:String?=nil, modelId:String?=nil) { sceneView = ARSCNView(frame:UIScreen.main.bounds) sceneView.alpha = 0 sceneView.frame.origin.y = 40 add3dClose() addClose() add3dText() addTapGestureToSceneView() let configuration = ARWorldTrackingConfiguration() sceneView.session.run(configuration) ACCOUNT_ID = accountId PRIVATE_KEY = privateKey MODEL_ID = modelId Shared.shared.ViewController.view.addSubview(sceneView) UIView.animate(withDuration: 0.4, delay: 1.0, options: UIViewAnimationOptions.curveEaseInOut, animations: { self.sceneView.alpha = 1 self.sceneView.frame.origin.y = 0 }, completion: { finished in}) } func pause() { sceneView.session.pause() } func addPlane() { let paths = FileManager.default.urls( for: .documentDirectory, in: .userDomainMask ) let url = URL( string:paths[0].absoluteString + "arasset/ship.scn") var scene2:SCNScene! do { scene2 = try SCNScene(url: url!, options:nil) sceneView.scene = scene2 } catch{} } func addBox() { //let box = SCNBox(width: 0.05, height: 0.05, length: 0.05, chamferRadius: 0) //let pyramid = SCNPyramid(width: 0.1, height: 0.1, length: 0.1) let plain = SCNPlane(width: 0.05, height: 0.05) //plain.insertMaterial(SCNMaterial, at: <#T##Int#>) let boxNode = SCNNode() boxNode.geometry = plain boxNode.position = SCNVector3(0, 0, -0.2) boxNode.name = "CLOSE" sceneView.scene.rootNode.addChildNode(boxNode) //sceneView.scene.a } func addBox(x: Float = 0, y: Float = 0, z: Float = -0.2) { let hapticParameter = NSMutableDictionary() hapticParameter.setValue( "medium", forKey: "type") let hapticSuccess = Command( commandCode: CommandCode.HAPTIC_FEEDBACK, parameter: hapticParameter, priority: .CRITICAL ) CommandProcessor.queue(command: hapticSuccess) let rotate = simd_float4x4(SCNMatrix4MakeRotation(sceneView.session.currentFrame!.camera.eulerAngles.y, 0, 1, 0)) let rotateTransform = simd_mul(touchpoint!.worldTransform, rotate) //node.position = SCNVector3(x:-0.15, y:-0.07, z:-0.45) let node3 = self.getNode( text: "Thinking..." ) node3.transform = SCNMatrix4(rotateTransform) node3.position = SCNVector3((x - 0.035), (y + 0.035), z) self.sceneView.scene.rootNode.addChildNode(node3) let generateEinsteinLabel = { (label: String) -> () in let node = self.getNode( text: label) node.transform = SCNMatrix4(rotateTransform) node.position = SCNVector3((x - 0.035), (y + 0.035), z) // // Create a LookAt constraint, point at the cameras POV // let constraint = SCNLookAtConstraint(target: self.sceneView.pointOfView) // // Keep the rotation on the horizon // constraint.isGimbalLockEnabled = true // // Slow the constraint down a bit // constraint.influenceFactor = 0.01 // // Finally add the constraint to the node // node.constraints = [constraint] self.sceneView.scene.rootNode.addChildNode(node) node3.removeFromParentNode() } snap( onSuccess: { imageFile in EinsteinAuth.instance.getToken(accountId: self.ACCOUNT_ID, privateKey: self.PRIVATE_KEY, onSuccess: { (token) in let execute = { base64val in EinsteinVision.instance.predict(token: token, modelId: self.MODEL_ID, base64: base64val, onSuccess: { (results) in if let probabilities = results.value(forKey: "probabilities") as? [NSDictionary] { let probability = probabilities[0] as NSDictionary let label = probability.value(forKey: "label") as! String var prob = probability.value(forKey: "probability") as! Double prob = round(prob * 100) generateEinsteinLabel( String(prob) + "%" + " " + label ) hapticParameter.setValue( "success", forKey: "type") let hapticSuccess = Command( commandCode: CommandCode.HAPTIC_FEEDBACK, parameter: hapticParameter, priority: .CRITICAL ) CommandProcessor.queue(command: hapticSuccess) } }, onFail: { (errorMessage) in print(errorMessage) generateEinsteinLabel( errorMessage ) hapticParameter.setValue( "error", forKey: "type") let hapticSuccess = Command( commandCode: CommandCode.HAPTIC_FEEDBACK, parameter: hapticParameter, priority: .CRITICAL ) CommandProcessor.queue(command: hapticSuccess) }) } EinsteinVision.instance.preprocessImage(imageFile: imageFile, onSuccess: { (base64) in execute( base64 ) }, onError: { (errorMessage) in generateEinsteinLabel( errorMessage ) hapticParameter.setValue( "error", forKey: "type") let hapticSuccess = Command( commandCode: CommandCode.HAPTIC_FEEDBACK, parameter: hapticParameter, priority: .CRITICAL ) CommandProcessor.queue(command: hapticSuccess) }) //print( imageFile.getFileName()! + " was generated" ) }, onFail: { (error) in print(error) }) }) } func snap(onSuccess:((ImageFile)->())?=nil, onFail:((String)->())?=nil) { do { let imageFile = try ImageFile(fileId: File.generateID(), uiimage: sceneView.snapshot(), savePath: SystemFilePath.CACHE.rawValue) onSuccess?( imageFile ) } catch let error as NSError { print(error) onFail?( error.localizedDescription ) } } @objc func didTap(withGestureRecognizer recognizer: UIGestureRecognizer) { let hapticParameter = NSMutableDictionary() let tapLocation = recognizer.location(in: sceneView) let hitTestResults = sceneView.hitTest(tapLocation) guard let node = hitTestResults.first?.node else { let hitTestResultsWithFeaturePoints = sceneView.hitTest(tapLocation, types: .featurePoint) if let hitTestResultWithFeaturePoints = hitTestResultsWithFeaturePoints.first { touchpoint = hitTestResultsWithFeaturePoints.first let translation = hitTestResultWithFeaturePoints.worldTransform.translation addBox(x: translation.x, y: translation.y, z: translation.z) } return } guard let name = node.name else { return } if name == "EINSTEIN" { hapticParameter.setValue( "medium", forKey: "type") let hapticSuccess = Command( commandCode: CommandCode.HAPTIC_FEEDBACK, parameter: hapticParameter, priority: .CRITICAL ) CommandProcessor.queue(command: hapticSuccess) node.removeFromParentNode() } else { hapticParameter.setValue( "error", forKey: "type") let hapticSuccess = Command( commandCode: CommandCode.HAPTIC_FEEDBACK, parameter: hapticParameter, priority: .CRITICAL ) CommandProcessor.queue(command: hapticSuccess) UIView.animate(withDuration: 0.4, delay: 0, options: UIViewAnimationOptions.curveEaseInOut, animations: { self.sceneView.alpha = 0 self.sceneView.frame.origin.y = 40 }, completion: { finished in self.sceneView.session.pause() self.sceneView.removeFromSuperview() }) } } } extension float4x4 { var translation: float3 { let translation = self.columns.3 return float3(translation.x, translation.y, translation.z) } }
gpl-3.0
3abb93109491620403eff4126eb9f5a4
40.57377
148
0.586514
4.653211
false
false
false
false
skerkewitz/SwignalR
SwignalR/Classes/Connection.swift
1
15334
// // Connection.swift // SignalR // // Created by Alex Billingsley on 10/17/11. // Copyright (c) 2011 DyKnow LLC. (http://dyknow.com/) // Created by Stefan Kerkewitz on 01/03/2017. // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated // documentation files (the "Software"), to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and // to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of // the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO // THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF // CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // import Foundation public class SRConnection: SRConnectionInterface { public var started: SRConnectionInterface.StartedBlock? public var received: SRConnectionInterface.ReceivedBlock? public var error: SRConnectionInterface.ErrorBlock? public var closed: SRConnectionInterface.ClosedBlock? public var reconnecting: SRConnectionInterface.ReconnectingBlock? public var reconnected: SRConnectionInterface.ReconnectedBlock? public var stateChanged: SRConnectionInterface.StateChangedBlock? public var connectionSlow: SRConnectionInterface.ConnectionSlowBlock? var assemblyVersion: SRVersion? = nil var defaultAbortTimeout: TimeInterval = 30 var disconnectTimeout: TimeInterval = 0 var disconnectTimeoutOperation: BlockOperation? var connectionData: String = "" var monitor: SRHeartbeatMonitor? = nil public let clientProtocol = SRVersion(major:1, minor:3) public var transportConnectTimeout: TimeInterval = 0 public var keepAliveData: SRKeepAliveData? public var messageId: String! public var groupsToken: String! public var connectionId: String! public var connectionToken: String! public var url: String public var queryString: [String: String] public var state: ConnectionState { didSet { /** Call the state change listener in any case. */ self.stateChanged?(self.state); } } public var transport: SRClientTransportInterface? public var headers = [String: String]() /* --- Initializing an SRConnection Object --- */ public init(urlString url: String, queryString: [String: String] = [String: String]()) { self.url = url.hasSuffix("/") ? url : url + "/" self.queryString = queryString; //self.disconnectTimeoutOperation = DisposableAction.Empty; //self.connectingMessageBuffer = new ConnectingMessageBuffer(this, OnMessageReceived); self.state = .disconnected; } /* --- Connection Management --- */ public func start() { /* Pick the best transport supported by the client. */ self.start(SRWebSocketTransport()) } func start(_ transport: SRClientTransportInterface) { if !self.changeState(.disconnected, toState:.connecting) { return } self.monitor = SRHeartbeatMonitor(connection: self) self.transport = transport self.negotiate(transport) } func negotiate(_ transport: SRClientTransportInterface) { SRLogDebug("will negotiate"); /* FIX ME: This will crash if we using a non hub connection. */ self.connectionData = self.onSending()! guard let transport = self.transport else { SRLogError("Can not negotiate because I have no transport!") return } transport.negotiate(self, connectionData: self.connectionData) { (negotiationResponse, error) in if let error = error { SRLogError("negotiation failed \(error)"); self.didReceive(error: error) self.disconnect() return } guard let negotiationResponse = negotiationResponse else { fatalError("No negotiation response.") } SRLogDebug("negotiation was successful \(negotiationResponse)") self.verifyProtocolVersion(negotiationResponse.protocolVersion) self.connectionId = negotiationResponse.connectionId self.connectionToken = negotiationResponse.connectionToken self.disconnectTimeout = negotiationResponse.disconnectTimeout self.transportConnectTimeout = self.transportConnectTimeout + negotiationResponse.transportConnectTimeout // If we have a keep alive if negotiationResponse.keepAliveTimeout > 0 { self.keepAliveData = SRKeepAliveData(timeout: negotiationResponse.keepAliveTimeout) } self.startTransport() } } func startTransport() { SRLogDebug("will start transport") guard let transport = self.transport else { SRLogError("Can not start transport because I have no transport!") return } transport.start(self, connectionData:self.connectionData) { (response, error) in if error == nil { SRLogInfo("Start transport was successful, using \(transport.name)") _ = self.changeState(.connecting, toState:.connected) if self.keepAliveData != nil && transport.supportsKeepAlive { SRLogDebug("connection starting keepalive monitor") self.monitor?.start() } self.started?() } else { SRLogError("start transport failed \(error!)") self.didReceive(error: error!) self.didClose() } } } public func changeState(_ oldState: ConnectionState, toState newState:ConnectionState) -> Bool { objc_sync_enter(self) defer { objc_sync_exit(self) } // If we're in the expected old state then change state and return true if (self.state == oldState) { self.state = newState; SRLogDebug("connection state did change from \(oldState) to \(newState)") return true } // Invalid transition SRLogWarn("Request for connection state change from \(oldState) to \(newState) but current state is \(self.state), ignoring...") return false } func verifyProtocolVersion(_ versionString: String) { guard let version = SRVersion.parse(from: versionString) else { fatalError("Could not parse version") } if version != self.clientProtocol { // SKerkewitz: how does versioning in signalR work? SRLogError("Remote SignalR version is \(versionString)") //SRLogError("Invalid version \(version), expected \(self.clientProtocol)") } } func stopAndCallServer() { self.stop(timeout: self.defaultAbortTimeout) } func stopButDoNotCallServer() { //immediately give up telling the server self.stop(timeout: -1) } public func stop() { self.stopAndCallServer() } /** timeout <= 0 does not call server (immediate timeout). */ public func stop(timeout: TimeInterval) { // Do nothing if the connection is offline if (self.state != .disconnected) { SRLogDebug("connection will stop monitoring keepalive") self.monitor!.stop() self.monitor = nil SRLogDebug("connection will abort transport") self.transport?.abort(self, timeout:timeout, connectionData:self.connectionData) self.disconnect() self.transport = nil } } public func disconnect() { if self.state != .disconnected { /* Force a disconnect. */ self.changeState(self.state, toState:.disconnected) self.monitor?.stop() self.monitor = nil // Clear the state for this connection self.connectionId = nil self.connectionToken = nil self.groupsToken = nil self.messageId = nil self.didClose() } } func didClose() { SRLogDebug("connection did close") self.closed?() } /* --- Sending Data --- */ public func onSending() -> String? { return nil; } public func send(_ object: Any, completionHandler block:((Any?, NSError?) -> ())?) { if self.state == .disconnected { let userInfo: [AnyHashable : Any] = [ NSLocalizedFailureReasonErrorKey : NSExceptionName.internalInconsistencyException, NSLocalizedDescriptionKey : NSLocalizedString("Start must be called before data can be sent", comment:"NSInternalInconsistencyException") ] let localizedString = NSLocalizedString("com.SignalR.SignalR-ObjC." + String(describing: self), comment: "") let error = NSError(domain: localizedString, code:0, userInfo:userInfo) self.didReceive(error :error) block?(nil, error); return; } if self.state == .connecting { let userInfo: [AnyHashable : Any] = [ NSLocalizedFailureReasonErrorKey : NSExceptionName.internalInconsistencyException, NSLocalizedDescriptionKey : NSLocalizedString("The connection has not been established", comment:"NSInternalInconsistencyException") ] let localizedString = NSLocalizedString("com.SignalR.SignalR-ObjC." + String(describing: self), comment: "") let error = NSError(domain: localizedString, code:0, userInfo:userInfo) self.didReceive(error: error) block?(nil, error); return; } let message: String if let str = object as? String { message = str; } else { let data: Data? if let serializable = object as? SRSerializable { data = try? JSONSerialization.data(withJSONObject: serializable.proxyForJson()) } else { data = try? JSONSerialization.data(withJSONObject: object) } message = String(data: data!, encoding: .utf8)! } guard let transport = self.transport else { SRLogError("Can not send data because I have no transport!") return } transport.send(self, data: message, connectionData: self.connectionData, completionHandler: block) } /* --- Received Data --- */ public func didReceiveData(_ message: Any) { SRLogDebug("connection did receive data \(message)") self.received?(message) } public func didReceive(error: Error) { SRLogError("Connection did receive error \(error)") self.error?(error); } public func willReconnect() { SRLogDebug("connection will reconnect") // Only allow the client to attempt to reconnect for a self.disconnectTimout TimeSpan which is set by // the server during negotiation. // If the client tries to reconnect for longer the server will likely have deleted its ConnectionId // topic along with the contained disconnect message. self.disconnectTimeoutOperation = BlockOperation(block: { SRLogWarn("connection failed to reconnect"); self.stopButDoNotCallServer() }) SRLogDebug("connection will disconnect if reconnect is not performed in \(self.disconnectTimeout)") self.disconnectTimeoutOperation!.perform(#selector(Operation.start), with:nil, afterDelay:self.disconnectTimeout) self.reconnecting?() } public func didReconnect() { SRLogDebug("connection did reconnect") if let disconnectTimeoutOperation = self.disconnectTimeoutOperation { NSObject.cancelPreviousPerformRequests(withTarget: disconnectTimeoutOperation, selector:#selector(Operation.start), object:nil) self.disconnectTimeoutOperation = nil; } self.reconnected?(); self.updateLastKeepAlive() } public func connectionDidSlow() { SRLogDebug("connection did slow") self.connectionSlow?() } /* --- Preparing Requests --- */ /** * Adds an HTTP header to the receiver’s HTTP header dictionary. * * @param value The value for the header field. * @param field the name of the header field. **/ func addValue(_ value: String, forHTTPHeaderField field: String) { self.headers[field] = value } public func updateLastKeepAlive() { self.keepAliveData?.lastKeepAlive = Date() } public func prepare(request: inout URLRequest) { #if TARGET_OS_IPHONE || TARGET_IPHONE_SIMULATOR request.addValue(self.createUserAgentString(NSLocalizedString("SignalR.Client.iOS", ""), forHTTPHeaderField:"User-Agent")) #elseif TARGET_OS_MAC request.addValue(self.createUserAgentString(NSLocalizedString("SignalR.Client.OSX", ""), forHTTPHeaderField:"User-Agent")) #endif //TODO: set credentials //[request setCredentials:self.credentials]; request.allHTTPHeaderFields = self.headers //TODO: Potentially set proxy here } func createUserAgentString(_ client: String) -> String { if self.assemblyVersion == nil { self.assemblyVersion = SRVersion(major:2, minor:0, build:0, revision:0) } #if TARGET_OS_IPHONE || TARGET_IPHONE_SIMULATOR return "\(client)/\(self.assemblyVersion), (\(UIDevice.currentDevice().localizedModel) \(UIDevice.currentDevice().systemVersion))" #elseif TARGET_OS_MAC // SKerkewitz: FIX ME // var environmentVersion = "" // if([[NSProcessInfo processInfo] operatingSystem] == NSMACHOperatingSystem) { // environmentVersion = [environmentVersion stringByAppendingString:@"Mac OS X"]; // NSString *version = [[NSProcessInfo processInfo] operatingSystemVersionString]; // if ([version rangeOfString:@"Version"].location != NSNotFound) { // environmentVersion = [environmentVersion stringByAppendingFormat:@" %@",version]; // } // return [NSString stringWithFormat:@"%@/%@ (%@)",client,self.assemblyVersion,environmentVersion]; // } // return [NSString stringWithFormat:@"%@/%@",client,self.assemblyVersion]; return "" #endif return "" } } extension SRConnection { @discardableResult class func ensureReconnecting(_ connection: SRConnectionInterface) -> Bool { if connection.changeState(.connected, toState:.reconnecting) { connection.willReconnect() } return connection.state == .reconnecting } }
mit
35ddf606a676efad77f4e6363fd462d8
35.855769
157
0.642186
5.227412
false
false
false
false
vector-im/vector-ios
RiotSwiftUI/Modules/Room/PollEditForm/PollEditFormViewModel.swift
1
4480
// // Copyright 2021 New Vector Ltd // // 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 SwiftUI import Combine struct PollEditFormViewModelParameters { let mode: PollEditFormMode let pollDetails: EditFormPollDetails } @available(iOS 14, *) typealias PollEditFormViewModelType = StateStoreViewModel <PollEditFormViewState, Never, PollEditFormViewAction> @available(iOS 14, *) class PollEditFormViewModel: PollEditFormViewModelType, PollEditFormViewModelProtocol { private struct Constants { static let minAnswerOptionsCount = 2 static let maxAnswerOptionsCount = 20 static let maxQuestionLength = 340 static let maxAnswerOptionLength = 340 } // MARK: - Properties // MARK: Private // MARK: Public var completion: ((PollEditFormViewModelResult) -> Void)? // MARK: - Setup init(parameters: PollEditFormViewModelParameters) { let state = PollEditFormViewState( minAnswerOptionsCount: Constants.minAnswerOptionsCount, maxAnswerOptionsCount: Constants.maxAnswerOptionsCount, mode: parameters.mode, bindings: PollEditFormViewStateBindings( question: PollEditFormQuestion(text: parameters.pollDetails.question, maxLength: Constants.maxQuestionLength), answerOptions: parameters.pollDetails.answerOptions.map { PollEditFormAnswerOption(text: $0, maxLength: Constants.maxAnswerOptionLength) }, type: parameters.pollDetails.type ) ) super.init(initialViewState: state) } // MARK: - Public override func process(viewAction: PollEditFormViewAction) { switch viewAction { case .cancel: completion?(.cancel) case .create: completion?(.create(buildPollDetails())) case .update: completion?(.update(buildPollDetails())) case .addAnswerOption: state.bindings.answerOptions.append(PollEditFormAnswerOption(text: "", maxLength: Constants.maxAnswerOptionLength)) case .deleteAnswerOption(let answerOption): state.bindings.answerOptions.removeAll { $0 == answerOption } } } // MARK: - PollEditFormViewModelProtocol func startLoading() { state.showLoadingIndicator = true } func stopLoading(errorAlertType: PollEditFormErrorAlertInfo.AlertType?) { state.showLoadingIndicator = false switch errorAlertType { case .failedCreatingPoll: state.bindings.alertInfo = PollEditFormErrorAlertInfo(id: .failedCreatingPoll, title: VectorL10n.pollEditFormPostFailureTitle, subtitle: VectorL10n.pollEditFormPostFailureSubtitle) case .failedUpdatingPoll: state.bindings.alertInfo = PollEditFormErrorAlertInfo(id: .failedUpdatingPoll, title: VectorL10n.pollEditFormUpdateFailureTitle, subtitle: VectorL10n.pollEditFormUpdateFailureSubtitle) case .none: break } } // MARK: - Private private func buildPollDetails() -> EditFormPollDetails { return EditFormPollDetails(type: state.bindings.type, question: state.bindings.question.text.trimmingCharacters(in: .whitespacesAndNewlines), answerOptions: state.bindings.answerOptions.compactMap({ answerOption in let text = answerOption.text.trimmingCharacters(in: .whitespacesAndNewlines) return text.isEmpty ? nil : text })) } }
apache-2.0
e28b7a03be88ebacd93fd3d9505364d4
38.298246
155
0.625223
5.750963
false
false
false
false
luvacu/Twitter-demo-app
Twitter Demo/Source/Screens/Timeline/TweetCellViewModel.swift
1
1775
// // TweetCellViewModel.swift // Twitter Demo // // Created by Luis Valdés on 16/7/17. // Copyright © 2017 Luis Valdés Cuesta. All rights reserved. // import Foundation import RxSwift import RxCocoa final class TweetCellViewModel { private static let dateFormatter: DateFormatter = { let dateFormatter = DateFormatter() dateFormatter.dateStyle = .long return dateFormatter }() private let disposeBag = DisposeBag() private let repository: TwitterRepository private let tweet: TwitterRepository.Tweet private let isFavourite: Variable<Bool> let userID: String let avatarImageURLDriver: Driver<String> let userNameTextDriver: Driver<String> let dateTextDriver: Driver<String> let tweetTextDriver: Driver<String> let isFavouriteDriver: Driver<Bool> init(repository: TwitterRepository, tweet: TwitterRepository.Tweet) { self.repository = repository self.tweet = tweet isFavourite = Variable(tweet.isLiked) userID = tweet.author.userID avatarImageURLDriver = Driver.just(tweet.author.profileImageLargeURL) userNameTextDriver = Driver.just(tweet.author.formattedScreenName) let dateFormatter = TweetCellViewModel.dateFormatter dateTextDriver = Driver.just(dateFormatter.string(from: tweet.createdAt)) tweetTextDriver = Driver.just(tweet.text) isFavouriteDriver = isFavourite.asDriver() } func toggleFavourite() { repository.markTweet(tweet, asFavourite: !isFavourite.value) .asObservable() .catchErrorJustReturn(isFavourite.value) .bind(to: isFavourite) .disposed(by: disposeBag) } }
mit
86587879347eac1baf40a7035f2ba295
29.033898
81
0.678894
4.908587
false
false
false
false
AnarchyTools/atbuild
atenvironment/environment.swift
1
1088
// 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. #if os(OSX) import Darwin #else import Glibc #endif import atfoundation public var environment: [String: String] { var r: [String: String] = [:] let e = _environment()! var i = 0 while e[i] != nil { let keyv = e[i]! let keyvalue_ = String(validatingUTF8: keyv)! let keyvalue = keyvalue_.split(string: "=", maxSplits: 1) let key = keyvalue[0] let value = keyvalue[1] r[key] = value i += 1 } return r }
apache-2.0
60932cf9ac1dfeb774c94f23602c1be9
30.085714
75
0.664522
3.871886
false
false
false
false
mastahyeti/SoftU2FTool
APDU/VersionRequest.swift
2
764
// // VersionRequest.swift // SoftU2F // // Created by Benjamin P Toews on 1/25/17. // import Foundation public struct VersionRequest: RawConvertible { public let header: CommandHeader public let body: Data public let trailer: CommandTrailer init() { self.header = CommandHeader(ins: .Version, dataLength: 0) self.body = Data() self.trailer = CommandTrailer(noBody: true) } } extension VersionRequest: Command { public init(header: CommandHeader, body: Data, trailer: CommandTrailer) { self.header = header self.body = body self.trailer = trailer } public func validateBody() throws { if body.count > 0 { throw ResponseStatus.WrongLength } } }
mit
4ae80c25b5dc31a8950371ad84c6446a
21.470588
77
0.636126
4.021053
false
false
false
false
crazypoo/PTools
Pods/JXSegmentedView/Sources/Core/JXSegmentedBaseCell.swift
1
3496
// // JXSegmentedBaseCell.swift // JXSegmentedView // // Created by jiaxin on 2018/12/26. // Copyright © 2018 jiaxin. All rights reserved. // import UIKit public typealias JXSegmentedCellSelectedAnimationClosure = (CGFloat)->() open class JXSegmentedBaseCell: UICollectionViewCell, JXSegmentedViewRTLCompatible { open var itemModel: JXSegmentedBaseItemModel? open var animator: JXSegmentedAnimator? private var selectedAnimationClosureArray = [JXSegmentedCellSelectedAnimationClosure]() deinit { animator?.stop() } open override func prepareForReuse() { super.prepareForReuse() animator?.stop() animator = nil } public override init(frame: CGRect) { super.init(frame: frame) commonInit() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) commonInit() } open func commonInit() { if segmentedViewShouldRTLLayout() { segmentedView(horizontalFlipForView: self) segmentedView(horizontalFlipForView: contentView) } } open func canStartSelectedAnimation(itemModel: JXSegmentedBaseItemModel, selectedType: JXSegmentedViewItemSelectedType) -> Bool { var isSelectedAnimatable = false if itemModel.isSelectedAnimable { if selectedType == .scroll { //滚动选中且没有开启左右过渡,允许动画 if !itemModel.isItemTransitionEnabled { isSelectedAnimatable = true } }else if selectedType == .click || selectedType == .code { //点击和代码选中,允许动画 isSelectedAnimatable = true } } return isSelectedAnimatable } open func appendSelectedAnimationClosure(closure: @escaping JXSegmentedCellSelectedAnimationClosure) { selectedAnimationClosureArray.append(closure) } open func startSelectedAnimationIfNeeded(itemModel: JXSegmentedBaseItemModel, selectedType: JXSegmentedViewItemSelectedType) { if itemModel.isSelectedAnimable && canStartSelectedAnimation(itemModel: itemModel, selectedType: selectedType) { //需要更新isTransitionAnimating,用于处理在过滤时,禁止响应点击,避免界面异常。 itemModel.isTransitionAnimating = true animator?.progressClosure = {[weak self] (percent) in guard self != nil else { return } for closure in self!.selectedAnimationClosureArray { closure(percent) } } animator?.completedClosure = {[weak self] in itemModel.isTransitionAnimating = false self?.selectedAnimationClosureArray.removeAll() } animator?.start() } } open func reloadData(itemModel: JXSegmentedBaseItemModel, selectedType: JXSegmentedViewItemSelectedType) { self.itemModel = itemModel if itemModel.isSelectedAnimable { selectedAnimationClosureArray.removeAll() if canStartSelectedAnimation(itemModel: itemModel, selectedType: selectedType) { animator = JXSegmentedAnimator() animator?.duration = itemModel.selectedAnimationDuration }else { animator?.stop() animator = nil } } } }
mit
05c5f7168a4500bac28289a76dbb2a25
32.127451
133
0.633323
5.736842
false
false
false
false
JohnSansoucie/MyProject2
BlueCap/Central/PeripheralServicesViewController.swift
1
4457
// // PeripheralServicesViewController.swift // BlueCap // // Created by Troy Stribling on 6/22/14. // Copyright (c) 2014 gnos.us. All rights reserved. // import UIKit import BlueCapKit class PeripheralServicesViewController : UITableViewController { weak var peripheral : Peripheral! var peripheralViewController : PeripheralViewController! var progressView = ProgressView() struct MainStoryboard { static let peripheralServiceCell = "PeripheralServiceCell" static let peripheralServicesCharacteritics = "PeripheralServicesCharacteritics" } required init(coder aDecoder:NSCoder) { super.init(coder:aDecoder) } override func viewDidLoad() { super.viewDidLoad() self.navigationItem.backBarButtonItem = UIBarButtonItem(title:"", style:.Bordered, target:nil, action:nil) } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) self.updateWhenActive() NSNotificationCenter.defaultCenter().addObserver(self, selector:"peripheralDisconnected", name:BlueCapNotification.peripheralDisconnected, object:self.peripheral!) NSNotificationCenter.defaultCenter().addObserver(self, selector:"didBecomeActive", name:BlueCapNotification.didBecomeActive, object:nil) NSNotificationCenter.defaultCenter().addObserver(self, selector:"didResignActive", name:BlueCapNotification.didResignActive, object:nil) } override func viewDidDisappear(animated: Bool) { super.viewDidDisappear(animated) NSNotificationCenter.defaultCenter().removeObserver(self) } override func prepareForSegue(segue:UIStoryboardSegue, sender:AnyObject!) { if segue.identifier == MainStoryboard.peripheralServicesCharacteritics { if let peripheral = self.peripheral { if let selectedIndex = self.tableView.indexPathForCell(sender as UITableViewCell) { let viewController = segue.destinationViewController as PeripheralServiceCharacteristicsViewController viewController.service = peripheral.services[selectedIndex.row] viewController.peripheralViewController = self.peripheralViewController } } } } override func shouldPerformSegueWithIdentifier(identifier:String?, sender:AnyObject?) -> Bool { return true } func peripheralDisconnected() { Logger.debug("PeripheralServicesViewController#peripheralDisconnected") if self.peripheralViewController.peripehealConnected { self.presentViewController(UIAlertController.alertWithMessage("Peripheral disconnected"), animated:true, completion:nil) self.peripheralViewController.peripehealConnected = false self.updateWhenActive() } } func didResignActive() { Logger.debug("PeripheralServicesViewController#didResignActive") self.navigationController?.popToRootViewControllerAnimated(false) } func didBecomeActive() { Logger.debug("PeripheralServicesViewController#didBecomeActive") } // UITableViewDataSource override func numberOfSectionsInTableView(tableView:UITableView) -> Int { return 1 } override func tableView(_:UITableView, numberOfRowsInSection section:Int) -> Int { if let peripheral = self.peripheral { return peripheral.services.count } else { return 0; } } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier(MainStoryboard.peripheralServiceCell, forIndexPath: indexPath) as NameUUIDCell let service = peripheral.services[indexPath.row] cell.nameLabel.text = service.name cell.uuidLabel.text = service.uuid.UUIDString if let peripheralViewController = self.peripheralViewController { if peripheralViewController.peripehealConnected { cell.nameLabel.textColor = UIColor.blackColor() } else { cell.nameLabel.textColor = UIColor.lightGrayColor() } } else { cell.nameLabel.textColor = UIColor.blackColor() } return cell } // UITableViewDelegate }
mit
52b14d74df885816d9ac14df5c08dcec
38.442478
171
0.689702
6.113855
false
false
false
false
chuckwired/ios-scroll-test
scrollTest/PeekedPageScrollViewController.swift
1
3874
// // PeekedPageScrollViewController.swift // scrollTest // // Created by Charles Rice on 05/11/2014. // Copyright (c) 2014 Cake Solutions. All rights reserved. // import UIKit class PeekedPageScrollViewController: UIViewController, UIScrollViewDelegate { @IBOutlet var scrollView: UIScrollView! @IBOutlet var pageControl: UIPageControl! var pageImages: [UIImage] = [] var pageViews: [UIImageView?] = [] override func viewDidLoad() { super.viewDidLoad() pageImages = [ UIImage(named: "photo1.png")!, UIImage(named: "photo2.png")!, UIImage(named: "photo3.png")!, UIImage(named: "photo4.png")!, UIImage(named: "photo5.png")! ] let pageCount = pageImages.count //setup page control pageControl.currentPage = 0 pageControl.numberOfPages = pageImages.count //prepare empty array for _ in 0..<pageCount { pageViews.append(nil) } //Setup content size of scrollview let pagesScrollViewSize = scrollView.frame.size scrollView.contentSize = CGSizeMake(pagesScrollViewSize.width * CGFloat(pageImages.count), pagesScrollViewSize.height) //Load pages loadVisiblePages() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func loadVisiblePages() { // First, determine which page is currently visible let pageWidth = scrollView.frame.size.width let page = Int(floor((scrollView.contentOffset.x * 2.0 + pageWidth) / (pageWidth * 2.0))) // Update the page control pageControl.currentPage = page // Work out which pages you want to load let firstPage = page - 1 let lastPage = page + 1 // Purge anything before the first page for var index = 0; index < firstPage; ++index { purgePage(index) } // Load pages in our range for index in firstPage...lastPage { loadPage(index) } // Purge anything after the last page for var index = lastPage+1; index < pageImages.count; ++index { purgePage(index) } } func loadPage(page: Int) { if page < 0 || page >= pageImages.count { // If it's outside the range of what you have to display, then do nothing return } // Load an individual page, first checking if you've already loaded it if let pageView = pageViews[page] { // Do nothing. The view is already loaded. } else { var frame = scrollView.bounds frame.origin.x = frame.size.width * CGFloat(page) frame.origin.y = 0.0 frame = CGRectInset(frame, 10.0, 0.0) //allows us to see the prev and next image let newPageView = UIImageView(image: pageImages[page]) newPageView.contentMode = .ScaleAspectFit newPageView.frame = frame scrollView.addSubview(newPageView) pageViews[page] = newPageView } } func purgePage(page: Int) { if page < 0 || page >= pageImages.count { // If it's outside the range of what you have to display, then do nothing return } // Remove a page from the scroll view and reset the container array if let pageView = pageViews[page] { pageView.removeFromSuperview() pageViews[page] = nil } } func scrollViewDidScroll(scrollView: UIScrollView!) { // Load the pages that are now on screen loadVisiblePages() } }
gpl-2.0
addc7223af4b6945d480bebe30736365
30.754098
126
0.578214
5.064052
false
false
false
false
koher/UIKit-PromiseK
UIKitPromiseK/UIKitPromiseK.swift
1
4275
import UIKit import PromiseK extension UIView { public class func promisedAnimate(withDuration duration: TimeInterval, delay: TimeInterval = 0.0, options: UIViewAnimationOptions = [UIViewAnimationOptions.curveEaseInOut], animations: @escaping () -> Void) -> Promise<Bool> { return Promise<Bool> { fulfill in UIView.animate(withDuration: duration, delay: delay, options: options, animations: animations) { finished in fulfill(finished) } } } } extension UIViewController { public func promisedPresentAlertController<T>(withTitle title: String? = nil, message: String? = nil, preferredStyle: UIAlertControllerStyle, buttons: [(title: String, style: UIAlertActionStyle, value: T)], configurePopoverPresentation: ((UIPopoverPresentationController) -> ())? = nil) -> Promise<T> { return Promise { fulfill in let alertController = UIAlertController(title: title, message: message, preferredStyle: preferredStyle) for button in buttons { alertController.addAction(UIAlertAction(title: button.title, style: button.style) { action in fulfill(button.value) }) } _ = alertController.popoverPresentationController.map { configurePopoverPresentation?($0) } self.present(alertController, animated: true, completion: nil) } } } extension UIAlertView { public func promisedShow() -> Promise<Int> { let delegate = AlertViewDelegate() self.delegate = delegate show() return delegate.promise } public class func promisedShow(withTitle title: String? = nil, message: String? = nil, cancelButtonTitle: String? = nil, buttonTitles: [String]) -> Promise<Int> { let alertView = UIAlertView(title: title, message: message, delegate: nil, cancelButtonTitle: cancelButtonTitle) for buttonTitle in buttonTitles { alertView.addButton(withTitle: buttonTitle) } return alertView.promisedShow() } } class AlertViewDelegate: NSObject, UIAlertViewDelegate { fileprivate var zelf: AlertViewDelegate! fileprivate var fulfill: ((Int) -> Void)! fileprivate var promise: Promise<Int>! override init() { super.init() zelf = self promise = Promise<Int> { fulfill in self.fulfill = fulfill } } func alertView(_ alertView: UIAlertView, clickedButtonAt buttonIndex: Int) { fulfill(buttonIndex) fulfill = nil DispatchQueue.main.async { self.zelf = nil } } } extension UIActionSheet { public func promisedShow(in view: UIView) -> Promise<Int> { let delegate = ActionSheetDelegate() self.delegate = delegate show(in: view) return delegate.promise } public class func promisedShow(in view: UIView, withTitle title: String? = nil, cancelButtonTitle: String? = nil, destructiveButtonTitle: String? = nil, buttonTitles: [String]) -> Promise<Int> { let actionSheet = UIActionSheet(title: title, delegate: nil, cancelButtonTitle: nil, destructiveButtonTitle: nil) if let title = destructiveButtonTitle { actionSheet.destructiveButtonIndex = actionSheet.addButton(withTitle: title) } for buttonTitle in buttonTitles { actionSheet.addButton(withTitle: buttonTitle) } if let title = cancelButtonTitle { actionSheet.cancelButtonIndex = actionSheet.addButton(withTitle: title) } return actionSheet.promisedShow(in: view) } } class ActionSheetDelegate: NSObject, UIActionSheetDelegate { fileprivate var zelf: ActionSheetDelegate! fileprivate var fulfill: ((Int) -> Void)! fileprivate var promise: Promise<Int>! override init() { super.init() zelf = self promise = Promise { fulfill in self.fulfill = fulfill } } func actionSheet(_ actionSheet: UIActionSheet, clickedButtonAt buttonIndex: Int) { fulfill(buttonIndex) fulfill = nil DispatchQueue.main.async { self.zelf = nil } } }
mit
f112977a0560e289c0e5cd858ef026cf
35.228814
306
0.643041
5.232558
false
false
false
false
Motsai/neblina-motiondemo-swift
NebFullBody/iOS/NebFullBody/ViewController.swift
2
3760
// // ViewController.swift // NebFullBody // // Created by Hoan Hoang on 2017-04-04. // Copyright © 2017 Hoan Hoang. All rights reserved. // import UIKit import CoreBluetooth import QuartzCore import SceneKit class ViewController: UIViewController, UITextFieldDelegate, NeblinaDelegate, SCNSceneRendererDelegate { let scene = SCNScene(named: "art.scnassets/Body_Mesh_Rigged.dae")! //let scene = SCNScene(named: "art.scnassets/ship.scn")! var body : SCNNode! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. // create and add a camera to the scene let cameraNode = SCNNode() cameraNode.camera = SCNCamera() scene.rootNode.addChildNode(cameraNode) // place the camera cameraNode.position = SCNVector3(x: 0, y: 1.5, z: 4) //cameraNode.position = SCNVector3(x: 0, y: 15, z: 0) //cameraNode.rotation = SCNVector4(0, 0, 1, GLKMathDegreesToRadians(-180)) //cameraNode.rotation = SCNVector3(x: // create and add a light to the scene let lightNode = SCNNode() lightNode.light = SCNLight() lightNode.light!.type = SCNLight.LightType.omni lightNode.position = SCNVector3(x: 0, y: 10, z: 50) scene.rootNode.addChildNode(lightNode) // create and add an ambient light to the scene let ambientLightNode = SCNNode() ambientLightNode.light = SCNLight() ambientLightNode.light!.type = SCNLight.LightType.ambient ambientLightNode.light!.color = UIColor.darkGray scene.rootNode.addChildNode(ambientLightNode) body = scene.rootNode.childNode(withName :"Armature", recursively: true)! //body = scene.rootNode.childNode(withName :"ship", recursively: true)! // set the scene to the view let scnView = self.view.subviews[0] as! SCNView // set the scene to the view scnView.scene = scene // allows the user to manipulate the camera scnView.allowsCameraControl = true // show statistics such as fps and timing information scnView.showsStatistics = true // configure the view scnView.backgroundColor = UIColor.black } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // ***** // NeblinaDelegate // ***** func didConnectNeblina(sender : Neblina ) { } func didReceiveRSSI(sender : Neblina , rssi : NSNumber) { } func didReceiveGeneralData(sender : Neblina, respType : Int32, cmdRspId : Int32, data : UnsafeRawPointer, dataLen : Int, errFlag : Bool) { } func didReceiveBatteryLevel(sender: Neblina, level: UInt8) { } func didReceiveResponsePacket(sender: Neblina, subsystem: Int32, cmdRspId: Int32, data: UnsafePointer<UInt8>, dataLen: Int) { } func didReceiveFusionData(sender : Neblina, respType : Int32, cmdRspId : Int32, data : NeblinaFusionPacket_t, errFlag : Bool) { } func didReceivePmgntData(sender : Neblina, respType : Int32, cmdRspId : Int32, data : UnsafePointer<UInt8>, dataLen : Int, errFlag : Bool) { } func didReceiveLedData(sender : Neblina, respType : Int32, cmdRspId : Int32, data : UnsafePointer<UInt8>, dataLen : Int, errFlag : Bool) { } func didReceiveDebugData(sender : Neblina, respType : Int32, cmdRspId : Int32, data : UnsafePointer<UInt8>, dataLen : Int, errFlag : Bool) { } func didReceiveRecorderData(sender : Neblina, respType : Int32, cmdRspId : Int32, data : UnsafePointer<UInt8>, dataLen : Int, errFlag : Bool) { } func didReceiveEepromData(sender : Neblina, respType : Int32, cmdRspId : Int32, data : UnsafePointer<UInt8>, dataLen : Int, errFlag : Bool) { } func didReceiveSensorData(sender : Neblina, respType : Int32, cmdRspId : Int32, data : UnsafePointer<UInt8>, dataLen : Int, errFlag : Bool) { } }
mit
2d0b18b36455241a9b4fce0d163724a5
30.325
144
0.716148
3.827902
false
false
false
false
wbraynen/SwiftMusicPlayer
MusicPlayer/AppDelegate.swift
1
7560
// // AppDelegate.swift // MusicPlayer2 // // Created by William Braynen on 12/2/15. // Copyright © 2015 Will Braynen. All rights reserved. // import UIKit import CoreData @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate, UISplitViewControllerDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. let splitViewController = self.window!.rootViewController as! UISplitViewController let navigationController = splitViewController.viewControllers[splitViewController.viewControllers.count-1] as! UINavigationController navigationController.topViewController!.navigationItem.leftBarButtonItem = splitViewController.displayModeButtonItem() splitViewController.delegate = self let masterNavigationController = splitViewController.viewControllers[0] as! UINavigationController let controller = masterNavigationController.topViewController as! MasterViewController controller.managedObjectContext = self.managedObjectContext return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. // Saves changes in the application's managed object context before the application terminates. self.saveContext() } // MARK: - Split view func splitViewController(splitViewController: UISplitViewController, collapseSecondaryViewController secondaryViewController:UIViewController, ontoPrimaryViewController primaryViewController:UIViewController) -> Bool { guard let secondaryAsNavController = secondaryViewController as? UINavigationController else { return false } guard let topAsDetailController = secondaryAsNavController.topViewController as? DetailViewController else { return false } if topAsDetailController.album == nil { // Return true to indicate that we have handled the collapse by doing nothing; the secondary controller will be discarded. return true } return false } // MARK: - Core Data stack lazy var applicationDocumentsDirectory: NSURL = { // The directory the application uses to store the Core Data store file. This code uses a directory named "com.samdurak.MusicPlayer2" in the application's documents Application Support directory. let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask) return urls[urls.count-1] }() lazy var managedObjectModel: NSManagedObjectModel = { // The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model. let modelURL = NSBundle.mainBundle().URLForResource("MusicPlayer", withExtension: "momd")! return NSManagedObjectModel(contentsOfURL: modelURL)! }() lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = { // The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. // Create the coordinator and store let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel) let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("SingleViewCoreData.sqlite") var failureReason = "There was an error creating or loading the application's saved data." do { try coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil) } catch { // Report any error we got. var dict = [String: AnyObject]() dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" dict[NSLocalizedFailureReasonErrorKey] = failureReason dict[NSUnderlyingErrorKey] = error as NSError let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict) // Replace this with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)") abort() } return coordinator }() lazy var managedObjectContext: NSManagedObjectContext = { // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail. let coordinator = self.persistentStoreCoordinator var managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType) managedObjectContext.persistentStoreCoordinator = coordinator return managedObjectContext }() // MARK: - Core Data Saving support func saveContext () { if managedObjectContext.hasChanges { do { try managedObjectContext.save() } catch { // Replace this implementation with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. let nserror = error as NSError NSLog("Unresolved error \(nserror), \(nserror.userInfo)") abort() } } } }
mit
8da4f7cec20f25121f29e5094950cb0e
57.146154
291
0.73343
6.211175
false
false
false
false
openbuild-sheffield/jolt
Sources/RouteCMS/model.CMSWords.swift
1
1442
import PerfectLib import OpenbuildExtensionPerfect public class ModelCMSWords: JSONConvertibleObject, DocumentationProtocol { static let registerName = "CMS.CMSWords" public var cms_words_id: Int? public var handle: String? public var words: String? public var errors: [String: String] = [:] public init(dictionary: [String : Any]) { self.cms_words_id = Int(dictionary["cms_words_id"]! as! UInt32) self.handle = dictionary["handle"] as? String self.words = dictionary["words"] as? String } public init(cms_words_id: Int, handle: String, words: String) { self.cms_words_id = cms_words_id self.handle = handle self.words = words } public init(cms_words_id: String, handle: String, words: String) { self.cms_words_id = Int(cms_words_id) self.handle = handle self.words = words } public init(handle: String, words: String) { self.handle = handle self.words = words } public override func getJSONValues() -> [String : Any] { return [ JSONDecoding.objectIdentifierKey:ModelCMSWords.registerName, "cms_words_id": cms_words_id! as Int, "handle": handle! as String, "words": words! as String ] } public static func describeRAML() -> [String] { //TODO / FIXME return ["CMS: ModelCMSWords TODO / FIXME"] } }
gpl-2.0
f7e5238e036bc2f889d772763af0aa7a
27.86
74
0.612344
3.99446
false
false
false
false
Tsiems/mobile-sensing-apps
AirDrummer/AIToolbox/Tree.swift
1
2900
// // Tree.swift // AIToolbox // // Created by Kevin Coble on 2/15/15. // Copyright (c) 2015 Kevin Coble. All rights reserved. // import Foundation // Trees are graphs with the property that no 'branches' interconnect. Therefore, the nodes down a path are guaranteed unique public protocol TreeNode { // Method to get child node at index. Return nil if index out of range func getChildNodeForIndex(index: Int) -> TreeNode? var getChildNodeList : [TreeNode] {get} } public class Tree<T : TreeNode> { // The root of the tree var rootNode : T // Initializer with root node public init(initRootNode: T) { rootNode = initRootNode } /// Computed property to get the root node public var getRootNode : T {return rootNode} /// Depth-first search for inclusion in tree from specified node. Pass nil to start at root node. /// Second parameter is a completion that returns a Bool from a node, indicating the node matches the search criteria public func containsNodeDepthFirst(startNode : T?, searchCriteria: (T) -> Bool) -> Bool { var currentNode : T if let sNode = startNode { currentNode = sNode } else { currentNode = rootNode } //!! let nodeList = currentNode.getChildNodeList // See if the start, or the children of start, meet the criteria return nodeContainsNodeDepthFirst(node: currentNode, searchCriteria: searchCriteria) } private func nodeContainsNodeDepthFirst(node : T, searchCriteria: (T) -> Bool) -> Bool { // If this node meets the criteria, return true if (searchCriteria(node)) {return true} // Iterate through each child node, and check it var childIndex = 0 var child : T? repeat { child = node.getChildNodeForIndex(index: childIndex) as! T? if let unwrappedChild = child { childIndex += 1 if (nodeContainsNodeDepthFirst(node: unwrappedChild, searchCriteria: searchCriteria)) {return true} } } while (child != nil) return false } /// Depth-first search for path through tree from specified node to target node. Pass nil to start at root node. /// Second parameter is a completion that returns a Bool from a node, indicating the node matches the search criteria. /// Return is an optional array of integers giving the child index for the path (0-based). Example: [1, 0, 3] indicates second child of start node, first child of that child, fourth child from that node. /// Returns empty set [] if start node matches. Returns nil if no node found that matches public func pathToNodeDepthFirst(startNode : T?, searchCriteria: (T) -> Bool) -> [Int]? { return nil } }
mit
9b92ba782bbe6624653ae13bbcaa0d16
37.157895
211
0.64069
4.545455
false
false
false
false
vickyisrulin/AM_App
ThakorjiDetail.swift
1
2289
// // ThakorjiDetail.swift // AM_App // // Created by Vicky Rana on 3/5/17. // Copyright © 2017 Vicky Rana. All rights reserved. // import Foundation import UIKit class ThakorjiImage: UIViewController { var mandir = String() var date = String() var id = Int16() var count = Int16() var templeurl = String() // var imagesURLS = [String]() @IBOutlet weak var ThakorjiImage: UIScrollView! @IBOutlet weak var mandirLabel: UILabel! @IBOutlet weak var dateLabel: UILabel! override func viewDidLoad() { if let templeint:Int16 = (id) as? Int16 { // var templeurl = "" if templeint == 1 { templeurl = "india" } else if templeint == 2 { templeurl = "uk" } else if templeint == 3 { templeurl = "usa" } else if templeint == 4 { templeurl = "kharghar" } else if templeint == 5 { templeurl = "surat" } else if templeint == 6 { templeurl = "vemar" } else if templeint == 7 { templeurl = "amdavad" } } mandirLabel.text = mandir dateLabel.text = date ThakorjiImage.frame = view.frame //for i in 0..<count { // imagesURLS.append("http://anoopam.org/thakorjitoday/\(id)/images/god0\(i+1)L.jpg") } for j in 0..<count { let imageview = UIImageView() imageview.sd_setImage(with: URL(string: "http://anoopam.org/thakorjitoday/\(templeurl)/images/god0\(j+1)L.jpg"))//,placeholderImage: UIImage(named: "Placeholder.png")) imageview.contentMode = .scaleAspectFit let xPos = self.view.frame.width * CGFloat(j) imageview.frame = CGRect(x: xPos, y: 0, width: self.view.frame.width, height: self.view.frame.height) ThakorjiImage.contentSize.width = ThakorjiImage.frame.width * CGFloat(j+1) ThakorjiImage.addSubview(imageview) } } }
mit
5fea75aba73e0df0be597af554eeb1f3
26.238095
179
0.499563
4.442718
false
false
false
false
SnowdogApps/Project-Needs-Partner
CooperationFinder/Controllers/SDMyApplicationsViewController.swift
1
6991
// // SDMyApplicationsViewController.swift // CooperationFinder // // Created by Rafal Kwiatkowski on 10.03.2015. // Copyright (c) 2015 Snowdog. All rights reserved. // import UIKit class SDMyApplicationsViewController: UITableViewController { var myApplications : [Application] = [] var applicationsToMyProjects : [Application] = [] var loggedUserId : String? var onceToken : dispatch_once_t = 0 var sizingCell : SDApplicationCell? var applications: [Application] { get { return self.myApplications + self.applicationsToMyProjects } } override func viewDidAppear(animated: Bool) { if let userId = Defaults["user_id"].string { self.loggedUserId = userId Application.getMyApplications() {(success, applications) -> Void in self.myApplications.removeAll(keepCapacity: true) if let apps = applications { self.myApplications += apps } Application.getApplicationsToMyProjects() { (success, applications) -> Void in self.applicationsToMyProjects.removeAll(keepCapacity: true) if let apps = applications { self.applicationsToMyProjects += apps } self.tableView.reloadData() } } } else { self.loggedUserId = nil self.myApplications.removeAll(keepCapacity: true) self.applicationsToMyProjects.removeAll(keepCapacity: true) self.tableView.reloadData() } } override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 2 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if (section == 0) { return (self.myApplications.count > 0 ? self.myApplications.count : 1) } else if (section == 1) { return (self.applicationsToMyProjects.count > 0 ? self.applicationsToMyProjects.count : 1) } return 0 } override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { var height : CGFloat = 80.0 if let application = self.applicationForIndexPath(indexPath) { dispatch_once(&onceToken, { () -> Void in self.sizingCell = tableView.dequeueReusableCellWithIdentifier("ApplicationCell") as? SDApplicationCell }) self.configureApplicationCell(self.sizingCell!, application: application) self.sizingCell?.bounds = CGRectMake(0.0, 0.0, tableView.bounds.size.width, 0.0) self.sizingCell?.setNeedsLayout() self.sizingCell?.layoutIfNeeded() self.sizingCell?.projectLabel?.preferredMaxLayoutWidth = self.sizingCell!.projectLabel!.bounds.size.width let size = self.sizingCell?.systemLayoutSizeFittingSize(UILayoutFittingCompressedSize) height = size!.height } return height } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { var cell : UITableViewCell! if let application = self.applicationForIndexPath(indexPath) { let appCell = tableView.dequeueReusableCellWithIdentifier("ApplicationCell") as! SDApplicationCell! self.configureApplicationCell(appCell, application: application) cell = appCell } else { let placeholderCell = tableView.dequeueReusableCellWithIdentifier("PlaceholderCell")as! SDPlaceholderCell! placeholderCell.titleLabel?.text = NSLocalizedString("There are no applications", comment: "") cell = placeholderCell } return cell } func configureApplicationCell(cell: SDApplicationCell, application:Application) { let username = application.user?.id == self.loggedUserId ? "My" : application.user?.fullname if (username == nil) { username == "" } cell.nameLabel?.text = username! + " " + NSLocalizedString("application for", comment:"") cell.projectLabel.text = application.project?.name cell.statusLabel.text = application.humanReadableStatus() cell.statusImageView.image = UIImage(named:application.statusIconName()) } override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? { if (section == 0) { return NSLocalizedString("My applications", comment: "") } else if (section == 1) { return NSLocalizedString("Applications to my projects", comment: "") } return nil } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { if (indexPath.section == 0) { let application = self.applicationForIndexPath(indexPath) if (application?.project != nil) { self.performSegueWithIdentifier("ProjectDetailsSegue", sender: nil) } else { let alert = UIAlertView(title: NSLocalizedString("Oops", comment:""), message: NSLocalizedString("Project does not exist", comment:""), delegate: nil, cancelButtonTitle: "OK") alert.show() } } else { self.performSegueWithIdentifier("CandidateSegue", sender: nil) } tableView.deselectRowAtIndexPath(indexPath, animated: true) } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { let indexPathRow = self.tableView.indexPathForSelectedRow() if let indexPath = indexPathRow { let application = self.applicationForIndexPath(indexPath) if segue.identifier == "CandidateSegue" { if let controller = segue.destinationViewController as? SDCandidateDetailsViewController { controller.application = application } } else if segue.identifier == "ProjectDetailsSegue" { if let controller = segue.destinationViewController as? SDProjectDetailsViewController { controller.project = application?.project } } } } func applicationForIndexPath(indexPath : NSIndexPath) -> Application? { var application : Application? if (indexPath.section == 0) { application = (self.myApplications.count > 0 ? self.myApplications[indexPath.row] : nil) } else { application = (self.applicationsToMyProjects.count > 0 ? self.applicationsToMyProjects[indexPath.row] : nil) } return application } @IBAction func unwindToCandidatesList(segue: UIStoryboardSegue) { } }
apache-2.0
5ed3a43978aab8017050b6b89a422cf6
40.613095
191
0.623373
5.665316
false
false
false
false
sswierczek/Helix-Movie-Guide-iOS
Helix Movie GuideTests/HomeMovieCellTest.swift
1
1360
// // HomeMovieCellTest.swift // Helix Movie Guide // // Created by Sebastian Swierczek on 16/03/2017. // Copyright © 2017 user. All rights reserved. // @testable import Helix_Movie_Guide import XCTest import ObjectMapper class HomeMovieCellTest: XCTestCase { let movie: Movie? = Movie(map: Map(mappingType: MappingType.fromJSON, JSON: [:])) var homeMovieCell = HackedHomeMovieCell() func test_WHEN_bindMovie_THEN_setLabelText() { movie?.original_title = "Title" homeMovieCell.bindMovie(movie: movie!) XCTAssertEqual("Title", homeMovieCell.label?.text) } func test_WHEN_bindMovie_THEN_loadImage() { movie?.poster_path = "/image_path" homeMovieCell.bindMovie(movie: movie!) XCTAssertEqual(URL(string: (movie?.getFullImagePath())!), homeMovieCell.imageView?.sd_imageURL()) } // Hack to avoid weak variable being recycled class HackedHomeMovieCell: HomeMovieCell { let stubbedLabel: UILabel! = UILabel() let stubbedImageView: UIImageView! = UIImageView() override var label: UILabel! { get { return stubbedLabel } set { } } override var imageView: UIImageView! { get { return stubbedImageView } set { } } } }
apache-2.0
edb856509dedadc7900fb55f36e45e37
24.166667
105
0.618102
4.455738
false
true
false
false
russbishop/swift
test/SILGen/indirect_enum.swift
1
20269
// RUN: %target-swift-frontend -emit-silgen %s | FileCheck %s indirect enum TreeA<T> { case Nil case Leaf(T) case Branch(left: TreeA<T>, right: TreeA<T>) } // CHECK-LABEL: sil hidden @_TF13indirect_enum11TreeA_casesurFTx1lGOS_5TreeAx_1rGS0_x__T_ func TreeA_cases<T>(_ t: T, l: TreeA<T>, r: TreeA<T>) { // CHECK: [[METATYPE:%.*]] = metatype $@thin TreeA<T>.Type // CHECK-NEXT: [[NIL:%.*]] = enum $TreeA<T>, #TreeA.Nil!enumelt // CHECK-NEXT: release_value [[NIL]] let _ = TreeA<T>.Nil // CHECK-NEXT: [[METATYPE:%.*]] = metatype $@thin TreeA<T>.Type // CHECK-NEXT: [[BOX:%.*]] = alloc_box $T // CHECK-NEXT: [[PB:%.*]] = project_box [[BOX]] // CHECK-NEXT: copy_addr %0 to [initialization] [[PB]] // CHECK-NEXT: [[LEAF:%.*]] = enum $TreeA<T>, #TreeA.Leaf!enumelt.1, [[BOX]] // CHECK-NEXT: release_value [[LEAF]] let _ = TreeA<T>.Leaf(t) // CHECK-NEXT: [[METATYPE:%.*]] = metatype $@thin TreeA<T>.Type // CHECK-NEXT: [[BOX:%.*]] = alloc_box $(left: TreeA<T>, right: TreeA<T>) // CHECK-NEXT: [[PB:%.*]] = project_box [[BOX]] // CHECK-NEXT: [[LEFT:%.*]] = tuple_element_addr [[PB]] : $*(left: TreeA<T>, right: TreeA<T>), 0 // CHECK-NEXT: [[RIGHT:%.*]] = tuple_element_addr [[PB]] : $*(left: TreeA<T>, right: TreeA<T>), 1 // CHECK-NEXT: retain_value %1 // CHECK-NEXT: store %1 to [[LEFT]] // CHECK-NEXT: retain_value %2 // CHECK-NEXT: store %2 to [[RIGHT]] // CHECK-NEXT: [[BRANCH:%.*]] = enum $TreeA<T>, #TreeA.Branch!enumelt.1, [[BOX]] // CHECK-NEXT: release_value [[BRANCH]] // CHECK-NEXT: release_value %2 // CHECK-NEXT: release_value %1 // CHECK-NEXT: destroy_addr %0 let _ = TreeA<T>.Branch(left: l, right: r) // CHECK: return } // CHECK-LABEL: sil hidden @_TF13indirect_enum16TreeA_reabstractFFSiSiT_ func TreeA_reabstract(_ f: (Int) -> Int) { // CHECK: [[METATYPE:%.*]] = metatype $@thin TreeA<(Int) -> Int>.Type // CHECK-NEXT: [[BOX:%.*]] = alloc_box $@callee_owned (@in Int) -> @out Int // CHECK-NEXT: [[PB:%.*]] = project_box [[BOX]] // CHECK-NEXT: strong_retain %0 // CHECK: [[THUNK:%.*]] = function_ref @_TTRXFo_dSi_dSi_XFo_iSi_iSi_ // CHECK-NEXT: [[FN:%.*]] = partial_apply [[THUNK]](%0) // CHECK-NEXT: store [[FN]] to [[PB]] // CHECK-NEXT: [[LEAF:%.*]] = enum $TreeA<(Int) -> Int>, #TreeA.Leaf!enumelt.1, [[BOX]] // CHECK-NEXT: release_value [[LEAF]] // CHECK-NEXT: strong_release %0 // CHECK: return let _ = TreeA<(Int) -> Int>.Leaf(f) } enum TreeB<T> { case Nil case Leaf(T) indirect case Branch(left: TreeB<T>, right: TreeB<T>) } // CHECK-LABEL: sil hidden @_TF13indirect_enum11TreeB_casesurFTx1lGOS_5TreeBx_1rGS0_x__T_ func TreeB_cases<T>(_ t: T, l: TreeB<T>, r: TreeB<T>) { // CHECK: [[METATYPE:%.*]] = metatype $@thin TreeB<T>.Type // CHECK: [[NIL:%.*]] = alloc_stack $TreeB<T> // CHECK-NEXT: inject_enum_addr [[NIL]] : $*TreeB<T>, #TreeB.Nil!enumelt // CHECK-NEXT: destroy_addr [[NIL]] // CHECK-NEXT: dealloc_stack [[NIL]] let _ = TreeB<T>.Nil // CHECK-NEXT: [[METATYPE:%.*]] = metatype $@thin TreeB<T>.Type // CHECK-NEXT: [[LEAF:%.*]] = alloc_stack $TreeB<T> // CHECK-NEXT: [[PAYLOAD:%.*]] = init_enum_data_addr [[LEAF]] : $*TreeB<T>, #TreeB.Leaf!enumelt.1 // CHECK-NEXT: copy_addr %0 to [initialization] [[PAYLOAD]] // CHECK-NEXT: inject_enum_addr [[LEAF]] : $*TreeB<T>, #TreeB.Leaf!enumelt // CHECK-NEXT: destroy_addr [[LEAF]] // CHECK-NEXT: dealloc_stack [[LEAF]] let _ = TreeB<T>.Leaf(t) // CHECK-NEXT: [[METATYPE:%.*]] = metatype $@thin TreeB<T>.Type // CHECK-NEXT: [[BOX:%.*]] = alloc_box $(left: TreeB<T>, right: TreeB<T>) // CHECK-NEXT: [[PB:%.*]] = project_box [[BOX]] // CHECK-NEXT: [[LEFT:%.*]] = tuple_element_addr [[PB]] // CHECK-NEXT: [[RIGHT:%.*]] = tuple_element_addr [[PB]] // CHECK-NEXT: copy_addr %1 to [initialization] [[LEFT]] : $*TreeB<T> // CHECK-NEXT: copy_addr %2 to [initialization] [[RIGHT]] : $*TreeB<T> // CHECK-NEXT: [[BRANCH:%.*]] = alloc_stack $TreeB<T> // CHECK-NEXT: [[PAYLOAD:%.*]] = init_enum_data_addr [[BRANCH]] // CHECK-NEXT: store [[BOX]] to [[PAYLOAD]] // CHECK-NEXT: inject_enum_addr [[BRANCH]] : $*TreeB<T>, #TreeB.Branch!enumelt.1 // CHECK-NEXT: destroy_addr [[BRANCH]] // CHECK-NEXT: dealloc_stack [[BRANCH]] // CHECK-NEXT: destroy_addr %2 // CHECK-NEXT: destroy_addr %1 // CHECK-NEXT: destroy_addr %0 let _ = TreeB<T>.Branch(left: l, right: r) // CHECK: return } // CHECK-LABEL: sil hidden @_TF13indirect_enum13TreeInt_casesFTSi1lOS_7TreeInt1rS0__T_ : $@convention(thin) (Int, @owned TreeInt, @owned TreeInt) -> () func TreeInt_cases(_ t: Int, l: TreeInt, r: TreeInt) { // CHECK: [[METATYPE:%.*]] = metatype $@thin TreeInt.Type // CHECK-NEXT: [[NIL:%.*]] = enum $TreeInt, #TreeInt.Nil!enumelt // CHECK-NEXT: release_value [[NIL]] let _ = TreeInt.Nil // CHECK-NEXT: [[METATYPE:%.*]] = metatype $@thin TreeInt.Type // CHECK-NEXT: [[LEAF:%.*]] = enum $TreeInt, #TreeInt.Leaf!enumelt.1, %0 // CHECK-NEXT: release_value [[LEAF]] let _ = TreeInt.Leaf(t) // CHECK-NEXT: [[METATYPE:%.*]] = metatype $@thin TreeInt.Type // CHECK-NEXT: [[BOX:%.*]] = alloc_box $(left: TreeInt, right: TreeInt) // CHECK-NEXT: [[PB:%.*]] = project_box [[BOX]] // CHECK-NEXT: [[LEFT:%.*]] = tuple_element_addr [[PB]] // CHECK-NEXT: [[RIGHT:%.*]] = tuple_element_addr [[PB]] // CHECK-NEXT: retain_value %1 // CHECK-NEXT: store %1 to [[LEFT]] // CHECK-NEXT: retain_value %2 // CHECK-NEXT: store %2 to [[RIGHT]] // CHECK-NEXT: [[BRANCH:%.*]] = enum $TreeInt, #TreeInt.Branch!enumelt.1, [[BOX]] // CHECK-NEXT: release_value [[BRANCH]] // CHECK-NEXT: release_value %2 // CHECK-NEXT: release_value %1 let _ = TreeInt.Branch(left: l, right: r) // CHECK: return } enum TreeInt { case Nil case Leaf(Int) indirect case Branch(left: TreeInt, right: TreeInt) } enum TrivialButIndirect { case Direct(Int) indirect case Indirect(Int) } func a() {} func b<T>(_ x: T) {} func c<T>(_ x: T, _ y: T) {} func d() {} // CHECK-LABEL: sil hidden @_TF13indirect_enum11switchTreeA func switchTreeA<T>(_ x: TreeA<T>) { // -- x +2 // CHECK: retain_value %0 // CHECK: switch_enum %0 : $TreeA<T> switch x { // CHECK: bb{{.*}}: // CHECK: function_ref @_TF13indirect_enum1aFT_T_ case .Nil: a() // CHECK: bb{{.*}}([[LEAF_BOX:%.*]] : $@box T): // CHECK: [[VALUE:%.*]] = project_box [[LEAF_BOX]] // CHECK: copy_addr [[VALUE]] to [initialization] [[X:%.*]] : $*T // CHECK: function_ref @_TF13indirect_enum1b // CHECK: destroy_addr [[X]] // CHECK: dealloc_stack [[X]] // -- x +1 // CHECK: strong_release [[LEAF_BOX]] // CHECK: br [[OUTER_CONT:bb[0-9]+]] case .Leaf(let x): b(x) // CHECK: bb{{.*}}([[NODE_BOX:%.*]] : $@box (left: TreeA<T>, right: TreeA<T>)): // CHECK: [[TUPLE_ADDR:%.*]] = project_box [[NODE_BOX]] // CHECK: [[TUPLE:%.*]] = load [[TUPLE_ADDR]] // CHECK: [[LEFT:%.*]] = tuple_extract [[TUPLE]] {{.*}}, 0 // CHECK: [[RIGHT:%.*]] = tuple_extract [[TUPLE]] {{.*}}, 1 // CHECK: switch_enum [[RIGHT]] {{.*}}, default [[FAIL_RIGHT:bb[0-9]+]] // CHECK: bb{{.*}}([[RIGHT_LEAF_BOX:%.*]] : $@box T): // CHECK: [[RIGHT_LEAF_VALUE:%.*]] = project_box [[RIGHT_LEAF_BOX]] // CHECK: switch_enum [[LEFT]] {{.*}}, default [[FAIL_LEFT:bb[0-9]+]] // CHECK: bb{{.*}}([[LEFT_LEAF_BOX:%.*]] : $@box T): // CHECK: [[LEFT_LEAF_VALUE:%.*]] = project_box [[LEFT_LEAF_BOX]] // CHECK: copy_addr [[LEFT_LEAF_VALUE]] // CHECK: copy_addr [[RIGHT_LEAF_VALUE]] // -- x +1 // CHECK: strong_release [[NODE_BOX]] // CHECK: br [[OUTER_CONT]] // CHECK: [[FAIL_LEFT]]: // CHECK: br [[DEFAULT:bb[0-9]+]] // CHECK: [[FAIL_RIGHT]]: // CHECK: br [[DEFAULT]] case .Branch(.Leaf(let x), .Leaf(let y)): c(x, y) // CHECK: [[DEFAULT]]: // -- x +1 // CHECK: release_value %0 default: d() } // CHECK: [[OUTER_CONT:%.*]]: // -- x +0 // CHECK: release_value %0 : $TreeA<T> } // CHECK-LABEL: sil hidden @_TF13indirect_enum11switchTreeB func switchTreeB<T>(_ x: TreeB<T>) { // CHECK: copy_addr %0 to [initialization] [[SCRATCH:%.*]] : // CHECK: switch_enum_addr [[SCRATCH]] switch x { // CHECK: bb{{.*}}: // CHECK: destroy_addr [[SCRATCH]] // CHECK: dealloc_stack [[SCRATCH]] // CHECK: function_ref @_TF13indirect_enum1aFT_T_ // CHECK: br [[OUTER_CONT:bb[0-9]+]] case .Nil: a() // CHECK: bb{{.*}}: // CHECK: copy_addr [[SCRATCH]] to [initialization] [[LEAF_COPY:%.*]] : // CHECK: [[LEAF_ADDR:%.*]] = unchecked_take_enum_data_addr [[LEAF_COPY]] // CHECK: copy_addr [take] [[LEAF_ADDR]] to [initialization] [[LEAF:%.*]] : // CHECK: function_ref @_TF13indirect_enum1b // CHECK: destroy_addr [[LEAF]] // CHECK: dealloc_stack [[LEAF]] // CHECK-NOT: destroy_addr [[LEAF_COPY]] // CHECK: dealloc_stack [[LEAF_COPY]] // CHECK: destroy_addr [[SCRATCH]] // CHECK: dealloc_stack [[SCRATCH]] // CHECK: br [[OUTER_CONT]] case .Leaf(let x): b(x) // CHECK: bb{{.*}}: // CHECK: copy_addr [[SCRATCH]] to [initialization] [[TREE_COPY:%.*]] : // CHECK: [[TREE_ADDR:%.*]] = unchecked_take_enum_data_addr [[TREE_COPY]] // -- box +1 immutable // CHECK: [[BOX:%.*]] = load [[TREE_ADDR]] // CHECK: [[TUPLE:%.*]] = project_box [[BOX]] // CHECK: [[LEFT:%.*]] = tuple_element_addr [[TUPLE]] // CHECK: [[RIGHT:%.*]] = tuple_element_addr [[TUPLE]] // CHECK: switch_enum_addr [[RIGHT]] {{.*}}, default [[RIGHT_FAIL:bb[0-9]+]] // CHECK: bb{{.*}}: // CHECK: copy_addr [[RIGHT]] to [initialization] [[RIGHT_COPY:%.*]] : // CHECK: [[RIGHT_LEAF:%.*]] = unchecked_take_enum_data_addr [[RIGHT_COPY]] : $*TreeB<T>, #TreeB.Leaf // CHECK: switch_enum_addr [[LEFT]] {{.*}}, default [[LEFT_FAIL:bb[0-9]+]] // CHECK: bb{{.*}}: // CHECK: copy_addr [[LEFT]] to [initialization] [[LEFT_COPY:%.*]] : // CHECK: [[LEFT_LEAF:%.*]] = unchecked_take_enum_data_addr [[LEFT_COPY]] : $*TreeB<T>, #TreeB.Leaf // CHECK: copy_addr [take] [[LEFT_LEAF]] to [initialization] [[X:%.*]] : // CHECK: copy_addr [take] [[RIGHT_LEAF]] to [initialization] [[Y:%.*]] : // CHECK: function_ref @_TF13indirect_enum1c // CHECK: destroy_addr [[Y]] // CHECK: dealloc_stack [[Y]] // CHECK: destroy_addr [[X]] // CHECK: dealloc_stack [[X]] // CHECK-NOT: destroy_addr [[LEFT_COPY]] // CHECK: dealloc_stack [[LEFT_COPY]] // CHECK-NOT: destroy_addr [[RIGHT_COPY]] // CHECK: dealloc_stack [[RIGHT_COPY]] // -- box +0 // CHECK: strong_release [[BOX]] // CHECK-NOT: destroy_addr [[TREE_COPY]] // CHECK: dealloc_stack [[TREE_COPY]] // CHECK: destroy_addr [[SCRATCH]] // CHECK: dealloc_stack [[SCRATCH]] case .Branch(.Leaf(let x), .Leaf(let y)): c(x, y) // CHECK: [[LEFT_FAIL]]: // CHECK: destroy_addr [[RIGHT_LEAF]] // CHECK-NOT: destroy_addr [[RIGHT_COPY]] // CHECK: dealloc_stack [[RIGHT_COPY]] // CHECK: strong_release [[BOX]] // CHECK-NOT: destroy_addr [[TREE_COPY]] // CHECK: dealloc_stack [[TREE_COPY]] // CHECK: br [[INNER_CONT:bb[0-9]+]] // CHECK: [[RIGHT_FAIL]]: // CHECK: strong_release [[BOX]] // CHECK-NOT: destroy_addr [[TREE_COPY]] // CHECK: dealloc_stack [[TREE_COPY]] // CHECK: br [[INNER_CONT:bb[0-9]+]] // CHECK: [[INNER_CONT]]: // CHECK: destroy_addr [[SCRATCH]] // CHECK: dealloc_stack [[SCRATCH]] // CHECK: function_ref @_TF13indirect_enum1dFT_T_ // CHECK: br [[OUTER_CONT]] default: d() } // CHECK: [[OUTER_CONT]]: // CHECK: destroy_addr %0 } // CHECK-LABEL: sil hidden @_TF13indirect_enum10guardTreeA func guardTreeA<T>(_ tree: TreeA<T>) { do { // CHECK: retain_value %0 // CHECK: switch_enum %0 : $TreeA<T>, case #TreeA.Nil!enumelt: [[YES:bb[0-9]+]], default [[NO:bb[0-9]+]] // CHECK: [[NO]]: // CHECK: release_value %0 // CHECK: [[YES]]: // CHECK: release_value %0 guard case .Nil = tree else { return } // CHECK: [[X:%.*]] = alloc_stack $T // CHECK: retain_value %0 // CHECK: switch_enum %0 : $TreeA<T>, case #TreeA.Leaf!enumelt.1: [[YES:bb[0-9]+]], default [[NO:bb[0-9]+]] // CHECK: [[NO]]: // CHECK: release_value %0 // CHECK: [[YES]]([[BOX:%.*]] : $@box T): // CHECK: [[VALUE_ADDR:%.*]] = project_box [[BOX]] // CHECK: [[TMP:%.*]] = alloc_stack // CHECK: copy_addr [[VALUE_ADDR]] to [initialization] [[TMP]] // CHECK: copy_addr [take] [[TMP]] to [initialization] [[X]] // CHECK: strong_release [[BOX]] guard case .Leaf(let x) = tree else { return } // CHECK: retain_value %0 // CHECK: switch_enum %0 : $TreeA<T>, case #TreeA.Branch!enumelt.1: [[YES:bb[0-9]+]], default [[NO:bb[0-9]+]] // CHECK: [[NO]]: // CHECK: release_value %0 // CHECK: [[YES]]([[BOX:%.*]] : $@box (left: TreeA<T>, right: TreeA<T>)): // CHECK: [[VALUE_ADDR:%.*]] = project_box [[BOX]] // CHECK: [[TUPLE:%.*]] = load [[VALUE_ADDR]] // CHECK: retain_value [[TUPLE]] // CHECK: [[L:%.*]] = tuple_extract [[TUPLE]] // CHECK: [[R:%.*]] = tuple_extract [[TUPLE]] // CHECK: strong_release [[BOX]] guard case .Branch(left: let l, right: let r) = tree else { return } // CHECK: release_value [[R]] // CHECK: release_value [[L]] // CHECK: destroy_addr [[X]] } do { // CHECK: retain_value %0 // CHECK: switch_enum %0 : $TreeA<T>, case #TreeA.Nil!enumelt: [[YES:bb[0-9]+]], default [[NO:bb[0-9]+]] // CHECK: [[NO]]: // CHECK: release_value %0 // CHECK: [[YES]]: // CHECK: release_value %0 if case .Nil = tree { } // CHECK: [[X:%.*]] = alloc_stack $T // CHECK: retain_value %0 // CHECK: switch_enum %0 : $TreeA<T>, case #TreeA.Leaf!enumelt.1: [[YES:bb[0-9]+]], default [[NO:bb[0-9]+]] // CHECK: [[NO]]: // CHECK: release_value %0 // CHECK: [[YES]]([[BOX:%.*]] : $@box T): // CHECK: [[VALUE_ADDR:%.*]] = project_box [[BOX]] // CHECK: [[TMP:%.*]] = alloc_stack // CHECK: copy_addr [[VALUE_ADDR]] to [initialization] [[TMP]] // CHECK: copy_addr [take] [[TMP]] to [initialization] [[X]] // CHECK: strong_release [[BOX]] // CHECK: destroy_addr [[X]] if case .Leaf(let x) = tree { } // CHECK: retain_value %0 // CHECK: switch_enum %0 : $TreeA<T>, case #TreeA.Branch!enumelt.1: [[YES:bb[0-9]+]], default [[NO:bb[0-9]+]] // CHECK: [[NO]]: // CHECK: release_value %0 // CHECK: [[YES]]([[BOX:%.*]] : $@box (left: TreeA<T>, right: TreeA<T>)): // CHECK: [[VALUE_ADDR:%.*]] = project_box [[BOX]] // CHECK: [[TUPLE:%.*]] = load [[VALUE_ADDR]] // CHECK: retain_value [[TUPLE]] // CHECK: [[L:%.*]] = tuple_extract [[TUPLE]] // CHECK: [[R:%.*]] = tuple_extract [[TUPLE]] // CHECK: strong_release [[BOX]] // CHECK: release_value [[R]] // CHECK: release_value [[L]] if case .Branch(left: let l, right: let r) = tree { } } } // CHECK-LABEL: sil hidden @_TF13indirect_enum10guardTreeB func guardTreeB<T>(_ tree: TreeB<T>) { do { // CHECK: copy_addr %0 to [initialization] [[TMP:%.*]] : // CHECK: switch_enum_addr [[TMP]] : $*TreeB<T>, case #TreeB.Nil!enumelt: [[YES:bb[0-9]+]], default [[NO:bb[0-9]+]] // CHECK: [[NO]]: // CHECK: destroy_addr [[TMP]] // CHECK: [[YES]]: // CHECK: destroy_addr [[TMP]] guard case .Nil = tree else { return } // CHECK: [[X:%.*]] = alloc_stack $T // CHECK: copy_addr %0 to [initialization] [[TMP:%.*]] : // CHECK: switch_enum_addr [[TMP]] : $*TreeB<T>, case #TreeB.Leaf!enumelt.1: [[YES:bb[0-9]+]], default [[NO:bb[0-9]+]] // CHECK: [[NO]]: // CHECK: destroy_addr [[TMP]] // CHECK: [[YES]]: // CHECK: [[VALUE:%.*]] = unchecked_take_enum_data_addr [[TMP]] // CHECK: copy_addr [take] [[VALUE]] to [initialization] [[X]] // CHECK: dealloc_stack [[TMP]] guard case .Leaf(let x) = tree else { return } // CHECK: [[L:%.*]] = alloc_stack $TreeB // CHECK: [[R:%.*]] = alloc_stack $TreeB // CHECK: copy_addr %0 to [initialization] [[TMP:%.*]] : // CHECK: switch_enum_addr [[TMP]] : $*TreeB<T>, case #TreeB.Branch!enumelt.1: [[YES:bb[0-9]+]], default [[NO:bb[0-9]+]] // CHECK: [[NO]]: // CHECK: destroy_addr [[TMP]] // CHECK: [[YES]]: // CHECK: [[BOX_ADDR:%.*]] = unchecked_take_enum_data_addr [[TMP]] // CHECK: [[BOX:%.*]] = load [[BOX_ADDR]] // CHECK: [[TUPLE_ADDR:%.*]] = project_box [[BOX]] // CHECK: copy_addr [[TUPLE_ADDR]] to [initialization] [[TUPLE_COPY:%.*]] : // CHECK: [[L_COPY:%.*]] = tuple_element_addr [[TUPLE_COPY]] // CHECK: copy_addr [take] [[L_COPY]] to [initialization] [[L]] // CHECK: [[R_COPY:%.*]] = tuple_element_addr [[TUPLE_COPY]] // CHECK: copy_addr [take] [[R_COPY]] to [initialization] [[R]] // CHECK: strong_release [[BOX]] guard case .Branch(left: let l, right: let r) = tree else { return } // CHECK: destroy_addr [[R]] // CHECK: destroy_addr [[L]] // CHECK: destroy_addr [[X]] } do { // CHECK: copy_addr %0 to [initialization] [[TMP:%.*]] : // CHECK: switch_enum_addr [[TMP]] : $*TreeB<T>, case #TreeB.Nil!enumelt: [[YES:bb[0-9]+]], default [[NO:bb[0-9]+]] // CHECK: [[NO]]: // CHECK: destroy_addr [[TMP]] // CHECK: [[YES]]: // CHECK: destroy_addr [[TMP]] if case .Nil = tree { } // CHECK: [[X:%.*]] = alloc_stack $T // CHECK: copy_addr %0 to [initialization] [[TMP:%.*]] : // CHECK: switch_enum_addr [[TMP]] : $*TreeB<T>, case #TreeB.Leaf!enumelt.1: [[YES:bb[0-9]+]], default [[NO:bb[0-9]+]] // CHECK: [[NO]]: // CHECK: destroy_addr [[TMP]] // CHECK: [[YES]]: // CHECK: [[VALUE:%.*]] = unchecked_take_enum_data_addr [[TMP]] // CHECK: copy_addr [take] [[VALUE]] to [initialization] [[X]] // CHECK: dealloc_stack [[TMP]] // CHECK: destroy_addr [[X]] if case .Leaf(let x) = tree { } // CHECK: [[L:%.*]] = alloc_stack $TreeB // CHECK: [[R:%.*]] = alloc_stack $TreeB // CHECK: copy_addr %0 to [initialization] [[TMP:%.*]] : // CHECK: switch_enum_addr [[TMP]] : $*TreeB<T>, case #TreeB.Branch!enumelt.1: [[YES:bb[0-9]+]], default [[NO:bb[0-9]+]] // CHECK: [[NO]]: // CHECK: destroy_addr [[TMP]] // CHECK: [[YES]]: // CHECK: [[BOX_ADDR:%.*]] = unchecked_take_enum_data_addr [[TMP]] // CHECK: [[BOX:%.*]] = load [[BOX_ADDR]] // CHECK: [[TUPLE_ADDR:%.*]] = project_box [[BOX]] // CHECK: copy_addr [[TUPLE_ADDR]] to [initialization] [[TUPLE_COPY:%.*]] : // CHECK: [[L_COPY:%.*]] = tuple_element_addr [[TUPLE_COPY]] // CHECK: copy_addr [take] [[L_COPY]] to [initialization] [[L]] // CHECK: [[R_COPY:%.*]] = tuple_element_addr [[TUPLE_COPY]] // CHECK: copy_addr [take] [[R_COPY]] to [initialization] [[R]] // CHECK: strong_release [[BOX]] // CHECK: destroy_addr [[R]] // CHECK: destroy_addr [[L]] if case .Branch(left: let l, right: let r) = tree { } } } func dontDisableCleanupOfIndirectPayload(_ x: TrivialButIndirect) { // CHECK: switch_enum %0 : $TrivialButIndirect, case #TrivialButIndirect.Direct!enumelt.1: [[YES:bb[0-9]+]], default [[NO:bb[0-9]+]] // CHECK: [[NO]]: // CHECK: release_value %0 guard case .Direct(let foo) = x else { return } // -- Cleanup isn't necessary on "no" path because .Direct is trivial // CHECK: switch_enum %0 : $TrivialButIndirect, case #TrivialButIndirect.Indirect!enumelt.1: [[YES:bb[0-9]+]], default [[NO:bb[0-9]+]] // CHECK-NOT: [[NO]]: // CHECK: [[YES]]({{.*}}): guard case .Indirect(let bar) = x else { return } }
apache-2.0
b36f1bd007167436cb19ae72a480416e
39.864919
151
0.533129
3.13616
false
false
false
false
tomlokhorst/Promissum
Sources/Promissum/Promise.swift
1
16096
// // Promise.swift // Promissum // // Created by Tom Lokhorst on 2014-10-11. // Copyright (c) 2014 Tom Lokhorst. All rights reserved. // import Foundation /** ## A future value _A Promise represents a future value._ To access it's value, register a handler using the `then` method: ``` somePromise.then { value in print("The value is: \(value)") } ``` You can register multiple handlers to access the value multiple times. To register more multiple handlers, simply call `then` multiple times. Once available, the value becomes immutable and will never change. ## Failure A Promise can fail during the computation of the future value. In that case the error can also be accessed by registering a handler with `trap`: ``` somePromise.trap { error in print("The error is: \(error)") } ``` ## States A Promise is always in one of three states: Unresolved, Resolved, or Rejected. Once a Promise changes from Unresolved to Resolved/Rejected the appropriate registered handlers are called. After the Promise has changed from Unresolved, it will always stay either Resolved or Rejected. It is possible to register for both the value and the error, like so: ``` somePromise .then { value in print("The value is: \(value)") } .trap { error in print("The error is: \(error)") } ``` ## Types The full type `Promise<Value, Error>` has two type arguments, for both the value and the error. For example; the type `Promise<String, NSError>` represents a future value of type `String` that can potentially fail with a `NSError`. When creating a Promise yourself, it is recommended to use a custom enum to represent the possible errors cases. In cases where an error is not applicable, you can use the `Never` type. ## Transforming a Promise value Similar to `Array`, a Promise has a `map` method to apply a transform the value of a Promise. In this example an age (Promise of int) is transformed to a future isAdult boolean: ``` // agePromise has type Promise<Int, Never> // isAdultPromise has type Promise<Bool, Never> let isAdultPromise = agePromise.map { age in age >= 18 } ``` Again, similar to Arrays, `flatMap` is also available. ## Creating a Promise To create a Promise, use a `PromiseSoure`. Note that it is often not needed to create a new Promise. If an existing Promise is available, transforming that using `map` or `flatMap` is often sufficient. */ public class Promise<Value, Error> where Error: Swift.Error { private let source: PromiseSource<Value, Error> // MARK: Initializers /// Initialize a resolved Promise with a value. /// /// Example: `Promise<Int, Never>(value: 42)` public init(value: Value) { self.source = PromiseSource(value: value) } /// Initialize a rejected Promise with an error. /// /// Example: `Promise<Int, Error>(error: MyError(message: "Oops"))` public init(error: Error) { self.source = PromiseSource(error: error) } /// Initialize a Promise using a closure taking a Promise Source. /// /// Example: /// ``` /// Promise { source in /// asyncFunction(completion: { source.resolve() }) /// } /// ``` public init(_ completion: (PromiseSource<Value, Error>) -> Void) { let source = PromiseSource<Value, Error>() self.source = source completion(source) } internal init(source: PromiseSource<Value, Error>) { self.source = source } // MARK: Computed properties /// Optionally get the underlying value of this Promise. /// Will be `nil` if Promise is Rejected or still Unresolved. /// /// In most situations it is recommended to register a handler with `then` method instead of directly using this property. public var value: Value? { if case .resolved(let value) = source.state { return value } return nil } /// Optionally get the underlying error of this Promise. /// Will be `nil` if Promise is Resolved or still Unresolved. /// /// In most situations it is recommended to register a handler with `trap` method instead of directly using this property. public var error: Error? { if case .rejected(let error) = source.state { return error } return nil } /// Optionally get the underlying result of this Promise. /// Will be `nil` if Promise still Unresolved. /// /// In most situations it is recommended to register a handler with `finallyResult` method instead of directly using this property. public var result: Result<Value, Error>? { switch source.state { case .resolved(let boxed): return .success(boxed) case .rejected(let boxed): return .failure(boxed) default: return nil } } // MARK: - Attach handlers /// Register a handler to be called when value is available. /// The value is passed as an argument to the handler. /// /// The handler is either called directly, if Promise is already resolved, or at a later point in time when the Promise becomes Resolved. /// /// Multiple handlers can be registered by calling `then` multiple times. /// /// ## Execution order /// Handlers registered with `then` are called in the order they have been registered. /// These are interleaved with the other success handlers registered via `finally` or `map`. /// /// ## Dispatch queue /// The handler is synchronously called on the current thread when Promise is already Resolved. /// Or, when Promise is resolved later on, the handler is called synchronously on the thread where `PromiseSource.resolve` is called. @discardableResult public func then(_ handler: @escaping (Value) -> Void) -> Promise<Value, Error> { let resultHandler: (Result<Value, Error>) -> Void = { result in switch result { case .success(let value): handler(value) case .failure: break } } source.addOrCallResultHandler(resultHandler) return self } /// Register a handler to be called when error is available. /// The error is passed as an argument to the handler. /// /// The handler is either called directly, if Promise is already rejected, or at a later point in time when the Promise becomes Rejected. /// /// Multiple handlers can be registered by calling `trap` multiple times. /// /// ## Execution order /// Handlers registered with `trap` are called in the order they have been registered. /// These are interleaved with the other failure handlers registered via `finally` or `mapError`. /// /// ## Dispatch queue /// The handler is synchronously called on the current thread when Promise is already Rejected. /// Or, when Promise is rejected later on, the handler is called synchronously on the thread where `PromiseSource.reject` is called. @discardableResult public func trap(_ handler: @escaping (Error) -> Void) -> Promise<Value, Error> { let resultHandler: (Result<Value, Error>) -> Void = { result in switch result { case .success: break case .failure(let error): handler(error) } } source.addOrCallResultHandler(resultHandler) return self } /// Register a handler to be called when Promise is resolved _or_ rejected. /// No argument is passed to the handler. /// /// The handler is either called directly, if Promise is already resolved or rejected, /// or at a later point in time when the Promise becomes Resolved or Rejected. /// /// Multiple handlers can be registered by calling `finally` multiple times. /// /// ## Execution order /// Handlers registered with `finally` are called in the order they have been registered. /// These are interleaved with the other result handlers registered via `then` or `trap`. /// /// ## Dispatch queue /// The handler is synchronously called on the current thread when Promise is already Resolved or Rejected. /// Or, when Promise is resolved or rejected later on, /// the handler is called synchronously on the thread where `PromiseSource.resolve` or `PromiseSource.reject` is called. @discardableResult public func finally(_ handler: @escaping () -> Void) -> Promise<Value, Error> { let resultHandler: (Result<Value, Error>) -> Void = { _ in handler() } source.addOrCallResultHandler(resultHandler) return self } /// Register a handler to be called when Promise is resolved _or_ rejected. /// A `Result<Value, Error>` argument is passed to the handler. /// /// The handler is either called directly, if Promise is already resolved or rejected, /// or at a later point in time when the Promise becomes Resolved or Rejected. /// /// Multiple handlers can be registered by calling `finally` multiple times. /// /// ## Execution order /// Handlers registered with `finally` are called in the order they have been registered. /// These are interleaved with the other result handlers registered via `then` or `trap`. /// /// ## Dispatch queue /// The handler is synchronously called on the current thread when Promise is already Resolved or Rejected. /// Or, when Promise is resolved or rejected later on, /// the handler is called synchronously on the thread where `PromiseSource.resolve` or `PromiseSource.reject` is called. @discardableResult public func finallyResult(_ handler: @escaping (Result<Value, Error>) -> Void) -> Promise<Value, Error> { source.addOrCallResultHandler(handler) return self } // MARK: Dispatch methods /// Returns a Promise that dispatches its handlers on the specified dispatch queue. public func dispatch(on queue: DispatchQueue) -> Promise<Value, Error> { let key = DispatchSpecificKey<Void>() queue.setSpecific(key: key, value: ()) return dispatch(on: .queue(queue), dispatchKey: key) } /// Returns a Promise that dispatches its handlers on the main dispatch queue. public func dispatchMain() -> Promise<Value, Error> { return dispatch(on: .main) } private func dispatch(on dispatchMethod: DispatchMethod, dispatchKey: DispatchSpecificKey<Void>) -> Promise<Value, Error> { let resultSource = PromiseSource<Value, Error>( state: .unresolved, dispatchKey: dispatchKey, dispatchMethod: dispatchMethod, warnUnresolvedDeinit: true ) source.addOrCallResultHandler(resultSource.resolveResult) return resultSource.promise } // MARK: - Value combinators /// Return a Promise containing the results of mapping `transform` over the value of `self`. public func map<NewValue>(_ transform: @escaping (Value) -> NewValue) -> Promise<NewValue, Error> { let resultSource = PromiseSource<NewValue, Error>( state: .unresolved, dispatchKey: source.dispatchKey, dispatchMethod: source.dispatchMethod, warnUnresolvedDeinit: true ) let handler: (Result<Value, Error>) -> Void = { result in switch result { case .success(let value): let transformed = transform(value) resultSource.resolve(transformed) case .failure(let error): resultSource.reject(error) } } source.addOrCallResultHandler(handler) return resultSource.promise } /// Returns the flattened result of mapping `transform` over the value of `self`. public func flatMap<NewValue>(_ transform: @escaping (Value) -> Promise<NewValue, Error>) -> Promise<NewValue, Error> { let resultSource = PromiseSource<NewValue, Error>( state: .unresolved, dispatchKey: source.dispatchKey, dispatchMethod: source.dispatchMethod, warnUnresolvedDeinit: true ) let handler: (Result<Value, Error>) -> Void = { result in switch result { case .success(let value): let transformedPromise = transform(value) transformedPromise .then(resultSource.resolve) .trap(resultSource.reject) case .failure(let error): resultSource.reject(error) } } source.addOrCallResultHandler(handler) return resultSource.promise } // MARK: Error combinators /// Return a Promise containing the results of mapping `transform` over the error of `self`. public func mapError<NewError>(_ transform: @escaping (Error) -> NewError) -> Promise<Value, NewError> { let resultSource = PromiseSource<Value, NewError>( state: .unresolved, dispatchKey: source.dispatchKey, dispatchMethod: source.dispatchMethod, warnUnresolvedDeinit: true ) let handler: (Result<Value, Error>) -> Void = { result in switch result { case .success(let value): resultSource.resolve(value) case .failure(let error): let transformed = transform(error) resultSource.reject(transformed) } } source.addOrCallResultHandler(handler) return resultSource.promise } /// Returns the flattened result of mapping `transform` over the error of `self`. public func flatMapError<NewError>(_ transform: @escaping (Error) -> Promise<Value, NewError>) -> Promise<Value, NewError> { let resultSource = PromiseSource<Value, NewError>( state: .unresolved, dispatchKey: source.dispatchKey, dispatchMethod: source.dispatchMethod, warnUnresolvedDeinit: true ) let handler: (Result<Value, Error>) -> Void = { result in switch result { case .success(let value): resultSource.resolve(value) case .failure(let error): let transformedPromise = transform(error) transformedPromise .then(resultSource.resolve) .trap(resultSource.reject) } } source.addOrCallResultHandler(handler) return resultSource.promise } // MARK: Result combinators /// Return a Promise containing the results of mapping `transform` over the result of `self`. public func mapResult<NewValue, NewError>(_ transform: @escaping (Result<Value, Error>) -> Result<NewValue, NewError>) -> Promise<NewValue, NewError> { let resultSource = PromiseSource<NewValue, NewError>( state: .unresolved, dispatchKey: source.dispatchKey, dispatchMethod: source.dispatchMethod, warnUnresolvedDeinit: true ) let handler: (Result<Value, Error>) -> Void = { result in switch transform(result) { case .success(let value): resultSource.resolve(value) case .failure(let error): resultSource.reject(error) } } source.addOrCallResultHandler(handler) return resultSource.promise } /// Returns the flattened result of mapping `transform` over the result of `self`. public func flatMapResult<NewValue, NewError>(_ transform: @escaping (Result<Value, Error>) -> Promise<NewValue, NewError>) -> Promise<NewValue, NewError> { let resultSource = PromiseSource<NewValue, NewError>( state: .unresolved, dispatchKey: source.dispatchKey, dispatchMethod: source.dispatchMethod, warnUnresolvedDeinit: true ) let handler: (Result<Value, Error>) -> Void = { result in let transformedPromise = transform(result) transformedPromise .then(resultSource.resolve) .trap(resultSource.reject) } source.addOrCallResultHandler(handler) return resultSource.promise } /// Return a Promise with the resolve or reject delayed by the specified number of seconds. public func delay(_ seconds: TimeInterval, queue: DispatchQueue? = nil) -> Promise<Value, Error> { let dispatchQueue = queue ?? source.dispatchMethod.queue return self .flatMapResult { result in let source = PromiseSource<Value, Error>() dispatchQueue.asyncAfter(deadline: .now() + seconds) { switch result { case .success(let value): source.resolve(value) case .failure(let error): source.reject(error) } } return source.promise } } } private extension DispatchMethod { var queue: DispatchQueue { switch self { case .unspecified: return DispatchQueue.main case .synchronous: return DispatchQueue.main case .queue(let queue): return queue } } }
mit
bb6c34ad4e1380517c19838264704f20
30.499022
158
0.687314
4.597544
false
false
false
false
KyoheiG3/SimpleAlert
SimpleAlert/Transition/AlertControllerPresentTransition.swift
1
1177
// // AlertControllerPresentTransition.swift // SimpleAlert // // Created by Kyohei Ito on 2017/11/25. // Copyright © 2017年 kyohei_ito. All rights reserved. // import UIKit class AlertControllerPresentTransition: ViewControllerAnimatedTransition { override func animateTransition(_ from: UIViewController, to: UIViewController, container: UIView, completion: @escaping (Bool) -> Void) { let backgroundView = UIView(frame: container.bounds) backgroundView.autoresizingMask = [.flexibleWidth, .flexibleHeight] backgroundView.alpha = 0 backgroundView.backgroundColor = backgroundColor.withAlphaComponent(0.4) container.addSubview(backgroundView) to.view.frame = container.bounds to.view.transform = from.view.transform.concatenating(CGAffineTransform(scaleX: 1.2, y: 1.2)) to.view.alpha = 0 container.addSubview(to.view) UIView.animate(withDuration: duration, animations: { to.view.transform = from.view.transform container.subviews.forEach { view in view.alpha = 1 } }) { _ in completion(true) } } }
mit
beea2bc254684b23b33d7c9fe89f4111
34.575758
142
0.67121
4.677291
false
false
false
false
EvsenevDev/SmartReceiptsiOS
SmartReceipts/Services/APIs/Models/Recognition.swift
2
2282
// // Recognition.swift // SmartReceipts // // Created by Bogdan Evsenev on 19/11/2018. // Copyright © 2018 Will Baumann. All rights reserved. // import Foundation struct Recognition: Codable { private(set) var id: String private(set) var status: String private(set) var s3path: String private(set) var result: RecognitonResult private(set) var createdAt: Date enum CodingKeys: String, CodingKey { case id case status case s3path = "s3_path" case result = "data" case createdAt = "created_at_iso8601" } } struct RecognitionData: Codable { private(set) var totalAmount: DoubleData? private(set) var taxAmount: DoubleData? private(set) var date: DateData? private(set) var merchantName: StringData? private(set) var merchantAddress: StringData? private(set) var merchantCity: StringData? private(set) var merchantState: StringData? private(set) var merchantCountryCode: StringData? private(set) var merchantTypes: StringArrayData? } struct RecognitonResult: Codable { private(set) var data: RecognitionData private(set) var amount: Double? private(set) var tax: Double? enum CodingKeys: String, CodingKey { case data = "recognition_data" case amount case tax } } //MARK: Internal Models struct DoubleData: Codable { private(set) var data: Double? private(set) var confidenceLevel: Double? } struct StringData: Codable { private(set) var data: String? private(set) var confidenceLevel: Double? } struct StringArrayData: Codable { private(set) var data: [String]? private(set) var confidenceLevel: Double? } fileprivate let MINIMUM_DATE_CONFIDENCE: Double = 0.4 struct DateData: Codable { private(set) var data: Date? private(set) var confidenceLevel: Double? public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) if let confidenceLevel = try? container.decode(Double.self, forKey: .confidenceLevel), confidenceLevel >= MINIMUM_DATE_CONFIDENCE { self.confidenceLevel = confidenceLevel self.data = try? container.decode(Date.self, forKey: .data) } } }
agpl-3.0
5f4a145fa6e2c56a93824a6ee3245442
25.835294
94
0.680403
4.044326
false
false
false
false
koba-uy/chivia-app-ios
src/Pods/MapboxCoreNavigation/MapboxCoreNavigation/SimulatedLocationManager.swift
1
9713
import Foundation import MapboxDirections import Turf fileprivate let maximumSpeed: CLLocationSpeed = 30 // ~108 kmh fileprivate let minimumSpeed: CLLocationSpeed = 6 // ~21 kmh fileprivate var distanceFilter: CLLocationDistance = 10 fileprivate var verticalAccuracy: CLLocationAccuracy = 10 fileprivate var horizontalAccuracy: CLLocationAccuracy = 40 // minimumSpeed will be used when a location have maximumTurnPenalty fileprivate let maximumTurnPenalty: CLLocationDirection = 90 // maximumSpeed will be used when a location have minimumTurnPenalty fileprivate let minimumTurnPenalty: CLLocationDirection = 0 // Go maximum speed if distance to nearest coordinate is >= `safeDistance` fileprivate let safeDistance: CLLocationDistance = 50 fileprivate class SimulatedLocation: CLLocation { var turnPenalty: Double = 0 override var description: String { return "\(super.description) \(turnPenalty)" } } /** The `SimulatedLocationManager` class simulates location updates along a given route. The route will be replaced upon a `RouteControllerDidReroute` notification. */ @objc(MBSimulatedLocationManager) public class SimulatedLocationManager: NavigationLocationManager { fileprivate var currentDistance: CLLocationDistance = 0 fileprivate var currentLocation = CLLocation() fileprivate var currentSpeed: CLLocationSpeed = 30 fileprivate var locations: [SimulatedLocation]! fileprivate var routeLine = [CLLocationCoordinate2D]() override public var location: CLLocation? { get { return currentLocation } } var route: Route? { didSet { reset() } } var routeProgress: RouteProgress? /** Initalizes a new `SimulatedLocationManager` with the given route. - parameter route: The initial route. - returns: A `SimulatedLocationManager` */ public init(route: Route) { super.init() self.route = route reset() NotificationCenter.default.addObserver(self, selector: #selector(didReroute(_:)), name: RouteControllerDidReroute, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(progressDidChange(_:)), name: RouteControllerProgressDidChange, object: nil) } private func reset() { if let coordinates = route?.coordinates { routeLine = coordinates locations = coordinates.simulatedLocationsWithTurnPenalties() currentDistance = 0 currentSpeed = 30 DispatchQueue.main.async { self.startUpdatingLocation() } } } @objc private func progressDidChange(_ notification: Notification) { routeProgress = notification.userInfo![RouteControllerAlertLevelDidChangeNotificationRouteProgressKey] as? RouteProgress } @objc private func didReroute(_ notification: Notification) { guard let routeController = notification.object as? RouteController else { return } route = routeController.routeProgress.route } deinit { NotificationCenter.default.removeObserver(self, name: RouteControllerDidReroute, object: nil) NotificationCenter.default.removeObserver(self, name: RouteControllerProgressDidChange, object: nil) } override public func startUpdatingLocation() { tick() } override public func stopUpdatingLocation() { NSObject.cancelPreviousPerformRequests(withTarget: self, selector: #selector(tick), object: nil) } @objc fileprivate func tick() { NSObject.cancelPreviousPerformRequests(withTarget: self, selector: #selector(tick), object: nil) let polyline = Polyline(routeLine) guard let newCoordinate = polyline.coordinateFromStart(distance: currentDistance) else { return } // Closest coordinate ahead guard let lookAheadCoordinate = polyline.coordinateFromStart(distance: currentDistance + 10) else { return } guard let closestCoordinate = polyline.closestCoordinate(to: newCoordinate) else { return } let closestLocation = locations[closestCoordinate.index] let distanceToClosest = closestLocation.distance(from: CLLocation(newCoordinate)) let distance = min(max(distanceToClosest, 10), safeDistance) let coordinatesNearby = polyline.trimmed(from: newCoordinate, distance: 100).coordinates // Simulate speed based on expected segment travel time if let expectedSegmentTravelTimes = routeProgress?.currentLeg.expectedSegmentTravelTimes, let coordinates = routeProgress?.route.coordinates, let closestCoordinateOnRoute = Polyline(routeProgress!.route.coordinates!).closestCoordinate(to: newCoordinate), let nextCoordinateOnRoute = coordinates.after(element: coordinates[closestCoordinateOnRoute.index]), let time = expectedSegmentTravelTimes.optional[closestCoordinateOnRoute.index] { let distance = coordinates[closestCoordinateOnRoute.index].distance(to: nextCoordinateOnRoute) currentSpeed = distance / time } // More than 10 nearby coordinates indicates that we are in a roundabout or similar complex shape. else if coordinatesNearby.count >= 10 { currentSpeed = minimumSpeed } // Maximum speed if we are a safe distance from the closest coordinate else if distance >= safeDistance { currentSpeed = maximumSpeed } // Base speed on previous or upcoming turn penalty else { let reversedTurnPenalty = maximumTurnPenalty - closestLocation.turnPenalty currentSpeed = reversedTurnPenalty.scale(minimumIn: minimumTurnPenalty, maximumIn: maximumTurnPenalty, minimumOut: minimumSpeed, maximumOut: maximumSpeed) } let location = CLLocation(coordinate: newCoordinate, altitude: 0, horizontalAccuracy: horizontalAccuracy, verticalAccuracy: verticalAccuracy, course: newCoordinate.direction(to: lookAheadCoordinate).wrap(min: 0, max: 360), speed: currentSpeed, timestamp: Date()) currentLocation = location lastKnownLocation = location delegate?.locationManager?(self, didUpdateLocations: [currentLocation]) currentDistance += currentSpeed perform(#selector(tick), with: nil, afterDelay: 0.95) } } extension Double { fileprivate func scale(minimumIn: Double, maximumIn: Double, minimumOut: Double, maximumOut: Double) -> Double { return ((maximumOut - minimumOut) * (self - minimumIn) / (maximumIn - minimumIn)) + minimumOut } } extension CLLocation { fileprivate convenience init(_ coordinate: CLLocationCoordinate2D) { self.init(latitude: coordinate.latitude, longitude: coordinate.longitude) } } extension Array where Element : Hashable { fileprivate struct OptionalSubscript { var elements: [Element] subscript (index: Int) -> Element? { return index < elements.count ? elements[index] : nil } } fileprivate var optional: OptionalSubscript { get { return OptionalSubscript(elements: self) } } } extension Array where Element : Equatable { fileprivate func after(element: Element) -> Element? { if let index = self.index(of: element), index + 1 <= self.count { return index + 1 == self.count ? self[0] : self[index + 1] } return nil } } extension Array where Element == CLLocationCoordinate2D { // Calculate turn penalty for each coordinate. fileprivate func simulatedLocationsWithTurnPenalties() -> [SimulatedLocation] { var locations = [SimulatedLocation]() for (coordinate, nextCoordinate) in zip(prefix(upTo: endIndex - 1), suffix(from: 1)) { let currentCoordinate = locations.isEmpty ? first! : coordinate let course = coordinate.direction(to: nextCoordinate).wrap(min: 0, max: 360) let turnPenalty = currentCoordinate.direction(to: coordinate).differenceBetween(coordinate.direction(to: nextCoordinate)) let location = SimulatedLocation(coordinate: coordinate, altitude: 0, horizontalAccuracy: horizontalAccuracy, verticalAccuracy: verticalAccuracy, course: course, speed: minimumSpeed, timestamp: Date()) location.turnPenalty = Swift.max(Swift.min(turnPenalty, maximumTurnPenalty), minimumTurnPenalty) locations.append(location) } locations.append(SimulatedLocation(coordinate: last!, altitude: 0, horizontalAccuracy: horizontalAccuracy, verticalAccuracy: verticalAccuracy, course: locations.last!.course, speed: minimumSpeed, timestamp: Date())) return locations } }
lgpl-3.0
5a17b386b0d2611cba4c4059fd1e6a81
41.047619
166
0.637805
5.844164
false
false
false
false
benlangmuir/swift
test/SILGen/access_marker_gen.swift
9
6272
// RUN: %target-swift-emit-silgen -module-name access_marker_gen -parse-as-library -Xllvm -sil-full-demangle -enforce-exclusivity=checked %s | %FileCheck %s func modify<T>(_ x: inout T) {} public struct S { var i: Int var o: AnyObject? } // CHECK-LABEL: sil hidden [noinline] [ossa] @$s17access_marker_gen5initSyAA1SVyXlSgF : $@convention(thin) (@guaranteed Optional<AnyObject>) -> @owned S { // CHECK: bb0(%0 : @guaranteed $Optional<AnyObject>): // CHECK: [[BOX:%.*]] = alloc_box ${ var S }, var, name "s" // CHECK: [[MARKED_BOX:%.*]] = mark_uninitialized [var] [[BOX]] : ${ var S } // CHECK: [[BOX_LIFETIME:%[^,]+]] = begin_borrow [lexical] [[MARKED_BOX]] // CHECK: [[ADDR:%.*]] = project_box [[BOX_LIFETIME]] : ${ var S }, 0 // CHECK: cond_br %{{.*}}, bb1, bb2 // CHECK: bb1: // CHECK: [[ACCESS1:%.*]] = begin_access [modify] [unknown] [[ADDR]] : $*S // CHECK: assign %{{.*}} to [[ACCESS1]] : $*S // CHECK: end_access [[ACCESS1]] : $*S // CHECK: bb2: // CHECK: [[ACCESS2:%.*]] = begin_access [modify] [unknown] [[ADDR]] : $*S // CHECK: assign %{{.*}} to [[ACCESS2]] : $*S // CHECK: end_access [[ACCESS2]] : $*S // CHECK: bb3: // CHECK: [[ACCESS3:%.*]] = begin_access [read] [unknown] [[ADDR]] : $*S // CHECK: [[RET:%.*]] = load [copy] [[ACCESS3]] : $*S // CHECK: end_access [[ACCESS3]] : $*S // CHECK: return [[RET]] : $S // CHECK-LABEL: } // end sil function '$s17access_marker_gen5initSyAA1SVyXlSgF' @inline(never) func initS(_ o: AnyObject?) -> S { var s: S if o == nil { s = S(i: 0, o: nil) } else { s = S(i: 1, o: o) } return s } @inline(never) func takeS(_ s: S) {} // CHECK-LABEL: sil [ossa] @$s17access_marker_gen14modifyAndReadSyyF : $@convention(thin) () -> () { // CHECK: bb0: // CHECK: %[[BOX:.*]] = alloc_box ${ var S }, var, name "s" // CHECK: %[[BOX_LIFETIME:[^,]+]] = begin_borrow [lexical] %[[BOX]] // CHECK: %[[ADDRS:.*]] = project_box %[[BOX_LIFETIME]] : ${ var S }, 0 // CHECK: %[[ACCESS1:.*]] = begin_access [modify] [unknown] %[[ADDRS]] : $*S // CHECK: %[[ADDRI:.*]] = struct_element_addr %[[ACCESS1]] : $*S, #S.i // CHECK: assign %{{.*}} to %[[ADDRI]] : $*Int // CHECK: end_access %[[ACCESS1]] : $*S // CHECK: %[[ACCESS2:.*]] = begin_access [read] [unknown] %[[ADDRS]] : $*S // CHECK: %{{.*}} = load [copy] %[[ACCESS2]] : $*S // CHECK: end_access %[[ACCESS2]] : $*S // CHECK-LABEL: } // end sil function '$s17access_marker_gen14modifyAndReadSyyF' public func modifyAndReadS() { var s = initS(nil) s.i = 42 takeS(s) } var global = S(i: 0, o: nil) func readGlobal() -> AnyObject? { return global.o } // CHECK-LABEL: sil hidden [ossa] @$s17access_marker_gen10readGlobalyXlSgyF // CHECK: [[ADDRESSOR:%.*]] = function_ref @$s17access_marker_gen6globalAA1SVvau : // CHECK-NEXT: [[T0:%.*]] = apply [[ADDRESSOR]]() // CHECK-NEXT: [[T1:%.*]] = pointer_to_address [[T0]] : $Builtin.RawPointer to [strict] $*S // CHECK-NEXT: [[T2:%.*]] = begin_access [read] [dynamic] [[T1]] // CHECK-NEXT: [[T3:%.*]] = struct_element_addr [[T2]] : $*S, #S.o // CHECK-NEXT: [[T4:%.*]] = load [copy] [[T3]] // CHECK-NEXT: end_access [[T2]] // CHECK-NEXT: return [[T4]] public struct HasTwoStoredProperties { var f: Int = 7 var g: Int = 9 // CHECK-LABEL: sil hidden [ossa] @$s17access_marker_gen22HasTwoStoredPropertiesV027noOverlapOnAssignFromPropToM0yyF : $@convention(method) (@inout HasTwoStoredProperties) -> () // CHECK: [[ACCESS1:%.*]] = begin_access [read] [unknown] [[SELF_ADDR:%.*]] : $*HasTwoStoredProperties // CHECK-NEXT: [[G_ADDR:%.*]] = struct_element_addr [[ACCESS1]] : $*HasTwoStoredProperties, #HasTwoStoredProperties.g // CHECK-NEXT: [[G_VAL:%.*]] = load [trivial] [[G_ADDR]] : $*Int // CHECK-NEXT: end_access [[ACCESS1]] : $*HasTwoStoredProperties // CHECK-NEXT: [[ACCESS2:%.*]] = begin_access [modify] [unknown] [[SELF_ADDR]] : $*HasTwoStoredProperties // CHECK-NEXT: [[F_ADDR:%.*]] = struct_element_addr [[ACCESS2]] : $*HasTwoStoredProperties, #HasTwoStoredProperties.f // CHECK-NEXT: assign [[G_VAL]] to [[F_ADDR]] : $*Int // CHECK-NEXT: end_access [[ACCESS2]] : $*HasTwoStoredProperties mutating func noOverlapOnAssignFromPropToProp() { f = g } } class C { final var x: Int = 0 let z: Int = 0 } func testClassInstanceProperties(c: C) { let y = c.x c.x = y } // CHECK-LABEL: sil hidden [ossa] @$s17access_marker_gen27testClassInstanceProperties1cyAA1CC_tF : // CHECK: bb0([[C:%.*]] : @guaranteed $C // CHECK-NEXT: debug_value // CHECK-NEXT: [[CX:%.*]] = ref_element_addr [[C]] : $C, #C.x // CHECK-NEXT: [[ACCESS:%.*]] = begin_access [read] [dynamic] [[CX]] : $*Int // CHECK-NEXT: [[Y:%.*]] = load [trivial] [[ACCESS]] // CHECK-NEXT: end_access [[ACCESS]] // CHECK-NEXT: debug_value // CHECK-NEXT: [[CX:%.*]] = ref_element_addr [[C]] : $C, #C.x // CHECK-NEXT: [[ACCESS:%.*]] = begin_access [modify] [dynamic] [[CX]] : $*Int // CHECK-NEXT: assign [[Y]] to [[ACCESS]] // CHECK-NEXT: end_access [[ACCESS]] func testClassLetProperty(c: C) -> Int { return c.z } // CHECK-LABEL: sil hidden [ossa] @$s17access_marker_gen20testClassLetProperty1cSiAA1CC_tF : $@convention(thin) (@guaranteed C) -> Int { // CHECK: bb0(%0 : @guaranteed $C): // CHECK: [[ADR:%.*]] = ref_element_addr %{{.*}} : $C, #C.z // CHECK-NOT: begin_access // CHECK: %{{.*}} = load [trivial] [[ADR]] : $*Int // CHECK-NOT: end_access // CHECK-NOT: destroy_value %0 : $C // CHECK: return %{{.*}} : $Int // CHECK-LABEL: } // end sil function '$s17access_marker_gen20testClassLetProperty1cSiAA1CC_tF' class D { var x: Int = 0 } // modify // CHECK-LABEL: sil hidden [transparent] [ossa] @$s17access_marker_gen1DC1xSivM // CHECK: [[T0:%.*]] = ref_element_addr %0 : $D, #D.x // CHECK-NEXT: [[T1:%.*]] = begin_access [modify] [dynamic] [[T0]] : $*Int // CHECK: yield [[T1]] : $*Int // CHECK: end_access [[T1]] : $*Int // CHECK: end_access [[T1]] : $*Int func testDispatchedClassInstanceProperty(d: D) { modify(&d.x) } // CHECK-LABEL: sil hidden [ossa] @$s17access_marker_gen35testDispatchedClassInstanceProperty1dyAA1DC_tF // CHECK: bb0([[D:%.*]] : @guaranteed $D // CHECK: [[METHOD:%.*]] = class_method [[D]] : $D, #D.x!modify // CHECK: begin_apply [[METHOD]]([[D]]) // CHECK-NOT: begin_access // CHECK: end_apply
apache-2.0
711de40931ca287dd5e45fb580574807
38.949045
177
0.594547
3.01974
false
false
false
false